From 972dbda0404caefaa8589dd2e5b060ccb2137537 Mon Sep 17 00:00:00 2001 From: William Date: Fri, 9 Aug 2024 19:01:47 +0100 Subject: [PATCH 001/165] Update rvc app integrate service area (#34887) * Updated the golabl data type's XMLs, removing the cluster entries. * Zap generated after XML update. * Fixed namespaces used of global structs. * Restyled by clang-format * Renamed LocationInfoStruct to AreaInfoStruct. * Zap generated after XML update. * Renamed LocationStruct to AreaStruct and its LocationID and LocationDesc fields. * Zap generated after XML update. * Updated SDK and example code to match the new naming. * Updated the ProgressStruct's LocationID name to AreaID. * Zap generated after XML update. * Updated the SDK code following name changes. * Updated the SelectLocationsStatus and SkipLocationStatus enum names and some of their enums. * Zap generated after XML update. * Updated the SelectLocationsStatus and SkipCurrentLocationStatus names and their enum names. * Updated the names of the SupportedLocations, SelectedLocations and CurrentLocation attributes. * Zap generated after XML update. * Updated the changed names in the SDK. * Updated the service area command names in XML. * Zap generated after XML update. * Updated the service area command names in the SDK. * Updated the rvc-example zap file. * Refactored LocationStructureWrapper to AreaStructureWrapper. * Restyled by clang-format * Regenerated zap files due to changes upsteram. * Removed unused generated file. * Updated the Service Area XML marking previously nullabel attributes as not-nullable. * Zap generated after XML update. * Updated the attribute encoding and some server logic following the romoval of the nullable quality for some attributes. * Explicitly set the Service Area version. * Zap generated after XML update. * Updated the service area features in the XML to match the current spec. * Zap generated after XML update. * Updated the SupportedArea validation logic as if the MAPS feature is not supported, the Delegate may choose not to implement map related methods. * Change the type of the MapID to uint32 to match the spec. * Added the SkippedArea arg to the SkipArea command. * Zap generated after XML update. * Updated the Service Area server code to handle the new SkippedArea command arg. * Updated the service area XML to match the current spec. This includes the addition of the LandmarkInfoStruct and updates of AreaInfoStruct, SelectAreasStatus. * Zap generated after XML update. * Updated SDK server code and rvc-example after changes to the XML. * Restyled by whitespace * added vector include. * spacing changes form zap regen. * Fixed minor mistake during merge. * Restyled by clang-format * Applied suggestions from review. * Restyled by whitespace * Updated the LondmarkInfoSturct PositionTag type. * Zap generated after XML update. * Fixed SDK following update to the position type. * Restyled by clang-format * Updated the AeraStructWrapper to not contain methods with a large number of params. Updated some relate Instance and Delegate methods. * Restyled by whitespace * Restyled by clang-format * Missed a submudule update. * Made the setters reture a ref to the sturct to allow chaining. * simplified the = oporator and add the == operator. * Restyled by clang-format * Added methods to set the SupportedMaps and SupproctedAreas. * Updated the RVC app to provide a way to defined service area methods that interacte with other clusters in the RvcDevice class. * Fixed typo. * minor change to get restyler going. * Restyled by clang-format * Fixed status text referance issue. * Fixed issue casued by a change in the way that registrations are made. * Fixed styling and minor bug in IsValidSupportedArea. * Implemented the IsValidSelectAreasSet method. * implemented SaHandleSkipCurrentArea. * Restyled by clang-format * Added methods to updated the service area current area and progress attributes when the device starts operating. * Updated the handle skip area method to use the GoToNextArea method. * Added the AreaComplete out-of-band message. * updated the reset evet handler to reset the service area attributes. * minor shifing of responsibilites. * Restyled by clang-format * reverted to adding the PID to the fifo name. * Updated readme and pics files. * Restyled by prettier-markdown --------- Co-authored-by: Restyled.io --- examples/rvc-app/README.md | 17 +- .../rvc-app/linux/RvcAppCommandDelegate.cpp | 9 + .../rvc-app/linux/RvcAppCommandDelegate.h | 2 + .../rvc-app/rvc-common/include/rvc-device.h | 15 + .../include/rvc-service-area-delegate.h | 77 ++++++ .../rvc-common/pics/rvc-app-pics-values | 28 ++ .../rvc-app/rvc-common/src/rvc-device.cpp | 69 +++++ .../src/rvc-service-area-delegate.cpp | 260 ++++++++++++++++-- .../service-area-delegate.h | 27 +- .../service-area-server.cpp | 2 +- 10 files changed, 465 insertions(+), 41 deletions(-) diff --git a/examples/rvc-app/README.md b/examples/rvc-app/README.md index 2943f54103..7431c663ef 100644 --- a/examples/rvc-app/README.md +++ b/examples/rvc-app/README.md @@ -20,6 +20,11 @@ must have a `"Name"` key that contains the command name. This name is shown in the state machine diagram above. Example `echo '{"Name": "Charged"}' > /tmp/chip_rvc_fifo_42`. +### `AreaComplete` message + +This indicates that the area currently being serviced as indicated by the +service area cluster is now complete. + ### `ErrorEvent` message The error event message requires the additional key `"Error"` which specifies @@ -37,10 +42,14 @@ and setting up the testing environment, python tests can be executed with `./scripts/tests/run_python_test.py --script src/python_testing/.py --script-args "--storage-path admin_storage.json --PICS examples/rvc-app/rvc-common/pics/RVC_App_Test_Plan.txt --int-arg "` **Note:** If the testing environment has not been commissioned with the RVC app, -use chip-tool to switch on the commissioning window -`chip-tool pairing open-commissioning-window`, and add the following flags to -the `--script-args` above. -`--commissioning-method on-network --discriminator XXXX --passcode XXXX`. + +1. use chip-tool to switch on the commissioning window + `out/debug/chip-tool pairing open-commissioning-window 0x1230 1 180 1000 42` +2. Get the manual pairing code. This will look something like + `Manual pairing code: [01073112097]`. +3. Run any one of the tests with the `--commission-only` and `--manual-code` + flags: + `./scripts/tests/run_python_test.py --script src/python_testing/TC_RVCCLEANM_1_2.py --script-args "--commissioning-method on-network --manual-code 01073112097 --commission-only"` Below are the PIXIT definitions required for the different python tests. diff --git a/examples/rvc-app/linux/RvcAppCommandDelegate.cpp b/examples/rvc-app/linux/RvcAppCommandDelegate.cpp index 58610e1b11..5a08dc6c9f 100644 --- a/examples/rvc-app/linux/RvcAppCommandDelegate.cpp +++ b/examples/rvc-app/linux/RvcAppCommandDelegate.cpp @@ -83,6 +83,10 @@ void RvcAppCommandHandler::HandleCommand(intptr_t context) { self->OnActivityCompleteHandler(); } + else if (name == "AreaComplete") + { + self->OnAreaCompleteHandler(); + } else if (name == "ErrorEvent") { std::string error = self->mJsonValue["Error"].asString(); @@ -140,6 +144,11 @@ void RvcAppCommandHandler::OnActivityCompleteHandler() mRvcDevice->HandleActivityCompleteEvent(); } +void RvcAppCommandHandler::OnAreaCompleteHandler() +{ + mRvcDevice->HandleAreaCompletedEvent(); +} + void RvcAppCommandHandler::OnErrorEventHandler(const std::string & error) { mRvcDevice->HandleErrorEvent(error); diff --git a/examples/rvc-app/linux/RvcAppCommandDelegate.h b/examples/rvc-app/linux/RvcAppCommandDelegate.h index 366772bf08..e8dc404de2 100644 --- a/examples/rvc-app/linux/RvcAppCommandDelegate.h +++ b/examples/rvc-app/linux/RvcAppCommandDelegate.h @@ -55,6 +55,8 @@ class RvcAppCommandHandler void OnActivityCompleteHandler(); + void OnAreaCompleteHandler(); + void OnErrorEventHandler(const std::string & error); void OnClearErrorHandler(); diff --git a/examples/rvc-app/rvc-common/include/rvc-device.h b/examples/rvc-app/rvc-common/include/rvc-device.h index da03422ffb..97f3475117 100644 --- a/examples/rvc-app/rvc-common/include/rvc-device.h +++ b/examples/rvc-app/rvc-common/include/rvc-device.h @@ -59,6 +59,11 @@ class RvcDevice mOperationalStateDelegate.SetPauseCallback(&RvcDevice::HandleOpStatePauseCallback, this); mOperationalStateDelegate.SetResumeCallback(&RvcDevice::HandleOpStateResumeCallback, this); mOperationalStateDelegate.SetGoHomeCallback(&RvcDevice::HandleOpStateGoHomeCallback, this); + + mServiceAreaDelegate.SetIsSetSelectedAreasAllowedCallback(&RvcDevice::SaIsSetSelectedAreasAllowed, this); + mServiceAreaDelegate.SetHandleSkipCurrentAreaCallback(&RvcDevice::SaHandleSkipCurrentArea, this); + mServiceAreaDelegate.SetIsSupportedAreasChangeAllowedCallback(&RvcDevice::SaIsSupportedAreasChangeAllowed, this); + mServiceAreaDelegate.SetIsSupportedMapChangeAllowedCallback(&RvcDevice::SaIsSupportedMapChangeAllowed, this); } /** @@ -97,6 +102,14 @@ class RvcDevice */ void HandleOpStateGoHomeCallback(Clusters::OperationalState::GenericOperationalError & err); + bool SaIsSetSelectedAreasAllowed(MutableCharSpan & statusText); + + bool SaHandleSkipCurrentArea(uint32_t skippedArea, MutableCharSpan & skipStatusText); + + bool SaIsSupportedAreasChangeAllowed(); + + bool SaIsSupportedMapChangeAllowed(); + /** * Updates the state machine when the device becomes fully-charged. */ @@ -112,6 +125,8 @@ class RvcDevice void HandleActivityCompleteEvent(); + void HandleAreaCompletedEvent(); + /** * Sets the device to an error state with the error state ID matching the error name given. * @param error The error name. Could be one of UnableToStartOrResume, UnableToCompleteOperation, CommandInvalidInState, diff --git a/examples/rvc-app/rvc-common/include/rvc-service-area-delegate.h b/examples/rvc-app/rvc-common/include/rvc-service-area-delegate.h index 41b8415c3d..4d065782dc 100644 --- a/examples/rvc-app/rvc-common/include/rvc-service-area-delegate.h +++ b/examples/rvc-app/rvc-common/include/rvc-service-area-delegate.h @@ -29,6 +29,10 @@ namespace Clusters { class RvcDevice; +typedef bool (RvcDevice::*IsSetSelectedAreasAllowedCallback)(MutableCharSpan & statusText); +typedef bool (RvcDevice::*HandleSkipCurrentAreaCallback)(uint32_t skippedArea, MutableCharSpan & skipStatusText); +typedef bool (RvcDevice::*IsChangeAllowedSimpleCallback)(); + namespace ServiceArea { class RvcServiceAreaDelegate : public Delegate @@ -40,6 +44,35 @@ class RvcServiceAreaDelegate : public Delegate std::vector mSelectedAreas; std::vector mProgressList; + RvcDevice * mIsSetSelectedAreasAllowedDeviceInstance; + IsSetSelectedAreasAllowedCallback mIsSetSelectedAreasAllowedCallback; + RvcDevice * mHandleSkipCurrentAreaDeviceInstance; + HandleSkipCurrentAreaCallback mHandleSkipCurrentAreaCallback; + RvcDevice * mIsSupportedAreasChangeAllowedDeviceInstance; + IsChangeAllowedSimpleCallback mIsSupportedAreasChangeAllowedCallback; + RvcDevice * mIsSupportedMapChangeAllowedDeviceInstance; + IsChangeAllowedSimpleCallback mIsSupportedMapChangeAllowedCallback; + + // hardcoded values for SUPPORTED MAPS. + const uint32_t supportedMapId_XX = 3; + const uint32_t supportedMapId_YY = 245; + + // hardcoded values for SUPPORTED AREAS. + const uint32_t supportedAreaID_A = 7; + const uint32_t supportedAreaID_B = 1234567; + const uint32_t supportedAreaID_C = 10050; + const uint32_t supportedAreaID_D = 0x88888888; + + /** + * Set the SupportedMaps and SupportedAreas where the SupportedMaps is not null. + */ + void SetMapTopology(); + + /** + * Set the SupportedMaps and SupportedAreas where the SupportedMaps is null. + */ + void SetNoMapTopology(); + public: CHIP_ERROR Init() override; @@ -112,6 +145,50 @@ class RvcServiceAreaDelegate : public Delegate const ServiceArea::Structs::ProgressStruct::Type & modifiedProgressElement) override; bool ClearProgress() override; + + //************************************************************************* + // RVC device callback setters + + void SetIsSetSelectedAreasAllowedCallback(IsSetSelectedAreasAllowedCallback callback, RvcDevice * instance) + { + mIsSetSelectedAreasAllowedCallback = callback; + mIsSetSelectedAreasAllowedDeviceInstance = instance; + } + + void SetHandleSkipCurrentAreaCallback(HandleSkipCurrentAreaCallback callback, RvcDevice * instance) + { + mHandleSkipCurrentAreaCallback = callback; + mHandleSkipCurrentAreaDeviceInstance = instance; + } + + void SetIsSupportedAreasChangeAllowedCallback(IsChangeAllowedSimpleCallback callback, RvcDevice * instance) + { + mIsSupportedAreasChangeAllowedCallback = callback; + mIsSupportedAreasChangeAllowedDeviceInstance = instance; + } + + void SetIsSupportedMapChangeAllowedCallback(IsChangeAllowedSimpleCallback callback, RvcDevice * instance) + { + mIsSupportedMapChangeAllowedCallback = callback; + mIsSupportedMapChangeAllowedDeviceInstance = instance; + } + + //************************************************************************* + // Helper methods for setting service area attributes. + + /** + * Sets the service area attributes at the start of a clean. + * This includes the current area an progress attributes. + */ + void SetAttributesAtCleanStart(); + + /** + * Go to the next area in the list of selected areas. + * @param currentAreaOpState The operational state to be set in the Status field of the Progress attribute for the current area. + * This can only be Completed or Skipped. + * @param finished true if there are no more areas to clean an we should end the clean. + */ + void GoToNextArea(OperationalStatusEnum currentAreaOpState, bool & finished); }; } // namespace ServiceArea diff --git a/examples/rvc-app/rvc-common/pics/rvc-app-pics-values b/examples/rvc-app/rvc-common/pics/rvc-app-pics-values index 669abd26c3..b158de538e 100644 --- a/examples/rvc-app/rvc-common/pics/rvc-app-pics-values +++ b/examples/rvc-app/rvc-common/pics/rvc-app-pics-values @@ -50,3 +50,31 @@ RVCRUNM.S.C01.Tx=1 RVCRUNM.S.F00=0 RVCRUNM.S.M.CAN_TEST_MODE_FAILURE=1 RVCRUNM.S.M.CAN_MANUALLY_CONTROLLED=1 + +SEAR.S=1 +SEAR.S.F00=0 +SEAR.S.F01=1 +SEAR.S.F02=1 +SEAR.S.A0000=1 +SEAR.S.A0001=1 +SEAR.S.A0002=1 +SEAR.S.A0003=1 +SEAR.S.A0004=1 +SEAR.S.A0005=1 +SEAR.S.C00.Rsp=1 +SEAR.S.C02.Rsp=1 +SEAR.S.C01.Tx=1 +SEAR.S.C03.Tx=1 +SEAR.S.M.REMOVE_AREA=0 +SEAR.S.M.ADD_AREA=0 +SEAR.S.M.REMOVE_MAP=0 +SEAR.S.M.ADD_MAP=0 +SEAR.S.M.INVALID_STATE_FOR_SELECT_AREAS=1 +SEAR.S.M.VALID_STATE_FOR_SELECT_AREAS=1 +SEAR.S.M.SELECT_AREAS_WHILE_NON_IDLE=1 +SEAR.S.M.HAS_MANUAL_SELAREA_STATE_CONTROL=1 +SEAR.S.M.HAS_MANUAL_SKIP_STATE_CONTROL=1 +SEAR.S.M.INVALID_STATE_FOR_SKIP=1 +SEAR.S.M.NO_SELAREA_FOR_SKIP=1 +SEAR.S.M.VALID_STATE_FOR_SKIP=1 +SEAR.S.M.HAS_MANUAL_OPERATING_STATE_CONTROL=1 \ No newline at end of file diff --git a/examples/rvc-app/rvc-common/src/rvc-device.cpp b/examples/rvc-app/rvc-common/src/rvc-device.cpp index e018e09293..db938a58e0 100644 --- a/examples/rvc-app/rvc-common/src/rvc-device.cpp +++ b/examples/rvc-app/rvc-common/src/rvc-device.cpp @@ -52,6 +52,7 @@ void RvcDevice::HandleRvcRunChangeToMode(uint8_t newMode, ModeBase::Commands::Ch mDocked = false; mRunModeInstance.UpdateCurrentMode(newMode); mOperationalStateInstance.SetOperationalState(to_underlying(OperationalState::OperationalStateEnum::kRunning)); + mServiceAreaDelegate.SetAttributesAtCleanStart(); response.status = to_underlying(ModeBase::StatusCode::kSuccess); return; } @@ -161,6 +162,55 @@ void RvcDevice::HandleOpStateGoHomeCallback(Clusters::OperationalState::GenericO } } +bool RvcDevice::SaIsSetSelectedAreasAllowed(MutableCharSpan & statusText) +{ + if (mOperationalStateInstance.GetCurrentOperationalState() == to_underlying(OperationalState::OperationalStateEnum::kRunning)) + { + CopyCharSpanToMutableCharSpan("cannot set the Selected Areas while the device is running"_span, statusText); + return false; + } + return true; +} + +bool RvcDevice::SaHandleSkipCurrentArea(uint32_t skippedArea, MutableCharSpan & skipStatusText) +{ + if (mServiceAreaInstance.GetCurrentArea() != skippedArea) + { + // This device only supports skipping the current location. + CopyCharSpanToMutableCharSpan("the skipped area does not match the current area"_span, skipStatusText); + return false; + } + + if (mOperationalStateInstance.GetCurrentOperationalState() != to_underlying(OperationalState::OperationalStateEnum::kRunning)) + { + // This device only accepts the skip are command while in the running state + CopyCharSpanToMutableCharSpan("skip area is only accepted when the device is running"_span, skipStatusText); + return false; + } + + bool finished; + mServiceAreaDelegate.GoToNextArea(ServiceArea::OperationalStatusEnum::kSkipped, finished); + + if (finished) + { + HandleActivityCompleteEvent(); + } + + return true; +} + +bool RvcDevice::SaIsSupportedAreasChangeAllowed() +{ + return mOperationalStateInstance.GetCurrentOperationalState() != + to_underlying(OperationalState::OperationalStateEnum::kRunning); +} + +bool RvcDevice::SaIsSupportedMapChangeAllowed() +{ + return mOperationalStateInstance.GetCurrentOperationalState() != + to_underlying(OperationalState::OperationalStateEnum::kRunning); +} + void RvcDevice::HandleChargedMessage() { if (mOperationalStateInstance.GetCurrentOperationalState() != @@ -258,6 +308,20 @@ void RvcDevice::HandleActivityCompleteEvent() mOperationalStateInstance.OnOperationCompletionDetected(0, a, b); mOperationalStateInstance.SetOperationalState(to_underlying(RvcOperationalState::OperationalStateEnum::kSeekingCharger)); + + mServiceAreaInstance.SetCurrentArea(DataModel::NullNullable); + mServiceAreaInstance.SetEstimatedEndTime(DataModel::NullNullable); +} + +void RvcDevice::HandleAreaCompletedEvent() +{ + bool finished; + mServiceAreaDelegate.GoToNextArea(ServiceArea::OperationalStatusEnum::kCompleted, finished); + + if (finished) + { + HandleActivityCompleteEvent(); + } } void RvcDevice::HandleErrorEvent(const std::string & error) @@ -334,4 +398,9 @@ void RvcDevice::HandleResetMessage() mRunModeInstance.UpdateCurrentMode(RvcRunMode::ModeIdle); mOperationalStateInstance.SetOperationalState(to_underlying(OperationalState::OperationalStateEnum::kStopped)); mCleanModeInstance.UpdateCurrentMode(RvcCleanMode::ModeQuick); + + mServiceAreaInstance.ClearSelectedAreas(); + mServiceAreaInstance.ClearProgress(); + mServiceAreaInstance.SetCurrentArea(DataModel::NullNullable); + mServiceAreaInstance.SetEstimatedEndTime(DataModel::NullNullable); } diff --git a/examples/rvc-app/rvc-common/src/rvc-service-area-delegate.cpp b/examples/rvc-app/rvc-common/src/rvc-service-area-delegate.cpp index d92910ea1a..11daac10ec 100644 --- a/examples/rvc-app/rvc-common/src/rvc-service-area-delegate.cpp +++ b/examples/rvc-app/rvc-common/src/rvc-service-area-delegate.cpp @@ -23,21 +23,13 @@ using namespace chip; using namespace chip::app::Clusters; using namespace chip::app::Clusters::ServiceArea; -CHIP_ERROR RvcServiceAreaDelegate::Init() +void RvcServiceAreaDelegate::SetMapTopology() { - // hardcoded fill of SUPPORTED MAPS for prototyping - uint32_t supportedMapId_XX = 3; - uint32_t supportedMapId_YY = 245; + ClearSupportedMaps(); GetInstance()->AddSupportedMap(supportedMapId_XX, "My Map XX"_span); GetInstance()->AddSupportedMap(supportedMapId_YY, "My Map YY"_span); - // hardcoded fill of SUPPORTED AREAS for prototyping - uint32_t supportedAreaID_A = 7; - uint32_t supportedAreaID_B = 1234567; - uint32_t supportedAreaID_C = 10050; - uint32_t supportedAreaID_D = 0x88888888; - // Area A has name, floor number, uses map XX auto areaA = AreaStructureWrapper{} @@ -47,7 +39,7 @@ CHIP_ERROR RvcServiceAreaDelegate::Init() // Area B has name, uses map XX auto areaB = AreaStructureWrapper{} - .SetMapId(supportedAreaID_B) + .SetAreaId(supportedAreaID_B) .SetMapId(supportedMapId_XX) .SetLocationInfo("My Location B"_span, DataModel::NullNullable, DataModel::NullNullable); @@ -69,6 +61,45 @@ CHIP_ERROR RvcServiceAreaDelegate::Init() GetInstance()->AddSupportedArea(areaB); GetInstance()->AddSupportedArea(areaC); GetInstance()->AddSupportedArea(areaD); +} + +void RvcServiceAreaDelegate::SetNoMapTopology() +{ + ClearSupportedMaps(); + + // Area A has name, floor number. + auto areaA = + AreaStructureWrapper{} + .SetAreaId(supportedAreaID_A) + .SetLocationInfo("My Location A"_span, DataModel::Nullable(4), DataModel::Nullable()); + + // Area B has name. + auto areaB = AreaStructureWrapper{} + .SetAreaId(supportedAreaID_B) + .SetLocationInfo("My Location B"_span, DataModel::NullNullable, DataModel::NullNullable); + + // Area C has full SemData, no name. + auto areaC = AreaStructureWrapper{} + .SetAreaId(supportedAreaID_C) + .SetLocationInfo(""_span, -1, Globals::AreaTypeTag::kPlayRoom) + .SetLandmarkInfo(Globals::LandmarkTag::kBackDoor, Globals::RelativePositionTag::kNextTo); + + // Area D has null values for all landmark fields. + auto areaD = AreaStructureWrapper{} + .SetAreaId(supportedAreaID_D) + .SetLocationInfo("My Location D"_span, DataModel::NullNullable, DataModel::NullNullable) + .SetLandmarkInfo(Globals::LandmarkTag::kCouch, Globals::RelativePositionTag::kNextTo); + + GetInstance()->AddSupportedArea(areaA); + GetInstance()->AddSupportedArea(areaB); + GetInstance()->AddSupportedArea(areaC); + GetInstance()->AddSupportedArea(areaD); +} + +CHIP_ERROR RvcServiceAreaDelegate::Init() +{ + SetMapTopology(); + GetInstance()->SetCurrentArea(supportedAreaID_C); return CHIP_NO_ERROR; @@ -79,21 +110,79 @@ CHIP_ERROR RvcServiceAreaDelegate::Init() bool RvcServiceAreaDelegate::IsSetSelectedAreasAllowed(MutableCharSpan & statusText) { - // TODO IMPLEMENT - return true; + return (mIsSetSelectedAreasAllowedDeviceInstance->*mIsSetSelectedAreasAllowedCallback)(statusText); }; bool RvcServiceAreaDelegate::IsValidSelectAreasSet(const Commands::SelectAreas::DecodableType & req, SelectAreasStatus & areaStatus, MutableCharSpan & statusText) { - // TODO IMPLEMENT + // if req is empty list return true. + { + size_t reqSize; + if (req.newAreas.ComputeSize(&reqSize) != CHIP_NO_ERROR) + { + areaStatus = SelectAreasStatus::kInvalidSet; // todo Not sure this is the correct error to use here + CopyCharSpanToMutableCharSpan("error computing number of selected areas"_span, statusText); + return false; + } + + if (reqSize == 0) + { + return true; + } + } + + // If there are less than 2 supported maps, any combination of areas is valid. + if (!GetInstance()->HasFeature(Feature::kMaps) || GetNumberOfSupportedMaps() <= 1) + { + return true; + } + + // Check that all the areas are in the same map. + auto newAreasIter = req.newAreas.begin(); + newAreasIter.Next(); + + AreaStructureWrapper tempArea; + uint32_t ignoredIndex; + if (!GetSupportedAreaById(newAreasIter.GetValue(), ignoredIndex, tempArea)) + { + areaStatus = SelectAreasStatus::kUnsupportedArea; + CopyCharSpanToMutableCharSpan("unable to find selected area in supported areas"_span, statusText); + return false; + } + + auto mapId = tempArea.mapID.Value(); // It is safe to call `.Value()` as we confirmed that there are at least 2 maps. + + while (newAreasIter.Next()) + { + if (!GetSupportedAreaById(newAreasIter.GetValue(), ignoredIndex, tempArea)) + { + areaStatus = SelectAreasStatus::kUnsupportedArea; + CopyCharSpanToMutableCharSpan("unable to find selected area in supported areas"_span, statusText); + return false; + } + + if (tempArea.mapID.Value() != mapId) + { + areaStatus = SelectAreasStatus::kInvalidSet; + CopyCharSpanToMutableCharSpan("all selected areas must be in the same map"_span, statusText); + return false; + } + } + + if (CHIP_NO_ERROR != newAreasIter.GetStatus()) + { + areaStatus = SelectAreasStatus::kInvalidSet; + CopyCharSpanToMutableCharSpan("error processing new areas."_span, statusText); + return false; + } + return true; }; bool RvcServiceAreaDelegate::HandleSkipCurrentArea(uint32_t skippedArea, MutableCharSpan & skipStatusText) { - // TODO IMPLEMENT - return true; + return (mHandleSkipCurrentAreaDeviceInstance->*mHandleSkipCurrentAreaCallback)(skippedArea, skipStatusText); }; //************************************************************************* @@ -101,8 +190,7 @@ bool RvcServiceAreaDelegate::HandleSkipCurrentArea(uint32_t skippedArea, Mutable bool RvcServiceAreaDelegate::IsSupportedAreasChangeAllowed() { - // TODO IMPLEMENT - return true; + return (mIsSupportedAreasChangeAllowedDeviceInstance->*mIsSupportedAreasChangeAllowedCallback)(); } uint32_t RvcServiceAreaDelegate::GetNumberOfSupportedAreas() @@ -196,8 +284,7 @@ bool RvcServiceAreaDelegate::ClearSupportedAreas() bool RvcServiceAreaDelegate::IsSupportedMapChangeAllowed() { - // TODO IMPLEMENT - return true; + return (mIsSupportedMapChangeAllowedDeviceInstance->*mIsSupportedMapChangeAllowedCallback)(); } uint32_t RvcServiceAreaDelegate::GetNumberOfSupportedMaps() @@ -397,8 +484,15 @@ bool RvcServiceAreaDelegate::AddProgressElement(const Structs::ProgressStruct::T bool RvcServiceAreaDelegate::ModifyProgressElement(uint32_t listIndex, const Structs::ProgressStruct::Type & modifiedProgressElement) { - // TODO IMPLEMENT - return false; + if (modifiedProgressElement.areaID != mProgressList[listIndex].areaID) + { + ChipLogError(Zcl, "ModifyProgressElement - areaID's do not match, new areaID %u, existing areaID %u", + modifiedProgressElement.areaID, mProgressList[listIndex].areaID); + return false; + } + + mProgressList[listIndex] = modifiedProgressElement; + return true; } bool RvcServiceAreaDelegate::ClearProgress() @@ -411,3 +505,125 @@ bool RvcServiceAreaDelegate::ClearProgress() return false; } + +void RvcServiceAreaDelegate::SetAttributesAtCleanStart() +{ + if (GetNumberOfSupportedAreas() == 0) + { + return; + } + + if (GetNumberOfSelectedAreas() == 0) + { + AreaStructureWrapper firstArea; + GetSupportedAreaByIndex(0, firstArea); + + GetInstance()->SetCurrentArea(firstArea.areaID); + + if (GetInstance()->HasFeature(Feature::kProgressReporting)) + { + GetInstance()->AddPendingProgressElement(firstArea.areaID); + GetInstance()->SetProgressStatus(firstArea.areaID, OperationalStatusEnum::kOperating); + } + } + else + { + uint32_t areaId; + GetSelectedAreaByIndex(0, areaId); + + GetInstance()->SetCurrentArea(areaId); + + if (GetInstance()->HasFeature(Feature::kProgressReporting)) + { + GetInstance()->AddPendingProgressElement(areaId); + GetInstance()->SetProgressStatus(areaId, OperationalStatusEnum::kOperating); + + uint32_t i = 1; + while (GetSelectedAreaByIndex(i, areaId)) + { + GetInstance()->AddPendingProgressElement(areaId); + i++; + } + } + } +} + +void RvcServiceAreaDelegate::GoToNextArea(OperationalStatusEnum currentAreaOpState, bool & finished) +{ + AreaStructureWrapper currentArea; + auto currentAreaIdN = GetInstance()->GetCurrentArea(); + + if (currentAreaIdN.IsNull()) + { + ChipLogError(Zcl, "GoToNextArea: Cannot go to the next area when the current area is null."); + return; + } + + if (currentAreaOpState != OperationalStatusEnum::kCompleted && currentAreaOpState != OperationalStatusEnum::kSkipped) + { + ChipLogError(Zcl, "GoToNextArea: currentAreaOpState must be either completed or skipped."); + return; + } + + auto currentAreaId = currentAreaIdN.Value(); + uint32_t currentAreaIndex; + GetSupportedAreaById(currentAreaId, currentAreaIndex, currentArea); + auto currentAreaMapId = currentArea.mapID; + finished = true; + + if (GetInstance()->HasFeature(Feature::kProgressReporting)) + { + GetInstance()->SetProgressStatus(currentAreaId, currentAreaOpState); + } + + if (GetNumberOfSelectedAreas() == 0) + { + AreaStructureWrapper nextArea; + uint32_t nextIndex = currentAreaIndex + 1; + while (GetSupportedAreaByIndex(nextIndex, nextArea)) + { + if (!currentAreaMapId.IsNull() && nextArea.mapID == currentAreaMapId.Value()) + { + GetInstance()->SetCurrentArea(nextArea.areaID); + + if (GetInstance()->HasFeature(Feature::kProgressReporting)) + { + GetInstance()->SetProgressStatus(nextArea.areaID, OperationalStatusEnum::kOperating); + } + + finished = false; + return; + } + + ++nextIndex; + } + } + else + { + uint32_t selectedAreaId; + uint32_t selectedAreaIndex = 0; + while (GetSelectedAreaByIndex(selectedAreaIndex, selectedAreaId)) + { + if (selectedAreaId == currentAreaId) + { + break; + } + ++selectedAreaIndex; + } + + uint32_t nextSelectedAreaId; + uint32_t nextSelectedAreaIndex = selectedAreaIndex + 1; + if (GetSelectedAreaByIndex(nextSelectedAreaIndex, nextSelectedAreaId)) + { + GetInstance()->SetCurrentArea(nextSelectedAreaId); + + if (GetInstance()->HasFeature(Feature::kProgressReporting)) + { + GetInstance()->SetProgressStatus(nextSelectedAreaId, OperationalStatusEnum::kOperating); + } + + finished = false; + return; + } + } +} diff --git a/src/app/clusters/service-area-server/service-area-delegate.h b/src/app/clusters/service-area-server/service-area-delegate.h index 24db2b10a7..01df2faeb0 100644 --- a/src/app/clusters/service-area-server/service-area-delegate.h +++ b/src/app/clusters/service-area-server/service-area-delegate.h @@ -104,22 +104,21 @@ class Delegate * * @note skipStatusText must be filled out by the function on failure. * - * @note If the device successfully accepts the request and the ListOrder feature is set to 1: - * The server SHALL stop operating at the current location. - * The server SHALL attempt to operate at the remaining locations on the SelectedAreas attribute list, starting with - * the next entry. If the end of the SelectedAreas attribute list is reached, the server SHALL stop operating. - * - * @note If the device successfully accepts the request and the ListOrder feature is set to 0: - * The server SHALL stop operating at the current location. - * The server SHALL attempt to operate at the locations on the SelectedAreas attribute list where operating has not - * been completed, using a vendor defined order. If the server has completed operating at all locations on the SelectedAreas - * attribute list, the server SHALL stop operating. + * @note If the device accepts the request: + * - If the device is currently operating at the area identified by SkippedArea, as indicated by either the CurrentArea or + * the Progress attributes, if implemented, the device SHALL stop operating at that area. + * - If the Progress attribute is implemented, the entry corresponding to SkippedArea SHALL be updated to indicate that the + * area was skipped. + * - The server SHALL attempt to operate only at the areas in the SelectedAreas attribute list where operating has not been + * skipped or completed, using a vendor defined order. + * - If the server has either skipped or completed operating at all areas on the SelectedAreas attribute list, the server + * SHALL stop operating. * * @note If the Status field is set to InvalidAreaList, the StatusText field SHALL be an empty string. * If the Status field is not set to Success, or InvalidAreaList, the StatusText field SHALL include a vendor defined - * error description which can be used to explain the error to the user. For example, if the Status field is set to - * InvalidInMode, the StatusText field SHOULD indicate why the request is not allowed, given the current mode of the device, - * which may involve other clusters. + * error description which can be used to explain the error to the user. For example, if the Status field is set to + * InvalidInMode, the StatusText field SHOULD indicate why the request is not allowed, given the current mode of the + * device, which may involve other clusters. */ virtual bool HandleSkipCurrentArea(uint32_t skippedArea, MutableCharSpan & skipStatusText) { @@ -262,7 +261,7 @@ class Delegate /** * This method is called by the server instance to modify an existing map in the list. * The server instance will ensure that the modifiedMap is a valid, unique map. - * @param[in] listIndexThe index of the map being modified. + * @param[in] listIndex The index of the map being modified. * @param[in] modifiedMapA map with the modified contents. * @return true if successful, false otherwise. * diff --git a/src/app/clusters/service-area-server/service-area-server.cpp b/src/app/clusters/service-area-server/service-area-server.cpp index 5f8b8ea70e..0e562c7875 100644 --- a/src/app/clusters/service-area-server/service-area-server.cpp +++ b/src/app/clusters/service-area-server/service-area-server.cpp @@ -1000,7 +1000,7 @@ bool Instance::SetProgressStatus(uint32_t aAreaId, OperationalStatusEnum opStatu // TotalOperationalTime SHALL be null if the Status field is not set to Completed or Skipped. if ((opStatus != OperationalStatusEnum::kCompleted) && (opStatus != OperationalStatusEnum::kSkipped)) { - progressElement.totalOperationalTime.Value().SetNull(); + progressElement.totalOperationalTime.Emplace(DataModel::NullNullable); } // add the updated element to the progress attribute From 5ad899a8e1b4c9c8140e600fbee3832e393ce52d Mon Sep 17 00:00:00 2001 From: Thomas Lea <35579828+tleacmcsa@users.noreply.github.com> Date: Fri, 9 Aug 2024 13:01:55 -0500 Subject: [PATCH 002/165] Update ACL API to support ARL use cases (#34537) * Update ACL API to support ARL use cases ARL needs to know what attribute/command/event is being accessed and with which interaction model action. This change brings this knowledge into the AccessControl classes Check method for further enhancement with ARL feature on top. * Addressed review comments * Addressed review comments * Clarified RequestType enum values and purpose * Renamed CanAccess to CanAccessEvent * Restyled by whitespace * Restyled by clang-format * Fixed some build issues - missed a spot to populate requestType and entityId - fix unused function definition for some cases * Fixed icd-management-server for ARL * fixed typo in previous fix :-( * Restyled by clang-format * Moved ARL related checks behind ARL feature flag Instead of validating requestType in AccessControl::Check, we will validate it is not unknown only if the ARL feature is enabled. * Add conditional ARL related validation Instead of removing ARL related validation from AccessControl::Check entirely, perform it only if the ARL feature is enabled. As of this commit, it is not enabled. * Restyled by clang-format --------- Co-authored-by: Restyled.io --- src/access/AccessControl.cpp | 32 +++++++++++++++-- src/access/AccessControl.h | 7 ++++ src/access/RequestPath.h | 18 ++++++++-- src/app/CommandHandlerImpl.cpp | 10 ++++-- src/app/EventManagement.cpp | 5 ++- src/app/InteractionModelEngine.cpp | 36 +++++++++++++------ .../icd-management-server.cpp | 5 ++- .../CodegenDataModelProvider_Read.cpp | 5 ++- .../CodegenDataModelProvider_Write.cpp | 5 ++- src/app/reporting/Engine.cpp | 5 ++- .../util/ember-compatibility-functions.cpp | 10 ++++-- 11 files changed, 115 insertions(+), 23 deletions(-) diff --git a/src/access/AccessControl.cpp b/src/access/AccessControl.cpp index 70921599fc..fcb5a43d97 100644 --- a/src/access/AccessControl.cpp +++ b/src/access/AccessControl.cpp @@ -171,6 +171,23 @@ char GetPrivilegeStringForLogging(Privilege privilege) return 'u'; } +char GetRequestTypeStringForLogging(RequestType requestType) +{ + switch (requestType) + { + case RequestType::kAttributeReadRequest: + return 'r'; + case RequestType::kAttributeWriteRequest: + return 'w'; + case RequestType::kCommandInvokeRequest: + return 'i'; + case RequestType::kEventReadOrSubscribeRequest: + return 'e'; + default: + return '?'; + } +} + #endif // CHIP_PROGRESS_LOGGING && CHIP_CONFIG_ACCESS_CONTROL_POLICY_LOGGING_VERBOSITY > 1 } // namespace @@ -306,6 +323,11 @@ void AccessControl::RemoveEntryListener(EntryListener & listener) } } +bool AccessControl::IsAccessRestrictionListSupported() const +{ + return false; // not yet supported +} + CHIP_ERROR AccessControl::Check(const SubjectDescriptor & subjectDescriptor, const RequestPath & requestPath, Privilege requestPrivilege) { @@ -316,14 +338,20 @@ CHIP_ERROR AccessControl::Check(const SubjectDescriptor & subjectDescriptor, con constexpr size_t kMaxCatsToLog = 6; char catLogBuf[kMaxCatsToLog * kCharsPerCatForLogging]; ChipLogProgress(DataManagement, - "AccessControl: checking f=%u a=%c s=0x" ChipLogFormatX64 " t=%s c=" ChipLogFormatMEI " e=%u p=%c", + "AccessControl: checking f=%u a=%c s=0x" ChipLogFormatX64 " t=%s c=" ChipLogFormatMEI " e=%u p=%c r=%c", subjectDescriptor.fabricIndex, GetAuthModeStringForLogging(subjectDescriptor.authMode), ChipLogValueX64(subjectDescriptor.subject), GetCatStringForLogging(catLogBuf, sizeof(catLogBuf), subjectDescriptor.cats), - ChipLogValueMEI(requestPath.cluster), requestPath.endpoint, GetPrivilegeStringForLogging(requestPrivilege)); + ChipLogValueMEI(requestPath.cluster), requestPath.endpoint, GetPrivilegeStringForLogging(requestPrivilege), + GetRequestTypeStringForLogging(requestPath.requestType)); } #endif // CHIP_PROGRESS_LOGGING && CHIP_CONFIG_ACCESS_CONTROL_POLICY_LOGGING_VERBOSITY > 1 + if (IsAccessRestrictionListSupported()) + { + VerifyOrReturnError(requestPath.requestType != RequestType::kRequestTypeUnknown, CHIP_ERROR_INVALID_ARGUMENT); + } + { CHIP_ERROR result = mDelegate->Check(subjectDescriptor, requestPath, requestPrivilege); if (result != CHIP_ERROR_NOT_IMPLEMENTED) diff --git a/src/access/AccessControl.h b/src/access/AccessControl.h index 6186c33d44..a7c3472f5d 100644 --- a/src/access/AccessControl.h +++ b/src/access/AccessControl.h @@ -627,6 +627,13 @@ class AccessControl // Removes a listener from the listener list, if in the list. void RemoveEntryListener(EntryListener & listener); + /** + * Check whether or not Access Restriction List is supported. + * + * @retval true if Access Restriction List is supported. + */ + bool IsAccessRestrictionListSupported() const; + /** * Check whether access (by a subject descriptor, to a request path, * requiring a privilege) should be allowed or denied. diff --git a/src/access/RequestPath.h b/src/access/RequestPath.h index 966f27afe8..af791d73eb 100644 --- a/src/access/RequestPath.h +++ b/src/access/RequestPath.h @@ -19,15 +19,29 @@ #pragma once #include +#include namespace chip { namespace Access { +enum class RequestType : uint8_t +{ + kRequestTypeUnknown, + kAttributeReadRequest, + kAttributeWriteRequest, + kCommandInvokeRequest, + kEventReadOrSubscribeRequest +}; + struct RequestPath { // NOTE: eventually this will likely also contain node, for proxying - ClusterId cluster = 0; - EndpointId endpoint = 0; + ClusterId cluster = 0; + EndpointId endpoint = 0; + RequestType requestType = RequestType::kRequestTypeUnknown; + + // entityId represents an attribute, command, or event ID, which is determined by the requestType. Wildcard if omitted. + std::optional entityId; }; } // namespace Access diff --git a/src/app/CommandHandlerImpl.cpp b/src/app/CommandHandlerImpl.cpp index b1843d23e8..1945e7e5e6 100644 --- a/src/app/CommandHandlerImpl.cpp +++ b/src/app/CommandHandlerImpl.cpp @@ -402,7 +402,10 @@ Status CommandHandlerImpl::ProcessCommandDataIB(CommandDataIB::Parser & aCommand { Access::SubjectDescriptor subjectDescriptor = GetSubjectDescriptor(); - Access::RequestPath requestPath{ .cluster = concretePath.mClusterId, .endpoint = concretePath.mEndpointId }; + Access::RequestPath requestPath{ .cluster = concretePath.mClusterId, + .endpoint = concretePath.mEndpointId, + .requestType = Access::RequestType::kCommandInvokeRequest, + .entityId = concretePath.mCommandId }; Access::Privilege requestPrivilege = RequiredPrivilege::ForInvokeCommand(concretePath); err = Access::GetAccessControl().Check(subjectDescriptor, requestPath, requestPrivilege); if (err != CHIP_NO_ERROR) @@ -548,7 +551,10 @@ Status CommandHandlerImpl::ProcessGroupCommandDataIB(CommandDataIB::Parser & aCo { Access::SubjectDescriptor subjectDescriptor = GetSubjectDescriptor(); - Access::RequestPath requestPath{ .cluster = concretePath.mClusterId, .endpoint = concretePath.mEndpointId }; + Access::RequestPath requestPath{ .cluster = concretePath.mClusterId, + .endpoint = concretePath.mEndpointId, + .requestType = Access::RequestType::kCommandInvokeRequest, + .entityId = concretePath.mCommandId }; Access::Privilege requestPrivilege = RequiredPrivilege::ForInvokeCommand(concretePath); err = Access::GetAccessControl().Check(subjectDescriptor, requestPath, requestPrivilege); if (err != CHIP_NO_ERROR) diff --git a/src/app/EventManagement.cpp b/src/app/EventManagement.cpp index 8e6d53c24c..4c5faab3cd 100644 --- a/src/app/EventManagement.cpp +++ b/src/app/EventManagement.cpp @@ -554,7 +554,10 @@ CHIP_ERROR EventManagement::CheckEventContext(EventLoadOutContext * eventLoadOut ReturnErrorOnFailure(ret); - Access::RequestPath requestPath{ .cluster = event.mClusterId, .endpoint = event.mEndpointId }; + Access::RequestPath requestPath{ .cluster = event.mClusterId, + .endpoint = event.mEndpointId, + .requestType = Access::RequestType::kEventReadOrSubscribeRequest, + .entityId = event.mEventId }; Access::Privilege requestPrivilege = RequiredPrivilege::ForReadEvent(path); CHIP_ERROR accessControlError = Access::GetAccessControl().Check(eventLoadOutContext->mSubjectDescriptor, requestPath, requestPrivilege); diff --git a/src/app/InteractionModelEngine.cpp b/src/app/InteractionModelEngine.cpp index 80312a5787..64d30bc6c0 100644 --- a/src/app/InteractionModelEngine.cpp +++ b/src/app/InteractionModelEngine.cpp @@ -494,7 +494,10 @@ CHIP_ERROR InteractionModelEngine::ParseAttributePaths(const Access::SubjectDesc // AttributePathExpandIterator. So we just need to check the ACL bits. for (; pathIterator.Get(readPath); pathIterator.Next()) { - Access::RequestPath requestPath{ .cluster = readPath.mClusterId, .endpoint = readPath.mEndpointId }; + // leave requestPath.entityId optional value unset to indicate wildcard + Access::RequestPath requestPath{ .cluster = readPath.mClusterId, + .endpoint = readPath.mEndpointId, + .requestType = Access::RequestType::kAttributeReadRequest }; err = Access::GetAccessControl().Check(aSubjectDescriptor, requestPath, RequiredPrivilege::ForReadAttribute(readPath)); if (err == CHIP_NO_ERROR) @@ -510,7 +513,10 @@ CHIP_ERROR InteractionModelEngine::ParseAttributePaths(const Access::SubjectDesc paramsList.mValue.mAttributeId); if (ConcreteAttributePathExists(concretePath)) { - Access::RequestPath requestPath{ .cluster = concretePath.mClusterId, .endpoint = concretePath.mEndpointId }; + Access::RequestPath requestPath{ .cluster = concretePath.mClusterId, + .endpoint = concretePath.mEndpointId, + .requestType = Access::RequestType::kAttributeReadRequest, + .entityId = paramsList.mValue.mAttributeId }; err = Access::GetAccessControl().Check(aSubjectDescriptor, requestPath, RequiredPrivilege::ForReadAttribute(concretePath)); @@ -532,17 +538,27 @@ CHIP_ERROR InteractionModelEngine::ParseAttributePaths(const Access::SubjectDesc return err; } -static bool CanAccess(const Access::SubjectDescriptor & aSubjectDescriptor, const ConcreteClusterPath & aPath, - Access::Privilege aNeededPrivilege) +#if !CHIP_CONFIG_ENABLE_EVENTLIST_ATTRIBUTE +static bool CanAccessEvent(const Access::SubjectDescriptor & aSubjectDescriptor, const ConcreteClusterPath & aPath, + Access::Privilege aNeededPrivilege) { - Access::RequestPath requestPath{ .cluster = aPath.mClusterId, .endpoint = aPath.mEndpointId }; + Access::RequestPath requestPath{ .cluster = aPath.mClusterId, + .endpoint = aPath.mEndpointId, + .requestType = Access::RequestType::kEventReadOrSubscribeRequest }; + // leave requestPath.entityId optional value unset to indicate wildcard CHIP_ERROR err = Access::GetAccessControl().Check(aSubjectDescriptor, requestPath, aNeededPrivilege); return (err == CHIP_NO_ERROR); } +#endif -static bool CanAccess(const Access::SubjectDescriptor & aSubjectDescriptor, const ConcreteEventPath & aPath) +static bool CanAccessEvent(const Access::SubjectDescriptor & aSubjectDescriptor, const ConcreteEventPath & aPath) { - return CanAccess(aSubjectDescriptor, aPath, RequiredPrivilege::ForReadEvent(aPath)); + Access::RequestPath requestPath{ .cluster = aPath.mClusterId, + .endpoint = aPath.mEndpointId, + .requestType = Access::RequestType::kEventReadOrSubscribeRequest, + .entityId = aPath.mEventId }; + CHIP_ERROR err = Access::GetAccessControl().Check(aSubjectDescriptor, requestPath, RequiredPrivilege::ForReadEvent(aPath)); + return (err == CHIP_NO_ERROR); } /** @@ -559,7 +575,7 @@ static bool HasValidEventPathForEndpointAndCluster(EndpointId aEndpoint, const E { ConcreteEventPath path(aEndpoint, aCluster->clusterId, aCluster->eventList[idx]); // If we get here, the path exists. We just have to do an ACL check for it. - bool isValid = CanAccess(aSubjectDescriptor, path); + bool isValid = CanAccessEvent(aSubjectDescriptor, path); if (isValid) { return true; @@ -571,7 +587,7 @@ static bool HasValidEventPathForEndpointAndCluster(EndpointId aEndpoint, const E // We have no way to expand wildcards. Just assume that we would need // View permissions for whatever events are involved. ConcreteClusterPath clusterPath(aEndpoint, aCluster->clusterId); - return CanAccess(aSubjectDescriptor, clusterPath, Access::Privilege::kView); + return CanAccessEvent(aSubjectDescriptor, clusterPath, Access::Privilege::kView); #endif } @@ -581,7 +597,7 @@ static bool HasValidEventPathForEndpointAndCluster(EndpointId aEndpoint, const E // Not an existing event path. return false; } - return CanAccess(aSubjectDescriptor, path); + return CanAccessEvent(aSubjectDescriptor, path); } /** diff --git a/src/app/clusters/icd-management-server/icd-management-server.cpp b/src/app/clusters/icd-management-server/icd-management-server.cpp index 8445cad117..c2625b050d 100644 --- a/src/app/clusters/icd-management-server/icd-management-server.cpp +++ b/src/app/clusters/icd-management-server/icd-management-server.cpp @@ -240,7 +240,10 @@ CHIP_ERROR IcdManagementAttributeAccess::ReadMaximumCheckInBackOff(EndpointId en */ CHIP_ERROR CheckAdmin(CommandHandler * commandObj, const ConcreteCommandPath & commandPath, bool & isClientAdmin) { - RequestPath requestPath{ .cluster = commandPath.mClusterId, .endpoint = commandPath.mEndpointId }; + RequestPath requestPath{ .cluster = commandPath.mClusterId, + .endpoint = commandPath.mEndpointId, + .requestType = RequestType::kCommandInvokeRequest, + .entityId = commandPath.mCommandId }; CHIP_ERROR err = GetAccessControl().Check(commandObj->GetSubjectDescriptor(), requestPath, Privilege::kAdminister); if (CHIP_NO_ERROR == err) { diff --git a/src/app/codegen-data-model-provider/CodegenDataModelProvider_Read.cpp b/src/app/codegen-data-model-provider/CodegenDataModelProvider_Read.cpp index 9f87e4c8f1..de17d1059b 100644 --- a/src/app/codegen-data-model-provider/CodegenDataModelProvider_Read.cpp +++ b/src/app/codegen-data-model-provider/CodegenDataModelProvider_Read.cpp @@ -273,7 +273,10 @@ DataModel::ActionReturnStatus CodegenDataModelProvider::ReadAttribute(const Data { ReturnErrorCodeIf(!request.subjectDescriptor.has_value(), CHIP_ERROR_INVALID_ARGUMENT); - Access::RequestPath requestPath{ .cluster = request.path.mClusterId, .endpoint = request.path.mEndpointId }; + Access::RequestPath requestPath{ .cluster = request.path.mClusterId, + .endpoint = request.path.mEndpointId, + .requestType = Access::RequestType::kAttributeReadRequest, + .entityId = request.path.mAttributeId }; CHIP_ERROR err = Access::GetAccessControl().Check(*request.subjectDescriptor, requestPath, RequiredPrivilege::ForReadAttribute(request.path)); if (err != CHIP_NO_ERROR) diff --git a/src/app/codegen-data-model-provider/CodegenDataModelProvider_Write.cpp b/src/app/codegen-data-model-provider/CodegenDataModelProvider_Write.cpp index 37371043aa..333c9e27e4 100644 --- a/src/app/codegen-data-model-provider/CodegenDataModelProvider_Write.cpp +++ b/src/app/codegen-data-model-provider/CodegenDataModelProvider_Write.cpp @@ -278,7 +278,10 @@ DataModel::ActionReturnStatus CodegenDataModelProvider::WriteAttribute(const Dat { ReturnErrorCodeIf(!request.subjectDescriptor.has_value(), Status::UnsupportedAccess); - Access::RequestPath requestPath{ .cluster = request.path.mClusterId, .endpoint = request.path.mEndpointId }; + Access::RequestPath requestPath{ .cluster = request.path.mClusterId, + .endpoint = request.path.mEndpointId, + .requestType = Access::RequestType::kAttributeWriteRequest, + .entityId = request.path.mAttributeId }; CHIP_ERROR err = Access::GetAccessControl().Check(*request.subjectDescriptor, requestPath, RequiredPrivilege::ForWriteAttribute(request.path)); diff --git a/src/app/reporting/Engine.cpp b/src/app/reporting/Engine.cpp index b5621e94bd..6d79e9e7b3 100644 --- a/src/app/reporting/Engine.cpp +++ b/src/app/reporting/Engine.cpp @@ -339,7 +339,10 @@ CHIP_ERROR Engine::CheckAccessDeniedEventPaths(TLV::TLVWriter & aWriter, bool & aHasEncodedData = true; } - Access::RequestPath requestPath{ .cluster = current->mValue.mClusterId, .endpoint = current->mValue.mEndpointId }; + Access::RequestPath requestPath{ .cluster = current->mValue.mClusterId, + .endpoint = current->mValue.mEndpointId, + .requestType = RequestType::kEventReadOrSubscribeRequest, + .entityId = current->mValue.mEventId }; Access::Privilege requestPrivilege = RequiredPrivilege::ForReadEvent(path); err = Access::GetAccessControl().Check(apReadHandler->GetSubjectDescriptor(), requestPath, requestPrivilege); diff --git a/src/app/util/ember-compatibility-functions.cpp b/src/app/util/ember-compatibility-functions.cpp index d556d8816c..ad0542a9ff 100644 --- a/src/app/util/ember-compatibility-functions.cpp +++ b/src/app/util/ember-compatibility-functions.cpp @@ -294,7 +294,10 @@ CHIP_ERROR ReadSingleClusterData(const SubjectDescriptor & aSubjectDescriptor, b // depending on whether the path was expanded. { - Access::RequestPath requestPath{ .cluster = aPath.mClusterId, .endpoint = aPath.mEndpointId }; + 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) @@ -686,7 +689,10 @@ CHIP_ERROR WriteSingleClusterData(const SubjectDescriptor & aSubjectDescriptor, } { - Access::RequestPath requestPath{ .cluster = aPath.mClusterId, .endpoint = aPath.mEndpointId }; + 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 })) From da3379b8d8da60754462beb44a8af5b77f1797e2 Mon Sep 17 00:00:00 2001 From: Nivi Sarkar <55898241+nivi-apple@users.noreply.github.com> Date: Fri, 9 Aug 2024 11:15:01 -0700 Subject: [PATCH 003/165] Rename PIC code TSTAT.S.CFE.Rsp -> TSTAT.S.Cfe.Rsp (#34912) --- src/python_testing/TC_TSTAT_4_2.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/python_testing/TC_TSTAT_4_2.py b/src/python_testing/TC_TSTAT_4_2.py index 2b3169af9a..5c289ced50 100644 --- a/src/python_testing/TC_TSTAT_4_2.py +++ b/src/python_testing/TC_TSTAT_4_2.py @@ -220,7 +220,7 @@ async def test_TC_TSTAT_4_2(self): self.step("3") - if self.pics_guard(self.check_pics("TSTAT.S.F08") and self.check_pics("TSTAT.S.A0050") and self.check_pics("TSTAT.S.CFE.Rsp")): + if self.pics_guard(self.check_pics("TSTAT.S.F08") and self.check_pics("TSTAT.S.A0050") and self.check_pics("TSTAT.S.Cfe.Rsp")): await self.send_atomic_request_begin_command() # Write to the presets attribute after calling AtomicRequest command @@ -405,7 +405,7 @@ async def test_TC_TSTAT_4_2(self): await self.send_atomic_request_commit_command(expected_status=Status.InvalidInState) self.step("14") - if self.pics_guard(self.check_pics("TSTAT.S.F08") and self.check_pics("TSTAT.S.A0050") and self.check_pics("TSTAT.S.CFE.Rsp")): + if self.pics_guard(self.check_pics("TSTAT.S.F08") and self.check_pics("TSTAT.S.A0050") and self.check_pics("TSTAT.S.Cfe.Rsp")): # Send the AtomicRequest begin command await self.send_atomic_request_begin_command() @@ -417,7 +417,7 @@ async def test_TC_TSTAT_4_2(self): await self.send_atomic_request_rollback_command() self.step("15") - if self.pics_guard(self.check_pics("TSTAT.S.F08") and self.check_pics("TSTAT.S.A0050") and self.check_pics("TSTAT.S.CFE.Rsp")): + if self.pics_guard(self.check_pics("TSTAT.S.F08") and self.check_pics("TSTAT.S.A0050") and self.check_pics("TSTAT.S.Cfe.Rsp")): # Send the AtomicRequest begin command from the secondary controller await self.send_atomic_request_begin_command() @@ -427,7 +427,7 @@ async def test_TC_TSTAT_4_2(self): await self.send_atomic_request_rollback_command() self.step("16") - if self.pics_guard(self.check_pics("TSTAT.S.F08") and self.check_pics("TSTAT.S.A0050") and self.check_pics("TSTAT.S.CFE.Rsp")): + if self.pics_guard(self.check_pics("TSTAT.S.F08") and self.check_pics("TSTAT.S.A0050") and self.check_pics("TSTAT.S.Cfe.Rsp")): # Send the AtomicRequest begin command from the secondary controller await self.send_atomic_request_begin_command(dev_ctrl=secondary_controller) From 7bda951895e670c1bef7fbece5ac3e9a21c8b13e Mon Sep 17 00:00:00 2001 From: Faisal Bhaiyat <87369468+fhbhaiyat@users.noreply.github.com> Date: Fri, 9 Aug 2024 19:16:33 +0100 Subject: [PATCH 004/165] evse app port for Silicon Labs, first draft (#34878) --- examples/energy-management-app/silabs/.gn | 29 ++ .../energy-management-app/silabs/BUILD.gn | 251 ++++++++++++ .../energy-management-app/silabs/README.md | 364 ++++++++++++++++++ .../silabs/build_for_wifi_args.gni | 24 ++ .../silabs/build_for_wifi_gnfile.gn | 28 ++ .../silabs/build_overrides | 1 + .../silabs/include/AppConfig.h | 28 ++ .../silabs/include/AppEvent.h | 54 +++ .../silabs/include/AppTask.h | 110 ++++++ .../silabs/include/CHIPProjectConfig.h | 102 +++++ .../silabs/openthread.gn | 29 ++ .../silabs/openthread.gni | 28 ++ .../silabs/src/AppTask.cpp | 212 ++++++++++ .../silabs/third_party/connectedhomeip | 1 + .../silabs/with_pw_rpc.gni | 30 ++ 15 files changed, 1291 insertions(+) create mode 100644 examples/energy-management-app/silabs/.gn create mode 100644 examples/energy-management-app/silabs/BUILD.gn create mode 100644 examples/energy-management-app/silabs/README.md create mode 100644 examples/energy-management-app/silabs/build_for_wifi_args.gni create mode 100644 examples/energy-management-app/silabs/build_for_wifi_gnfile.gn create mode 120000 examples/energy-management-app/silabs/build_overrides create mode 100644 examples/energy-management-app/silabs/include/AppConfig.h create mode 100644 examples/energy-management-app/silabs/include/AppEvent.h create mode 100644 examples/energy-management-app/silabs/include/AppTask.h create mode 100644 examples/energy-management-app/silabs/include/CHIPProjectConfig.h create mode 100644 examples/energy-management-app/silabs/openthread.gn create mode 100644 examples/energy-management-app/silabs/openthread.gni create mode 100644 examples/energy-management-app/silabs/src/AppTask.cpp create mode 120000 examples/energy-management-app/silabs/third_party/connectedhomeip create mode 100644 examples/energy-management-app/silabs/with_pw_rpc.gni diff --git a/examples/energy-management-app/silabs/.gn b/examples/energy-management-app/silabs/.gn new file mode 100644 index 0000000000..b05216fc9d --- /dev/null +++ b/examples/energy-management-app/silabs/.gn @@ -0,0 +1,29 @@ +# 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. + +import("//build_overrides/build.gni") + +# The location of the build configuration file. +buildconfig = "${build_root}/config/BUILDCONFIG.gn" + +# CHIP uses angle bracket includes. +check_system_includes = true + +default_args = { + target_cpu = "arm" + target_os = "freertos" + chip_openthread_ftd = true + + import("//openthread.gni") +} diff --git a/examples/energy-management-app/silabs/BUILD.gn b/examples/energy-management-app/silabs/BUILD.gn new file mode 100644 index 0000000000..b51ed59de6 --- /dev/null +++ b/examples/energy-management-app/silabs/BUILD.gn @@ -0,0 +1,251 @@ +# 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. + +import("//build_overrides/build.gni") +import("//build_overrides/chip.gni") +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("${chip_root}/examples/common/pigweed/pigweed_rpcs.gni") +import("${chip_root}/src/platform/device.gni") +import("${chip_root}/third_party/silabs/silabs_board.gni") + +if (chip_enable_pw_rpc) { + import("//build_overrides/pigweed.gni") + import("$dir_pw_build/target_types.gni") +} + +assert(current_os == "freertos") + +silabs_project_dir = "${chip_root}/examples/energy-management-app/silabs" +examples_common_plat_dir = "${chip_root}/examples/platform/silabs" + +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") + examples_plat_dir = "${chip_root}/examples/platform/silabs/efr32" +} + +import("${examples_common_plat_dir}/args.gni") + +declare_args() { + # Dump memory usage at link time. + chip_print_memory_usage = false +} + +if (slc_generate) { + # Generate Project Specific config (Board, hardware used etc..) + print(exec_script("${chip_root}/third_party/silabs/slc_gen/run_slc.py", + [ + rebase_path(chip_root), + "${silabs_board}", + "${disable_lcd}", + "${use_wstk_buttons}", + "${use_wstk_leds}", + "${use_external_flash}", + "${silabs_mcu}", + rebase_path(slc_gen_path), + ], + "list lines")) +} + +if (wifi_soc) { + siwx917_sdk("sdk") { + sources = [ + "${examples_common_plat_dir}/FreeRTOSConfig.h", + "${silabs_project_dir}/include/CHIPProjectConfig.h", + ] + + include_dirs = [ + "${chip_root}/src/platform/silabs/SiWx917", + "${silabs_project_dir}/include", + "${examples_plat_dir}", + "${chip_root}/src/lib", + "${examples_common_plat_dir}", + ] + + defines = [] + if (chip_enable_pw_rpc) { + defines += [ + "HAL_VCOM_ENABLE=1", + "PW_RPC_ENABLED", + ] + } + } +} else { + efr32_sdk("sdk") { + sources = [ + "${examples_common_plat_dir}/FreeRTOSConfig.h", + "${silabs_project_dir}/include/CHIPProjectConfig.h", + ] + + include_dirs = [ + "${chip_root}/src/platform/silabs/efr32", + "${silabs_project_dir}/include", + "${examples_plat_dir}", + "${chip_root}/src/lib", + "${examples_common_plat_dir}", + "../energy-management-common/include", + ] + + if (use_wf200) { + # TODO efr32_sdk should not need a header from this location + include_dirs += [ "${examples_plat_dir}/wf200" ] + } + + if (chip_enable_ble_rs911x) { + # TODO efr32_sdk should not need a header from this location + include_dirs += [ + "${examples_plat_dir}/rs911x", + "${examples_plat_dir}/rs911x/hal", + ] + } + + defines = [] + if (chip_enable_pw_rpc) { + defines += [ + "HAL_VCOM_ENABLE=1", + "PW_RPC_ENABLED", + ] + } + } +} +silabs_executable("energy-management-app") { + output_name = "matter-silabs-energy-management-example.out" + include_dirs = [ "include" ] + defines = [] + + if (silabs_board == "BRD2704A") { + defines += [ "SL_STATUS_LED=0" ] + } + + sources = [ + "${chip_root}/examples/energy-management-app/energy-management-common/src/ChargingTargetsMemMgr.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/src/DEMTestEventTriggers.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/src/DeviceEnergyManagementDelegateImpl.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/src/DeviceEnergyManagementManager.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/src/EVSEManufacturerImpl.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/src/ElectricalPowerMeasurementDelegate.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/src/EnergyEvseDelegateImpl.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/src/EnergyEvseEventTriggers.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/src/EnergyEvseMain.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/src/EnergyEvseManager.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/src/EnergyEvseTargetsStore.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/src/EnergyReportingEventTriggers.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/src/EnergyTimeUtils.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/src/FakeReadings.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/src/PowerTopologyDelegate.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/src/device-energy-management-mode.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/src/energy-evse-mode.cpp", + "${examples_common_plat_dir}/main.cpp", + "src/AppTask.cpp", + ] + + deps = [ + ":sdk", + app_data_model, + ] + + if (wifi_soc) { + deps += [ "${examples_plat_dir}:siwx917-common" ] + } else { + deps += [ "${examples_plat_dir}:efr32-common" ] + } + + if (chip_enable_pw_rpc) { + defines += [ + "PW_RPC_ENABLED", + "PW_RPC_ATTRIBUTE_SERVICE=1", + "PW_RPC_BUTTON_SERVICE=1", + "PW_RPC_DESCRIPTOR_SERVICE=1", + "PW_RPC_DEVICE_SERVICE=1", + "PW_RPC_LIGHTING_SERVICE=1", + "PW_RPC_OTCLI_SERVICE=1", + "PW_RPC_THREAD_SERVICE=1", + "PW_RPC_TRACING_SERVICE=1", + ] + + sources += [ + "${chip_root}/examples/common/pigweed/RpcService.cpp", + "${chip_root}/examples/common/pigweed/efr32/PigweedLoggerMutex.cpp", + "${examples_common_plat_dir}/PigweedLogger.cpp", + "${examples_common_plat_dir}/Rpc.cpp", + ] + + deps += [ + "$dir_pw_hdlc:rpc_channel_output", + "$dir_pw_stream:sys_io_stream", + "$dir_pw_trace", + "$dir_pw_trace_tokenized", + "$dir_pw_trace_tokenized:trace_rpc_service", + "${chip_root}/config/efr32/lib/pw_rpc:pw_rpc", + "${chip_root}/examples/common/pigweed:attributes_service.nanopb_rpc", + "${chip_root}/examples/common/pigweed:button_service.nanopb_rpc", + "${chip_root}/examples/common/pigweed:descriptor_service.nanopb_rpc", + "${chip_root}/examples/common/pigweed:device_service.nanopb_rpc", + "${chip_root}/examples/common/pigweed:lighting_service.nanopb_rpc", + "${chip_root}/examples/common/pigweed:ot_cli_service.nanopb_rpc", + "${chip_root}/examples/common/pigweed:thread_service.nanopb_rpc", + ] + + if (wifi_soc) { + deps += [ "${examples_plat_dir}/pw_sys_io:pw_sys_io_siwx917" ] + } else { + deps += [ "${examples_common_plat_dir}/pw_sys_io:pw_sys_io_silabs" ] + } + + deps += pw_build_LINK_DEPS + + include_dirs += [ + "${chip_root}/examples/common", + "${chip_root}/examples/common/pigweed/efr32", + ] + } + + ldscript = "${examples_common_plat_dir}/ldscripts/${silabs_family}.ld" + + inputs = [ ldscript ] + + ldflags = [ "-T" + rebase_path(ldscript, root_build_dir) ] + + if (chip_print_memory_usage) { + ldflags += [ + "-Wl,--print-memory-usage", + "-fstack-usage", + ] + } + + # WiFi Settings + if (chip_enable_wifi) { + ldflags += [ + "-Wl,--defsym", + "-Wl,SILABS_WIFI=1", + ] + } + + output_dir = root_out_dir +} + +group("silabs") { + deps = [ ":energy-management-app" ] +} + +group("default") { + deps = [ ":silabs" ] +} diff --git a/examples/energy-management-app/silabs/README.md b/examples/energy-management-app/silabs/README.md new file mode 100644 index 0000000000..06fc6f5c46 --- /dev/null +++ b/examples/energy-management-app/silabs/README.md @@ -0,0 +1,364 @@ +# Matter EFR32 Energy Management Example + +An example showing the use of CHIP on the Silicon Labs EFR32 MG12 and MG24. + +
+ +- [Matter EFR32 Energy Management Example](#matter-efr32-energy-management-example) + - [Introduction](#introduction) + - [Building](#building) + - [Flashing the Application](#flashing-the-application) + - [Viewing Logging Output](#viewing-logging-output) + - [Running the Complete Example](#running-the-complete-example) + - [Notes](#notes) + - [Running RPC console](#running-rpc-console) + - [Device Tracing](#device-tracing) + - [Memory settings](#memory-settings) + - [OTA Software Update](#ota-software-update) + - [Group Communication (Multicast)](#group-communication-multicast) + - [Building options](#building-options) + - [Disabling logging](#disabling-logging) + - [Debug build / release build](#debug-build--release-build) + - [Disabling LCD](#disabling-lcd) + - [KVS maximum entry count](#kvs-maximum-entry-count) + +
+ +> **NOTE:** Silicon Laboratories now maintains a public matter GitHub repo with +> frequent releases thoroughly tested and validated. Developers looking to +> develop matter products with silabs hardware are encouraged to use our latest +> release with added tools and documentation. +> [Silabs Matter Github](https://github.com/SiliconLabs/matter/releases) + +## Introduction + +The EFR32 Energy Management example provides a baseline demonstration of a EVSE +device, built using Matter and the Silicon Labs gecko SDK. It can be controlled +by a Chip controller over an Openthread or Wifi network.. + +The EFR32 device can be commissioned over Bluetooth Low Energy where the device +and the Chip controller will exchange security information with the Rendez-vous +procedure. If using Thread, Thread Network credentials are then provided to the +EFR32 device which will then join the Thread network. + +If the LCD is enabled, the LCD on the Silabs WSTK shows a QR Code containing the +needed commissioning information for the BLE connection and starting the +Rendez-vous procedure. + +The EVSE example is intended to serve both as a means to explore the workings of +Matter as well as a template for creating real products based on the Silicon +Labs platform. + +## Building + +- Download the + [Simplicity Commander](https://www.silabs.com/mcu/programming-options) + command line tool, and ensure that `commander` is your shell search path. + (For Mac OS X, `commander` is located inside + `Commander.app/Contents/MacOS/`.) + +- Download and install a suitable ARM gcc tool chain: + [GNU Arm Embedded Toolchain 9-2019-q4-major](https://developer.arm.com/tools-and-software/open-source-software/developer-tools/gnu-toolchain/gnu-rm/downloads) + +- Install some additional tools (likely already present for CHIP developers): + + - Linux: `sudo apt-get install git ninja-build` + + - Mac OS X: `brew install ninja` + +- Supported hardware: + + - > For the latest supported hardware please refer to the + > [Hardware Requirements](https://github.com/SiliconLabs/matter/blob/latest/docs/silabs/general/HARDWARE_REQUIREMENTS.md) + > in the Silicon Labs Matter Github Repo + + MG24 boards : + + - BRD2601B / SLWSTK6000B / Wireless Starter Kit / 2.4GHz@10dBm + - BRD2703A / SLWSTK6000B / Wireless Starter Kit / 2.4GHz@10dBm + - BRD4186A / SLWSTK6006A / Wireless Starter Kit / 2.4GHz@10dBm + - BRD4186C / SLWSTK6006A / Wireless Starter Kit / 2.4GHz@10dBm + - BRD4187A / SLWSTK6006A / Wireless Starter Kit / 2.4GHz@20dBm + - BRD4187C / SLWSTK6006A / Wireless Starter Kit / 2.4GHz@20dBm + - BRD2703A / MG24 Explorer Kit + - BRD2704A / SparkFun Thing Plus MGM240P board + +* Build the example application: + + cd ~/connectedhomeip + ./scripts/examples/gn_silabs_example.sh ./examples/energy-management-app/silabs/ ./out/energy-management-app BRD4187C + +- To delete generated executable, libraries and object files use: + + $ cd ~/connectedhomeip + $ rm -rf ./out/ + + OR use GN/Ninja directly + + $ cd ~/connectedhomeip/examples/energy-management-app/silabs + $ git submodule update --init + $ source third_party/connectedhomeip/scripts/activate.sh + $ export SILABS_BOARD=BRD4187C + $ gn gen out/debug + $ ninja -C out/debug + +- To delete generated executable, libraries and object files use: + + $ cd ~/connectedhomeip/examples/energy-management-app/silabs + $ rm -rf out/ + +* Build the example as Intermittently Connected Device (ICD) + + $ ./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")' + + or use GN/Ninja Directly + + $ cd ~/connectedhomeip/examples/energy-management-app/silabs + $ git submodule update --init + $ source third_party/connectedhomeip/scripts/activate.sh + $ export SILABS_BOARD=BRD4187C + $ gn gen out/debug --args='import("//with_pw_rpc.gni")' + $ ninja -C out/debug + + [Running Pigweed RPC console](#running-rpc-console) + +For more build options, help is provided when running the build script without +arguments + + ./scripts/examples/gn_silabs_example.sh + +## Flashing the Application + +- On the command line: + + $ cd ~/connectedhomeip/examples/energy-management-app/silabs + $ python3 out/debug/matter-silabs-energy-management-example.flash.py + +- Or with the Ozone debugger, just load the .out file. + +All EFR32 boards require a bootloader, see Silicon Labs documentation for more +info. Pre-built bootloader binaries are available in the Assets section of the +Releases page on +[Silabs Matter Github](https://github.com/SiliconLabs/matter/releases) . + +## Viewing Logging Output + +The example application is built to use the SEGGER Real Time Transfer (RTT) +facility for log output. RTT is a feature built-in to the J-Link Interface MCU +on the WSTK development board. It allows bi-directional communication with an +embedded application without the need for a dedicated UART. + +Using the RTT facility requires downloading and installing the _SEGGER J-Link +Software and Documentation Pack_ +([web site](https://www.segger.com/downloads/jlink#J-LinkSoftwareAndDocumentationPack)). + +Alternatively, SEGGER Ozone J-Link debugger can be used to view RTT logs too +after flashing the .out file. + +- Download the J-Link installer by navigating to the appropriate URL and + agreeing to the license agreement. + +- [JLink_Linux_x86_64.deb](https://www.segger.com/downloads/jlink/JLink_Linux_x86_64.deb) +- [JLink_MacOSX.pkg](https://www.segger.com/downloads/jlink/JLink_MacOSX.pkg) + +* Install the J-Link software + + $ cd ~/Downloads + $ sudo dpkg -i JLink_Linux_V*_x86_64.deb + +* In Linux, grant the logged in user the ability to talk to the development + hardware via the linux tty device (/dev/ttyACMx) by adding them to the + dialout group. + + $ sudo usermod -a -G dialout ${USER} + +Once the above is complete, log output can be viewed using the JLinkExe tool in +combination with JLinkRTTClient as follows: + +- Run the JLinkExe tool with arguments to autoconnect to the WSTK board: + + For MG12 use: + + $ JLinkExe -device EFR32MG12PXXXF1024 -if JTAG -speed 4000 -autoconnect 1 + + For MG21 use: + + $ JLinkExe -device EFR32MG21AXXXF1024 -if SWD -speed 4000 -autoconnect 1 + +- In a second terminal, run the JLinkRTTClient to view logs: + + $ JLinkRTTClient + +## Running the Complete Example + +- It is assumed here that you already have an OpenThread border router + configured and running. If not see the following guide + [Openthread_border_router](https://github.com/project-chip/connectedhomeip/blob/master/docs/guides/openthread_border_router_pi.md) + for more information on how to setup a border router on a raspberryPi. + + Take note that the RCP code is available directly through + [Simplicity Studio 5](https://www.silabs.com/products/development-tools/software/simplicity-studio/simplicity-studio-5) + under File->New->Project Wizard->Examples->Thread : ot-rcp + +- User interface : **LCD** The LCD on Silabs WSTK shows a QR Code. This QR + Code is be scanned by the CHIP Tool app For the Rendez-vous procedure over + BLE + + * On devices that do not have or support the LCD Display like the BRD4166A Thunderboard Sense 2, + a URL can be found in the RTT logs. + + [SVR] Copy/paste the below URL in a browser to see the QR Code: + [SVR] https://project-chip.github.io/connectedhomeip/qrcode.html?data=CH%3AI34NM%20-00%200C9SS0 + + **LED 0** shows the overall state of the device and its connectivity. The + following states are possible: + + - _Short Flash On (50 ms on/950 ms off)_ ; The device is in the + unprovisioned (unpaired) state and is waiting for a commissioning + application to connect. + + - _Rapid Even Flashing_ ; (100 ms on/100 ms off)_ — The device is in the + unprovisioned state and a commissioning application is connected through + Bluetooth LE. + + - _Short Flash Off_ ; (950ms on/50ms off)_ — The device is fully + provisioned, but does not yet have full Thread network or service + connectivity. + + - _Solid On_ ; The device is fully provisioned and has full Thread + network and service connectivity. + + **Push Button 0** + + - _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. + + - _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 + procedure. **LEDs** blink in unison when the factory reset procedure is + initiated. + +* You can provision and control the Chip device using the python controller, + Chip tool standalone, Android or iOS app + +* You can provision and control the Chip device using the python controller, + Chip tool standalone, Android or iOS app + + [CHIPTool](https://github.com/project-chip/connectedhomeip/blob/master/examples/chip-tool/README.md) + + Here is an example with the chip-tool: + + $ chip-tool pairing ble-thread 1 hex: 20202021 3840 + +### Notes + +- Depending on your network settings your router might not provide native ipv6 + addresses to your devices (Border router / PC). If this is the case, you + need to add a static ipv6 addresses on both device and then an ipv6 route to + the border router on your PC + + - On Border Router: `sudo ip addr add dev 2002::2/64` + + - On PC(Linux): `sudo ip addr add dev 2002::1/64` + + - Add Ipv6 route on PC(Linux) + `sudo ip route add /64 via 2002::2` + +## Running RPC console + +- As part of building the example with RPCs enabled the chip_rpc python + interactive console is installed into your venv. The python wheel files are + also created in the output folder: out/debug/chip_rpc_console_wheels. To + install the wheel files without rebuilding: + `pip3 install out/debug/chip_rpc_console_wheels/*.whl` + +- To use the chip-rpc console after it has been installed run: + `chip-console --device /dev/tty. -b 115200 -o //pw_log.out` + +- Then you can simulate a button press or release using the following command + where : idx = 0 or 1 for Button PB0 or PB1 action = 0 for PRESSED, 1 for + RELEASE Test toggling the LED with + `rpcs.chip.rpc.Button.Event(idx=1, pushed=True)` + +## Device Tracing + +Device tracing is available to analyze the device performance. To turn on +tracing, build with RPC enabled. See Build the example with pigweed RPC. + +Obtain tracing json file. + + $ ./{PIGWEED_REPO}/pw_trace_tokenized/py/pw_trace_tokenized/get_trace.py -d {PORT} -o {OUTPUT_FILE} \ + -t {ELF_FILE} {PIGWEED_REPO}/pw_trace_tokenized/pw_trace_protos/trace_rpc.proto + +## Memory settings + +While most of the RAM usage in CHIP is static, allowing easier debugging and +optimization with symbols analysis, we still need some HEAP for the crypto and +OpenThread. Size of the HEAP can be modified by changing the value of the +`configTOTAL_HEAP_SIZE` define inside of the FreeRTOSConfig.h file of this +example. Please take note that a HEAP size smaller than 13k can and will cause a +Mbedtls failure during the BLE rendez-vous or CASE session + +To track memory usage you can set `enable_heap_monitoring = true` either in the +BUILD.gn file or pass it as a build argument to gn. This will print on the RTT +console the RAM usage of each individual task and the number of Memory +allocation and Free. While this is not extensive monitoring you're welcome to +modify `examples/platform/silabs/MemMonitoring.cpp` to add your own memory +tracking code inside the `trackAlloc` and `trackFree` function + +## OTA Software Update + +For the description of Software Update process with EFR32 example applications +see +[EFR32 OTA Software Update](../../../docs/guides/silabs_efr32_software_update.md) + +## Group Communication (Multicast) + +With this Energy Management example you can also use group communication to send +Energy Management commands to multiples devices at once. Please refer to the +[chip-tool documentation](../../chip-tool/README.md) _Configuring the server +side for Group Commands_ and _Using the Client to Send Group (Multicast) Matter +Commands_ + +## Building options + +All of Silabs's examples within the Matter repo have all the features enabled by +default, as to provide the best end user experience. However some of those +features can easily be toggled on or off. Here is a short list of options to be +passed to the build scripts. + +### Disabling logging + +`chip_progress_logging, chip_detail_logging, chip_automation_logging` + + $ ./scripts/examples/gn_silabs_example.sh ./examples/energy-management-app/silabs ./out/energy-management-app BRD4164A "chip_detail_logging=false chip_automation_logging=false chip_progress_logging=false" + +### Debug build / release build + +`is_debug` + + $ ./scripts/examples/gn_silabs_example.sh ./examples/energy-management-app/silabs ./out/energy-management-app BRD4164A "is_debug=false" + +### Disabling LCD + +`show_qr_code` + + $ ./scripts/examples/gn_silabs_example.sh ./examples/energy-management-app/silabs ./out/energy-management-app BRD4164A "show_qr_code=false" + +### KVS maximum entry count + +`kvs_max_entries` + + Set the maximum Kvs entries that can be stored in NVM (Default 75) + Thresholds: 30 <= kvs_max_entries <= 255 + + $ ./scripts/examples/gn_silabs_example.sh ./examples/energy-management-app/silabs ./out/energy-management-app BRD4164A kvs_max_entries=50 diff --git a/examples/energy-management-app/silabs/build_for_wifi_args.gni b/examples/energy-management-app/silabs/build_for_wifi_args.gni new file mode 100644 index 0000000000..bfded904a3 --- /dev/null +++ b/examples/energy-management-app/silabs/build_for_wifi_args.gni @@ -0,0 +1,24 @@ +# 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. +import("//build_overrides/chip.gni") +import("${chip_root}/config/standalone/args.gni") + +silabs_sdk_target = get_label_info(":sdk", "label_no_toolchain") +chip_enable_openthread = false +import("${chip_root}/src/platform/silabs/wifi_args.gni") + +chip_enable_ota_requestor = false +disable_lcd = true +app_data_model = + "${chip_root}/examples/energy-management-app/energy-management-common" diff --git a/examples/energy-management-app/silabs/build_for_wifi_gnfile.gn b/examples/energy-management-app/silabs/build_for_wifi_gnfile.gn new file mode 100644 index 0000000000..d391814190 --- /dev/null +++ b/examples/energy-management-app/silabs/build_for_wifi_gnfile.gn @@ -0,0 +1,28 @@ +# 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. + +import("//build_overrides/build.gni") + +# The location of the build configuration file. +buildconfig = "${build_root}/config/BUILDCONFIG.gn" + +# CHIP uses angle bracket includes. +check_system_includes = true + +default_args = { + target_cpu = "arm" + target_os = "freertos" + chip_enable_wifi = true + import("//build_for_wifi_args.gni") +} diff --git a/examples/energy-management-app/silabs/build_overrides b/examples/energy-management-app/silabs/build_overrides new file mode 120000 index 0000000000..e578e73312 --- /dev/null +++ b/examples/energy-management-app/silabs/build_overrides @@ -0,0 +1 @@ +../../build_overrides \ No newline at end of file diff --git a/examples/energy-management-app/silabs/include/AppConfig.h b/examples/energy-management-app/silabs/include/AppConfig.h new file mode 100644 index 0000000000..bbd4d20112 --- /dev/null +++ b/examples/energy-management-app/silabs/include/AppConfig.h @@ -0,0 +1,28 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2019 Google LLC. + * 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 "silabs_utils.h" + +// ---- EVSE Example App Config ---- + +#define APP_TASK_NAME "EVSE" + +#define BLE_DEV_NAME "SiLabs-EVSE" diff --git a/examples/energy-management-app/silabs/include/AppEvent.h b/examples/energy-management-app/silabs/include/AppEvent.h new file mode 100644 index 0000000000..7f28962b50 --- /dev/null +++ b/examples/energy-management-app/silabs/include/AppEvent.h @@ -0,0 +1,54 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2018 Nest Labs, Inc. + * 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 + +struct AppEvent; +typedef void (*EventHandler)(AppEvent *); + +struct AppEvent +{ + enum AppEventTypes + { + kEventType_Button = 0, + kEventType_Timer, + kEventType_Install, + }; + + uint16_t Type; + + union + { + struct + { + uint8_t Action; + } ButtonEvent; + struct + { + void * Context; + } TimerEvent; + struct + { + uint8_t Action; + int32_t Actor; + } EvseEvent; + }; + + EventHandler Handler; +}; diff --git a/examples/energy-management-app/silabs/include/AppTask.h b/examples/energy-management-app/silabs/include/AppTask.h new file mode 100644 index 0000000000..9911461094 --- /dev/null +++ b/examples/energy-management-app/silabs/include/AppTask.h @@ -0,0 +1,110 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2019 Google LLC. + * 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 + +/********************************************************** + * Includes + *********************************************************/ + +#include +#include + +#include "AppEvent.h" +#include "BaseApplication.h" +#include "EnergyEvseManager.h" +#include "FreeRTOS.h" +#include "timers.h" // provides FreeRTOS timer support +#include +#include +#include + +/********************************************************** + * Defines + *********************************************************/ + +// Application-defined error codes in the CHIP_ERROR space. +#define APP_ERROR_EVENT_QUEUE_FAILED CHIP_APPLICATION_ERROR(0x01) +#define APP_ERROR_CREATE_TASK_FAILED CHIP_APPLICATION_ERROR(0x02) +#define APP_ERROR_UNHANDLED_EVENT CHIP_APPLICATION_ERROR(0x03) +#define APP_ERROR_CREATE_TIMER_FAILED CHIP_APPLICATION_ERROR(0x04) +#define APP_ERROR_START_TIMER_FAILED CHIP_APPLICATION_ERROR(0x05) +#define APP_ERROR_STOP_TIMER_FAILED CHIP_APPLICATION_ERROR(0x06) + +/********************************************************** + * AppTask Declaration + *********************************************************/ + +class AppTask : public BaseApplication +{ + +public: + AppTask() = default; + + static AppTask & GetAppTask() { return sAppTask; } + + /** + * @brief AppTask task main loop function + * + * @param pvParameter FreeRTOS task parameter + */ + static void AppTaskMain(void * pvParameter); + + CHIP_ERROR StartAppTask(); + + /** + * @brief Event handler when a button is pressed + * Function posts an event for button processing + * + * @param buttonHandle APP_FUNCTION_BUTTON + * @param btnAction button action - SL_SIMPLE_BUTTON_PRESSED, + * SL_SIMPLE_BUTTON_RELEASED or SL_SIMPLE_BUTTON_DISABLED + */ + static void ButtonEventHandler(uint8_t button, uint8_t btnAction); + +private: + static AppTask sAppTask; + static void EvseActionEventHandler(AppEvent * aEvent); + + static void UpdateClusterState(intptr_t context); + + /** + * @brief AppTask initialisation function + * + * @return CHIP_ERROR + */ + CHIP_ERROR Init(); + + /** + * @brief PB0 Button event processing function + * Press and hold will trigger a factory reset timer start + * Press and release will restart BLEAdvertising if not commisionned + * + * @param aEvent button event being processed + */ + static void ButtonHandler(AppEvent * aEvent); + + /** + * @brief PB1 Button event processing function + * Function triggers a switch action sent to the CHIP task + * + * @param aEvent button event being processed + */ + static void SwitchActionEventHandler(AppEvent * aEvent); +}; diff --git a/examples/energy-management-app/silabs/include/CHIPProjectConfig.h b/examples/energy-management-app/silabs/include/CHIPProjectConfig.h new file mode 100644 index 0000000000..62943f4eef --- /dev/null +++ b/examples/energy-management-app/silabs/include/CHIPProjectConfig.h @@ -0,0 +1,102 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2019 Google LLC. + * 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 + * Example project configuration file for CHIP. + * + * This is a place to put application or project-specific overrides + * to the default configuration values for general CHIP features. + * + */ + +#pragma once + +// Use a default pairing code if one hasn't been provisioned in flash. +#ifndef CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE +#define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE 20202021 +#endif + +#ifndef CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR +#define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR 0xF00 +#endif + +// For convenience, Chip Security Test Mode can be enabled and the +// requirement for authentication in various protocols can be disabled. +// +// WARNING: These options make it possible to circumvent basic Chip security functionality, +// including message encryption. Because of this they MUST NEVER BE ENABLED IN PRODUCTION BUILDS. +// +#define CHIP_CONFIG_SECURITY_TEST_MODE 0 + +/** + * CHIP_DEVICE_CONFIG_DEVICE_VENDOR_ID + * + * 0xFFF1: Test vendor + */ +#define CHIP_DEVICE_CONFIG_DEVICE_VENDOR_ID 0xFFF1 + +/** + * CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_ID + * + * 0x8005: example EVSE app + */ +#define CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_ID 0x8005 + +/** + * CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE + * + * Enable support for Chip-over-BLE (CHIPoBLE). + */ +#define CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE 1 + +/** + * CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER + * + * Enables the use of a hard-coded default serial number if none + * is found in Chip NV storage. + */ +#define CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER "TEST_SN" + +/** + * CHIP_DEVICE_CONFIG_EVENT_LOGGING_UTC_TIMESTAMPS + * + * Enable recording UTC timestamps. + */ +#define CHIP_DEVICE_CONFIG_EVENT_LOGGING_UTC_TIMESTAMPS 1 + +/** + * CHIP_DEVICE_CONFIG_EVENT_LOGGING_DEBUG_BUFFER_SIZE + * + * A size, in bytes, of the individual debug event logging buffer. + */ +#define CHIP_DEVICE_CONFIG_EVENT_LOGGING_DEBUG_BUFFER_SIZE (512) + +/** + * @def CHIP_CONFIG_MRP_LOCAL_ACTIVE_RETRY_INTERVAL + * + * @brief + * Active retransmit interval, or time to wait before retransmission after + * subsequent failures in milliseconds. + * + * This is the default value, that might be adjusted by end device depending on its + * needs (e.g. sleeping period) using Service Discovery TXT record CRA key. + * + */ +#define CHIP_CONFIG_MRP_LOCAL_ACTIVE_RETRY_INTERVAL (2000_ms32) diff --git a/examples/energy-management-app/silabs/openthread.gn b/examples/energy-management-app/silabs/openthread.gn new file mode 100644 index 0000000000..b05216fc9d --- /dev/null +++ b/examples/energy-management-app/silabs/openthread.gn @@ -0,0 +1,29 @@ +# 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. + +import("//build_overrides/build.gni") + +# The location of the build configuration file. +buildconfig = "${build_root}/config/BUILDCONFIG.gn" + +# CHIP uses angle bracket includes. +check_system_includes = true + +default_args = { + target_cpu = "arm" + target_os = "freertos" + chip_openthread_ftd = true + + import("//openthread.gni") +} diff --git a/examples/energy-management-app/silabs/openthread.gni b/examples/energy-management-app/silabs/openthread.gni new file mode 100644 index 0000000000..2813a5a1fb --- /dev/null +++ b/examples/energy-management-app/silabs/openthread.gni @@ -0,0 +1,28 @@ +# 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. + +import("//build_overrides/chip.gni") +import("${chip_root}/config/standalone/args.gni") +import("${chip_root}/src/platform/silabs/efr32/args.gni") + +silabs_sdk_target = get_label_info(":sdk", "label_no_toolchain") + +app_data_model = + "${chip_root}/examples/energy-management-app/energy-management-common" +chip_enable_ota_requestor = false +chip_enable_openthread = true +disable_lcd = true + +openthread_external_platform = + "${chip_root}/third_party/openthread/platforms/efr32:libopenthread-efr32" diff --git a/examples/energy-management-app/silabs/src/AppTask.cpp b/examples/energy-management-app/silabs/src/AppTask.cpp new file mode 100644 index 0000000000..4ed73efb28 --- /dev/null +++ b/examples/energy-management-app/silabs/src/AppTask.cpp @@ -0,0 +1,212 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2019 Google LLC. + * 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 "AppTask.h" +#include "AppConfig.h" +#include "AppEvent.h" +#include "LEDWidget.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include + +#include + +#include + +#if (defined(SL_CATALOG_SIMPLE_LED_LED1_PRESENT) || defined(SIWX_917)) +#define EVSE_LED 1 +#else +#define EVSE_LED 0 +#endif + +#define APP_FUNCTION_BUTTON 0 +#define APP_EVSE_SWITCH 1 + +namespace { +LEDWidget sEvseLED; +} + +using namespace chip; +using namespace chip::app; +using namespace chip::app::Clusters; +using namespace chip::app::Clusters::DeviceEnergyManagement; +using namespace chip::app::Clusters::DeviceEnergyManagement::Attributes; +using namespace ::chip::DeviceLayer; +using namespace ::chip::DeviceLayer::Silabs; +using namespace ::chip::DeviceLayer::Internal; +using namespace chip::TLV; + +namespace chip { +namespace app { +namespace Clusters { +namespace DeviceEnergyManagement { + +// Keep track of the parsed featureMap option +static chip::BitMask sFeatureMap(Feature::kPowerAdjustment, Feature::kPowerForecastReporting, + Feature::kStateForecastReporting, Feature::kStartTimeAdjustment, Feature::kPausable, + Feature::kForecastAdjustment, Feature::kConstraintBasedAdjustment); + +chip::BitMask GetFeatureMapFromCmdLine() +{ + return sFeatureMap; +} + +} // namespace DeviceEnergyManagement +} // namespace Clusters +} // namespace app +} // namespace chip + +AppTask AppTask::sAppTask; + +void ApplicationInit() +{ + chip::DeviceLayer::PlatformMgr().LockChipStack(); + EvseApplicationInit(); + sEvseLED.Init(EVSE_LED); + chip::DeviceLayer::PlatformMgr().UnlockChipStack(); +} +void ApplicationShutdown() +{ + chip::DeviceLayer::PlatformMgr().LockChipStack(); + EvseApplicationShutdown(); + chip::DeviceLayer::PlatformMgr().UnlockChipStack(); +} + +CHIP_ERROR AppTask::Init() +{ + CHIP_ERROR err = CHIP_NO_ERROR; + chip::DeviceLayer::Silabs::GetPlatform().SetButtonsCb(AppTask::ButtonEventHandler); + +#ifdef DISPLAY_ENABLED + GetLCD().Init((uint8_t *) "energy-management-App"); +#endif + + err = BaseApplication::Init(); + if (err != CHIP_NO_ERROR) + { + SILABS_LOG("BaseApplication::Init() failed"); + appError(err); + } + + ApplicationInit(); + +// Update the LCD with the Stored value. Show QR Code if not provisioned +#ifdef DISPLAY_ENABLED + GetLCD().WriteDemoUI(LightMgr().IsLightOn()); +#ifdef QR_CODE_ENABLED +#ifdef SL_WIFI + if (!chip::DeviceLayer::ConnectivityMgr().IsWiFiStationProvisioned()) +#else + if (!chip::DeviceLayer::ConnectivityMgr().IsThreadProvisioned()) +#endif /* !SL_WIFI */ + { + GetLCD().ShowQRCode(true); + } +#endif // QR_CODE_ENABLED +#endif + + return err; +} + +CHIP_ERROR AppTask::StartAppTask() +{ + return BaseApplication::StartAppTask(AppTaskMain); +} + +void AppTask::AppTaskMain(void * pvParameter) +{ + AppEvent event; + osMessageQueueId_t sAppEventQueue = *(static_cast(pvParameter)); + + CHIP_ERROR err = sAppTask.Init(); + if (err != CHIP_NO_ERROR) + { + SILABS_LOG("AppTask.Init() failed"); + appError(err); + } + + SILABS_LOG("App Task started"); + + while (true) + { + osStatus_t eventReceived = osMessageQueueGet(sAppEventQueue, &event, NULL, osWaitForever); + while (eventReceived == osOK) + { + sAppTask.DispatchEvent(&event); + eventReceived = osMessageQueueGet(sAppEventQueue, &event, NULL, 0); + } + } +} + +void AppTask::EvseActionEventHandler(AppEvent * aEvent) +{ + bool initiated = false; + int32_t actor; + CHIP_ERROR err = CHIP_NO_ERROR; + + if (aEvent->Type == AppEvent::kEventType_Button) + { + actor = AppEvent::kEventType_Button; + SILABS_LOG("button event %d ", actor); + } + else + { + err = APP_ERROR_UNHANDLED_EVENT; + } + + if (err == CHIP_NO_ERROR) + { + if (!initiated) + { + SILABS_LOG("Action is already in progress or active."); + } + } +} + +void AppTask::ButtonEventHandler(uint8_t button, uint8_t btnAction) +{ + AppEvent button_event = {}; + button_event.Type = AppEvent::kEventType_Button; + button_event.ButtonEvent.Action = btnAction; + + if (button == APP_EVSE_SWITCH && btnAction == static_cast(SilabsPlatform::ButtonAction::ButtonPressed)) + { + button_event.Handler = EvseActionEventHandler; + AppTask::GetAppTask().PostEvent(&button_event); + } + else if (button == APP_FUNCTION_BUTTON) + { + button_event.Handler = BaseApplication::ButtonHandler; + AppTask::GetAppTask().PostEvent(&button_event); + } +} diff --git a/examples/energy-management-app/silabs/third_party/connectedhomeip b/examples/energy-management-app/silabs/third_party/connectedhomeip new file mode 120000 index 0000000000..c866b86874 --- /dev/null +++ b/examples/energy-management-app/silabs/third_party/connectedhomeip @@ -0,0 +1 @@ +../../../.. \ No newline at end of file diff --git a/examples/energy-management-app/silabs/with_pw_rpc.gni b/examples/energy-management-app/silabs/with_pw_rpc.gni new file mode 100644 index 0000000000..ac5d9953a3 --- /dev/null +++ b/examples/energy-management-app/silabs/with_pw_rpc.gni @@ -0,0 +1,30 @@ +# Copyright (c) 2021 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. + +# add this gni as import in your build args to use pigweed in the example +# 'import("//with_pw_rpc.gni")' + +import("//build_overrides/chip.gni") +import("${chip_root}/config/efr32/lib/pw_rpc/pw_rpc.gni") +import("${chip_root}/examples/platform/silabs/args.gni") + +silabs_sdk_target = get_label_info(":sdk", "label_no_toolchain") + +app_data_model = + "${chip_root}/examples/energy-management-app/energy-management-common" +chip_enable_pw_rpc = true +chip_enable_openthread = true + +# Light app on EFR enables tracing server +pw_trace_BACKEND = "$dir_pw_trace_tokenized" From 594da6acadca4d349bea7d98d62660c524ed3cd5 Mon Sep 17 00:00:00 2001 From: Amine Alami <43780877+Alami-Amine@users.noreply.github.com> Date: Fri, 9 Aug 2024 20:41:44 +0200 Subject: [PATCH 005/165] Remove pybindings from stack (#34892) * remove pybindings sourcecode * remove code that interacts with pybinding * removing pybind11 submodule --- .github/dependabot.yml | 1 - .github/workflows/build.yaml | 3 +- .gitmodules | 4 - BUILD.gn | 7 - scripts/build_python.sh | 23 +-- scripts/build_python_device.sh | 25 +-- scripts/tools/check_includes_config.py | 1 - src/pybindings/pycontroller/BUILD.gn | 175 ---------------- .../ControllerBindings/PyChip_ChipError.cpp | 77 ------- .../ControllerBindings/PyChip_ErrorStr.cpp | 53 ----- .../ControllerBindings/PyChip_Main.cpp | 51 ----- .../pycontroller/build-chip-wheel.py | 191 ------------------ .../pycontroller/pychip/__init__.py | 4 - third_party/pybind11/repo | 1 - 14 files changed, 10 insertions(+), 606 deletions(-) delete mode 100644 src/pybindings/pycontroller/BUILD.gn delete mode 100644 src/pybindings/pycontroller/ControllerBindings/PyChip_ChipError.cpp delete mode 100644 src/pybindings/pycontroller/ControllerBindings/PyChip_ErrorStr.cpp delete mode 100644 src/pybindings/pycontroller/ControllerBindings/PyChip_Main.cpp delete mode 100644 src/pybindings/pycontroller/build-chip-wheel.py delete mode 100644 src/pybindings/pycontroller/pychip/__init__.py delete mode 160000 third_party/pybind11/repo diff --git a/.github/dependabot.yml b/.github/dependabot.yml index b55417cdba..8c618416fb 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -54,7 +54,6 @@ updates: - dependency-name: "third_party/open-iot-sdk/repo" - dependency-name: "third_party/ot-br-posix/repo" - dependency-name: "third_party/perfetto/repo" - - dependency-name: "third_party/pybind11/repo" - dependency-name: "third_party/qpg_sdk/repo" - dependency-name: "third_party/silabs/repo" - dependency-name: "third_party/simw-top-mini/repo" diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index 3ec8fd379c..58e6d14cd8 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -308,7 +308,7 @@ jobs: - name: Setup Build, Run Build and Run Tests run: | - scripts/build/gn_gen.sh --args="enable_rtti=true enable_pylib=true chip_config_memory_debug_checks=false chip_config_memory_debug_dmalloc=false chip_generate_link_map_file=false" + 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 @@ -414,7 +414,6 @@ jobs: # "host clang" build, which uses the pigweed # clang. "default") GN_ARGS='target_os="all" is_asan=true enable_host_clang_build=false';; - "python_lib") GN_ARGS='enable_rtti=true enable_pylib=true';; esac BUILD_TYPE=$BUILD_TYPE scripts/build/gn_gen.sh --args="$GN_ARGS" --export-compile-commands scripts/run_in_build_env.sh "ninja -C ./out/$BUILD_TYPE" diff --git a/.gitmodules b/.gitmodules index 1f4129f9f2..0b015f8d14 100644 --- a/.gitmodules +++ b/.gitmodules @@ -165,10 +165,6 @@ path = third_party/infineon/psoc6/psoc6_sdk/libs/recipe-make-cat1a url = https://github.com/Infineon/recipe-make-cat1a platforms = infineon -[submodule "third_party/pybind11/repo"] - path = third_party/pybind11/repo - url = https://github.com/pybind/pybind11 - branch = stable [submodule "p6/lwip"] path = third_party/infineon/psoc6/psoc6_sdk/libs/lwip url = https://github.com/lwip-tcpip/lwip.git diff --git a/BUILD.gn b/BUILD.gn index 8a78d8f55f..c8e4197659 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -44,7 +44,6 @@ if (current_toolchain != "${dir_pw_toolchain}/default:default") { chip_enable_python_modules = (current_os == "mac" || current_os == "linux") && (host_cpu == "x64" || host_cpu == "arm64" || host_cpu == "arm") - enable_pylib = false # Build the Linux all clusters app example with default group chip_build_all_clusters_app = false @@ -112,9 +111,6 @@ if (current_toolchain != "${dir_pw_toolchain}/default:default") { "${chip_root}/src/controller/python:chip-repl", "${chip_root}/src/python_testing/matter_testing_infrastructure:metadata_parser.wheel", ] - if (enable_pylib) { - deps += [ "${chip_root}/src/pybindings/pycontroller" ] - } } } @@ -214,9 +210,6 @@ if (current_toolchain != "${dir_pw_toolchain}/default:default") { data_deps = [ "${chip_root}/examples/chip-tool" ] if (chip_enable_python_modules) { - if (enable_pylib) { - data_deps += [ "${chip_root}/src/pybindings/pycontroller" ] - } data_deps += [ "${chip_root}/src/controller/python:chip-repl" ] } diff --git a/scripts/build_python.sh b/scripts/build_python.sh index e70b220130..9bb919605e 100755 --- a/scripts/build_python.sh +++ b/scripts/build_python.sh @@ -39,7 +39,6 @@ OUTPUT_ROOT="$CHIP_ROOT/out/python_lib" declare enable_ble=true declare chip_detail_logging=false -declare enable_pybindings=false declare chip_mdns declare case_retry_delta declare install_virtual_env @@ -49,7 +48,7 @@ declare install_jupyterlab=no help() { - echo "Usage: $file_name [ options ... ] [ -chip_detail_logging ChipDetailLoggingValue ] [ -chip_mdns ChipMDNSValue ] [-enable_pybindings EnableValue]" + echo "Usage: $file_name [ options ... ] [ -chip_detail_logging ChipDetailLoggingValue ] [ -chip_mdns ChipMDNSValue ]" echo "General Options: -h, --help Display this information. @@ -59,8 +58,6 @@ Input Options: By default it is false. -m, --chip_mdns ChipMDNSValue Specify ChipMDNSValue as platform or minimal. By default it is minimal. - -p, --enable_pybindings Specify whether to enable pybindings as python controller. - -t --time_between_case_retries MRPActiveRetryInterval Specify MRPActiveRetryInterval value Default is 300 ms -i, --install_virtual_env Create a virtual environment with the wheels installed @@ -104,14 +101,6 @@ while (($#)); do chip_mdns=$2 shift ;; - --enable_pybindings | -p) - enable_pybindings=$2 - if [[ "$enable_pybindings" != "true" && "$enable_pybindings" != "false" ]]; then - echo "enable_pybindings should have a true/false value, not '$enable_pybindings'" - exit - fi - shift - ;; --time_between_case_retries | -t) chip_case_retry_delta=$2 shift @@ -157,7 +146,7 @@ while (($#)); do done # Print input values -echo "Input values: chip_detail_logging = $chip_detail_logging , chip_mdns = \"$chip_mdns\", enable_pybindings = $enable_pybindings, chip_case_retry_delta=\"$chip_case_retry_delta\", pregen_dir=\"$pregen_dir\", enable_ble=\"$enable_ble\"" +echo "Input values: chip_detail_logging = $chip_detail_logging , chip_mdns = \"$chip_mdns\", chip_case_retry_delta=\"$chip_case_retry_delta\", pregen_dir=\"$pregen_dir\", enable_ble=\"$enable_ble\"" # Ensure we have a compilation environment source "$CHIP_ROOT/scripts/activate.sh" @@ -184,7 +173,7 @@ export SYSTEM_VERSION_COMPAT=0 # Make all possible human redable tracing available. tracing_options="matter_log_json_payload_hex=true matter_log_json_payload_decode_full=true matter_enable_tracing_support=true" -gn --root="$CHIP_ROOT" gen "$OUTPUT_ROOT" --args="$tracing_options chip_detail_logging=$chip_detail_logging enable_pylib=$enable_pybindings enable_rtti=$enable_pybindings chip_project_config_include_dirs=[\"//config/python\"] $chip_mdns_arg $chip_case_retry_arg $pregen_dir_arg chip_config_network_layer_ble=$enable_ble chip_enable_ble=$enable_ble chip_crypto=\"boringssl\"" +gn --root="$CHIP_ROOT" gen "$OUTPUT_ROOT" --args="$tracing_options chip_detail_logging=$chip_detail_logging chip_project_config_include_dirs=[\"//config/python\"] $chip_mdns_arg $chip_case_retry_arg $pregen_dir_arg chip_config_network_layer_ble=$enable_ble chip_enable_ble=$enable_ble chip_crypto=\"boringssl\"" function ninja_target() { # Print the ninja target required to build a gn label. @@ -206,11 +195,7 @@ function wheel_output_dir() { ninja -C "$OUTPUT_ROOT" python_wheels # Add wheels from chip_python_wheel_action templates. -if [ "$enable_pybindings" == true ]; then - WHEEL=("$OUTPUT_ROOT"/pybindings/pycontroller/pychip-*.whl) -else - WHEEL=("$OUTPUT_ROOT"/controller/python/chip*.whl) -fi +WHEEL=("$OUTPUT_ROOT"/controller/python/chip*.whl) # Add the matter_testing_infrastructure wheel WHEEL+=("$OUTPUT_ROOT"/python/obj/src/python_testing/matter_testing_infrastructure/metadata_parser._build_wheel/metadata_parser-*.whl) diff --git a/scripts/build_python_device.sh b/scripts/build_python_device.sh index 894ea1bad6..9b21d28954 100755 --- a/scripts/build_python_device.sh +++ b/scripts/build_python_device.sh @@ -39,12 +39,11 @@ OUTPUT_ROOT="$CHIP_ROOT/out/python_lib" ENVIRONMENT_ROOT="$CHIP_ROOT/out/python_env" declare chip_detail_logging=false -declare enable_pybindings=false declare chip_mdns help() { - echo "Usage: $file_name [ options ... ] [ -chip_detail_logging ChipDetailLoggingValue ] [ -chip_mdns ChipMDNSValue ] [-enable_pybindings EnableValue]" + echo "Usage: $file_name [ options ... ] [ -chip_detail_logging ChipDetailLoggingValue ] [ -chip_mdns ChipMDNSValue ]" echo "General Options: -h, --help Display this information. @@ -53,7 +52,6 @@ Input Options: By default it is false. -m, --chip_mdns ChipMDNSValue Specify ChipMDNSValue as platform or minimal. By default it is minimal. - -p, --enable_pybindings EnableValue Specify whether to enable pybindings as python controller. " } @@ -73,10 +71,6 @@ while (($#)); do chip_mdns=$2 shift ;; - --enable_pybindings | -p) - enable_pybindings=$2 - shift - ;; -*) help echo "Unknown Option \"$1\"" @@ -87,7 +81,7 @@ while (($#)); do done # Print input values -echo "Input values: chip_detail_logging = $chip_detail_logging , chip_mdns = \"$chip_mdns\", enable_pybindings = $enable_pybindings" +echo "Input values: chip_detail_logging = $chip_detail_logging , chip_mdns = \"$chip_mdns\"" # Ensure we have a compilation environment source "$CHIP_ROOT/scripts/activate.sh" @@ -97,26 +91,17 @@ source "$CHIP_ROOT/scripts/activate.sh" chip_data_model_arg="chip_data_model=\"///examples/lighting-app/lighting-common\"" -gn --root="$CHIP_ROOT" gen "$OUTPUT_ROOT" --args="chip_detail_logging=$chip_detail_logging enable_pylib=$enable_pybindings enable_rtti=$enable_pybindings $chip_mdns_arg chip_controller=false $chip_data_model_arg" +gn --root="$CHIP_ROOT" gen "$OUTPUT_ROOT" --args="chip_detail_logging=$chip_detail_logging $chip_mdns_arg chip_controller=false $chip_data_model_arg" # Compiles python files -# Check pybindings was requested -if [ "$enable_pybindings" == true ]; then - ninja -v -C "$OUTPUT_ROOT" pycontroller -else - ninja -v -C "$OUTPUT_ROOT" chip-core -fi +ninja -v -C "$OUTPUT_ROOT" chip-core # Create a virtual environment that has access to the built python tools virtualenv --clear "$ENVIRONMENT_ROOT" # Activate the new environment to register the python WHL -if [ "$enable_pybindings" == true ]; then - WHEEL=("$OUTPUT_ROOT"/pybindings/pycontroller/pychip-*.whl) -else - WHEEL=("$OUTPUT_ROOT"/controller/python/chip_core*.whl) -fi +WHEEL=("$OUTPUT_ROOT"/controller/python/chip_core*.whl) source "$ENVIRONMENT_ROOT"/bin/activate "$ENVIRONMENT_ROOT"/bin/python -m pip install --upgrade pip diff --git a/scripts/tools/check_includes_config.py b/scripts/tools/check_includes_config.py index 8790faf166..2af375d7c4 100644 --- a/scripts/tools/check_includes_config.py +++ b/scripts/tools/check_includes_config.py @@ -29,7 +29,6 @@ '/java/', '/Jni', '/mock/', - '/pybindings/', '/python/', '/Test', '/tests/', diff --git a/src/pybindings/pycontroller/BUILD.gn b/src/pybindings/pycontroller/BUILD.gn deleted file mode 100644 index 0949f7baf7..0000000000 --- a/src/pybindings/pycontroller/BUILD.gn +++ /dev/null @@ -1,175 +0,0 @@ -# Copyright (c) 2021 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/python.gni") - -import("${chip_root}/build/chip/tools.gni") -import("${chip_root}/src/platform/device.gni") -import("${dir_pw_unit_test}/test.gni") - -if (current_os == "mac") { - import("${build_root}/config/mac/mac_sdk.gni") -} - -config("controller_wno_deprecate") { - cflags = [ - "-Wno-deprecated-declarations", - "-Wno-shadow", - "-Wno-unused-result", - "-Wsign-compare", - "-Wunreachable-code", - "-Wno-macro-redefined", - ] -} - -shared_library("CHIPController") { - configs -= [ "//build/config/compiler:exceptions_default" ] - - output_name = "PyChip" - output_dir = "${target_out_dir}/pychip" - - # TODO: Update to use GN tools to get actual paths - include_dirs = [ "${chip_root}/third_party/pybind11/repo/include" ] - if (current_os == "mac") { - include_dirs += - [ "${chip_root}/.environment/cipd/packages/python/include/python3.9" ] - } else if (current_os == "linux") { - include_dirs += [ "/usr/include/python3.9" ] - } else { - assert(false, "OS not supported.") - } - - sources = [ - "ControllerBindings/PyChip_ChipError.cpp", - "ControllerBindings/PyChip_ErrorStr.cpp", - "ControllerBindings/PyChip_Main.cpp", - ] - - public_deps = [ - "${chip_root}/src/app", - "${chip_root}/src/controller/data_model", - "${chip_root}/src/lib", - "${chip_root}/src/lib/core", - "${chip_root}/src/lib/dnssd", - "${chip_root}/src/lib/support", - "${chip_root}/src/platform", - "${chip_root}/src/platform/logging:default", - "${chip_root}/src/setup_payload", - "${chip_root}/src/tracing/json", - "${chip_root}/src/tracing/perfetto", - "${chip_root}/src/tracing/perfetto:file_output", - "${chip_root}/src/transport", - "${chip_root}/third_party/jsoncpp", - ] - deps = [ - "${chip_root}/src/tracing/perfetto:event_storage", - "${chip_root}/src/tracing/perfetto:simple_initialization", - ] - configs += [ ":controller_wno_deprecate" ] - if (current_os == "mac") { - ldflags = [ - "-undefined", - "dynamic_lookup", - ] - } - if (current_os == "linux") { - libs = [ "python3.9" ] - } -} - -pw_python_action("pycontroller") { - script = "build-chip-wheel.py" - - _py_manifest_files = [ - { - src_dir = "." - sources = [ "pychip/__init__.py" ] - }, - { - src_dir = target_out_dir - sources = [ "${target_out_dir}/pychip/PyChip.so" ] - }, - { - src_dir = "//" - sources = [ "//LICENSE" ] - }, - ] - - _py_manifest_file = "${target_gen_dir}/${target_name}.py_manifest.json" - - inputs = [] - _py_manifest_files_rebased = [] - foreach(_manifest_entry, _py_manifest_files) { - inputs += _manifest_entry.sources - _py_manifest_files_rebased += [ - { - src_dir = rebase_path(_manifest_entry.src_dir, - get_path_info(_py_manifest_file, "dir")) - sources = rebase_path(_manifest_entry.sources, _manifest_entry.src_dir) - }, - ] - } - - _py_manifest = { - files = _py_manifest_files_rebased - } - - write_file(_py_manifest_file, _py_manifest, "json") - - _dist_dir = "${root_out_dir}/pybindings/pycontroller" - - if (current_cpu == "x64") { - cpu_tag = "x86_64" - } else if (current_cpu == "arm64") { - cpu_tag = "aarch64" - } else { - cpu_tag = current_cpu - } - - if (current_os == "mac") { - platform_tag = string_replace( - string_replace(mac_deployment_target, "macos", "macosx."), - ".", - "_") - } else { - platform_tag = current_os - } - - platform_tag = platform_tag + "_" + cpu_tag - - tags = "cp37-" + platform_tag - - args = [ - "--package_name", - "pychip", - "--build_number", - "0.0", - "--build_dir", - rebase_path("${target_gen_dir}/${target_name}.py_build", root_build_dir), - "--dist_dir", - rebase_path(_dist_dir, root_build_dir), - "--manifest", - rebase_path(_py_manifest_file, root_build_dir), - "--plat-name", - platform_tag, - ] - - public_deps = [ ":CHIPController" ] - - output_name = "pychip-0.0.dist-info-0.0-${tags}.whl" - outputs = [ "${_dist_dir}/$output_name" ] -} diff --git a/src/pybindings/pycontroller/ControllerBindings/PyChip_ChipError.cpp b/src/pybindings/pycontroller/ControllerBindings/PyChip_ChipError.cpp deleted file mode 100644 index d1fc3cf67b..0000000000 --- a/src/pybindings/pycontroller/ControllerBindings/PyChip_ChipError.cpp +++ /dev/null @@ -1,77 +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 - -#ifndef BINDER_PYBIND11_TYPE_CASTER -#define BINDER_PYBIND11_TYPE_CASTER -PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr) -PYBIND11_DECLARE_HOLDER_TYPE(T, T *) -PYBIND11_MAKE_OPAQUE(std::shared_ptr) -#endif - -void bind_PyChip_ChipError(std::function & M) -{ - { - pybind11::class_> cl( - M("chip"), "ChipError", - "This is a helper class for managing `CHIP_ERROR` numbers.\n\n At the top level, an error belongs to a `Range` and has " - "an integral Value whose meaning depends on the `Range`.\n One, `Range::kSDK`, is used for the CHIP SDK's own errors; " - "others encapsulate error codes from external sources\n (e.g. libraries, OS) into a `CHIP_ERROR`.\n\n CHIP SDK errors " - "inside `Range::kSDK` consist of a component identifier given by `SdkPart` and an arbitrary small\n integer Code."); - cl.def(pybind11::init([]() { return new chip::ChipError(); })); - cl.def(pybind11::init(), pybind11::arg("error")); - - cl.def(pybind11::init([](chip::ChipError const & o) { return new chip::ChipError(o); })); - - pybind11::enum_(cl, "Range", "Top-level error classification.") - .value("kSDK", chip::ChipError::Range::kSDK) - .value("kOS", chip::ChipError::Range::kOS) - .value("kPOSIX", chip::ChipError::Range::kPOSIX) - .value("kLwIP", chip::ChipError::Range::kLwIP) - .value("kOpenThread", chip::ChipError::Range::kOpenThread) - .value("kPlatform", chip::ChipError::Range::kPlatform); - - pybind11::enum_(cl, "SdkPart", "Secondary classification of errors in `Range::kSDK`.") - .value("kCore", chip::ChipError::SdkPart::kCore) - .value("kInet", chip::ChipError::SdkPart::kInet) - .value("kDevice", chip::ChipError::SdkPart::kDevice) - .value("kASN1", chip::ChipError::SdkPart::kASN1) - .value("kBLE", chip::ChipError::SdkPart::kBLE) - .value("kApplication", chip::ChipError::SdkPart::kApplication); - - cl.def("__eq__", (bool(chip::ChipError::*)(const class chip::ChipError &) const) & chip::ChipError::operator==, - "C++: chip::ChipError::operator==(const class chip::ChipError &) const --> bool", pybind11::arg("other")); - cl.def("__ne__", (bool(chip::ChipError::*)(const class chip::ChipError &) const) & chip::ChipError::operator!=, - "C++: chip::ChipError::operator!=(const class chip::ChipError &) const --> bool", pybind11::arg("other")); - cl.def_static("IsSuccess", (bool (*)(unsigned int)) & chip::ChipError::IsSuccess, - "C++: chip::ChipError::IsSuccess(unsigned int) --> bool", pybind11::arg("error")); - cl.def_static("IsSuccess", (bool (*)(class chip::ChipError)) & chip::ChipError::IsSuccess, - "C++: chip::ChipError::IsSuccess(class chip::ChipError) --> bool", pybind11::arg("error")); - } - M("chip").def("RegisterCHIPLayerErrorFormatter", (void (*)()) & chip::RegisterCHIPLayerErrorFormatter, - "C++: chip::RegisterCHIPLayerErrorFormatter() --> void"); - - M("chip").def("FormatCHIPError", (bool (*)(char *, unsigned short, unsigned int)) & chip::FormatCHIPError, - "C++: chip::FormatCHIPError(char *, unsigned short, unsigned int) --> bool", pybind11::arg("buf"), - pybind11::arg("bufSize"), pybind11::arg("err")); -} diff --git a/src/pybindings/pycontroller/ControllerBindings/PyChip_ErrorStr.cpp b/src/pybindings/pycontroller/ControllerBindings/PyChip_ErrorStr.cpp deleted file mode 100644 index b59424d10d..0000000000 --- a/src/pybindings/pycontroller/ControllerBindings/PyChip_ErrorStr.cpp +++ /dev/null @@ -1,53 +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 - -#ifndef BINDER_PYBIND11_TYPE_CASTER -#define BINDER_PYBIND11_TYPE_CASTER -PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr) -PYBIND11_DECLARE_HOLDER_TYPE(T, T *) -PYBIND11_MAKE_OPAQUE(std::shared_ptr) -#endif - -void bind_PyChip_ErrorStr(std::function & M) -{ - { - pybind11::class_> cl(M("chip"), "ErrorFormatter", ""); - cl.def(pybind11::init([]() { return new chip::ErrorFormatter(); })); - } - M("chip").def("ErrorStr", (const char * (*) (CHIP_ERROR)) & chip::ErrorStr, - "C++: chip::ErrorStr(unsigned int) --> const char *", pybind11::return_value_policy::automatic, - pybind11::arg("err")); - - M("chip").def("RegisterErrorFormatter", (void (*)(struct chip::ErrorFormatter *)) & chip::RegisterErrorFormatter, - "C++: chip::RegisterErrorFormatter(struct chip::ErrorFormatter *) --> void", pybind11::arg("errFormatter")); - - M("chip").def("DeregisterErrorFormatter", (void (*)(struct chip::ErrorFormatter *)) & chip::DeregisterErrorFormatter, - "C++: chip::DeregisterErrorFormatter(struct chip::ErrorFormatter *) --> void", pybind11::arg("errFormatter")); - - M("chip").def("FormatError", (void (*)(char *, unsigned short, const char *, unsigned int, const char *)) & chip::FormatError, - "C++: chip::FormatError(char *, unsigned short, const char *, unsigned int, const char *) --> void", - pybind11::arg("buf"), pybind11::arg("bufSize"), pybind11::arg("subsys"), pybind11::arg("err"), - pybind11::arg("desc")); -} diff --git a/src/pybindings/pycontroller/ControllerBindings/PyChip_Main.cpp b/src/pybindings/pycontroller/ControllerBindings/PyChip_Main.cpp deleted file mode 100644 index d7cc4effcb..0000000000 --- a/src/pybindings/pycontroller/ControllerBindings/PyChip_Main.cpp +++ /dev/null @@ -1,51 +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 - -typedef std::function ModuleGetter; - -void bind_PyChip_ErrorStr(std::function & M); -void bind_PyChip_ChipError(std::function & M); - -PYBIND11_MODULE(PyChip, root_module) -{ - root_module.doc() = "PyChip module"; - - std::map modules; - ModuleGetter M = [&](std::string const & namespace_) -> pybind11::module & { - auto it = modules.find(namespace_); - if (it == modules.end()) - throw std::runtime_error("Attempt to access pybind11::module for namespace " + namespace_ + " that does not exist!!!"); - return it->second; - }; - - modules[""] = root_module; - - std::vector> sub_modules{ { "", "chip" } }; - for (auto & p : sub_modules) - modules[p.first.size() ? p.first + "::" + p.second : p.second] = - modules[p.first].def_submodule(p.second.c_str(), ("Bindings for " + p.first + "::" + p.second + " namespace").c_str()); - - bind_PyChip_ErrorStr(M); - bind_PyChip_ChipError(M); -} diff --git a/src/pybindings/pycontroller/build-chip-wheel.py b/src/pybindings/pycontroller/build-chip-wheel.py deleted file mode 100644 index 61bdf373e8..0000000000 --- a/src/pybindings/pycontroller/build-chip-wheel.py +++ /dev/null @@ -1,191 +0,0 @@ -# -# Copyright (c) 2020 Project CHIP Authors -# Copyright (c) 2019 Google LLC. -# 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. -# - -# -# Description: -# Builds a Python wheel package for CHIP. -# - -from __future__ import absolute_import - -import argparse -import json -import os -import platform -import shutil - -from setuptools import setup -from wheel.bdist_wheel import bdist_wheel - -parser = argparse.ArgumentParser( - description='build the pip package for chip using chip components generated during the build and python source code') -parser.add_argument('--package_name', default='chip', - help='configure the python package name') -parser.add_argument('--build_number', default='0.0', - help='configure the chip build number') -parser.add_argument('--build_dir', help='directory to build in') -parser.add_argument('--dist_dir', help='directory to place distribution in') -parser.add_argument('--manifest', help='list of files to package') -parser.add_argument( - '--plat-name', help='platform name to embed in generated filenames') - -args = parser.parse_args() - - -class InstalledScriptInfo: - """Information holder about a script that is to be installed.""" - - def __init__(self, name): - self.name = name - self.installName = os.path.splitext(name)[0] - - -chipDLLName = 'PyChip.so' -packageName = args.package_name -chipPackageVer = args.build_number - -installScripts = [ - # InstalledScriptInfo('chip-repl.py'), -] - -# Record the current directory at the start of execution. -curDir = os.curdir - -manifestFile = os.path.abspath(args.manifest) -buildDir = os.path.abspath(args.build_dir) -distDir = os.path.abspath(args.dist_dir) - -# Use a temporary directory within the build directory to assemble the components -# for the installable package. -tmpDir = os.path.join(buildDir, 'pychip-wheel-components') - -manifest = json.load(open(manifestFile, 'r')) - -try: - - # - # Perform a series of setup steps prior to creating the chip package... - # - - # Create the temporary components directory. - if os.path.isdir(tmpDir): - shutil.rmtree(tmpDir) - os.makedirs(tmpDir, exist_ok=True) - - # Switch to the temporary directory. (Foolishly, setuptools relies on the current directory - # for many of its features.) - os.chdir(tmpDir) - - manifestBase = os.path.dirname(manifestFile) - for entry in manifest['files']: - srcDir = os.path.join(manifestBase, entry['src_dir']) - for path in entry['sources']: - srcFile = os.path.join(srcDir, path) - dstFile = os.path.join(tmpDir, path) - os.makedirs(os.path.dirname(dstFile), exist_ok=True) - shutil.copyfile(srcFile, dstFile) - - for script in installScripts: - os.rename(os.path.join(tmpDir, script.name), - os.path.join(tmpDir, script.installName)) - - # Define a custom version of the bdist_wheel command that configures the - # resultant wheel as platform-specific (i.e. not "pure"). - class bdist_wheel_override(bdist_wheel): - def finalize_options(self): - bdist_wheel.finalize_options(self) - self.root_is_pure = False - - requiredPackages = [ - "coloredlogs", - 'construct', - 'ipython', - ] - - if platform.system() == 'Darwin': - requiredPackages.append('pyobjc-framework-corebluetooth') - - if platform.system() == 'Linux': - requiredPackages.append('pygobject') - - # - # Build the chip package... - # - packages = [ - 'pychip', - ] - - # Invoke the setuptools 'bdist_wheel' command to generate a wheel containing - # the CHIP python packages, shared libraries and scripts. - setup( - name=packageName, - version=chipPackageVer, - description='Python-base APIs and tools for CHIP.', - url='https://github.com/project-chip/connectedhomeip', - license='Apache', - classifiers=[ - 'Intended Audience :: Developers', - 'License :: OSI Approved :: Apache Software License', - 'Programming Language :: Python :: 2', - 'Programming Language :: Python :: 2.7', - 'Programming Language :: Python :: 3', - ], - python_requires='>=2.7', - packages=packages, - package_dir={ - # By default, look in the tmp directory for packages/modules to be included. - '': tmpDir, - }, - package_data={ - packageName: [ - # Include the wrapper DLL as package data in the "chip" package. - chipDLLName - ] - }, - scripts=[name for name in map( - lambda script: os.path.join(tmpDir, script.installName), - installScripts - )], - install_requires=requiredPackages, - options={ - 'bdist_wheel': { - 'universal': False, - # Place the generated .whl in the dist directory. - 'dist_dir': distDir, - 'py_limited_api': 'cp37', - 'plat_name': args.plat_name, - }, - 'egg_info': { - # Place the .egg-info subdirectory in the tmp directory. - 'egg_base': tmpDir - } - }, - cmdclass={ - 'bdist_wheel': bdist_wheel_override - }, - script_args=['clean', '--all', 'bdist_wheel'] - ) - -finally: - - # Switch back to the initial current directory. - os.chdir(curDir) - - # Remove the temporary directory. - if os.path.isdir(tmpDir): - shutil.rmtree(tmpDir) diff --git a/src/pybindings/pycontroller/pychip/__init__.py b/src/pybindings/pycontroller/pychip/__init__.py deleted file mode 100644 index c2020be2dc..0000000000 --- a/src/pybindings/pycontroller/pychip/__init__.py +++ /dev/null @@ -1,4 +0,0 @@ - -from .PyChip import chip - -__all__ = [chip] diff --git a/third_party/pybind11/repo b/third_party/pybind11/repo deleted file mode 160000 index 8b03ffa7c0..0000000000 --- a/third_party/pybind11/repo +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 8b03ffa7c06cd9c8a38297b1c8923695d1ff1b07 From 2e603f9bf5d2399d00b6ea7d774ecb809ded0806 Mon Sep 17 00:00:00 2001 From: Harshith-GRL <145322529+Harshith-GRL@users.noreply.github.com> Date: Sat, 10 Aug 2024 01:39:52 +0530 Subject: [PATCH 006/165] Added DRLK_2_13 for Aliro Feature (#34875) * Adding TC-DRLK-2.13 * Adding TC-DRLK-2.13 Removed TODO comments * Restyled by autopep8 * Restyled by isort * Made Fix for GIT jobs * Used restyle to fix styling * Removed unused Variable 'response' * Added license Header and CI Argument header * Restyled by autopep8 * Made Fix for GIT jobs * Fixed CI Arguments, it will use CHIP_LOCK_APP * Updated CI Arguments with PICS path * Updated some comments in step execution * Adding TC-DRLK-2.13 * Adding TC-DRLK-2.13 Removed TODO comments * Restyled by autopep8 * Restyled by isort * Made Fix for GIT jobs * Used restyle to fix styling * Removed unused Variable 'response' * Added license Header and CI Argument header * Restyled by autopep8 * Made Fix for GIT jobs * Fixed CI Arguments, it will use CHIP_LOCK_APP * Updated CI Arguments with PICS path * Updated some comments in step execution * Made Changes inaccordance with andy's comments. * Code is updated as per Andre's comments --------- Co-authored-by: Restyled.io Co-authored-by: cjandhyala <68604034+cjandhyala@users.noreply.github.com> --- src/python_testing/TC_DRLK_2_13.py | 655 +++++++++++++++++++++++++++++ 1 file changed, 655 insertions(+) create mode 100644 src/python_testing/TC_DRLK_2_13.py diff --git a/src/python_testing/TC_DRLK_2_13.py b/src/python_testing/TC_DRLK_2_13.py new file mode 100644 index 0000000000..5e1cdf6dcf --- /dev/null +++ b/src/python_testing/TC_DRLK_2_13.py @@ -0,0 +1,655 @@ +# +# 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. + +# See https://github.com/project-chip/connectedhomeip/blob/master/docs/testing/python.md#defining-the-ci-test-arguments +# for details about the block below. +# +# === BEGIN CI TEST ARGUMENTS === +# test-runner-runs: run1 +# test-runner-run/run1/app: ${CHIP_LOCK_APP} +# test-runner-run/run1/factoryreset: True +# test-runner-run/run1/quiet: True +# test-runner-run/run1/app-args: --discriminator 1234 --KVS kvs1 --trace-to json:${TRACE_APP}.json +# test-runner-run/run1/script-args: --storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --PICS src/app/tests/suites/certification/ci-pics-values --trace-to json:${TRACE_TEST_JSON}.json --trace-to perfetto:${TRACE_TEST_PERFETTO}.perfetto +# === END CI TEST ARGUMENTS === + +import logging +import random +from dataclasses import dataclass + +import chip.clusters as Clusters +from chip.clusters.Attribute import EventPriority +from chip.clusters.Types import NullValue +from chip.interaction_model import InteractionModelError, Status +from matter_testing_support import MatterBaseTest, TestStep, async_test_body, default_matter_test_main, type_matches +from mobly import asserts + +logger = logging.getLogger(__name__) + +cluster = Clusters.DoorLock + + +@dataclass +class AliroAttributeVerify: + th_step: str + attribute: Clusters.DoorLock.Attributes + attribute_value: bytes + + +class TC_DRLK_2_13(MatterBaseTest): + + def steps_TC_DRLK_2_13(self) -> list[TestStep]: + steps = [ + TestStep("1a", "TH reads OperationalCredentials cluster's CurrentFabricIndex and save the attribute", + "TH Reads Attribute Successfully"), + TestStep("1b", "TH sends ClearUser Command to DUT with the UserIndex as 0xFFFE to clear all the users", + "DUT responds with Success response"), + TestStep("1c", "TH sends ClearCredential Command to DUT to clear all the credentials", + "Verify that the DUT sends SUCCESS response"), + TestStep("2a", + "TH sends ClearAliroReaderConfig Command to DUT for clearing any existing Aliro Configuration", + "Verify that the DUT sends SUCCESS response"), + TestStep("2b", ",TH sends SetAliroReaderConfig Command to DUT without GroupResolvingKey", + "DUT sends success response"), + TestStep("2c", "TH sends SetAliroReaderConfig Command to DUT with GroupResolvingKey", + "DUT sends success response"), + TestStep("3", "TH reads AliroReaderVerificationKey attribute from DUT", + "Verify that AliroReaderVerificationKey value is same as 'verificationkey'"), + TestStep("4", "TH reads AliroReaderGroupIdentifier attribute from DUT", + "Verify that AliroReaderGroupIdentifier value is same as 'groupidentifier'"), + TestStep("5", "TH reads AliroGroupResolvingKey attribute from DUT", + "Verify that AliroGroupResolvingKey value is same 'groupresolvingkey'"), + TestStep("6a", ",TH sends SetAliroReaderConfig Command to DUT without GroupResolvingKey", + "Verify that the DUT sends INVALID_IN_STATE response"), + TestStep("6b", "TH sends SetAliroReaderConfig Command to DUT with GroupResolvingKey", + "Verify that the DUT sends INVALID_IN_STATE response"), + TestStep("7", "TH sends ClearAliroReaderConfig Command to DUT", + "Verify that the DUT sends SUCCESS response"), + TestStep("8", "TH reads AliroReaderVerificationKey attribute from DUT", + "Verify that AliroReaderVerificationKey value is null"), + TestStep("9", "TH reads AliroReaderGroupIdentifier attribute from DUT", + "Verify that AliroReaderGroupIdentifier value is null"), + TestStep("10", "TH reads AliroGroupResolvingKey attribute from DUT", + "Verify that AliroGroupResolvingKey value is null"), + TestStep("11a", ",TH sends SetAliroReaderConfig Command to DUT without GroupResolvingKey", + "DUT sends success response"), + TestStep("11b", "TH sends SetAliroReaderConfig Command to DUT with GroupResolvingKey", + "DUT sends success response"), + TestStep("12a", + "TH reads NumberOfAliroEndpointKeysSupported store as 'max_aliro_keys_supported' if max_aliro_keys_supported>= 2 continue with the next steps," + "Verify that Read operation is successful"), + TestStep("12b", + "TH sends SetUser Command to DUT to create an Aliro user using username as 'AliroUser' and unique id 111", + "Verify that the DUT sends SUCCESS response"""), + TestStep("13a", "TH sends SetCredential Command Credential as (6, 2)", + "Verify that the DUT responds with SetCredentialResponse command, DUT responds with status success in SetCredentialResponse"), + TestStep("13b", "TH sends SetCredential Command with Credential as (6, 1)", + "Verify that the DUT responds with SetCredentialResponse command, DUT responds with status success in SetCredentialResponse"), + TestStep("14", "TH reads the LockUserChange event list from DUT", + "Verify list has an event LockDataType: 11 as latest event with DataOperationType: 0(DataOperationTypeEnum.Add) along with other information"), + TestStep("15", "TH sends GetCredentialStatus Command with Credential as (6,1)", + "Verify DUT responds with GetCredentialStatusResponse having CredentialExists is true and UserIndex as 1"), + TestStep("16", + "TH sends ClearCredential Command to DUT to clear the CredentialType of AliroCredentialIssuerKey", + "Verify that the DUT sends SUCCESS response"), + TestStep("17", "TH reads the LockUserChange event list from DUT", + "Verify list has an event LockDataType: 11 as latest event with DataOperationType: 1(DataOperationTypeEnum.Clear) along with other information"), + TestStep("18", "TH sends SetCredential Command to DUT with CredentialType as AliroEvictableEndpointKey", + "Verify that the DUT responds with SetCredentialResponse command, DUT responds with status success in SetCredentialResponse"), + TestStep("19", "TH reads the LockUserChange event list from DUT", + "Verify list has an event LockDataType: 11 as latest event with DataOperationType: 0(DataOperationTypeEnum.Add) along with other information"), + TestStep("20", "TH sends GetCredentialStatus Command with Credential as 7 1", + "Verify DUT responds with GetCredentialStatusResponse having CredentialExists is true and UserIndex as 1"), + TestStep("21", + "TH sends ClearCredential Command to DUT to clear the CredentialType of AliroEvictableEndpointKey", + "Verify that the DUT sends SUCCESS response"), + TestStep("22", "TH reads the LockUserChange event list from DUT", + "Verify list has an event LockDataType: 12 as latest event with DataOperationType: 1(DataOperationTypeEnum.Clear) along with other information"), + TestStep("23", "TH sends SetCredential Command to DUT with CredentialType as AliroNonEvictableEndpointKey ", + "Verify that the DUT responds with SetCredentialResponse command and Status success."), + TestStep("24", "TH reads the LockUserChange event list from DUT", + "Verify list has an event LockDataType: 12 as latest event with DataOperationType: 0(DataOperationTypeEnum.Add) along with other information"), + TestStep("25", "TH sends GetCredentialStatus Command with Credential as 8 1", + "Verify DUT responds with GetCredentialStatusResponse having CredentialExists is true and UserIndex as 1"), + TestStep("26", + "TH sends ClearCredential Command to DUT to clear the CredentialType of AliroNonEvictableEndpointKey", + "DUT sends SUCCESS response"), + TestStep("27", "TH reads the LockUserChange event list from DUT", + "Verify list has an event LockDataType: 13 as latest event with DataOperationType: 1(DataOperationTypeEnum.Clear) along with other information"), + TestStep("28a", "Th Reads NumberOfCredentialsSupportedPerUser saves as numberofcredentialsupportedperuser," + "Read operation is successful"), + TestStep("28b", "TH sends ClearCredential Command to DUT to clear all the credentials of Aliro type " + "TH sends ClearUser Command with UserIndex as 1 to DUT to clear alirouser" + "Executing steps 29 to 35 only when 'max_aliro_keys_supported <= numberofcredentialsupportedperuser' else exit script", + "Verify that Read operation is successful"), + TestStep("29a", "TH sends SetUser Command to DUT to create an Aliro user", + "DUT sends SUCCESS response"), + TestStep("29b", + "TH performs repeated number of SetCredential commands with credentials as 8 'startcredentialindex' until 'max_aliro_keys_supported - 1', startcredentialindex initially has value 1 .", + "Verify that the DUT responds with SetCredentialResponse command and Status success."), + TestStep("30", + "TH sends SetCredential Command to DUT with CredentialType as AliroEvictableEndpointKey for the 'alirouser' ", + "Verify that the DUT responds with SetCredentialResponse command and Status success. This step will fill the last slot with credentialType as AliroEvictableEndpointKey"), + TestStep("31", + "TH sends SetCredential Command to DUT with CredentialType as AliroNonEvictableEndpointKey and number of credentials for 'alirouser' exceeds the max_aliro_keys_supported", + "Verify that the DUT responds with SetCredentialResponse command and Status success."), + TestStep("32", "TH sends GetCredentialStatus Command with Credential as 7 startcredentialindex+1", + "DUT responds with GetCredentialStatusResponse Command and CredentialExists is false"), + TestStep("33", "TH sends GetCredentialStatus Command with Credential as 8 startcredentialindex+1", + "Verify DUT responds with GetCredentialStatusResponse having CredentialExists is true and UserIndex as 1"), + TestStep("34", "TH sends ClearCredential Command to DUT to clear the ALIRO CredentialType", + "Verify that the DUT sends SUCCESS response"), + TestStep("35", "TH sends ClearUser Command to DUT with the UserIndex as 1", + "Verify that the DUT sends SUCCESS response"), + ] + + return steps + + async def read_attributes_from_dut(self, endpoint, cluster, attribute, expected_status: Status = Status.Success): + try: + attribute_value = await self.read_single_attribute_check_success(endpoint=endpoint, cluster=cluster, + attribute=attribute) + asserts.assert_equal(expected_status, Status.Success) + return attribute_value + except Exception as e: + logging.error(e) + asserts.assert_equal(expected_status, Status.Success, + f"Error reading attributes, response={attribute_value}") + + async def aliro_attribute_verifiers(self, aliro_attribute_verify_steps: list[AliroAttributeVerify]): + + for aliro_attribute_step in aliro_attribute_verify_steps: + th_step = aliro_attribute_step.th_step + self.step(th_step) + if aliro_attribute_step.attribute == Clusters.DoorLock.Attributes.AliroReaderVerificationKey: + pics_condition = self.pics_guard(self.check_pics("DRLK.S.F0d") and self.check_pics("DRLK.S.A0080")) + elif aliro_attribute_step.attribute == Clusters.DoorLock.Attributes.AliroReaderGroupIdentifier: + pics_condition = self.pics_guard(self.check_pics("DRLK.S.F0d") and self.check_pics("DRLK.S.A0081")) + elif aliro_attribute_step.attribute == Clusters.DoorLock.Attributes.AliroGroupResolvingKey: + pics_condition = self.pics_guard(self.check_pics("DRLK.S.F0d") and self.check_pics("DRLK.S.A0084")) + else: + pics_condition = False + + if pics_condition: + dut_aliro_key = await self.read_attributes_from_dut(endpoint=self.app_cluster_endpoint, + cluster=Clusters.Objects.DoorLock, + attribute=aliro_attribute_step.attribute) + asserts.assert_equal(dut_aliro_key, aliro_attribute_step.attribute_value, + f"Aliro Attribute key verification Failed, readAttributeResponse{dut_aliro_key}") + + def pics_TC_DRLK_2_13(self) -> list[str]: + return ["DRLK.S.F0d"] + + async def send_clear_user_cmd(self, user_index, expected_status: Status = Status.Success): + try: + await self.send_single_cmd(cmd=Clusters.DoorLock.Commands.ClearUser(userIndex=user_index), + endpoint=self.app_cluster_endpoint, + timedRequestTimeoutMs=1000) + asserts.assert_equal(expected_status, Status.Success) + except InteractionModelError as e: + asserts.assert_equal(e.status, expected_status, f"Unexpected error returned: {e}") + + async def send_clear_aliro_reader_config_cmd(self, expected_status: Status = Status.Success): + try: + await self.send_single_cmd(cmd=Clusters.DoorLock.Commands.ClearAliroReaderConfig(), + endpoint=self.app_cluster_endpoint, + timedRequestTimeoutMs=1000) + asserts.assert_equal(expected_status, Status.Success) + except InteractionModelError as e: + asserts.assert_equal(e.status, expected_status, f"Unexpected error returned: {e}") + + async def send_set_aliro_reader_config_cmd(self, use_group_resolving_key: bool, + expected_status: Status = Status.Success): + try: + # Checks Pics condition + if use_group_resolving_key is False: + pics_check = self.pics_guard(self.check_pics("DRLK.S.F0d") and not self.check_pics("DRLK.S.F0e") and + self.check_pics("DRLK.S.C28.Rsp")) + + else: + pics_check = self.pics_guard(self.check_pics("DRLK.S.F0e") and self.check_pics("DRLK.S.C28.Rsp")) + + if not use_group_resolving_key and pics_check: + await self.send_single_cmd(cmd=Clusters.DoorLock.Commands.SetAliroReaderConfig( + signingKey=self.signingKey, + verificationKey=self.verificationKey, + groupIdentifier=self.groupIdentifier), + endpoint=self.app_cluster_endpoint, + timedRequestTimeoutMs=1000) + asserts.assert_equal(expected_status, Status.Success) + elif use_group_resolving_key and pics_check: + await self.send_single_cmd(cmd=Clusters.DoorLock.Commands.SetAliroReaderConfig( + signingKey=self.signingKey, + verificationKey=self.verificationKey, + groupIdentifier=self.groupIdentifier, + groupResolvingKey=self.groupResolvingKey), + endpoint=self.app_cluster_endpoint, + timedRequestTimeoutMs=1000) + asserts.assert_equal(expected_status, Status.Success) + except InteractionModelError as e: + logging.exception(f"Got exception when performing SetAliroReaderConfig {e}") + asserts.assert_equal(e.status, expected_status, f"Unexpected error returned: {e}") + + async def get_credentials_status(self, credentialIndex: int, credentialType: cluster.Enums.CredentialTypeEnum, + step, userIndex, credential_exists=True): + if step: + self.step(step) + try: + flags = ["DRLK.S.F0d", "DRLK.S.C24.Rsp", "DRLK.S.C25.Tx"] + if not self.pics_guard(all([self.check_pics(p) for p in flags])): + credentials_struct = cluster.Structs.CredentialStruct(credentialIndex=credentialIndex, + credentialType=credentialType) + response = await self.send_single_cmd(endpoint=self.app_cluster_endpoint, timedRequestTimeoutMs=1000, + cmd=cluster.Commands.GetCredentialStatus( + credential=credentials_struct)) + asserts.assert_true(type_matches(response, Clusters.DoorLock.Commands.GetCredentialStatusResponse), + "Unexpected return type for GetCredentialStatus") + asserts.assert_true(response.credentialExists == credential_exists, + "Error when executing GetCredentialStatus command, credentialExists={}".format( + str(response.credentialExists))) + asserts.assert_equal(userIndex, response.userIndex, + f"User Index is not matching, UserIndex={response.userIndex}") + return response + except InteractionModelError as e: + logging.error(e) + asserts.assert_equal(e.status, Status.Success, f"Unexpected error returned: {e}") + + async def set_credential_cmd(self, credential_enum: Clusters.DoorLock.Enums.CredentialTypeEnum, credentialIndex, + operationType, userIndex, credentialData, userStatus, userType, step=None): + if step: + self.step(step) + credentials = cluster.Structs.CredentialStruct( + credentialType=credential_enum, + credentialIndex=credentialIndex) + if self.pics_guard(self.check_pics("DRLK.S.F0d") and self.check_pics("DRLK.S.C22.Rsp")): + try: + response = await self.send_single_cmd(cmd=Clusters.Objects.DoorLock.Commands.SetCredential( + operationType=operationType, + credential=credentials, + credentialData=credentialData, + userStatus=userStatus, + userType=userType, + userIndex=userIndex), + endpoint=self.app_cluster_endpoint, + timedRequestTimeoutMs=1000) + asserts.assert_true(type_matches(response, Clusters.Objects.DoorLock.Commands.SetCredentialResponse), + "Unexpected return type for SetCredential") + asserts.assert_true(response.status == Status.Success, + "Error sending SetCredential command, status={}".format(str(response.status))) + except InteractionModelError as e: + logging.exception(e) + asserts.assert_equal(e.status, Status.Success, f"Unexpected error returned: {e}") + + async def read_and_validate_lock_event_change(self, verify_lock_data_type, priority, operation_source, + data_type_operation, fabric_index, node_id, data_index, user_index): + response_event_list = await self.default_controller.ReadEvent(self.dut_node_id, + [1, cluster.Events.LockUserChange]) + for event_read_result in reversed(response_event_list): + if not hasattr(event_read_result.Data, "lockDataType"): + continue + if event_read_result.Data.lockDataType == verify_lock_data_type: + asserts.assert_equal(event_read_result.Header.Priority, priority, + f"Priority mismatch, Priority={event_read_result.Header.Priority}") + asserts.assert_equal(event_read_result.Data.operationSource, operation_source, + f"OperationSource not matching, operationSource={operation_source}") + asserts.assert_equal(event_read_result.Data.fabricIndex, fabric_index, + f"FabricIndex not matching, fabricIndex={fabric_index}") + asserts.assert_equal(event_read_result.Data.dataIndex, data_index, + f"DataIndex not matching, dataIndex={data_index}") + asserts.assert_equal(event_read_result.Data.sourceNode, node_id, + f"SourceNode not matching, sourceNode={node_id}") + asserts.assert_equal(event_read_result.Data.userIndex, user_index, + f"UserIndex not matching, userIndex={user_index}") + asserts.assert_equal(event_read_result.Data.dataOperationType, data_type_operation, + f"DataOperationType not matching, dataOperationType={data_type_operation}") + break + + async def clear_credentials_cmd(self, credential, step=None, expected_status: Status = Status.Success): + try: + if step is not None: + self.step(step) + if self.pics_guard(self.check_pics("DRLK.S.F0d") and self.check_pics("DRLK.S.C26.Rsp")): + await self.send_single_cmd(cmd=Clusters.DoorLock.Commands.ClearCredential(credential=credential), + endpoint=self.app_cluster_endpoint, + timedRequestTimeoutMs=1000) + asserts.assert_equal(expected_status, Status.Success) + except InteractionModelError as e: + logging.exception(e) + asserts.assert_equal(e.status, expected_status, f"Unexpected error returned: {e}") + + async def clear_all_aliro_credential(self): + all_aliro_cred_list = [] + aliro_cred_issuer_credentials = cluster.Structs.CredentialStruct(credentialIndex=1, + credentialType=Clusters.DoorLock.Enums.CredentialTypeEnum.kAliroCredentialIssuerKey) + all_aliro_cred_list.append(aliro_cred_issuer_credentials) + aliro_evict_endpoint_credentials = cluster.Structs.CredentialStruct(credentialIndex=1, + credentialType=Clusters.DoorLock.Enums.CredentialTypeEnum.kAliroEvictableEndpointKey) + all_aliro_cred_list.append(aliro_evict_endpoint_credentials) + aliro_non_evict_endpoint_credentials = cluster.Structs.CredentialStruct(credentialIndex=1, + credentialType=Clusters.DoorLock.Enums.CredentialTypeEnum.kAliroNonEvictableEndpointKey) + all_aliro_cred_list.append(aliro_non_evict_endpoint_credentials) + for creds in all_aliro_cred_list: + await self.clear_credentials_cmd(credential=creds) + + def generate_unique_octbytes(self, length=65) -> bytes: + return ''.join(random.choices('01234567', k=length)).encode() + + @async_test_body + async def test_TC_DRLK_2_13(self): + self.max_aliro_keys_supported = None + self.numberofcredentialsupportedperuser = None + self.signingKey = bytes.fromhex("89d085fc302ca53e279bfcdecdf3c4adb2f5d9bc9ea6c49e9566d144367df3ff") + self.verificationKey = bytes.fromhex( + "047a4c992d753924cdf3779a3c84fec2debaa6f0b3084450878acc7ddcce7856ae57b1ebbe2561015103dd7474c2a183675378ec55f1e465ac3436bf3dd5ca54d4") + self.groupIdentifier = bytes.fromhex("89d085fc302ca53e279bfcdecdf3c4ad") + self.groupResolvingKey = bytes.fromhex("89d0859bfcdecdf3c4adfc302ca53e27") + self.common_cluster_endpoint = 0 + self.app_cluster_endpoint = 1 + self.alirouser = "AliroUser" + self.alirocredentialissuerkey = bytes.fromhex( + "047a4c882d753924cdf3779a3c84fec2debaa6f0b3084450878acc7ddcce7856ae57b1ebbe2561015103dd7474c2a183675378ec55f1e465ac3436bf3dd5ca54d4") + self.alirocredentialissuerkey_secondary = bytes.fromhex( + "047a4c112d753924cdf3779a3c84fec2debaa6f0b3084450878acc7ddcce7856ae57b1ebbe2561015103dd7474c2a183675378ec55f1e465ac3436bf3dd5ca54d4") + self.aliroevictableendpointkey = bytes.fromhex( + "047a4c772d753924cdf3779a3c84fec2debaa6f0b3084450878acc7ddcce7856ae57b1ebbe2561015103dd7474c2a183675378ec55f1e465ac3436bf3dd5ca54d4") + self.alirononevictableendpointkey = bytes.fromhex( + "047a4c662d753924cdf3779a3c84fec2debaa6f0b3084450878acc7ddcce7856ae57b1ebbe2561015103dd7474c2a183675378ec55f1e465ac3436bf3dd5ca54d4") + self.alirononevictableendpointkey1 = bytes.fromhex( + "047a4c552d753924cdf3779a3c84fec2debaa6f0b3084450878acc7ddcce7856ae57b1ebbe2561015103dd7474c2a183675378ec55f1e465ac3436bf3dd5ca54d4") + # step 1 TH reads DUT Endpoint 0 OperationalCredentials cluster CurrentFabricIndex attribute + self.step("1a") + self.fabric_idx1 = await self.read_attributes_from_dut(endpoint=self.common_cluster_endpoint, + cluster=Clusters.Objects.OperationalCredentials, + attribute=Clusters.OperationalCredentials.Attributes.CurrentFabricIndex + ) + self.step("1b") + if self.pics_guard(self.check_pics("DRLK.S.C1d.Rsp")): + await self.send_clear_user_cmd(user_index=int(0xFFFE)) + + self.step("1c") + if self.pics_guard(self.check_pics("DRLK.S.C26.Rsp")): + await self.clear_credentials_cmd(credential=NullValue) + + # step 2 + self.step("2a") + if self.pics_guard(self.check_pics("DRLK.S.C26.Rsp")): + await self.send_clear_aliro_reader_config_cmd() + self.step("2b") + await self.send_set_aliro_reader_config_cmd(use_group_resolving_key=False, expected_status=Status.Success) + self.step("2c") + await self.send_set_aliro_reader_config_cmd(use_group_resolving_key=True, expected_status=Status.Success) + # step 3,4,5 + aliro_attribute_verify_steps = [ + AliroAttributeVerify(th_step="3", attribute=Clusters.Objects.DoorLock.Attributes.AliroReaderVerificationKey, + attribute_value=self.verificationKey), + AliroAttributeVerify(th_step="4", attribute=Clusters.Objects.DoorLock.Attributes.AliroReaderGroupIdentifier, + attribute_value=self.groupIdentifier), + AliroAttributeVerify(th_step="5", attribute=Clusters.Objects.DoorLock.Attributes.AliroGroupResolvingKey, + attribute_value=self.groupResolvingKey) + ] + await self.aliro_attribute_verifiers(aliro_attribute_verify_steps=aliro_attribute_verify_steps) + + # step 6 + self.step("6a") + await self.send_set_aliro_reader_config_cmd(use_group_resolving_key=False, + expected_status=Status.InvalidInState) + self.step("6b") + await self.send_set_aliro_reader_config_cmd(use_group_resolving_key=True, expected_status=Status.InvalidInState) + # step 7 + self.step("7") + if self.check_pics("DRLK.S.C26.Rsp"): + await self.send_clear_aliro_reader_config_cmd() + + # steps 8,9,10 + aliro_attribute_verify_steps = [ + AliroAttributeVerify(th_step="8", attribute=Clusters.Objects.DoorLock.Attributes.AliroReaderVerificationKey, + attribute_value=NullValue), + AliroAttributeVerify(th_step="9", attribute=Clusters.Objects.DoorLock.Attributes.AliroReaderGroupIdentifier, + attribute_value=NullValue), + AliroAttributeVerify(th_step="10", attribute=Clusters.Objects.DoorLock.Attributes.AliroGroupResolvingKey, + attribute_value=NullValue) + ] + await self.aliro_attribute_verifiers(aliro_attribute_verify_steps=aliro_attribute_verify_steps) + + # step 11 + self.step("11a") + await self.send_set_aliro_reader_config_cmd(use_group_resolving_key=False, expected_status=Status.Success) + self.step("11b") + await self.send_set_aliro_reader_config_cmd(use_group_resolving_key=True, expected_status=Status.Success) + + # step 12 Setting User + self.step("12a") + if self.pics_guard(self.check_pics("DRLK.S.A0088")): + self.max_aliro_keys_supported = await self.read_attributes_from_dut(endpoint=self.app_cluster_endpoint, + cluster=Clusters.Objects.DoorLock, + attribute=Clusters.DoorLock.Attributes.NumberOfAliroEndpointKeysSupported) + if self.max_aliro_keys_supported < 2: + self.skip_all_remaining_steps("13") + return + self.step("12b") + if self.pics_guard(self.check_pics("DRLK.S.F08") and self.check_pics("DRLK.S.C1a.Rsp")): + try: + await self.send_single_cmd(cmd=Clusters.Objects.DoorLock.Commands.SetUser( + operationType=Clusters.DoorLock.Enums.DataOperationTypeEnum.kAdd, + userIndex=1, + userName=self.alirouser, + userUniqueID=111, + userStatus=Clusters.DoorLock.Enums.UserStatusEnum.kOccupiedEnabled, + userType=Clusters.DoorLock.Enums.UserTypeEnum.kUnrestrictedUser, + credentialRule=Clusters.DoorLock.Enums.CredentialRuleEnum.kSingle), + endpoint=self.app_cluster_endpoint, + timedRequestTimeoutMs=1000) + except InteractionModelError as e: + logging.exception(e) + asserts.assert_equal(e.status, Status.Success, f"Unexpected error returned: {e}") + + # step 13 + self.step("13a") + # The first SetCredentialsCommand is done as a placeholder for the user slot as ClearCredentials removes user info as well + await self.set_credential_cmd(credentialData=self.alirononevictableendpointkey1, + operationType=cluster.Enums.DataOperationTypeEnum.kAdd, + credential_enum=cluster.Enums.CredentialTypeEnum.kAliroNonEvictableEndpointKey, + credentialIndex=2, userIndex=1, userStatus=NullValue, userType=NullValue) + self.step("13b") + await self.set_credential_cmd(credentialData=self.alirocredentialissuerkey, + operationType=cluster.Enums.DataOperationTypeEnum.kAdd, + credential_enum=cluster.Enums.CredentialTypeEnum.kAliroCredentialIssuerKey, + credentialIndex=1, userIndex=1, userStatus=NullValue, userType=NullValue) + + # step 14 + self.step("14") + await self.read_and_validate_lock_event_change( + verify_lock_data_type=Clusters.DoorLock.Enums.LockDataTypeEnum.kAliroCredentialIssuerKey, + operation_source=Clusters.DoorLock.Enums.OperationSourceEnum.kRemote, user_index=1, + data_index=1, fabric_index=self.fabric_idx1, node_id=self.matter_test_config.controller_node_id, + data_type_operation=Clusters.DoorLock.Enums.DataOperationTypeEnum.kAdd, priority=EventPriority.INFO + ) + + # step 15 + self.step("15") + await self.get_credentials_status(credentialIndex=1, + credentialType=cluster.Enums.CredentialTypeEnum.kAliroCredentialIssuerKey, + step=None, userIndex=1) + + # step 16 + credentials = cluster.Structs.CredentialStruct(credentialIndex=1, + credentialType=cluster.Enums.CredentialTypeEnum.kAliroCredentialIssuerKey) + await self.clear_credentials_cmd(step="16", credential=credentials) + + # step 17 + self.step("17") + await self.read_and_validate_lock_event_change( + verify_lock_data_type=Clusters.DoorLock.Enums.LockDataTypeEnum.kAliroCredentialIssuerKey, + operation_source=Clusters.DoorLock.Enums.OperationSourceEnum.kRemote, user_index=1, + data_index=1, fabric_index=self.fabric_idx1, node_id=self.matter_test_config.controller_node_id, + data_type_operation=Clusters.DoorLock.Enums.DataOperationTypeEnum.kClear, priority=EventPriority.INFO + ) + + # step 18 + await self.set_credential_cmd(step="18", credentialData=self.aliroevictableendpointkey, + operationType=cluster.Enums.DataOperationTypeEnum.kAdd, + credential_enum=cluster.Enums.CredentialTypeEnum.kAliroEvictableEndpointKey, + credentialIndex=1, userIndex=1, userStatus=NullValue, userType=NullValue) + # step 19 + self.step("19") + await self.read_and_validate_lock_event_change( + verify_lock_data_type=Clusters.DoorLock.Enums.LockDataTypeEnum.kAliroEvictableEndpointKey, + operation_source=Clusters.DoorLock.Enums.OperationSourceEnum.kRemote, user_index=1, + data_index=1, fabric_index=self.fabric_idx1, node_id=self.matter_test_config.controller_node_id, + data_type_operation=Clusters.DoorLock.Enums.DataOperationTypeEnum.kAdd, priority=EventPriority.INFO + ) + # step 20 + await self.get_credentials_status(credentialIndex=1, + credentialType=cluster.Enums.CredentialTypeEnum.kAliroEvictableEndpointKey, + step="20", userIndex=1) + # step 21 + evictable_credentials = cluster.Structs.CredentialStruct(credentialIndex=1, + credentialType=cluster.Enums.CredentialTypeEnum.kAliroEvictableEndpointKey) + await self.clear_credentials_cmd(step="21", credential=evictable_credentials) + + # step 22 + self.step("22") + await self.read_and_validate_lock_event_change( + verify_lock_data_type=Clusters.DoorLock.Enums.LockDataTypeEnum.kAliroEvictableEndpointKey, + operation_source=Clusters.DoorLock.Enums.OperationSourceEnum.kRemote, user_index=1, + data_index=1, fabric_index=self.fabric_idx1, node_id=self.matter_test_config.controller_node_id, + data_type_operation=Clusters.DoorLock.Enums.DataOperationTypeEnum.kClear, priority=EventPriority.INFO + ) + + # step 23 + await self.set_credential_cmd(step="23", credentialData=self.alirononevictableendpointkey, + operationType=cluster.Enums.DataOperationTypeEnum.kAdd, + credential_enum=cluster.Enums.CredentialTypeEnum.kAliroNonEvictableEndpointKey, + credentialIndex=1, userIndex=1, userStatus=NullValue, userType=NullValue) + # step 24 + self.step("24") + await self.read_and_validate_lock_event_change( + verify_lock_data_type=Clusters.DoorLock.Enums.LockDataTypeEnum.kAliroNonEvictableEndpointKey, + operation_source=Clusters.DoorLock.Enums.OperationSourceEnum.kRemote, user_index=1, + data_index=1, fabric_index=self.fabric_idx1, node_id=self.matter_test_config.controller_node_id, + data_type_operation=Clusters.DoorLock.Enums.DataOperationTypeEnum.kAdd, priority=EventPriority.INFO + ) + + # step 25 + await self.get_credentials_status(step="25", credentialIndex=1, + credentialType=cluster.Enums.CredentialTypeEnum.kAliroNonEvictableEndpointKey, + userIndex=1) + + # step 26 + non_evictable_credentials = cluster.Structs.CredentialStruct(credentialIndex=1, + credentialType=cluster.Enums.CredentialTypeEnum.kAliroNonEvictableEndpointKey) + await self.clear_credentials_cmd(step="26", credential=non_evictable_credentials) + + # step 27 + self.step("27") + await self.read_and_validate_lock_event_change( + verify_lock_data_type=Clusters.DoorLock.Enums.LockDataTypeEnum.kAliroNonEvictableEndpointKey, + operation_source=Clusters.DoorLock.Enums.OperationSourceEnum.kRemote, user_index=1, + data_index=1, fabric_index=self.fabric_idx1, node_id=self.matter_test_config.controller_node_id, + data_type_operation=Clusters.DoorLock.Enums.DataOperationTypeEnum.kClear, priority=EventPriority.INFO + ) + + # step 28 + self.step("28a") + if self.check_pics("DRLK.S.A001c"): + self.numberofcredentialsupportedperuser = await self.read_attributes_from_dut( + endpoint=self.app_cluster_endpoint, + cluster=Clusters.Objects.DoorLock, + attribute=Clusters.DoorLock.Attributes.NumberOfCredentialsSupportedPerUser) + self.step("28b") + await self.clear_all_aliro_credential() + await self.send_clear_user_cmd(user_index=1) + if self.pics_guard(self.check_pics("DRLK.S.A001c") and self.check_pics("DRLK.S.A0088")): + if self.max_aliro_keys_supported > self.numberofcredentialsupportedperuser: + logging.info( + "Skipping execution from Step 29a to step 35 since 'max_aliro_keys_supported > numberofcredentialsupportedperuser' as per test plan spec") + self.skip_all_remaining_steps("29a") + else: + # Perform setUser as we have removed user in previous step and SetCredentials always expects a user with index to be present + self.step("29a") + if self.pics_guard(self.check_pics("DRLK.S.F08") and self.check_pics("DRLK.S.C1a.Rsp")): + try: + await self.send_single_cmd(cmd=Clusters.Objects.DoorLock.Commands.SetUser( + operationType=Clusters.DoorLock.Enums.DataOperationTypeEnum.kAdd, + userIndex=1, + userName="alirouser", + userUniqueID=111, + userStatus=Clusters.DoorLock.Enums.UserStatusEnum.kOccupiedEnabled, + userType=Clusters.DoorLock.Enums.UserTypeEnum.kUnrestrictedUser, + credentialRule=Clusters.DoorLock.Enums.CredentialRuleEnum.kSingle), + endpoint=self.app_cluster_endpoint, + timedRequestTimeoutMs=1000) + except InteractionModelError as e: + logging.exception(e) + asserts.assert_equal(e.status, Status.Success, f"Unexpected error returned: {e}") + self.step("29b") + logging.info("setting 'start_credential_index' to value 1 ") + start_credential_index = 1 + credentials_data = self.alirononevictableendpointkey + while 1: + if start_credential_index <= (self.max_aliro_keys_supported - 2): + if start_credential_index != 1: + credentials_data = self.generate_unique_octbytes() + + await self.set_credential_cmd(credentialData=credentials_data, + operationType=cluster.Enums.DataOperationTypeEnum.kAdd, + credential_enum=cluster.Enums.CredentialTypeEnum.kAliroNonEvictableEndpointKey, + credentialIndex=start_credential_index, userIndex=1, + userStatus=NullValue, + userType=NullValue) + start_credential_index += 1 + logging.info(f"The updated value of start_credential_index is {start_credential_index}") + else: + break + + # step 30 + logging.info(f"the value of start_credential_index is {start_credential_index} for step 30") + self.step("30") + await self.set_credential_cmd(credentialData=self.alirononevictableendpointkey, + operationType=cluster.Enums.DataOperationTypeEnum.kAdd, + credential_enum=cluster.Enums.CredentialTypeEnum.kAliroEvictableEndpointKey, + credentialIndex=start_credential_index, userIndex=1, userStatus=NullValue, + userType=NullValue) + # step 31 + self.step("31") + await self.set_credential_cmd(credentialData=self.alirononevictableendpointkey1, + operationType=cluster.Enums.DataOperationTypeEnum.kAdd, + credential_enum=cluster.Enums.CredentialTypeEnum.kAliroNonEvictableEndpointKey, + credentialIndex=start_credential_index, userIndex=1, userStatus=NullValue, + userType=NullValue) + # step 32 + dut_get_cred_response = await self.get_credentials_status(step="32", + credentialIndex=start_credential_index, + credentialType=cluster.Enums.CredentialTypeEnum.kAliroEvictableEndpointKey, + credential_exists=False, userIndex=NullValue) + asserts.assert_equal(dut_get_cred_response.credentialExists, NullValue, + f"Error when comparing for {dut_get_cred_response} of null") + + # step 33 + await self.get_credentials_status(step="33", credentialIndex=start_credential_index, + credentialType=cluster.Enums.CredentialTypeEnum.kAliroNonEvictableEndpointKey, + credential_exists=True, userIndex=1) + # step 34 + self.step("34") + await self.clear_all_aliro_credential() + + # step 35 + self.step("35") + await self.send_clear_user_cmd(user_index=1) + + +if __name__ == '__main__': + default_matter_test_main() From d169234e7847d4a425b6d68d6d005699a167c920 Mon Sep 17 00:00:00 2001 From: Wang Qixiang <43193572+wqx6@users.noreply.github.com> Date: Sat, 10 Aug 2024 04:13:33 +0800 Subject: [PATCH 007/165] fix ESP Thread Border Router example (#34896) --- examples/thread-br-app/esp32/main/main.cpp | 2 ++ examples/thread-br-app/esp32/partitions.csv | 4 ++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/examples/thread-br-app/esp32/main/main.cpp b/examples/thread-br-app/esp32/main/main.cpp index d419e2a735..dcafcc1c74 100644 --- a/examples/thread-br-app/esp32/main/main.cpp +++ b/examples/thread-br-app/esp32/main/main.cpp @@ -88,6 +88,8 @@ static void InitServer(intptr_t context) sThreadBRDelegate = chip::Platform::New(storageDelegate); sThreadBRMgmtInstance = chip::Platform::New( kThreadBRMgmtEndpoint, sThreadBRDelegate, chip::Server::GetInstance().GetFailSafeContext()); + char borderRouterName[] = "Espressif-ThreadBR"; + sThreadBRDelegate->SetThreadBorderRouterName(CharSpan(borderRouterName)); sThreadBRMgmtInstance->Init(); } diff --git a/examples/thread-br-app/esp32/partitions.csv b/examples/thread-br-app/esp32/partitions.csv index c451874965..745321df37 100644 --- a/examples/thread-br-app/esp32/partitions.csv +++ b/examples/thread-br-app/esp32/partitions.csv @@ -4,5 +4,5 @@ nvs, data, nvs, , 0xC000, otadata, data, ota, , 0x2000, phy_init, data, phy, , 0x1000, ota_0, app, ota_0, , 1800K, -ota_1, app, ota_1, , 1200K, -rcp_fw, data, spiffs, , 640K, +ota_1, app, ota_1, , 1800K, +rcp_fw, data, spiffs, , 300K, From 4996fdc664dd0daba3619a81f9a283c3421b831f Mon Sep 17 00:00:00 2001 From: mkardous-silabs <84793247+mkardous-silabs@users.noreply.github.com> Date: Fri, 9 Aug 2024 16:35:05 -0400 Subject: [PATCH 008/165] [ICD] Add ICDM 3.4 Python Tests (#34784) * Add ICDM 3.4 Python Tests * Restyled by isort * Delete yaml since it was replaced with python --------- Co-authored-by: Restyled.io --- .../certification/Test_TC_ICDM_3_4.yaml | 201 ------------------ src/app/tests/suites/ciTests.json | 1 - src/python_testing/TC_ICDM_3_4.py | 119 +++++++++++ 3 files changed, 119 insertions(+), 202 deletions(-) delete mode 100644 src/app/tests/suites/certification/Test_TC_ICDM_3_4.yaml create mode 100644 src/python_testing/TC_ICDM_3_4.py diff --git a/src/app/tests/suites/certification/Test_TC_ICDM_3_4.yaml b/src/app/tests/suites/certification/Test_TC_ICDM_3_4.yaml deleted file mode 100644 index a4eb232b98..0000000000 --- a/src/app/tests/suites/certification/Test_TC_ICDM_3_4.yaml +++ /dev/null @@ -1,201 +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. - -name: 217.1.6. [TC-ICDM-3.4] ICDCounter persistence with DUT as Server - -PICS: - - ICDM.S - -config: - nodeId: 0x12344321 - cluster: "ICD Management" - endpoint: 0 - - CheckInNodeID1: - type: node_id - defaultValue: 1 - MonitorSubID1: - type: subject-id - defaultValue: 2 - Key1: - type: octstr - defaultValue: "hex:1234567890abcdef1234567890abcdef" - IdleModedurationValue: - type: int16u - defaultValue: 5 - -tests: - - label: - "Precondition: Commission DUT to TH (can be skipped if done in a - preceding test)" - cluster: "DelayCommands" - command: "WaitForCommissionee" - arguments: - values: - - name: "nodeId" - value: nodeId - - - label: - "Precondition: TH reads the RegisteredClients attribute from the DUT" - PICS: ICDM.S.A0003 - command: "readAttribute" - attribute: "RegisteredClients" - response: - saveAs: RegisteredClientsIDs - constraints: - type: list - - - label: - "Precondition: If list of registered clients is not empty, unregister - existing client(s)" - verification: | - Please send the 'unregister client' command using the check-in nodeID received from the previous read - ./chip-tool icdmanagement unregister-client 112233 1 0 - - [1704888949.629057][71657:71659] CHIP:DMG: - [1704888949.629066][71657:71659] CHIP:DMG: InteractionModelRevision = 11 - [1704888949.629074][71657:71659] CHIP:DMG: }, - [1704888949.629125][71657:71659] CHIP:DMG: Received Command Response Status for Endpoint=0 Cluster=0x0000_0046 Command=0x0000_0002 Status=0x0 - [1704888949.629153][71657:71659] CHIP:DMG: ICR moving to [AwaitingDe] - cluster: "LogCommands" - command: "UserPrompt" - PICS: PICS_USER_PROMPT && ICDM.S.C02.Rsp - arguments: - values: - - name: "message" - value: "Please enter 'y' for success" - - name: "expectedValue" - value: "y" - - - label: - "Precondition: TH reads from the DUT the RegisteredClients attribute. - Verify that the DUT response contains empty list of registered - clients." - PICS: ICDM.S.A0003 && PICS_USER_PROMPT - command: "readAttribute" - attribute: "RegisteredClients" - response: - value: [] - constraints: - type: list - - - label: "Step 1: TH reads from the DUT the IdleModeDuration attribute" - PICS: ICDM.S.A0000 - command: "readAttribute" - attribute: "IdleModeDuration" - response: - saveAs: IdleModeDuration1 - constraints: - type: int32u - minValue: 1 - maxValue: 64800 - - - label: "Step 2: TH reads from the DUT the ICDCounter attribute." - PICS: ICDM.S.A0004 - command: "readAttribute" - attribute: "ICDCounter" - response: - saveAs: ICDCounter1 - constraints: - type: int32u - minValue: 0 - maxValue: 4294967295 - - - label: - "Step 3a & 3b: TH sends RegisterClient command. - CheckInNodeID: - registering clients node ID (CheckInNodeID1) - MonitoredSubject: - monitored subject ID (MonitorSubID1) - Key: shared secret between the - client and the ICD (Key1). Verify DUT responds w/ status - SUCCESS(0x00); Verify that the DUT response contains IcdCounter1" - PICS: ICDM.S.C00.Rsp && ICDM.S.C01.Tx - command: "RegisterClient" - arguments: - values: - - name: "CheckInNodeID" - value: CheckInNodeID1 - - name: "MonitoredSubject" - value: MonitorSubID1 - - name: "Key" - value: Key1 - # Adding input for the test to pass for now - Full test script needs to be updated - - name: "ClientType" - value: ClientTypeEnum.Permanent - response: - values: - - name: "ICDCounter" - value: ICDCounter1 - constraints: - type: int32u - - - label: "Step 4: Wait for 1 or more Idle Mode duration." - cluster: "DelayCommands" - command: "WaitForMs" - arguments: - values: - - name: "ms" - value: ( IdleModedurationValue * 1000 ) - - #Issue https://github.com/project-chip/connectedhomeip/issues/31297 - - label: "Step 5: TH reads from the DUT the ICDCounter attribute." - verification: | - ./chip-tool icdmanagement read icdcounter 1 0 - - [1702421000.635860][1431:1433] CHIP:TOO: Endpoint: 0 Cluster: 0x0000_0046 Attribute 0x0000_0004 DataVersion: 2255930497 - [1702421000.635970][1431:1433] CHIP:TOO: ICDCounter: 1706188496 - cluster: "LogCommands" - command: "UserPrompt" - PICS: PICS_USER_PROMPT && ICDM.S.A0004 - arguments: - values: - - name: "message" - value: "Please enter 'y' for success" - - name: "expectedValue" - value: "y" - - - label: "Step 6: Reboot DUT" - PICS: PICS_SDK_CI_ONLY - cluster: "SystemCommands" - endpoint: 0 - command: "Reboot" - - - label: "Step Reboot target device(DUT)" - verification: | - Did the DUT successfully reboot? - cluster: "LogCommands" - command: "UserPrompt" - PICS: PICS_SKIP_SAMPLE_APP - arguments: - values: - - name: "message" - value: "Please reboot the DUT and enter 'y' after DUT starts" - - name: "expectedValue" - value: "y" - - - label: "Wait for the commissioned device to be retrieved" - cluster: "DelayCommands" - command: "WaitForCommissionee" - arguments: - values: - - name: "nodeId" - value: nodeId - - - label: "Step 7: TH reads from the DUT the ICDCounter attribute." - PICS: ICDM.S.A0004 && PICS_USER_PROMPT - command: "readAttribute" - attribute: "ICDCounter" - response: - constraints: - type: int32u - minValue: ICDCounter2 - maxValue: 4294967295 diff --git a/src/app/tests/suites/ciTests.json b/src/app/tests/suites/ciTests.json index 1e2410650b..d976d76232 100644 --- a/src/app/tests/suites/ciTests.json +++ b/src/app/tests/suites/ciTests.json @@ -71,7 +71,6 @@ "IcdManagement": [ "TestIcdManagementCluster", "Test_TC_ICDM_1_1", - "Test_TC_ICDM_3_4", "Test_TC_ICDM_4_1" ], "Identify": ["Test_TC_I_2_1", "Test_TC_I_2_2", "Test_TC_I_2_3"], diff --git a/src/python_testing/TC_ICDM_3_4.py b/src/python_testing/TC_ICDM_3_4.py new file mode 100644 index 0000000000..6123053217 --- /dev/null +++ b/src/python_testing/TC_ICDM_3_4.py @@ -0,0 +1,119 @@ + +# +# Copyright (c) 2023 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. +# + +# See https://github.com/project-chip/connectedhomeip/blob/master/docs/testing/python.md#defining-the-ci-test-arguments +# for details about the block below. +# +# === BEGIN CI TEST ARGUMENTS === +# test-runner-runs: run1 +# test-runner-run/run1/app: ${LIT_ICD_APP} +# test-runner-run/run1/factoryreset: True +# test-runner-run/run1/quiet: True +# test-runner-run/run1/app-args: --discriminator 1234 --KVS kvs1 --trace-to json:${TRACE_APP}.json +# test-runner-run/run1/script-args: --storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --PICS src/app/tests/suites/certification/ci-pics-values --trace-to json:${TRACE_TEST_JSON}.json --trace-to perfetto:${TRACE_TEST_PERFETTO}.perfetto +# === END CI TEST ARGUMENTS === + +import logging +import time + +import chip.clusters as Clusters +from matter_testing_support import MatterBaseTest, TestStep, async_test_body, default_matter_test_main +from mobly import asserts + +logger = logging.getLogger(__name__) + +kRootEndpointId = 0 +cluster = Clusters.Objects.IcdManagement +attributes = cluster.Attributes + + +class TC_ICDM_3_4(MatterBaseTest): + + # + # Class Helper functions + # + async def _read_icdm_attribute_expect_success(self, attribute): + return await self.read_single_attribute_check_success(endpoint=kRootEndpointId, cluster=cluster, attribute=attribute) + + # + # Test Harness Helpers + # + + def desc_TC_ICDM_3_4(self) -> str: + """Returns a description of this test""" + return "[TC-ICDM-3.4] ICDCounter Persistence with DUT as Server" + + def steps_TC_ICDM_3_4(self) -> list[TestStep]: + steps = [ + TestStep(0, "Commissioning, already done", is_commissioning=True), + TestStep(1, "TH reads from the DUT the ICDCounter attribute."), + TestStep("2a", "Reboot DUT."), + TestStep("2b", "TH waits for {PIXIT.WAITTIME.REBOOT}"), + TestStep(3, "Verify that the DUT response contains value of ICDCounter and stores in IcdCounter2. \ + IcdCounter2 is greater or equal to IcdCounter1. \ + ICDCounter attribute can roll over. If the attribute rolls over, it will be greater or equal to 0.") + ] + return steps + + def pics_TC_ICDM_3_4(self) -> list[str]: + """ This function returns a list of PICS for this test case that must be True for the test to be run""" + pics = [ + "ICDM.S", + "ICDM.S.F00" + ] + return pics + + # + # ICDM 3.4 Test Body + # + + @async_test_body + async def test_TC_ICDM_3_4(self): + is_ci = self.check_pics("PICS_SDK_CI_ONLY") + + if not is_ci: + asserts.assert_true('PIXIT.WAITTIME.REBOOT' in self.matter_test_config.global_test_params, + "PIXIT.WAITTIME.REBOOT must be included on the command line in " + "the --int-arg flag as PIXIT.WAITTIME.REBOOT:") + + wait_time_reboot = self.matter_test_config.global_test_params['PIXIT.WAITTIME.REBOOT'] + if wait_time_reboot == 0: + asserts.fail("PIXIT.WAITTIME.REBOOT shall be higher than 0.") + + # Pre-Condition: Commissioning + self.step(0) + + self.step(1) + icdCounter1 = await self._read_icdm_attribute_expect_success(attribute=attributes.ICDCounter) + + self.step("2a") + if not is_ci: + self.wait_for_user_input(prompt_msg="Restart DUT. Press Enter when restart has been initiated.") + + self.step("2b") + if not is_ci: + time.sleep(wait_time_reboot) + + self.step(3) + icdCounter2 = await self._read_icdm_attribute_expect_success(attribute=attributes.ICDCounter) + asserts.assert_greater_equal(icdCounter2, icdCounter1, + "ICDCounter have reboot is not greater or equal to the ICDCounter read before the reboot.") + + +if __name__ == "__main__": + default_matter_test_main() From 43179703e20caf6d06f9c299324a3371bc094737 Mon Sep 17 00:00:00 2001 From: William Date: Fri, 9 Aug 2024 22:53:27 +0100 Subject: [PATCH 009/165] Fixed some attribute access errors and improved the logic following the new lanmark structure. (#34908) --- src/python_testing/TC_SEAR_1_2.py | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/src/python_testing/TC_SEAR_1_2.py b/src/python_testing/TC_SEAR_1_2.py index a938ae6c31..939f4be638 100644 --- a/src/python_testing/TC_SEAR_1_2.py +++ b/src/python_testing/TC_SEAR_1_2.py @@ -59,7 +59,7 @@ async def read_and_validate_supported_maps(self, step): self.print_step(step, "Read SupportedMaps attribute") supported_maps = await self.read_sear_attribute_expect_success( endpoint=self.endpoint, attribute=Clusters.ServiceArea.Attributes.SupportedMaps) - logging.info("SupportedMaps: %s" % (supported_maps)) + logging.info("SupportedMaps: %s" % supported_maps) asserts.assert_less_equal(len(supported_maps), 255, "SupportedMaps should have max 255 entries") @@ -69,14 +69,14 @@ async def read_and_validate_supported_maps(self, step): name_list = [m.name for m in supported_maps] asserts.assert_true(len(set(name_list)) == len(name_list), "SupportedMaps must have unique Name values!") - # save so other methods can use this if neeeded + # save so other methods can use this if needed self.mapid_list = mapid_list async def read_and_validate_supported_areas(self, step): self.print_step(step, "Read SupportedAreas attribute") supported_areas = await self.read_sear_attribute_expect_success( endpoint=self.endpoint, attribute=Clusters.ServiceArea.Attributes.SupportedAreas) - logging.info("SupportedAreas: %s" % (supported_areas)) + logging.info("SupportedAreas: %s" % supported_areas) asserts.assert_less_equal(len(supported_areas), 255, "SupportedAreas should have max 255 entries") areaid_list = [] @@ -103,15 +103,16 @@ async def read_and_validate_supported_areas(self, step): asserts.assert_true(k not in areadesc_s, f"SupportedAreas must have unique AreaDesc({a.areaDesc}) values!") areadesc_s.add(k) - if a.locationInfo is NullValue and a.landmarkTag is NullValue: + if a.areaDesc.locationInfo is NullValue and a.areaDesc.landmarkInfo is NullValue: asserts.assert_true( - f"SupportedAreas entry with AreaID({a.areaID}) should not have null LocationInfo and null LandmarkTag") - if a.landmarkTag is not NullValue: - asserts.assert_true(a.landmarkTag <= self.MAX_LANDMARK_ID, - f"SupportedAreas entry with AreaID({a.areaID}) has invalid LandmarkTag({a.landmarkTag})") - asserts.assert_true(a.positionTag is NullValue or a.positionTag in range(0, self.MAX_RELPOS_ID), - f"SupportedAreas entry with AreaID({a.areaID}) has invalid PositionTag({a.positionTag})") - # save so other methods can use this if neeeded + f"SupportedAreas entry with AreaID({a.areaID}) should not have null LocationInfo and null LandmarkInfo") + if a.areaDesc.landmarkInfo is not NullValue: + asserts.assert_true(a.areaDesc.landmarkInfo.landmarkTag <= self.MAX_LANDMARK_ID, + f"SupportedAreas entry with AreaID({a.areaID}) has invalid LandmarkTag({a.areaDesc.landmarkInfo.landmarkTag})") + asserts.assert_true(a.areaDesc.landmarkInfo.positionTag is NullValue or a + .areaDesc.landmarkInfo.positionTag in range(0, self.MAX_RELPOS_ID), + f"SupportedAreas entry with AreaID({a.areaID}) has invalid PositionTag({a.areaDesc.landmarkInfo.positionTag})") + # save so other methods can use this if needed self.areaid_list = areaid_list async def read_and_validate_selected_areas(self, step): @@ -130,7 +131,7 @@ async def read_and_validate_selected_areas(self, step): for a in selected_areas: asserts.assert_true(a in self.areaid_list, f"SelectedAreas entry {a} has invalid value") - # save so other methods can use this if neeeded + # save so other methods can use this if needed self.selareaid_list = selected_areas async def read_and_validate_current_area(self, step): @@ -143,7 +144,7 @@ async def read_and_validate_current_area(self, step): or current_area in self.selareaid_list, f"CurrentArea {current_area} is invalid. SelectedAreas is {self.selareaid_list}.") - # save so other methods can use this if neeeded + # save so other methods can use this if needed self.current_area = current_area async def read_and_validate_estimated_end_time(self, step): From 6c3abfbbfd11a82a7dbf7d2ae4f36454f8c6a1e6 Mon Sep 17 00:00:00 2001 From: Axel Le Bourhis <45206070+axelnxp@users.noreply.github.com> Date: Sat, 10 Aug 2024 00:33:41 +0200 Subject: [PATCH 010/165] Bump west version to 1.2.0 (#34909) west 1.0.0 is not compatible with Zephyr 3.7 LTS, so bumping to latest 1.2.0 Signed-off-by: Axel Le Bourhis --- scripts/setup/constraints.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/setup/constraints.txt b/scripts/setup/constraints.txt index a5af1b462f..3f396a83c7 100644 --- a/scripts/setup/constraints.txt +++ b/scripts/setup/constraints.txt @@ -273,7 +273,7 @@ wcwidth==0.2.6 # via prompt-toolkit websockets==10.4 # via -r requirements.all.txt -west==1.0.0 +west==1.2.0 # via -r requirements.zephyr.txt wheel==0.38.4 ; sys_platform == "linux" # via From d977749bad5031c45bb925d42e955919dd4f7bbe Mon Sep 17 00:00:00 2001 From: William Date: Sat, 10 Aug 2024 00:21:06 +0100 Subject: [PATCH 011/165] Fix test 1.3 and 1.4 (#34911) * Updated the golabl data type's XMLs, removing the cluster entries. * Zap generated after XML update. * Fixed namespaces used of global structs. * Restyled by clang-format * Renamed LocationInfoStruct to AreaInfoStruct. * Zap generated after XML update. * Renamed LocationStruct to AreaStruct and its LocationID and LocationDesc fields. * Zap generated after XML update. * Updated SDK and example code to match the new naming. * Updated the ProgressStruct's LocationID name to AreaID. * Zap generated after XML update. * Updated the SDK code following name changes. * Updated the SelectLocationsStatus and SkipLocationStatus enum names and some of their enums. * Zap generated after XML update. * Updated the SelectLocationsStatus and SkipCurrentLocationStatus names and their enum names. * Updated the names of the SupportedLocations, SelectedLocations and CurrentLocation attributes. * Zap generated after XML update. * Updated the changed names in the SDK. * Updated the service area command names in XML. * Zap generated after XML update. * Updated the service area command names in the SDK. * Updated the rvc-example zap file. * Refactored LocationStructureWrapper to AreaStructureWrapper. * Restyled by clang-format * Regenerated zap files due to changes upsteram. * Removed unused generated file. * Updated the Service Area XML marking previously nullabel attributes as not-nullable. * Zap generated after XML update. * Updated the attribute encoding and some server logic following the romoval of the nullable quality for some attributes. * Explicitly set the Service Area version. * Zap generated after XML update. * Updated the service area features in the XML to match the current spec. * Zap generated after XML update. * Updated the SupportedArea validation logic as if the MAPS feature is not supported, the Delegate may choose not to implement map related methods. * Change the type of the MapID to uint32 to match the spec. * Added the SkippedArea arg to the SkipArea command. * Zap generated after XML update. * Updated the Service Area server code to handle the new SkippedArea command arg. * Updated the service area XML to match the current spec. This includes the addition of the LandmarkInfoStruct and updates of AreaInfoStruct, SelectAreasStatus. * Zap generated after XML update. * Updated SDK server code and rvc-example after changes to the XML. * Restyled by whitespace * added vector include. * spacing changes form zap regen. * Fixed minor mistake during merge. * Restyled by clang-format * Applied suggestions from review. * Restyled by whitespace * Updated the LondmarkInfoSturct PositionTag type. * Zap generated after XML update. * Fixed SDK following update to the position type. * Restyled by clang-format * Updated the AeraStructWrapper to not contain methods with a large number of params. Updated some relate Instance and Delegate methods. * Restyled by whitespace * Restyled by clang-format * Missed a submudule update. * Made the setters reture a ref to the sturct to allow chaining. * simplified the = oporator and add the == operator. * Restyled by clang-format * Added methods to set the SupportedMaps and SupproctedAreas. * Updated the RVC app to provide a way to defined service area methods that interacte with other clusters in the RvcDevice class. * Fixed typo. * minor change to get restyler going. * Restyled by clang-format * Fixed status text referance issue. * Fixed issue casued by a change in the way that registrations are made. * Fixed styling and minor bug in IsValidSupportedArea. * Implemented the IsValidSelectAreasSet method. * implemented SaHandleSkipCurrentArea. * Restyled by clang-format * Added methods to updated the service area current area and progress attributes when the device starts operating. * Updated the handle skip area method to use the GoToNextArea method. * Added the AreaComplete out-of-band message. * updated the reset evet handler to reset the service area attributes. * minor shifing of responsibilites. * Restyled by clang-format * reverted to adding the PID to the fifo name. * Updated readme and pics files. * Restyled by prettier-markdown * Fixed tests 1.3 and 1.4. Updated the readme and the pics. * Restyled by prettier-markdown --------- Co-authored-by: Restyled.io --- examples/rvc-app/README.md | 20 ++++++++++ .../rvc-common/pics/rvc-app-pics-values | 2 +- src/python_testing/TC_SEAR_1_3.py | 37 +++++++++++-------- src/python_testing/TC_SEAR_1_4.py | 4 -- 4 files changed, 43 insertions(+), 20 deletions(-) diff --git a/examples/rvc-app/README.md b/examples/rvc-app/README.md index 7431c663ef..1be714fb43 100644 --- a/examples/rvc-app/README.md +++ b/examples/rvc-app/README.md @@ -136,3 +136,23 @@ to transition to the required states. After commissioning the device, all the yaml tests can be run by running the `run_all_yaml_tests.sh` script from the root dir with the node ID that the device was commissioned with. + +### Service Area Cluster + +### TC 1.2 + +Example command: +`./scripts/tests/run_python_test.py --script src/python_testing/TC_SEAR_1_2.py --script-args "--storage-path admin_storage.json --PICS examples/rvc-app/rvc-common/pics/rvc-app-pics-values --endpoint 1"` + +### TC 1.3 + +todo once the +[test plan issue](https://github.com/CHIP-Specifications/chip-test-plans/issues/4454) +is resolved, add the required PIXIT and set the +PICS`SEAR.S.M.VALID_STATE_FOR_SELECT_AREAS=1`. PIXIT: `` Example command: +`./scripts/tests/run_python_test.py --script src/python_testing/TC_SEAR_1_3.py --script-args "--storage-path admin_storage.json --PICS examples/rvc-app/rvc-common/pics/rvc-app-pics-values --endpoint 1` + +### TC 1.4 + +Example command: +`./scripts/tests/run_python_test.py --script src/python_testing/TC_SEAR_1_4.py --script-args "--storage-path admin_storage.json --PICS examples/rvc-app/rvc-common/pics/rvc-app-pics-values --endpoint 1` diff --git a/examples/rvc-app/rvc-common/pics/rvc-app-pics-values b/examples/rvc-app/rvc-common/pics/rvc-app-pics-values index b158de538e..24558915f6 100644 --- a/examples/rvc-app/rvc-common/pics/rvc-app-pics-values +++ b/examples/rvc-app/rvc-common/pics/rvc-app-pics-values @@ -70,7 +70,7 @@ SEAR.S.M.ADD_AREA=0 SEAR.S.M.REMOVE_MAP=0 SEAR.S.M.ADD_MAP=0 SEAR.S.M.INVALID_STATE_FOR_SELECT_AREAS=1 -SEAR.S.M.VALID_STATE_FOR_SELECT_AREAS=1 +SEAR.S.M.VALID_STATE_FOR_SELECT_AREAS=0 SEAR.S.M.SELECT_AREAS_WHILE_NON_IDLE=1 SEAR.S.M.HAS_MANUAL_SELAREA_STATE_CONTROL=1 SEAR.S.M.HAS_MANUAL_SKIP_STATE_CONTROL=1 diff --git a/src/python_testing/TC_SEAR_1_3.py b/src/python_testing/TC_SEAR_1_3.py index 3e8d60fa6a..2ea2e86b7d 100644 --- a/src/python_testing/TC_SEAR_1_3.py +++ b/src/python_testing/TC_SEAR_1_3.py @@ -51,7 +51,7 @@ async def read_supported_areas(self, step): self.print_step(step, "Read SupportedAreas attribute") supported_areas = await self.read_sear_attribute_expect_success( endpoint=self.endpoint, attribute=Clusters.ServiceArea.Attributes.SupportedAreas) - logging.info("SupportedAreas: %s" % (supported_areas)) + logging.info("SupportedAreas: %s" % supported_areas) self.supported_areas = supported_areas @@ -70,16 +70,16 @@ async def send_cmd_select_areas_expect_response(self, step, new_areas, expected_ ret = await self.send_single_cmd(cmd=Clusters.Objects.ServiceArea.Commands.SelectAreas(newAreas=new_areas), endpoint=self.endpoint) - asserts.assert_equal(ret.commandResponseState.errorStateID, + asserts.assert_equal(ret.status, expected_response, - f"Command response ({ret.commandResponseState}) doesn't match the expected one") + f"Command response ({ret.status}) doesn't match the expected one") # Sends and out-of-band command to the rvc-app def write_to_app_pipe(self, command): with open(self.app_pipe, "w") as app_pipe: app_pipe.write(command + "\n") # Allow some time for the command to take effect. - # This removes the test flakyness which is very annoying for everyone in CI. + # This removes the test flakiness which is very annoying for everyone in CI. sleep(0.001) def TC_SEAR_1_3(self) -> list[str]: @@ -110,47 +110,54 @@ async def test_TC_SEAR_1_3(self): duplicated_areas = [valid_area_id, valid_area_id] # FIXME need to check if this is the correct name of this status code - await self.send_cmd_select_areas_expect_response(step=3, new_areas=duplicated_areas, expected_response=Clusters.ServiceArea.SelectAreasStatus.kDuplicatedAreas) + await self.send_cmd_select_areas_expect_response(step=3, new_areas=duplicated_areas, expected_response=Clusters.ServiceArea.Enums.SelectAreasStatus.kDuplicatedAreas) - await self.send_cmd_select_areas_expect_response(step=4, new_areas=[], expected_response=Clusters.ServiceArea.SelectAreasStatus.kSuccess) + await self.send_cmd_select_areas_expect_response(step=4, new_areas=[], expected_response=Clusters.ServiceArea.Enums.SelectAreasStatus.kSuccess) selected_areas = await self.read_selected_areas(step=5) asserts.assert_true(len(selected_areas) == 0, "SelectedAreas should be empty") - await self.send_cmd_select_areas_expect_response(step=6, new_areas=[invalid_area_id], expected_response=Clusters.ServiceArea.SelectAreasStatus.kUnsupportedArea) + await self.send_cmd_select_areas_expect_response(step=6, new_areas=[invalid_area_id], expected_response=Clusters.ServiceArea.Enums.SelectAreasStatus.kUnsupportedArea) if self.check_pics("SEAR.S.M.INVALID_STATE_FOR_SELECT_AREAS") and self.check_pics("SEAR.S.M.HAS_MANUAL_SELAREA_STATE_CONTROL"): test_step = "Manually intervene to put the device in a state that prevents it from executing the SelectAreas command" self.print_step("7", test_step) - if not self.is_ci: + if self.is_ci: + await self.send_single_cmd(cmd=Clusters.Objects.RvcRunMode.Commands.ChangeToMode(newMode=1), endpoint=self.endpoint) + else: self.wait_for_user_input(prompt_msg=f"{test_step}, and press Enter when done.\n") - await self.send_cmd_select_areas_expect_response(step=8, new_areas=[valid_area_id], expected_response=Clusters.ServiceArea.SelectAreasStatus.kInvalidInMode) + await self.send_cmd_select_areas_expect_response(step=8, new_areas=[valid_area_id], expected_response=Clusters.ServiceArea.Enums.SelectAreasStatus.kInvalidInMode) if self.check_pics("SEAR.S.M.VALID_STATE_FOR_SELECT_AREAS") and self.check_pics("SEAR.S.M.HAS_MANUAL_SELAREA_STATE_CONTROL"): test_step = f"Manually intervene to put the device in a state that allows it to execute the SelectAreas({supported_area_ids}) command" self.print_step("9", test_step) - if not self.is_ci: + if self.is_ci: + self.write_to_app_pipe('{"Name": "Reset"}') + else: self.wait_for_user_input(prompt_msg=f"{test_step}, and press Enter when done.\n") - await self.send_cmd_select_areas_expect_response(step=10, new_areas=supported_area_ids, expected_response=Clusters.ServiceArea.SelectAreasStatus.kSuccess) + await self.send_cmd_select_areas_expect_response(step=10, new_areas=supported_area_ids, expected_response=Clusters.ServiceArea.Enums.SelectAreasStatus.kSuccess) selected_areas = await self.read_selected_areas(step=11) asserts.assert_true(len(selected_areas) == len(supported_area_ids), f"SelectedAreas({selected_areas}) should match SupportedAreas({supported_area_ids})") - await self.send_cmd_select_areas_expect_response(step=12, new_areas=supported_area_ids, expected_response=Clusters.ServiceArea.SelectAreasStatus.kSuccess) + await self.send_cmd_select_areas_expect_response(step=12, new_areas=supported_area_ids, expected_response=Clusters.ServiceArea.Enums.SelectAreasStatus.kSuccess) if self.check_pics("SEAR.S.M.VALID_STATE_FOR_SELECT_AREAS") and self.check_pics("SEAR.S.M.HAS_MANUAL_SELAREA_STATE_CONTROL") and self.check_pics("SEAR.S.M.SELECT_AREAS_WHILE_NON_IDLE"): test_step = f"Manually intervene to put the device in a state that allows it to execute the SelectAreas({valid_area_id}) command, and put the device in a non-idle state" self.print_step("13", test_step) - if not self.is_ci: + if self.is_ci: + self.write_to_app_pipe('{"Name": "Reset"}') + await self.send_single_cmd(cmd=Clusters.Objects.RvcRunMode.Commands.ChangeToMode(newMode=1), endpoint=self.endpoint) + else: self.wait_for_user_input(prompt_msg=f"{test_step}, and press Enter when done.\n") if self.check_pics("SEAR.S.F00"): - await self.send_cmd_select_areas_expect_response(step=14, new_areas=[valid_area_id], expected_response=Clusters.ServiceArea.SelectAreasStatus.kSuccess) + await self.send_cmd_select_areas_expect_response(step=14, new_areas=[valid_area_id], expected_response=Clusters.ServiceArea.Enums.SelectAreasStatus.kSuccess) else: - await self.send_cmd_select_areas_expect_response(step=14, new_areas=[valid_area_id], expected_response=Clusters.ServiceArea.SelectAreasStatus.kInvalidInMode) + await self.send_cmd_select_areas_expect_response(step=14, new_areas=[valid_area_id], expected_response=Clusters.ServiceArea.Enums.SelectAreasStatus.kInvalidInMode) if __name__ == "__main__": diff --git a/src/python_testing/TC_SEAR_1_4.py b/src/python_testing/TC_SEAR_1_4.py index a6326559be..d31dcc2b13 100644 --- a/src/python_testing/TC_SEAR_1_4.py +++ b/src/python_testing/TC_SEAR_1_4.py @@ -62,10 +62,6 @@ async def test_TC_SEAR_1_4(self): self.print_step(1, "Commissioning, already done") - # Ensure that the device is in the correct state - if self.is_ci: - self.write_to_app_pipe('{"Name": "Reset"}') - attribute_list = await self.read_sear_attribute_expect_success( endpoint=self.endpoint, attribute=Clusters.ServiceArea.Attributes.AttributeList) logging.info("AttributeList: %s" % (attribute_list)) From b8c3627042d10ebe3ebb31fb58f5371f8ddebb05 Mon Sep 17 00:00:00 2001 From: William Date: Sat, 10 Aug 2024 00:55:15 +0100 Subject: [PATCH 012/165] Fixed test 1.5 and updated the scrict to work in CI. (#34915) --- src/python_testing/TC_SEAR_1_5.py | 59 +++++++++++++++++++------------ 1 file changed, 37 insertions(+), 22 deletions(-) diff --git a/src/python_testing/TC_SEAR_1_5.py b/src/python_testing/TC_SEAR_1_5.py index adcf8341c9..a90c1feaf9 100644 --- a/src/python_testing/TC_SEAR_1_5.py +++ b/src/python_testing/TC_SEAR_1_5.py @@ -52,7 +52,7 @@ async def read_supported_areas(self, step): self.print_step(step, "Read SupportedAreas attribute") supported_areas = await self.read_sear_attribute_expect_success( endpoint=self.endpoint, attribute=Clusters.ServiceArea.Attributes.SupportedAreas) - logging.info("SupportedAreas: %s" % (supported_areas)) + logging.info("SupportedAreas: %s" % supported_areas) return [a.areaID for a in supported_areas] @@ -85,9 +85,9 @@ async def send_cmd_skip_area_expect_response(self, step, skipped_area, expected_ ret = await self.send_single_cmd(cmd=Clusters.Objects.ServiceArea.Commands.SkipArea(skippedArea=skipped_area), endpoint=self.endpoint) - asserts.assert_equal(ret.commandResponseState.errorStateID, + asserts.assert_equal(ret.status, expected_response, - f"Command response ({ret.commandResponseState}) doesn't match the expected one") + f"Command response ({ret.status}) doesn't match the expected one") # Sends and out-of-band command to the rvc-app @@ -95,7 +95,7 @@ def write_to_app_pipe(self, command): with open(self.app_pipe, "w") as app_pipe: app_pipe.write(command + "\n") # Allow some time for the command to take effect. - # This removes the test flakyness which is very annoying for everyone in CI. + # This removes the test flakiness which is very annoying for everyone in CI. sleep(0.001) def TC_SEAR_1_5(self) -> list[str]: @@ -131,26 +131,35 @@ async def test_TC_SEAR_1_5(self): self.wait_for_user_input(prompt_msg=f"{test_step}, and press Enter when done.\n") await self.send_cmd_skip_area_expect_response(step=4, skipped_area=valid_area_id, - expected_response=Clusters.ServiceArea.SkipAreaStatus.kInvalidInMode) + expected_response=Clusters.ServiceArea.Enums.SkipAreaStatus.kInvalidInMode) if self.check_pics("SEAR.S.M.NO_SELAREA_FOR_SKIP") and self.check_pics("SEAR.S.M.HAS_MANUAL_SKIP_STATE_CONTROL"): test_step = "Manually intervene to put the device in a state where the state would allow it to execute the SkipArea command, \ if SelectedAreas wasn't empty, and SelectedAreas is empty" self.print_step("5", test_step) - if not self.is_ci: + if self.is_ci: + await self.send_single_cmd(cmd=Clusters.Objects.RvcRunMode.Commands.ChangeToMode(newMode=1), + endpoint=self.endpoint) + else: self.wait_for_user_input(prompt_msg=f"{test_step}, and press Enter when done.\n") await self.send_cmd_skip_area_expect_response(step=6, skipped_area=valid_area_id, - expected_response=Clusters.ServiceArea.SkipAreaStatus.kInvalidAreaList) + expected_response=Clusters.ServiceArea.Enums.SkipAreaStatus.kInvalidAreaList) if self.check_pics("SEAR.S.M.VALID_STATE_FOR_SKIP") and self.check_pics("SEAR.S.M.HAS_MANUAL_SKIP_STATE_CONTROL"): test_step = "Manually intervene to put the device in a state that allows it to execute the SkipArea command" self.print_step("7", test_step) - if not self.is_ci: + if self.is_ci: + self.write_to_app_pipe('{"Name": "Reset"}') + await self.send_single_cmd(cmd=Clusters.Objects.ServiceArea.Commands.SelectAreas(newAreas=[7, 1234567]), + endpoint=self.endpoint) + await self.send_single_cmd(cmd=Clusters.Objects.RvcRunMode.Commands.ChangeToMode(newMode=1), + endpoint=self.endpoint) + else: self.wait_for_user_input(prompt_msg=f"{test_step}, and press Enter when done.\n") await self.send_cmd_skip_area_expect_response(step=8, skipped_area=invalid_area_id, - expected_response=Clusters.ServiceArea.SkipAreaStatus.kInvalidSkippedArea) + expected_response=Clusters.ServiceArea.Enums.SkipAreaStatus.kInvalidSkippedArea) if not self.check_pics("SEAR.S.M.VALID_STATE_FOR_SKIP"): return @@ -169,7 +178,7 @@ async def test_TC_SEAR_1_5(self): self.print_step("12", "") if old_current_area is not NullValue: await self.send_cmd_skip_area_expect_response(step=13, skipped_area=old_current_area, - expected_response=Clusters.ServiceArea.SkipAreaStatus.kSuccess) + expected_response=Clusters.ServiceArea.Enums.SkipAreaStatus.kSuccess) if self.check_pics("SEAR.S.M.HAS_MANUAL_SKIP_STATE_CONTROL"): test_step = "(Manual operation) wait for the device to skip the current area, and start operating at\ the next one it should process, or stop operating" @@ -189,7 +198,7 @@ async def test_TC_SEAR_1_5(self): new_current_area = await self.read_current_area(step=16) for p in new_progress_list: if p.areaID == old_current_area: - asserts.assert_true(p.status == Clusters.ServiceArea.OperationalStatusEnum.kSkipped, + asserts.assert_true(p.status == Clusters.ServiceArea.Enums.OperationalStatusEnum.kSkipped, "Progress for areaID({old_current_area}) should be Skipped") break test_step = "Indicate whether the device has stopped operating (y/n)" @@ -199,7 +208,7 @@ async def test_TC_SEAR_1_5(self): if ret != "y": for p in new_progress_list: if p.areaID == new_current_area: - asserts.assert_true(p.status == Clusters.ServiceArea.OperationalStatusEnum.kOperating, + asserts.assert_true(p.status == Clusters.ServiceArea.Enums.OperationalStatusEnum.kOperating, "Progress for areaID({new_current_area}) should be Operating") break @@ -208,8 +217,8 @@ async def test_TC_SEAR_1_5(self): was_only_skipped_or_completed = True for p in old_progress_list: if p.areaID != old_current_area: - if p.status not in (Clusters.ServiceArea.OperationalStatusEnum.kSkipped, - Clusters.ServiceArea.OperationalStatusEnum.kCompleted): + if p.status not in (Clusters.ServiceArea.Enums.OperationalStatusEnum.kSkipped, + Clusters.ServiceArea.Enums.OperationalStatusEnum.kCompleted): was_only_skipped_or_completed = False break if was_only_skipped_or_completed: @@ -224,7 +233,13 @@ async def test_TC_SEAR_1_5(self): if self.check_pics("SEAR.S.M.HAS_MANUAL_SKIP_STATE_CONTROL"): test_step = "Manually intervene to put the device in a state that allows it to execute the SkipArea command" self.print_step("18", test_step) - if not self.is_ci: + if self.is_ci: + self.write_to_app_pipe('{"Name": "Reset"}') + await self.send_single_cmd(cmd=Clusters.Objects.ServiceArea.Commands.SelectAreas(newAreas=[7, 1234567]), + endpoint=self.endpoint) + await self.send_single_cmd(cmd=Clusters.Objects.RvcRunMode.Commands.ChangeToMode(newMode=1), + endpoint=self.endpoint) + else: self.wait_for_user_input(prompt_msg=f"{test_step}, and press Enter when done.\n") self.print_step("19", "") @@ -234,8 +249,8 @@ async def test_TC_SEAR_1_5(self): area_to_skip = NullValue self.print_step("20", "") for p in old_progress_list: - if p.status in (Clusters.ServiceArea.OperationalStatusEnum.kPending, - Clusters.ServiceArea.OperationalStatusEnum.kOperating): + if p.status in (Clusters.ServiceArea.Enums.OperationalStatusEnum.kPending, + Clusters.ServiceArea.Enums.OperationalStatusEnum.kOperating): area_to_skip = p.areaID break @@ -243,7 +258,7 @@ async def test_TC_SEAR_1_5(self): return await self.send_cmd_skip_area_expect_response(step=21, skipped_area=area_to_skip, - expected_response=Clusters.ServiceArea.SkipAreaStatus.kSuccess) + expected_response=Clusters.ServiceArea.Enums.SkipAreaStatus.kSuccess) if self.check_pics("SEAR.S.M.HAS_MANUAL_SKIP_STATE_CONTROL"): test_step = "(Manual operation) wait for the device to update Progress or to stop operating" @@ -256,7 +271,7 @@ async def test_TC_SEAR_1_5(self): for p in new_progress_list: if p.areaID == area_to_skip: - asserts.assert_true(p.status == Clusters.ServiceArea.OperationalStatusEnum.kSkipped, + asserts.assert_true(p.status == Clusters.ServiceArea.Enums.OperationalStatusEnum.kSkipped, "Progress for areaID({new_current_area}) should be Skipped") break @@ -266,15 +281,15 @@ async def test_TC_SEAR_1_5(self): was_only_skipped_or_completed = True for p in old_progress_list: if p.areaID != area_to_skip: - if p.status not in (Clusters.ServiceArea.OperationalStatusEnum.kSkipped, - Clusters.ServiceArea.OperationalStatusEnum.kCompleted): + if p.status not in (Clusters.ServiceArea.Enums.OperationalStatusEnum.kSkipped, + Clusters.ServiceArea.Enums.OperationalStatusEnum.kCompleted): was_only_skipped_or_completed = False break if was_only_skipped_or_completed: asserts.assert_true(ret == "y", "The device should not be operating") for p in new_progress_list: if p.areaID == old_current_area: - asserts.assert_true(p.status == Clusters.ServiceArea.OperationalStatusEnum.kSkipped, + asserts.assert_true(p.status == Clusters.ServiceArea.Enums.OperationalStatusEnum.kSkipped, "Progress for areaID({old_current_area}) should be Skipped") break From f53050c2403059d1e9e7cfa6b453ed66efaabdef Mon Sep 17 00:00:00 2001 From: C Freeman Date: Sat, 10 Aug 2024 08:47:50 -0400 Subject: [PATCH 013/165] TC-LVL-2.3: Update step 3 to set level immediately (#34917) Previously, the device might still have been changing when we read the current value in step 5. --- src/python_testing/TC_LVL_2_3.py | 36 ++++++++++++++++++++++---------- 1 file changed, 25 insertions(+), 11 deletions(-) diff --git a/src/python_testing/TC_LVL_2_3.py b/src/python_testing/TC_LVL_2_3.py index 8d31b8641c..f3fac953b4 100644 --- a/src/python_testing/TC_LVL_2_3.py +++ b/src/python_testing/TC_LVL_2_3.py @@ -43,15 +43,18 @@ def steps_TC_LVL_2_3(self) -> list[TestStep]: THRead = "TH reads" THcommand = "TH sends the command" return [TestStep(1, test_plan_support.commission_if_required(), is_commissioning=True), - TestStep(2, f"{THRead} FeatureMap attribute."), - TestStep(3, f"{THRead} MaxLevel attribute and store value as maxLevel", test_plan_support.verify_success()), - TestStep(4, f"{THcommand} MoveWithOnOff with MoveMode field set to Down and remaining fields set to 0", + TestStep(2, f"{THRead} FeatureMap attribute and the AttributeList value"), + TestStep( + "3a", f"If the MaxLevel attribute is in the AttributeList, {THRead} MaxLevel attribute and store value as maxLevel, otherwise set maxLevel to 254", test_plan_support.verify_success()), + TestStep( + "3b", f"If the MinLevel attribute is in the AttributeList, {THRead} MinLevel attribute and store value as minLevel, otherwise set minLevel to 1", test_plan_support.verify_success()), + TestStep(4, f"{THcommand} MoveWithOnOff with MoveMode field set to Down and rate set to 254 and remaining fields set to 0", test_plan_support.verify_success()), TestStep(5, f"{THRead} CurrentLevel attribute and store value as startCurrentLevel", test_plan_support.verify_success()), TestStep(6, "Set up a subscription wildcard subscription for the Level Control Cluster, with MinIntervalFloor set to 0, MaxIntervalCeiling set to 30 and KeepSubscriptions set to false", "Subscription successfully established"), - TestStep(7, f"{THcommand} MoveToLevel with Level field set to maxLevel, TransitionTime field set to 100 (10s) and remaining fields set to 0", + TestStep(7, f"{THcommand} MoveToLevelWithOnOff with Level field set to maxLevel, TransitionTime field set to 100 (10s) and remaining fields set to 0", test_plan_support.verify_success()), TestStep(8, "TH stores the reported values of CurrentLevel in all incoming reports for CurrentLevel attribute, that contains data in reportedCurrentLevelValuesList, over a period of 30 seconds."), TestStep(9, "TH verifies that reportedCurrentLevelValuesList does not contain more than 10 entries for CurrentLevel", @@ -90,16 +93,28 @@ async def test_TC_LVL_2_3(self): self.step(2) feature_map = await self.read_single_attribute_check_success(cluster=lvl, attribute=lvl.Attributes.FeatureMap) + attributes = await self.read_single_attribute_check_success(cluster=lvl, attribute=lvl.Attributes.AttributeList) - self.step(3) - max_level = await self.read_single_attribute_check_success(cluster=lvl, attribute=lvl.Attributes.MaxLevel) + self.step("3a") + attributes = await self.read_single_attribute_check_success(cluster=lvl, attribute=lvl.Attributes.AttributeList) + + if lvl.Attributes.MaxLevel.attribute_id in attributes: + max_level = await self.read_single_attribute_check_success(cluster=lvl, attribute=lvl.Attributes.MaxLevel) + else: + max_level = 254 + + self.step("3b") + if lvl.Attributes.MinLevel.attribute_id in attributes: + min_level = await self.read_single_attribute_check_success(cluster=lvl, attribute=lvl.Attributes.MinLevel) + else: + min_level = 1 self.step(4) - cmd = Clusters.LevelControl.Commands.MoveWithOnOff(moveMode=lvl.Enums.MoveModeEnum.kDown) + cmd = Clusters.LevelControl.Commands.MoveToLevelWithOnOff(level=min_level, transitionTime=0) await self.send_single_cmd(cmd) # NOTE: added this sleep to let the DUT have some time to move - logging.info("Test waits for 5 seconds") - time.sleep(5) + logging.info("Test waits for 1 seconds") + time.sleep(1) self.step(5) start_current_level = await self.read_single_attribute_check_success(cluster=lvl, attribute=lvl.Attributes.CurrentLevel) @@ -109,8 +124,6 @@ async def test_TC_LVL_2_3(self): await sub_handler.start(self.default_controller, self.dut_node_id, self.matter_test_config.endpoint) self.step(7) - # NOTE: had to use the WithOnOff version of this command because the dut is off at this point thanks to the above command - # TODO: Need to check above and here that the on/off cluster is actually implemented. cmd = lvl.Commands.MoveToLevelWithOnOff(level=max_level, transitionTime=100, optionsMask=0, optionsOverride=0) await self.send_single_cmd(cmd) @@ -135,6 +148,7 @@ async def test_TC_LVL_2_3(self): last_value = start_current_level for e in sub_handler.attribute_reports[lvl.Attributes.CurrentLevel]: asserts.assert_greater_equal(e.value, last_value, "Values are not increasing") + last_value = e.value self.step(12) asserts.assert_equal(e.value, max_level, "Last entry is not max value") From 681f9510ae60bec35a0dba4ea9d9935bb94fcc0a Mon Sep 17 00:00:00 2001 From: William Date: Sat, 10 Aug 2024 13:48:20 +0100 Subject: [PATCH 014/165] update the status field of progress elements at the end of a clean. (#34919) * update the status field of progress elements at the end of a clean. * Added some style suggestions from the review of PR 34887. * update the readme. * Restyled by prettier-markdown --------- Co-authored-by: Restyled.io --- examples/rvc-app/README.md | 10 ++++++++ .../rvc-app/rvc-common/include/rvc-device.h | 6 +++++ .../rvc-app/rvc-common/src/rvc-device.cpp | 23 +++++++++++++++++++ .../src/rvc-service-area-delegate.cpp | 4 ++-- 4 files changed, 41 insertions(+), 2 deletions(-) diff --git a/examples/rvc-app/README.md b/examples/rvc-app/README.md index 1be714fb43..8cc6e7308b 100644 --- a/examples/rvc-app/README.md +++ b/examples/rvc-app/README.md @@ -156,3 +156,13 @@ PICS`SEAR.S.M.VALID_STATE_FOR_SELECT_AREAS=1`. PIXIT: `` Example command: Example command: `./scripts/tests/run_python_test.py --script src/python_testing/TC_SEAR_1_4.py --script-args "--storage-path admin_storage.json --PICS examples/rvc-app/rvc-common/pics/rvc-app-pics-values --endpoint 1` + +#### TC 1.5 + +Example command: +`./scripts/tests/run_python_test.py --script src/python_testing/TC_SEAR_1_5.py --script-args "--storage-path admin_storage.json --PICS examples/rvc-app/rvc-common/pics/rvc-app-pics-values --endpoint 1"` + +#### TC 1.6 + +Example command: +`./scripts/tests/run_python_test.py --script src/python_testing/TC_SEAR_1_6.py --script-args "--storage-path admin_storage.json --PICS examples/rvc-app/rvc-common/pics/rvc-app-pics-values --endpoint 1` diff --git a/examples/rvc-app/rvc-common/include/rvc-device.h b/examples/rvc-app/rvc-common/include/rvc-device.h index 97f3475117..40a5232966 100644 --- a/examples/rvc-app/rvc-common/include/rvc-device.h +++ b/examples/rvc-app/rvc-common/include/rvc-device.h @@ -138,6 +138,12 @@ class RvcDevice void HandleClearErrorMessage(); void HandleResetMessage(); + + /** + * Updates the Service area progress elements when an activity has ended. + * Sets any remaining Operating or Pending states to Skipped. + */ + void UpdateServiceAreaProgressOnExit(); }; } // namespace Clusters diff --git a/examples/rvc-app/rvc-common/src/rvc-device.cpp b/examples/rvc-app/rvc-common/src/rvc-device.cpp index db938a58e0..8619d28ff4 100644 --- a/examples/rvc-app/rvc-common/src/rvc-device.cpp +++ b/examples/rvc-app/rvc-common/src/rvc-device.cpp @@ -69,6 +69,8 @@ void RvcDevice::HandleRvcRunChangeToMode(uint8_t newMode, ModeBase::Commands::Ch mRunModeInstance.UpdateCurrentMode(newMode); mOperationalStateInstance.SetOperationalState(to_underlying(RvcOperationalState::OperationalStateEnum::kSeekingCharger)); response.status = to_underlying(ModeBase::StatusCode::kSuccess); + + UpdateServiceAreaProgressOnExit(); return; } break; @@ -311,6 +313,7 @@ void RvcDevice::HandleActivityCompleteEvent() mServiceAreaInstance.SetCurrentArea(DataModel::NullNullable); mServiceAreaInstance.SetEstimatedEndTime(DataModel::NullNullable); + UpdateServiceAreaProgressOnExit(); } void RvcDevice::HandleAreaCompletedEvent() @@ -404,3 +407,23 @@ void RvcDevice::HandleResetMessage() mServiceAreaInstance.SetCurrentArea(DataModel::NullNullable); mServiceAreaInstance.SetEstimatedEndTime(DataModel::NullNullable); } + +void RvcDevice::UpdateServiceAreaProgressOnExit() +{ + if (!mServiceAreaInstance.HasFeature(ServiceArea::Feature::kProgressReporting)) + { + return; + } + + uint32_t i = 0; + ServiceArea::Structs::ProgressStruct::Type progressElement; + while (mServiceAreaDelegate.GetProgressElementByIndex(i, progressElement)) + { + if (progressElement.status == ServiceArea::OperationalStatusEnum::kOperating || + progressElement.status == ServiceArea::OperationalStatusEnum::kPending) + { + mServiceAreaInstance.SetProgressStatus(progressElement.areaID, ServiceArea::OperationalStatusEnum::kSkipped); + } + i++; + } +} diff --git a/examples/rvc-app/rvc-common/src/rvc-service-area-delegate.cpp b/examples/rvc-app/rvc-common/src/rvc-service-area-delegate.cpp index 11daac10ec..f7e17aa49a 100644 --- a/examples/rvc-app/rvc-common/src/rvc-service-area-delegate.cpp +++ b/examples/rvc-app/rvc-common/src/rvc-service-area-delegate.cpp @@ -132,13 +132,13 @@ bool RvcServiceAreaDelegate::IsValidSelectAreasSet(const Commands::SelectAreas:: } } - // If there are less than 2 supported maps, any combination of areas is valid. + // If there is 1 or 0 supported maps, any combination of areas is valid. if (!GetInstance()->HasFeature(Feature::kMaps) || GetNumberOfSupportedMaps() <= 1) { return true; } - // Check that all the areas are in the same map. + // Check that all the requested areas are in the same map. auto newAreasIter = req.newAreas.begin(); newAreasIter.Next(); From 798b576c7f8c55abc3400780790382344329b979 Mon Sep 17 00:00:00 2001 From: Ank Khandelwal <108660995+ankk-css@users.noreply.github.com> Date: Mon, 12 Aug 2024 00:08:24 +0800 Subject: [PATCH 015/165] [Infineon] Provision to enable/disable NOC key-pair generation using HSM (#34770) * Provision to select NOC key-pair generation using Trust M MTR or fw. * Added the flag ENABLE_TRUSTM_NOC_KEYGEN in the config. * Updated the functions to support NOC keygen with and without trustm. * Restyled changes * Minor bug fixes. --- .../trustm/CHIPCryptoPALHsm_P256_trustm.cpp | 76 +++++++++---------- .../trustm/CHIPCryptoPALHsm_config_trustm.h | 10 +-- .../trustm/CHIPCryptoPALHsm_utils_trustm.h | 2 +- .../psoc6_sdk/configs/mbedtls_user_config.h | 34 +++++---- 4 files changed, 61 insertions(+), 61 deletions(-) diff --git a/src/platform/Infineon/crypto/trustm/CHIPCryptoPALHsm_P256_trustm.cpp b/src/platform/Infineon/crypto/trustm/CHIPCryptoPALHsm_P256_trustm.cpp index 23856be89d..485ff22186 100644 --- a/src/platform/Infineon/crypto/trustm/CHIPCryptoPALHsm_P256_trustm.cpp +++ b/src/platform/Infineon/crypto/trustm/CHIPCryptoPALHsm_P256_trustm.cpp @@ -78,7 +78,6 @@ extern CHIP_ERROR ECDSA_validate_msg_signature_H(const P256PublicKey * public_ke extern CHIP_ERROR ECDSA_validate_hash_signature_H(const P256PublicKey * public_key, const uint8_t * hash, const size_t hash_length, const P256ECDSASignature & signature); -#if (ENABLE_TRUSTM_GENERATE_EC_KEY || ENABLE_TRUSTM_ECDSA_VERIFY) static CHIP_ERROR get_trustm_keyid_from_keypair(const P256KeypairContext mKeypair, uint32_t * key_id) { if (0 != memcmp(&mKeypair.mBytes[0], trustm_magic_no, sizeof(trustm_magic_no))) @@ -87,36 +86,21 @@ static CHIP_ERROR get_trustm_keyid_from_keypair(const P256KeypairContext mKeypai } *key_id += (mKeypair.mBytes[CRYPTO_KEYPAIR_KEYID_OFFSET]) | (mKeypair.mBytes[CRYPTO_KEYPAIR_KEYID_OFFSET + 1] << 8); - return CHIP_NO_ERROR; } -#endif // #if (ENABLE_TRUSTM_GENERATE_EC_KEY || ENABLE_TRUSTM_ECDSA_VERIFY) P256Keypair::~P256Keypair() { - // Add method to get the keyid if (CHIP_NO_ERROR != get_trustm_keyid_from_keypair(mKeypair, &keyid)) { Clear(); } - else - { - // Delete the key in SE - } } CHIP_ERROR P256Keypair::Initialize(ECPKeyTarget key_target) { CHIP_ERROR error = CHIP_ERROR_INTERNAL; -#if !ENABLE_TRUSTM_GENERATE_EC_KEY - if (CHIP_NO_ERROR == Initialize_H(this, &mPublicKey, &mKeypair)) - { - mInitialized = true; - } - error = CHIP_NO_ERROR; - return error; -#else uint8_t pubkey[128] = { 0, }; @@ -136,11 +120,20 @@ CHIP_ERROR P256Keypair::Initialize(ECPKeyTarget key_target) } else { +#if !ENABLE_TRUSTM_NOC_KEYGEN + error = Initialize_H(this, &mPublicKey, &mKeypair); + if (CHIP_NO_ERROR == error) + { + mInitialized = true; + } + return error; +#else // Add the logic to use different keyid keyid = TRUSTM_NODE_OID_KEY_START; // Trust M ECC 256 Key Gen ChipLogDetail(Crypto, "Generating NIST256 key in TrustM !"); key_usage = (optiga_key_usage_t) (OPTIGA_KEY_USAGE_SIGN | OPTIGA_KEY_USAGE_AUTHENTICATION); +#endif //! ENABLE_TRUSTM_NOC_KEYGEN } // Trust M init trustm_Open(); @@ -167,14 +160,13 @@ CHIP_ERROR P256Keypair::Initialize(ECPKeyTarget key_target) trustm_close(); } return error; -#endif } CHIP_ERROR P256Keypair::ECDSA_sign_msg(const uint8_t * msg, size_t msg_length, P256ECDSASignature & out_signature) const { -#if !ENABLE_TRUSTM_GENERATE_EC_KEY - return ECDSA_sign_msg_H(&mKeypair, msg, msg_length, out_signature); -#else + VerifyOrReturnError(mInitialized, CHIP_ERROR_UNINITIALIZED); + uint16_t keyid = (mKeypair.mBytes[CRYPTO_KEYPAIR_KEYID_OFFSET]) | (mKeypair.mBytes[CRYPTO_KEYPAIR_KEYID_OFFSET + 1] << 8); + CHIP_ERROR error = CHIP_ERROR_INTERNAL; optiga_lib_status_t return_status = OPTIGA_LIB_BUSY; @@ -188,20 +180,31 @@ CHIP_ERROR P256Keypair::ECDSA_sign_msg(const uint8_t * msg, size_t msg_length, P VerifyOrReturnError(msg != nullptr, CHIP_ERROR_INVALID_ARGUMENT); VerifyOrReturnError(msg_length > 0, CHIP_ERROR_INVALID_ARGUMENT); - ChipLogDetail(Crypto, "TrustM: ECDSA_sign_msg"); // Trust M Init trustm_Open(); // Hash to get the digest Hash_SHA256(msg, msg_length, &digest[0]); - uint16_t keyid = (mKeypair.mBytes[CRYPTO_KEYPAIR_KEYID_OFFSET]) | (mKeypair.mBytes[CRYPTO_KEYPAIR_KEYID_OFFSET + 1] << 8); - // Api call to calculate the signature - if (keyid == OPTIGA_KEY_ID_E0F2) + + if (keyid == OPTIGA_KEY_ID_E0F0) { - return_status = trustm_ecdsa_sign(OPTIGA_KEY_ID_E0F2, digest, digest_length, signature_trustm, &signature_trustm_len); + ChipLogDetail(Crypto, "TrustM: ECDSA_sign_msg"); + + // Api call to calculate the signature + return_status = trustm_ecdsa_sign(OPTIGA_KEY_ID_E0F0, digest, digest_length, signature_trustm, &signature_trustm_len); } else { - return_status = trustm_ecdsa_sign(OPTIGA_KEY_ID_E0F0, digest, digest_length, signature_trustm, &signature_trustm_len); +#if !ENABLE_TRUSTM_NOC_KEYGEN + // Use the mbedtls based method + ChipLogDetail(Crypto, "ECDSA sing msg mbedtls"); + return ECDSA_sign_msg_H(&mKeypair, msg, msg_length, out_signature); +#else + if (keyid == OPTIGA_KEY_ID_E0F2) + { + ChipLogDetail(Crypto, "TrustM: ECDSA_sign_msg"); + return_status = trustm_ecdsa_sign(OPTIGA_KEY_ID_E0F2, digest, digest_length, signature_trustm, &signature_trustm_len); + } +#endif //! ENABLE_TRUSTM_NOC_KEYGEN } VerifyOrExit(return_status == OPTIGA_LIB_SUCCESS, error = CHIP_ERROR_INTERNAL); @@ -220,14 +223,10 @@ CHIP_ERROR P256Keypair::ECDSA_sign_msg(const uint8_t * msg, size_t msg_length, P trustm_close(); } return error; -#endif } CHIP_ERROR P256Keypair::ECDH_derive_secret(const P256PublicKey & remote_public_key, P256ECDHDerivedSecret & out_secret) const { -#if !ENABLE_TRUSTM_GENERATE_EC_KEY - return ECDH_derive_secret_H(&mKeypair, remote_public_key, out_secret); -#else CHIP_ERROR error = CHIP_ERROR_INTERNAL; optiga_lib_status_t return_status = OPTIGA_LIB_BUSY; size_t secret_length = (out_secret.Length() == 0) ? out_secret.Capacity() : out_secret.Length(); @@ -262,7 +261,6 @@ CHIP_ERROR P256Keypair::ECDH_derive_secret(const P256PublicKey & remote_public_k trustm_close(); } return error; -#endif } CHIP_ERROR P256PublicKey::ECDSA_validate_hash_signature(const uint8_t * hash, size_t hash_length, @@ -313,6 +311,12 @@ CHIP_ERROR P256Keypair::Serialize(P256SerializedKeypair & output) const 0, }; + if (0 != memcmp(&mKeypair.mBytes[0], trustm_magic_no, sizeof(trustm_magic_no))) + { + VerifyOrReturnError(mInitialized, CHIP_ERROR_UNINITIALIZED); + return Serialize_H(mKeypair, mPublicKey, output); + } + /* Set the public key */ P256PublicKey & public_key = const_cast(Pubkey()); bbuf.Put(Uint8::to_uchar(public_key), public_key.Length()); @@ -358,16 +362,11 @@ CHIP_ERROR P256Keypair::Deserialize(P256SerializedKeypair & input) } else { -#if !ENABLE_TRUSTM_KEY_IMPORT if (CHIP_NO_ERROR == (error = Deserialize_H(this, &mPublicKey, &mKeypair, input))) { mInitialized = true; } return error; -#else - // Add in code for Trust M - return CHIP_NO_ERROR; -#endif } } @@ -430,9 +429,6 @@ static void add_tlv(uint8_t * buf, size_t buf_index, uint8_t tag, size_t len, ui CHIP_ERROR P256Keypair::NewCertificateSigningRequest(uint8_t * csr, size_t & csr_length) const { -#if !ENABLE_TRUSTM_GENERATE_EC_KEY - return NewCertificateSigningRequest_H(&mKeypair, csr, csr_length); -#else CHIP_ERROR error = CHIP_ERROR_INTERNAL; optiga_lib_status_t return_status = OPTIGA_LIB_BUSY; @@ -585,8 +581,6 @@ CHIP_ERROR P256Keypair::NewCertificateSigningRequest(uint8_t * csr, size_t & csr trustm_close(); } return error; - -#endif } } // namespace Crypto diff --git a/src/platform/Infineon/crypto/trustm/CHIPCryptoPALHsm_config_trustm.h b/src/platform/Infineon/crypto/trustm/CHIPCryptoPALHsm_config_trustm.h index 44d841c5d8..56c1c78da9 100644 --- a/src/platform/Infineon/crypto/trustm/CHIPCryptoPALHsm_config_trustm.h +++ b/src/platform/Infineon/crypto/trustm/CHIPCryptoPALHsm_config_trustm.h @@ -32,11 +32,6 @@ */ #define ENABLE_TRUSTM_ECDSA_VERIFY 1 -/* - * Enable Key Import for trustm - */ -#define ENABLE_TRUSTM_KEY_IMPORT 0 - /* * Enable trustm for HKDF SHA256 */ @@ -51,3 +46,8 @@ * Enable trustm for DA */ #define ENABLE_TRUSTM_DEVICE_ATTESTATION 1 + +/* + * Enable trustm for NOC key-pair generation + */ +#define ENABLE_TRUSTM_NOC_KEYGEN 0 diff --git a/src/platform/Infineon/crypto/trustm/CHIPCryptoPALHsm_utils_trustm.h b/src/platform/Infineon/crypto/trustm/CHIPCryptoPALHsm_utils_trustm.h index 4efd6ade24..be74bf4f3d 100644 --- a/src/platform/Infineon/crypto/trustm/CHIPCryptoPALHsm_utils_trustm.h +++ b/src/platform/Infineon/crypto/trustm/CHIPCryptoPALHsm_utils_trustm.h @@ -51,7 +51,7 @@ extern optiga_util_t * p_local_util; } static const uint8_t trustm_magic_no[] = IFX_CRYPTO_KEY_MAGIC; -static const uint8_t DA_KEY_ID[] = { 0xE0, 0xF0 }; +static const uint8_t DA_KEY_ID[] = { 0xF0, 0xE0 }; // OID --> 0xE0F0 /* Open session to trustm */ void trustm_Open(void); void read_certificate_from_optiga(uint16_t optiga_oid, char * cert_pem, uint16_t * cert_pem_length); diff --git a/third_party/infineon/psoc6/psoc6_sdk/configs/mbedtls_user_config.h b/third_party/infineon/psoc6/psoc6_sdk/configs/mbedtls_user_config.h index 45a1fd8fd0..38f4d3bf32 100644 --- a/third_party/infineon/psoc6/psoc6_sdk/configs/mbedtls_user_config.h +++ b/third_party/infineon/psoc6/psoc6_sdk/configs/mbedtls_user_config.h @@ -73,13 +73,13 @@ * Uncomment a macro to enable alternate implementation of specific base * platform function */ -//#define MBEDTLS_PLATFORM_EXIT_ALT +// #define MBEDTLS_PLATFORM_EXIT_ALT #define MBEDTLS_PLATFORM_TIME_ALT -//#define MBEDTLS_PLATFORM_FPRINTF_ALT -//#define MBEDTLS_PLATFORM_PRINTF_ALT -//#define MBEDTLS_PLATFORM_SNPRINTF_ALT -//#define MBEDTLS_PLATFORM_NV_SEED_ALT -//#define MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT +// #define MBEDTLS_PLATFORM_FPRINTF_ALT +// #define MBEDTLS_PLATFORM_PRINTF_ALT +// #define MBEDTLS_PLATFORM_SNPRINTF_ALT +// #define MBEDTLS_PLATFORM_NV_SEED_ALT +// #define MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT /** * \def MBEDTLS_ENTROPY_HARDWARE_ALT @@ -103,7 +103,7 @@ */ #undef MBEDTLS_ECP_DP_SECP192R1_ENABLED #undef MBEDTLS_ECP_DP_SECP224R1_ENABLED -//#define MBEDTLS_ECP_DP_SECP256R1_ENABLED +// #define MBEDTLS_ECP_DP_SECP256R1_ENABLED #undef MBEDTLS_ECP_DP_SECP384R1_ENABLED #undef MBEDTLS_ECP_DP_SECP521R1_ENABLED #undef MBEDTLS_ECP_DP_SECP192K1_ENABLED @@ -112,7 +112,7 @@ #undef MBEDTLS_ECP_DP_BP256R1_ENABLED #undef MBEDTLS_ECP_DP_BP384R1_ENABLED #undef MBEDTLS_ECP_DP_BP512R1_ENABLED -//#undef MBEDTLS_ECP_DP_CURVE25519_ENABLED +// #undef MBEDTLS_ECP_DP_CURVE25519_ENABLED #undef MBEDTLS_ECP_DP_CURVE448_ENABLED /** @@ -246,7 +246,7 @@ * * Uncomment this macro to enable support for SSLv2 Client Hello messages. */ -//#define MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO +// #define MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO /** * \def MBEDTLS_SSL_PROTO_TLS1 @@ -468,7 +468,7 @@ * * This module is required for X.509 CRL parsing. */ -//#undef MBEDTLS_X509_CRL_PARSE_C +// #undef MBEDTLS_X509_CRL_PARSE_C /** * \def MBEDTLS_X509_CSR_PARSE_C @@ -482,7 +482,7 @@ * * This module is used for reading X.509 certificate request. */ -//#undef MBEDTLS_X509_CSR_PARSE_C +// #undef MBEDTLS_X509_CSR_PARSE_C /** * \def MBEDTLS_X509_CREATE_C @@ -495,7 +495,7 @@ * * This module is the basis for creating X.509 certificates and CSRs. */ -//#undef MBEDTLS_X509_CREATE_C +// #undef MBEDTLS_X509_CREATE_C /** * \def MBEDTLS_X509_CSR_WRITE_C @@ -508,7 +508,7 @@ * * This module is required for X.509 certificate request writing. */ -//#undef MBEDTLS_X509_CSR_WRITE_C +// #undef MBEDTLS_X509_CSR_WRITE_C /** * \def MBEDTLS_X509_CRT_WRITE_C @@ -521,7 +521,7 @@ * * This module is required for X.509 certificate creation. */ -//#undef MBEDTLS_X509_CRT_WRITE_C +// #undef MBEDTLS_X509_CRT_WRITE_C /** * \def MBEDTLS_CERTS_C @@ -779,4 +779,10 @@ */ #define MBEDTLS_DEPRECATED_REMOVED +#define MBEDTLS_ASN1_WRITE_C +#define MBEDTLS_ECDSA_C +#define MBEDTLS_PK_WRITE_C +#define MBEDTLS_X509_CREATE_C +#define MBEDTLS_X509_CSR_WRITE_C + #endif /* MBEDTLS_USER_CONFIG_HEADER */ From 3b90fed9faf8f98fb30fccfe2867e4567dc46929 Mon Sep 17 00:00:00 2001 From: Yufeng Wang Date: Sun, 11 Aug 2024 21:24:28 -0700 Subject: [PATCH 016/165] [FS Example] Update the FS Example apps to support fabric sync setup process part I (#34906) * [FS Example] Update the FS Example apps to support fabric sync setup process * Move all command handling to device manager using StringBuilder --- .../commands/clusters/ReportCommand.cpp | 10 +- .../commands/common/CHIPCommand.h | 2 + .../fabric-sync/FabricSyncCommand.cpp | 53 ++--- .../commands/fabric-sync/FabricSyncCommand.h | 8 - .../device_manager/DeviceManager.cpp | 214 +++++++++++++++++- .../device_manager/DeviceManager.h | 74 +++++- examples/fabric-admin/rpc/RpcServer.cpp | 8 +- .../fabric-bridge-common/BUILD.gn | 2 + .../include/CommissionerControl.h | 57 +++++ .../src/CommissionerControl.cpp | 175 ++++++++++++++ examples/fabric-bridge-app/linux/main.cpp | 9 + 11 files changed, 556 insertions(+), 56 deletions(-) create mode 100644 examples/fabric-bridge-app/fabric-bridge-common/include/CommissionerControl.h create mode 100644 examples/fabric-bridge-app/fabric-bridge-common/src/CommissionerControl.cpp diff --git a/examples/fabric-admin/commands/clusters/ReportCommand.cpp b/examples/fabric-admin/commands/clusters/ReportCommand.cpp index 8eb2cc7c33..ff52a30e66 100644 --- a/examples/fabric-admin/commands/clusters/ReportCommand.cpp +++ b/examples/fabric-admin/commands/clusters/ReportCommand.cpp @@ -46,7 +46,7 @@ void ReportCommand::OnAttributeData(const app::ConcreteDataAttributePath & path, LogErrorOnFailure(RemoteDataModelLogger::LogAttributeAsJSON(path, data)); - DeviceMgr().HandleAttributeChange(path, data); + DeviceMgr().HandleAttributeData(path, data); } void ReportCommand::OnEventData(const app::EventHeader & eventHeader, TLV::TLVReader * data, const app::StatusIB * status) @@ -73,11 +73,5 @@ void ReportCommand::OnEventData(const app::EventHeader & eventHeader, TLV::TLVRe LogErrorOnFailure(RemoteDataModelLogger::LogEventAsJSON(eventHeader, data)); - CHIP_ERROR error = DataModelLogger::LogEvent(eventHeader, data); - if (CHIP_NO_ERROR != error) - { - ChipLogError(NotSpecified, "Response Failure: Can not decode Data"); - mError = error; - return; - } + DeviceMgr().HandleEventData(eventHeader, data); } diff --git a/examples/fabric-admin/commands/common/CHIPCommand.h b/examples/fabric-admin/commands/common/CHIPCommand.h index af833f5f71..a02adbfbb5 100644 --- a/examples/fabric-admin/commands/common/CHIPCommand.h +++ b/examples/fabric-admin/commands/common/CHIPCommand.h @@ -51,6 +51,8 @@ inline constexpr char kIdentityGamma[] = "gamma"; // (CASE) communcation. inline constexpr char kIdentityNull[] = "null-fabric-commissioner"; +constexpr uint16_t kMaxCommandSize = 128; + class CHIPCommand : public Command { public: diff --git a/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.cpp b/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.cpp index 3e050e9090..efb7cfd222 100644 --- a/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.cpp +++ b/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.cpp @@ -35,9 +35,11 @@ namespace { // Constants constexpr uint32_t kCommissionPrepareTimeMs = 500; constexpr uint16_t kMaxManaulCodeLength = 21; -constexpr uint16_t kSubscribeMinInterval = 0; -constexpr uint16_t kSubscribeMaxInterval = 60; -constexpr uint16_t kRemoteBridgePort = 5540; + +void CheckFabricBridgeSynchronizationSupport(intptr_t ignored) +{ + DeviceMgr().ReadSupportedDeviceCategories(); +} } // namespace @@ -45,8 +47,16 @@ void FabricSyncAddBridgeCommand::OnCommissioningComplete(chip::NodeId deviceId, { if (mBridgeNodeId != deviceId) { - ChipLogProgress(NotSpecified, "Commissioning complete for non-bridge device: NodeId: " ChipLogFormatX64, - ChipLogValueX64(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; } @@ -56,11 +66,15 @@ void FabricSyncAddBridgeCommand::OnCommissioningComplete(chip::NodeId deviceId, ChipLogProgress(NotSpecified, "Successfully paired bridge device: NodeId: " ChipLogFormatX64, ChipLogValueX64(mBridgeNodeId)); - char command[kMaxCommandSize]; - snprintf(command, sizeof(command), "descriptor subscribe parts-list %d %d %ld %d", kSubscribeMinInterval, - kSubscribeMaxInterval, mBridgeNodeId, kAggragatorEndpointId); + DeviceMgr().SubscribeRemoteFabricBridge(); - PushCommand(command); + // After successful commissioning of the Commissionee, initiate Reverse Commissioning + // via the Commissioner Control Cluster. However, we must first verify that the + // remote Fabric-Bridge supports Fabric Synchronization. + // + // Note: The Fabric-Admin MUST NOT send the RequestCommissioningApproval command + // if the remote Fabric-Bridge lacks Fabric Synchronization support. + DeviceLayer::PlatformMgr().ScheduleWork(CheckFabricBridgeSynchronizationSupport, 0); } else { @@ -80,10 +94,6 @@ CHIP_ERROR FabricSyncAddBridgeCommand::RunCommand(NodeId remoteId) return CHIP_NO_ERROR; } - char command[kMaxCommandSize]; - snprintf(command, sizeof(command), "pairing already-discovered %ld %d %s %d", remoteId, kSetupPinCode, - reinterpret_cast(mRemoteAddr.data()), kRemoteBridgePort); - PairingCommand * pairingCommand = static_cast(CommandMgr().GetCommandByName("pairing", "already-discovered")); if (pairingCommand == nullptr) @@ -95,7 +105,7 @@ CHIP_ERROR FabricSyncAddBridgeCommand::RunCommand(NodeId remoteId) pairingCommand->RegisterCommissioningDelegate(this); mBridgeNodeId = remoteId; - PushCommand(command); + DeviceMgr().PairRemoteFabricBridge(remoteId, reinterpret_cast(mRemoteAddr.data())); return CHIP_NO_ERROR; } @@ -136,9 +146,6 @@ CHIP_ERROR FabricSyncRemoveBridgeCommand::RunCommand() mBridgeNodeId = bridgeNodeId; - char command[kMaxCommandSize]; - snprintf(command, sizeof(command), "pairing unpair %ld", mBridgeNodeId); - PairingCommand * pairingCommand = static_cast(CommandMgr().GetCommandByName("pairing", "unpair")); if (pairingCommand == nullptr) @@ -149,7 +156,7 @@ CHIP_ERROR FabricSyncRemoveBridgeCommand::RunCommand() pairingCommand->RegisterPairingDelegate(this); - PushCommand(command); + DeviceMgr().UnpairRemoteFabricBridge(); return CHIP_NO_ERROR; } @@ -163,9 +170,7 @@ void FabricSyncDeviceCommand::OnCommissioningWindowOpened(NodeId deviceId, CHIP_ CHIP_ERROR error = ManualSetupPayloadGenerator(payload).payloadDecimalStringRepresentation(manualCode); if (error == CHIP_NO_ERROR) { - char command[kMaxCommandSize]; NodeId nodeId = DeviceMgr().GetNextAvailableNodeId(); - snprintf(command, sizeof(command), "pairing code %ld %s", nodeId, payloadBuffer); PairingCommand * pairingCommand = static_cast(CommandMgr().GetCommandByName("pairing", "code")); @@ -180,7 +185,7 @@ void FabricSyncDeviceCommand::OnCommissioningWindowOpened(NodeId deviceId, CHIP_ usleep(kCommissionPrepareTimeMs * 1000); - PushCommand(command); + DeviceMgr().PairRemoteDevice(nodeId, payloadBuffer); } else { @@ -224,10 +229,6 @@ CHIP_ERROR FabricSyncDeviceCommand::RunCommand(EndpointId remoteId) return CHIP_NO_ERROR; } - char command[kMaxCommandSize]; - snprintf(command, sizeof(command), "pairing open-commissioning-window %ld %d %d %d %d %d", DeviceMgr().GetRemoteBridgeNodeId(), - remoteId, kEnhancedCommissioningMethod, kWindowTimeout, kIteration, kDiscriminator); - OpenCommissioningWindowCommand * openCommand = static_cast(CommandMgr().GetCommandByName("pairing", "open-commissioning-window")); @@ -238,7 +239,7 @@ CHIP_ERROR FabricSyncDeviceCommand::RunCommand(EndpointId remoteId) openCommand->RegisterDelegate(this); - PushCommand(command); + DeviceMgr().OpenRemoteDeviceCommissioningWindow(remoteId); 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 038094583c..ca1b105207 100644 --- a/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.h +++ b/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.h @@ -22,14 +22,6 @@ #include #include -constexpr uint32_t kSetupPinCode = 20202021; -constexpr uint16_t kMaxCommandSize = 64; -constexpr uint16_t kDiscriminator = 3840; -constexpr uint16_t kWindowTimeout = 300; -constexpr uint16_t kIteration = 1000; -constexpr uint16_t kAggragatorEndpointId = 1; -constexpr uint8_t kEnhancedCommissioningMethod = 1; - class FabricSyncAddBridgeCommand : public CHIPCommand, public CommissioningDelegate { public: diff --git a/examples/fabric-admin/device_manager/DeviceManager.cpp b/examples/fabric-admin/device_manager/DeviceManager.cpp index 4ea0b033c4..aea9722bc8 100644 --- a/examples/fabric-admin/device_manager/DeviceManager.cpp +++ b/examples/fabric-admin/device_manager/DeviceManager.cpp @@ -19,6 +19,8 @@ #include "DeviceManager.h" #include +#include +#include #include #include @@ -26,6 +28,21 @@ using namespace chip; using namespace chip::app::Clusters; +namespace { + +// Constants +constexpr uint32_t kSetupPinCode = 20202021; +constexpr uint16_t kRemoteBridgePort = 5540; +constexpr uint16_t kDiscriminator = 3840; +constexpr uint16_t kWindowTimeout = 300; +constexpr uint16_t kIteration = 1000; +constexpr uint16_t kSubscribeMinInterval = 0; +constexpr uint16_t kSubscribeMaxInterval = 60; +constexpr uint16_t kAggragatorEndpointId = 1; +constexpr uint8_t kEnhancedCommissioningMethod = 1; + +} // namespace + // Define the static member DeviceManager DeviceManager::sInstance; @@ -97,8 +114,154 @@ void DeviceManager::RemoveSyncedDevice(NodeId nodeId) ChipLogValueX64(device->GetNodeId()), device->GetEndpointId()); } -void DeviceManager::HandleAttributeChange(const app::ConcreteDataAttributePath & path, TLV::TLVReader * data) +void DeviceManager::OpenDeviceCommissioningWindow(NodeId nodeId, uint32_t commissioningTimeout, uint32_t iterations, + uint32_t discriminator, const char * saltHex, const char * verifierHex) +{ + // Open the commissioning window of a device within its own fabric. + StringBuilder<512> commandBuilder; + + commandBuilder.Add("pairing open-commissioning-window "); + commandBuilder.AddFormat("%lu %d %d %d %d %d --salt hex:%s --verifier hex:%s", nodeId, kRootEndpointId, + kEnhancedCommissioningMethod, commissioningTimeout, iterations, discriminator, saltHex, verifierHex); + + PushCommand(commandBuilder.c_str()); +} + +void DeviceManager::OpenRemoteDeviceCommissioningWindow(EndpointId remoteEndpointId) +{ + // Open the commissioning window of a device from another fabric via its fabric bridge. + // This method constructs and sends a command to open the commissioning window for a device + // that is part of a different fabric, accessed through a fabric bridge. + StringBuilder commandBuilder; + + commandBuilder.Add("pairing open-commissioning-window "); + commandBuilder.AddFormat("%lu %d %d %d %d %d", mRemoteBridgeNodeId, remoteEndpointId, kEnhancedCommissioningMethod, + kWindowTimeout, kIteration, kDiscriminator); + + PushCommand(commandBuilder.c_str()); +} + +void DeviceManager::PairRemoteFabricBridge(NodeId nodeId, const char * deviceRemoteIp) +{ + StringBuilder commandBuilder; + + commandBuilder.Add("pairing already-discovered "); + commandBuilder.AddFormat("%lu %d %s %d", nodeId, kSetupPinCode, deviceRemoteIp, kRemoteBridgePort); + + PushCommand(commandBuilder.c_str()); +} + +void DeviceManager::PairRemoteDevice(chip::NodeId nodeId, const char * payload) +{ + StringBuilder commandBuilder; + + commandBuilder.Add("pairing code "); + commandBuilder.AddFormat("%lu %s", nodeId, payload); + + PushCommand(commandBuilder.c_str()); +} + +void DeviceManager::UnpairRemoteFabricBridge() +{ + StringBuilder commandBuilder; + + commandBuilder.Add("pairing unpair "); + commandBuilder.AddFormat("%lu", mRemoteBridgeNodeId); + + PushCommand(commandBuilder.c_str()); +} + +void DeviceManager::SubscribeRemoteFabricBridge() +{ + // Listen to the state changes of the remote fabric bridge. + StringBuilder commandBuilder; + + // Prepare and push the descriptor subscribe command + commandBuilder.Add("descriptor subscribe parts-list "); + commandBuilder.AddFormat("%d %d %lu %d", kSubscribeMinInterval, kSubscribeMaxInterval, mRemoteBridgeNodeId, + kAggragatorEndpointId); + PushCommand(commandBuilder.c_str()); + + // Clear the builder for the next command + commandBuilder.Reset(); + + // Prepare and push the commissioner control subscribe command + commandBuilder.Add("commissionercontrol subscribe-event commissioning-request-result "); + commandBuilder.AddFormat("%d %d %lu %d --is-urgent true", kSubscribeMinInterval, kSubscribeMaxInterval, mRemoteBridgeNodeId, + kRootEndpointId); + PushCommand(commandBuilder.c_str()); +} + +void DeviceManager::ReadSupportedDeviceCategories() +{ + if (!IsFabricSyncReady()) + { + // print to console + fprintf(stderr, "Remote Fabric Bridge is not configured yet.\n"); + return; + } + + StringBuilder commandBuilder; + + commandBuilder.Add("commissionercontrol read supported-device-categories "); + commandBuilder.AddFormat("%ld ", mRemoteBridgeNodeId); + commandBuilder.AddFormat("%d", kRootEndpointId); + + PushCommand(commandBuilder.c_str()); +} + +void DeviceManager::StartReverseCommissioning() +{ + ChipLogProgress(NotSpecified, "Starting reverse commissioning for bridge device: NodeId: " ChipLogFormatX64, + ChipLogValueX64(mRemoteBridgeNodeId)); + + uint64_t requestId = Crypto::GetRandU64(); + uint16_t vendorId = static_cast(CHIP_DEVICE_CONFIG_DEVICE_VENDOR_ID); + uint16_t productId = static_cast(CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_ID); + + StringBuilder commandBuilder; + commandBuilder.Add("commissionercontrol request-commissioning-approval "); + commandBuilder.AddFormat("%lu %u %u %lu %d", requestId, vendorId, productId, mRemoteBridgeNodeId, kRootEndpointId); + + mRequestId = requestId; + PushCommand(commandBuilder.c_str()); +} + +void DeviceManager::CommissionApprovedRequest(uint64_t requestId, uint16_t responseTimeoutSeconds) { + ChipLogProgress(NotSpecified, "Request the Commissioner Control Server to begin commissioning a previously approved request."); + + StringBuilder commandBuilder; + commandBuilder.Add("commissionercontrol commission-node "); + commandBuilder.AddFormat("%lu %u %lu %d", requestId, responseTimeoutSeconds, mRemoteBridgeNodeId, kRootEndpointId); + + PushCommand(commandBuilder.c_str()); +} + +void DeviceManager::HandleAttributeData(const app::ConcreteDataAttributePath & path, TLV::TLVReader * data) +{ + if (path.mClusterId == CommissionerControl::Id && + path.mAttributeId == CommissionerControl::Attributes::SupportedDeviceCategories::Id) + { + ChipLogProgress(NotSpecified, "Attribute SupportedDeviceCategories detected."); + + BitMask value; + CHIP_ERROR error = app::DataModel::Decode(*data, value); + if (error != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to decode attribute value. Error: %" CHIP_ERROR_FORMAT, error.Format()); + return; + } + + if (value.Has(CommissionerControl::SupportedDeviceCategoryBitmap::kFabricSynchronization)) + { + ChipLogProgress(NotSpecified, "Remote Fabric-Bridge supports Fabric Synchronization, start reverse commissioning."); + StartReverseCommissioning(); + } + + return; + } + if (path.mClusterId != Descriptor::Id || path.mAttributeId != Descriptor::Attributes::PartsList::Id) { return; @@ -167,9 +330,10 @@ void DeviceManager::HandleAttributeChange(const app::ConcreteDataAttributePath & if (mAutoSyncEnabled) { - char command[64]; - snprintf(command, sizeof(command), "fabricsync sync-device %d", endpoint); - PushCommand(command); + StringBuilder commandBuilder; + commandBuilder.Add("fabricsync sync-device "); + commandBuilder.AddFormat("%d", endpoint); + PushCommand(commandBuilder.c_str()); } } @@ -188,8 +352,9 @@ void DeviceManager::HandleAttributeChange(const app::ConcreteDataAttributePath & if (mAutoSyncEnabled) { - char command[64]; - snprintf(command, sizeof(command), "pairing unpair %ld", device->GetNodeId()); + StringBuilder commandBuilder; + commandBuilder.Add("pairing unpair "); + commandBuilder.AddFormat("%lu", device->GetNodeId()); PairingCommand * pairingCommand = static_cast(CommandMgr().GetCommandByName("pairing", "unpair")); @@ -200,11 +365,46 @@ void DeviceManager::HandleAttributeChange(const app::ConcreteDataAttributePath & } pairingCommand->RegisterPairingDelegate(this); - PushCommand(command); + PushCommand(commandBuilder.c_str()); } } } +void DeviceManager::HandleEventData(const chip::app::EventHeader & header, chip::TLV::TLVReader * data) +{ + if (header.mPath.mClusterId != CommissionerControl::Id || + header.mPath.mEventId != CommissionerControl::Events::CommissioningRequestResult::Id) + { + return; + } + + ChipLogProgress(NotSpecified, "CommissioningRequestResult event received."); + + CommissionerControl::Events::CommissioningRequestResult::DecodableType value; + CHIP_ERROR error = app::DataModel::Decode(*data, value); + if (error != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to decode event value. Error: %" CHIP_ERROR_FORMAT, error.Format()); + return; + } + + if (value.requestId != mRequestId) + { + ChipLogError(NotSpecified, "The RequestId does not match the RequestId provided to RequestCommissioningApproval"); + return; + } + + if (value.statusCode != static_cast(Protocols::InteractionModel::Status::Success)) + { + ChipLogError(NotSpecified, "The server is not ready to begin commissioning the requested device"); + return; + } + + // The server is ready to begin commissioning the requested device, request the Commissioner Control Server to begin + // commissioning a previously approved request. + CommissionApprovedRequest(value.requestId, kResponseTimeoutSeconds); +} + void DeviceManager::OnDeviceRemoved(NodeId deviceId, CHIP_ERROR err) { if (err != CHIP_NO_ERROR) diff --git a/examples/fabric-admin/device_manager/DeviceManager.h b/examples/fabric-admin/device_manager/DeviceManager.h index 6270cfd40e..cad573a931 100644 --- a/examples/fabric-admin/device_manager/DeviceManager.h +++ b/examples/fabric-admin/device_manager/DeviceManager.h @@ -24,6 +24,8 @@ #include +constexpr uint16_t kResponseTimeoutSeconds = 30; + class Device { public: @@ -67,7 +69,76 @@ class DeviceManager : public PairingDelegate void RemoveSyncedDevice(chip::NodeId nodeId); - void HandleAttributeChange(const chip::app::ConcreteDataAttributePath & path, chip::TLV::TLVReader * data); + /** + * @brief Open the commissioning window for a specific device within its own fabric. + * + * This function initiates the process to open the commissioning window for a device identified by the given node ID. + * + * @param nodeId The ID of the node that should open the commissioning window. + * @param commissioningTimeout The time in seconds before the commissioning window closes. This value determines + * how long the commissioning window remains open for incoming connections. + * @param iterations The number of PBKDF (Password-Based Key Derivation Function) iterations to use + * for deriving the PAKE (Password Authenticated Key Exchange) verifier. + * @param discriminator The device-specific discriminator, determined during commissioning, which helps + * to uniquely identify the device among others. + * @param saltHex The hexadecimal-encoded salt used in the cryptographic operations for commissioning. + * @param verifierHex The hexadecimal-encoded PAKE verifier used to authenticate the commissioning process. + * + */ + void OpenDeviceCommissioningWindow(chip::NodeId nodeId, uint32_t commissioningTimeout, uint32_t iterations, + uint32_t discriminator, const char * saltHex, const char * verifierHex); + + /** + * @brief Open the commissioning window of a device from another fabric via its fabric bridge. + * + * This function initiates the process to open the commissioning window for a device that belongs to another + * fabric, accessed through a fabric bridge. + * + * @param remoteEndpointId The endpoint ID of the remote device that should open the commissioning window. + * This endpoint is associated with the device in the other fabric, accessed via the + * fabric bridge. + * + * @note This function is used when the device to be commissioned is part of a different fabric and must be + * accessed through an intermediary fabric bridge. + */ + void OpenRemoteDeviceCommissioningWindow(chip::EndpointId remoteEndpointId); + + /** + * @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 deviceRemoteIp The IP address of the remote device that is being paired as part of the fabric bridge. + */ + void PairRemoteFabricBridge(chip::NodeId nodeId, const char * deviceRemoteIp); + + /** + * @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. + */ + void PairRemoteDevice(chip::NodeId nodeId, const char * payload); + + void UnpairRemoteFabricBridge(); + + void SubscribeRemoteFabricBridge(); + + void StartReverseCommissioning(); + + void ReadSupportedDeviceCategories(); + + void CommissionApprovedRequest(uint64_t requestId, uint16_t responseTimeoutSeconds); + + void HandleAttributeData(const chip::app::ConcreteDataAttributePath & path, chip::TLV::TLVReader * data); + + void HandleEventData(const chip::app::EventHeader & header, chip::TLV::TLVReader * data); void OnDeviceRemoved(chip::NodeId deviceId, CHIP_ERROR err) override; @@ -81,6 +152,7 @@ class DeviceManager : public PairingDelegate std::set mSyncedDevices; bool mAutoSyncEnabled = false; bool mInitialized = false; + uint64_t mRequestId = 0; Device * FindDeviceByEndpoint(chip::EndpointId endpointId); Device * FindDeviceByNode(chip::NodeId nodeId); diff --git a/examples/fabric-admin/rpc/RpcServer.cpp b/examples/fabric-admin/rpc/RpcServer.cpp index cb06b359d6..16ff695e15 100644 --- a/examples/fabric-admin/rpc/RpcServer.cpp +++ b/examples/fabric-admin/rpc/RpcServer.cpp @@ -22,6 +22,7 @@ #include #include +#include #include #include @@ -54,12 +55,7 @@ class FabricAdmin final : public rpc::FabricAdmin ChipLogProgress(NotSpecified, "Received OpenCommissioningWindow request: 0x%lx", nodeId); - char command[512]; - snprintf(command, sizeof(command), "pairing open-commissioning-window %ld %d %d %d %d %d --salt hex:%s --verifier hex:%s", - nodeId, kRootEndpointId, kEnhancedCommissioningMethod, commissioningTimeout, iterations, discriminator, saltHex, - verifierHex); - - PushCommand(command); + DeviceMgr().OpenDeviceCommissioningWindow(nodeId, commissioningTimeout, iterations, discriminator, saltHex, verifierHex); response.success = true; diff --git a/examples/fabric-bridge-app/fabric-bridge-common/BUILD.gn b/examples/fabric-bridge-app/fabric-bridge-common/BUILD.gn index 7f2fbcbbfe..b7b07d3be3 100644 --- a/examples/fabric-bridge-app/fabric-bridge-common/BUILD.gn +++ b/examples/fabric-bridge-app/fabric-bridge-common/BUILD.gn @@ -45,9 +45,11 @@ source_set("fabric-bridge-lib") { "include/BridgedDeviceBasicInformationImpl.h", "include/BridgedDeviceManager.h", "include/CHIPProjectAppConfig.h", + "include/CommissionerControl.h", "src/BridgedDevice.cpp", "src/BridgedDeviceBasicInformationImpl.cpp", "src/BridgedDeviceManager.cpp", + "src/CommissionerControl.cpp", "src/ZCLCallbacks.cpp", ] diff --git a/examples/fabric-bridge-app/fabric-bridge-common/include/CommissionerControl.h b/examples/fabric-bridge-app/fabric-bridge-common/include/CommissionerControl.h new file mode 100644 index 0000000000..b5caa6a2ce --- /dev/null +++ b/examples/fabric-bridge-app/fabric-bridge-common/include/CommissionerControl.h @@ -0,0 +1,57 @@ +/* + * + * 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 + +namespace chip { +namespace app { +namespace Clusters { +namespace CommissionerControl { + +class CommissionerControlDelegate : public Delegate +{ +public: + CHIP_ERROR HandleCommissioningApprovalRequest(const CommissioningApprovalRequest & request) override; + CHIP_ERROR ValidateCommissionNodeCommand(NodeId clientNodeId, uint64_t requestId) override; + CHIP_ERROR GetCommissioningWindowParams(CommissioningWindowParams & outParams) override; + CHIP_ERROR ReverseCommissionNode(const CommissioningWindowParams & params, const Optional & ipAddress, + const Optional & port) override; + + ~CommissionerControlDelegate() = default; + +private: + static constexpr size_t kLabelBufferSize = 64; + + uint64_t mRequestId = 0; + NodeId mClientNodeId = kUndefinedNodeId; + VendorId mVendorId = VendorId::Unspecified; + uint16_t mProductId = 0; + char mLabelBuffer[kLabelBufferSize + 1]; + Optional mLabel; +}; + +} // namespace CommissionerControl +} // namespace Clusters +} // namespace app +} // namespace chip + +CHIP_ERROR CommissionerControlInit(); +CHIP_ERROR CommissionerControlShutdown(); diff --git a/examples/fabric-bridge-app/fabric-bridge-common/src/CommissionerControl.cpp b/examples/fabric-bridge-app/fabric-bridge-common/src/CommissionerControl.cpp new file mode 100644 index 0000000000..076ced8165 --- /dev/null +++ b/examples/fabric-bridge-app/fabric-bridge-common/src/CommissionerControl.cpp @@ -0,0 +1,175 @@ +/* + * + * 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 "CommissionerControl.h" + +#include +#include +#include +#include + +using namespace chip; +using namespace chip::app; + +namespace { + +std::unique_ptr sCommissionerControlDelegate; + +} // namespace + +namespace chip { +namespace app { +namespace Clusters { +namespace CommissionerControl { + +CHIP_ERROR CommissionerControlDelegate::HandleCommissioningApprovalRequest(const CommissioningApprovalRequest & request) +{ + CommissionerControl::Events::CommissioningRequestResult::Type result; + result.requestId = request.requestId; + result.clientNodeId = request.clientNodeId; + result.fabricIndex = request.fabricIndex; + result.statusCode = static_cast(Protocols::InteractionModel::Status::Success); + + mRequestId = request.requestId; + mClientNodeId = request.clientNodeId; + mVendorId = request.vendorId; + mProductId = request.productId; + + if (request.label.HasValue()) + { + const CharSpan & labelSpan = request.label.Value(); + size_t labelLength = labelSpan.size(); + + if (labelLength >= kLabelBufferSize) + { + ChipLogError(Zcl, "Label too long to fit in buffer"); + return CHIP_ERROR_BUFFER_TOO_SMALL; + } + + if (labelLength == 0) + { + mLabel.ClearValue(); + } + else + { + memcpy(mLabelBuffer, labelSpan.data(), labelLength); + mLabelBuffer[labelLength] = '\0'; // Null-terminate the copied string + mLabel.SetValue(CharSpan(mLabelBuffer, labelLength)); + } + } + else + { + mLabel.ClearValue(); + } + + return CommissionerControlServer::Instance().GenerateCommissioningRequestResultEvent(result); +} + +CHIP_ERROR CommissionerControlDelegate::ValidateCommissionNodeCommand(NodeId clientNodeId, uint64_t requestId) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + + // Verify if the CommissionNode command is sent from the same NodeId as the RequestCommissioningApproval. + VerifyOrExit(mClientNodeId == clientNodeId, err = CHIP_ERROR_WRONG_NODE_ID); + + // Verify if the provided RequestId matches the value provided to the RequestCommissioningApproval. + VerifyOrExit(mRequestId == requestId, err = CHIP_ERROR_INCORRECT_STATE); + +exit: + return err; +} + +CHIP_ERROR CommissionerControlDelegate::GetCommissioningWindowParams(CommissioningWindowParams & outParams) +{ + // TODO: Populate outParams with the required details. + // outParams.commissioningWindowParams.iterations = mIterations; + // outParams.commissioningWindowParams.commissioningTimeout = mCommissioningTimeout; + // outParams.commissioningWindowParams.discriminator = mDiscriminator; + // outParams.commissioningWindowParams.PAKEPasscodeVerifier = mPAKEPasscodeVerifier; + // outParams.commissioningWindowParams.salt = mSalt; + + // outParams.ipAddress = mIpAddress; + // outParams.port = mPort; + + return CHIP_NO_ERROR; +} + +CHIP_ERROR CommissionerControlDelegate::ReverseCommissionNode(const CommissioningWindowParams & params, + const Optional & ipAddress, const Optional & port) +{ + return CHIP_NO_ERROR; +} + +} // namespace CommissionerControl +} // namespace Clusters +} // namespace app +} // namespace chip + +CHIP_ERROR CommissionerControlInit() +{ + CHIP_ERROR err; + + if (sCommissionerControlDelegate) + { + ChipLogError(NotSpecified, "Commissioner Control Delegate already exists."); + return CHIP_ERROR_INCORRECT_STATE; + } + + sCommissionerControlDelegate = std::make_unique(); + if (!sCommissionerControlDelegate) + { + ChipLogError(NotSpecified, "Failed to allocate memory for Commissioner Control Delegate."); + return CHIP_ERROR_NO_MEMORY; + } + + err = Clusters::CommissionerControl::CommissionerControlServer::Instance().Init(*sCommissionerControlDelegate); + if (err != CHIP_NO_ERROR) + { + ChipLogError(AppServer, "Initialization failed on Commissioner Control Delegate."); + sCommissionerControlDelegate.reset(); + return err; + } + + ChipLogProgress(Zcl, "Initializing SupportedDeviceCategories of Commissioner Control Cluster for this device."); + + BitMask supportedDeviceCategories; + supportedDeviceCategories.SetField(Clusters::CommissionerControl::SupportedDeviceCategoryBitmap::kFabricSynchronization, 1); + + Protocols::InteractionModel::Status status = + Clusters::CommissionerControl::CommissionerControlServer::Instance().SetSupportedDeviceCategoriesValue( + kRootEndpointId, supportedDeviceCategories); + + if (status != Protocols::InteractionModel::Status::Success) + { + ChipLogError(NotSpecified, "Failed to set SupportedDeviceCategories: %d", static_cast(status)); + sCommissionerControlDelegate.reset(); + return CHIP_ERROR_INTERNAL; + } + + return CHIP_NO_ERROR; +} + +CHIP_ERROR CommissionerControlShutdown() +{ + if (sCommissionerControlDelegate) + { + sCommissionerControlDelegate.reset(); + } + + return CHIP_NO_ERROR; +} diff --git a/examples/fabric-bridge-app/linux/main.cpp b/examples/fabric-bridge-app/linux/main.cpp index 1678ec59a8..57907db887 100644 --- a/examples/fabric-bridge-app/linux/main.cpp +++ b/examples/fabric-bridge-app/linux/main.cpp @@ -22,6 +22,7 @@ #include "BridgedDeviceBasicInformationImpl.h" #include "BridgedDeviceManager.h" #include "CommissionableInit.h" +#include "CommissionerControl.h" #include #include @@ -257,11 +258,19 @@ void ApplicationInit() pollingThread.detach(); BridgeDeviceMgr().Init(); + + VerifyOrDieWithMsg(CommissionerControlInit() == CHIP_NO_ERROR, NotSpecified, + "Failed to initialize Commissioner Control Server"); } void ApplicationShutdown() { ChipLogDetail(NotSpecified, "Fabric-Bridge: ApplicationShutdown()"); + + if (CommissionerControlShutdown() != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to shutdown Commissioner Control Server"); + } } int main(int argc, char * argv[]) From 04ac212a3a9e519d1fc65132578f069c6db0210b Mon Sep 17 00:00:00 2001 From: Marius Tache <102153746+marius-alex-tache@users.noreply.github.com> Date: Mon, 12 Aug 2024 16:11:09 +0300 Subject: [PATCH 017/165] [NXP][docker] Update k32w1 SDK (#34927) Signed-off-by: marius-alex-tache --- .../docker/images/base/chip-build/version | 2 +- .../images/stage-2/chip-build-k32w/Dockerfile | 17 +++++++++++------ 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/integrations/docker/images/base/chip-build/version b/integrations/docker/images/base/chip-build/version index 885f3e3912..0d78b8e5f7 100644 --- a/integrations/docker/images/base/chip-build/version +++ b/integrations/docker/images/base/chip-build/version @@ -1 +1 @@ -69 : [Infineon] Update ModusToolbox version to 3.2 +70 : [NXP] Update k32w1 SDK diff --git a/integrations/docker/images/stage-2/chip-build-k32w/Dockerfile b/integrations/docker/images/stage-2/chip-build-k32w/Dockerfile index 83f9f75613..d1b162e66c 100644 --- a/integrations/docker/images/stage-2/chip-build-k32w/Dockerfile +++ b/integrations/docker/images/stage-2/chip-build-k32w/Dockerfile @@ -14,7 +14,10 @@ RUN set -x \ WORKDIR /opt/sdk RUN set -x \ - && python3 -m pip install --break-system-packages -U --no-cache-dir west==1.0.0 \ + && python3 -m pip install --break-system-packages -U --no-cache-dir west==1.2.0 \ + && : # last line + +RUN set -x \ && west init -m https://github.com/nxp-mcuxpresso/mcux-sdk --mr "MCUX_2.6.14_K32W0" \ && west update \ && chmod +x core/tools/imagetool/sign_images.sh \ @@ -24,14 +27,16 @@ RUN set -x \ && : # last line RUN set -x \ - && mkdir -p k32w1 \ - && wget https://cache.nxp.com/lgfiles/bsps/SDK_2_12_7_K32W148-EVK.zip \ - && unzip SDK_2_12_7_K32W148-EVK.zip -d k32w1 \ - && rm -rf SDK_2_12_7_K32W148-EVK.zip + && mkdir -p k32w1/repo \ + && cd k32w1/repo + && west init -m https://github.com/nxp-mcuxpresso/mcux-sdk --mr "MCUX_2.16.000" \ + && west update -o=--depth=1 -n -f smart \ + && cd - \ + && : # last line FROM ghcr.io/project-chip/chip-build:${VERSION} COPY --from=build /opt/sdk/ /opt/sdk/ ENV NXP_K32W0_SDK_ROOT=/opt/sdk/core -ENV NXP_K32W1_SDK_ROOT=/opt/sdk/k32w1 +ENV NXP_SDK_ROOT=/opt/sdk/k32w1/repo From dc5bba717ac83edd61eeb8f2bbdf497a93aabcf1 Mon Sep 17 00:00:00 2001 From: PSONALl <77670766+PSONALl@users.noreply.github.com> Date: Mon, 12 Aug 2024 18:42:39 +0530 Subject: [PATCH 018/165] [ESP32] Delta OTA Feature (#29011) * [ESP32] Delta OTA Feature * Fix some issues with header * Update readme * Some refactoring and cleanups * Address review comments * Apply suggestions from code review Co-authored-by: Shubham Patil --------- Co-authored-by: PSONALl Co-authored-by: Rohit Jadhav Co-authored-by: Rohit Jadhav <69809379+jadhavrohit924@users.noreply.github.com> Co-authored-by: Shubham Patil --- config/esp32/components/chip/CMakeLists.txt | 6 + config/esp32/components/chip/Kconfig | 9 + .../esp32/components/chip/idf_component.yml | 6 + docs/guides/esp32/ota.md | 63 +++++ src/platform/ESP32/OTAImageProcessorImpl.cpp | 222 +++++++++++++++++- src/platform/ESP32/OTAImageProcessorImpl.h | 19 ++ 6 files changed, 324 insertions(+), 1 deletion(-) diff --git a/config/esp32/components/chip/CMakeLists.txt b/config/esp32/components/chip/CMakeLists.txt index ea2316851b..7e9894a8d6 100644 --- a/config/esp32/components/chip/CMakeLists.txt +++ b/config/esp32/components/chip/CMakeLists.txt @@ -483,6 +483,12 @@ endif() if (NOT EXECUTABLE_COMPONENT_NAME) set(EXECUTABLE_COMPONENT_NAME "main") endif() + +if (CONFIG_ENABLE_DELTA_OTA) + idf_component_get_property(esp_delta_ota_lib espressif__esp_delta_ota COMPONENT_LIB) + list(APPEND chip_libraries $) +endif() + idf_component_get_property(main_lib ${EXECUTABLE_COMPONENT_NAME} COMPONENT_LIB) list(APPEND chip_libraries $) diff --git a/config/esp32/components/chip/Kconfig b/config/esp32/components/chip/Kconfig index 5cd2700bb9..d3f621f98f 100644 --- a/config/esp32/components/chip/Kconfig +++ b/config/esp32/components/chip/Kconfig @@ -256,6 +256,15 @@ menu "CHIP Core" help Enable this option to use the pre encrypted OTA image + config ENABLE_DELTA_OTA + bool "Enable delta OTA" + depends on ENABLE_OTA_REQUESTOR + default n + help + Enable this option for delta OTA image updates. + Delta OTA updates allow for smaller, more efficient updates by only + sending the changes between the current and new firmware versions. + config OTA_AUTO_REBOOT_ON_APPLY bool "Reboot the device after applying the OTA image" depends on ENABLE_OTA_REQUESTOR diff --git a/config/esp32/components/chip/idf_component.yml b/config/esp32/components/chip/idf_component.yml index 8ef6302c5d..b56040ea3a 100644 --- a/config/esp32/components/chip/idf_component.yml +++ b/config/esp32/components/chip/idf_component.yml @@ -30,3 +30,9 @@ dependencies: version: "1.0.3" rules: - if: "idf_version >=5.0" + + espressif/esp_delta_ota: + version: "^1.1.0" + require: public + rules: + - if: "idf_version >=4.3" diff --git a/docs/guides/esp32/ota.md b/docs/guides/esp32/ota.md index 7c9c388b42..ae43e09bc0 100644 --- a/docs/guides/esp32/ota.md +++ b/docs/guides/esp32/ota.md @@ -121,3 +121,66 @@ Please follow the steps below to generate an application image for OTA upgrades: ``` 3. Use the `lighting-app-encrypted-ota.bin` file with the OTA Provider app. + +## Delta OTA + +Delta OTA Updates is a feature that enables Over-the-Air (OTA) firmware update +with compressed delta binaries. Patch files have smaller size than the original +firmware file, which reduces the time and network usage to download the file +from the server. Also, no additional storage partition is required for the +"patch". + +### Firmware Changes + +- Enable configuration options for OTA requestor and Delta OTA: + + ``` + CONFIG_ENABLE_OTA_REQUESTOR=y + CONFIG_ENABLE_DELTA_OTA=y + ``` + +Please follow the steps below to generate an application image for OTA upgrades: + +1. Delta binary needs to be generated using binary delta encoding in Python + 3.6+. You can install `detools` using the following command. + + ``` + pip install detools>=0.49.0 + ``` + +2. Generate delta binary. + + ``` + python managed_components/espressif__esp_delta_ota/examples/https_delta_ota/tools/esp_delta_ota_patch_gen.py --chip --base_binary --new_binary --patch_file_name + ``` + +3. Append the Matter OTA header: + `src/app/ota_image_tool.py create --vendor-id 0xFFF1 --product-id 0x8000 --version 2 --version-str "v2.0" -da sha256 lighting-app-delta-ota.bin` + +4. Use the `lighting-app-delta-ota.bin` file with the OTA Provider app. + +## Encrypted Delta OTA + +To use encrypted delta OTA, follow the below steps. + +### Firmware Changes + +- Enable configuration options for OTA requestor, Delta OTA and Encrypted OTA: + + ``` + CONFIG_ENABLE_OTA_REQUESTOR=y + CONFIG_ENABLE_DELTA_OTA=y + CONFIG_ENABLE_ENCRYPTED_OTA=y + ``` + +1. Follow the step of `Generate a new RSA-3072 key pair or use an existing one` + of + [Encrypted OTA](https://github.com/project-chip/connectedhomeip/blob/master/docs/guides/esp32/ota.md#encrypted-ota) + to build your binary. + +2. Create delta binary as shown in `Generate delta binary` of + [Delta OTA](https://github.com/project-chip/connectedhomeip/blob/master/docs/guides/esp32/ota.md#delta-ota) + +3. Encrypt the application binary. + +4. Append the Matter OTA header. diff --git a/src/platform/ESP32/OTAImageProcessorImpl.cpp b/src/platform/ESP32/OTAImageProcessorImpl.cpp index 73ba759c87..a35ca9a274 100644 --- a/src/platform/ESP32/OTAImageProcessorImpl.cpp +++ b/src/platform/ESP32/OTAImageProcessorImpl.cpp @@ -21,6 +21,7 @@ #include #include "OTAImageProcessorImpl.h" +#include "esp_app_format.h" #include "esp_err.h" #include "esp_log.h" #include "esp_ota_ops.h" @@ -31,7 +32,17 @@ #include #endif // CONFIG_ENABLE_ENCRYPTED_OTA +#ifdef CONFIG_ENABLE_DELTA_OTA +#include +#endif // CONFIG_ENABLE_DELTA_OTA + #define TAG "OTAImageProcessor" + +#ifdef CONFIG_ENABLE_DELTA_OTA +#define PATCH_HEADER_SIZE 64 +#define DIGEST_SIZE 32 +#endif // CONFIG_ENABLE_DELTA_OTA + using namespace chip::System; using namespace ::chip::DeviceLayer::Internal; @@ -123,6 +134,152 @@ CHIP_ERROR OTAImageProcessorImpl::ProcessBlock(ByteSpan & block) return CHIP_NO_ERROR; } +#ifdef CONFIG_ENABLE_DELTA_OTA +bool OTAImageProcessorImpl::VerifyChipId(esp_chip_id_t chipId) +{ + if (chipId != CONFIG_IDF_FIRMWARE_CHIP_ID) + { + ESP_LOGE(TAG, "Mismatch chip id, expected %d, found %d", CONFIG_IDF_FIRMWARE_CHIP_ID, chipId); + return false; + } + return true; +} + +bool OTAImageProcessorImpl::VerifyPatchHeader(void * imgHeaderData) +{ + const uint32_t espDeltaOtaMagic = 0xfccdde10; + if (!imgHeaderData) + { + return false; + } + uint32_t recvMagic = *(uint32_t *) imgHeaderData; + uint8_t * digest = (uint8_t *) ((uint8_t *) imgHeaderData + 4); + if (recvMagic != espDeltaOtaMagic) + { + ESP_LOGE(TAG, "Invalid magic word in patch"); + return false; + } + uint8_t sha_256[DIGEST_SIZE] = { 0 }; + esp_partition_get_sha256(esp_ota_get_running_partition(), sha_256); + if (memcmp(sha_256, digest, DIGEST_SIZE) != 0) + { + ESP_LOGE(TAG, "SHA256 of current firmware differs from than in patch header. Invalid patch for current firmware"); + return false; + } + return true; +} + +esp_err_t OTAImageProcessorImpl::VerifyHeaderData(const uint8_t * buf, size_t size, int * index) +{ + static char patchHeader[PATCH_HEADER_SIZE]; + static int headerDataRead = 0; + if (!patchHeaderVerified) + { + if (headerDataRead + size < PATCH_HEADER_SIZE) + { + memcpy(patchHeader + headerDataRead, buf, size); + headerDataRead += size; + return ESP_OK; + } + else + { + *index = PATCH_HEADER_SIZE - headerDataRead; + memcpy(patchHeader + headerDataRead, buf, *index); + if (!VerifyPatchHeader(patchHeader)) + { + return ESP_ERR_INVALID_VERSION; + } + headerDataRead = 0; + *index = PATCH_HEADER_SIZE; + patchHeaderVerified = true; + } + } + return ESP_OK; +} + +void OTAImageProcessorImpl::DeltaOTACleanUp(intptr_t context) +{ + auto * imageProcessor = reinterpret_cast(context); + if (imageProcessor == nullptr) + { + ChipLogError(SoftwareUpdate, "ImageProcessor context is null"); + return; + } + imageProcessor->patchHeaderVerified = false; + imageProcessor->chipIdVerified = false; + return; +} + +esp_err_t OTAImageProcessorImpl::DeltaOTAReadCallback(uint8_t * buf, size_t size, int srcOffset) +{ + if (size <= 0 || buf == NULL) + { + return ESP_ERR_INVALID_ARG; + } + + const esp_partition_t * currentPartition = esp_ota_get_running_partition(); + if (currentPartition == NULL) + { + return ESP_FAIL; + } + + esp_err_t err = esp_partition_read(currentPartition, srcOffset, buf, size); + + if (err != ESP_OK) + { + ESP_LOGE(TAG, "esp_partition_read failed (%s)!", esp_err_to_name(err)); + } + + return err; +} + +esp_err_t OTAImageProcessorImpl::DeltaOTAWriteCallback(const uint8_t * buf, size_t size, void * arg) +{ + auto * imageProcessor = reinterpret_cast(arg); + if (size <= 0 || buf == NULL) + { + return ESP_ERR_INVALID_ARG; + } + + int index = 0; + static int headerDataRead = 0; + static char headerData[IMG_HEADER_LEN]; + + if (!imageProcessor->chipIdVerified) + { + if (headerDataRead + size - index <= IMG_HEADER_LEN) + { + memcpy(headerData + headerDataRead, buf, size - index); + headerDataRead += size - index; + return ESP_OK; + } + else + { + index = IMG_HEADER_LEN - headerDataRead; + memcpy(headerData + headerDataRead, buf, index); + + esp_image_header_t * header = (esp_image_header_t *) headerData; + if (!VerifyChipId(header->chip_id)) + { + return ESP_ERR_INVALID_VERSION; + } + imageProcessor->chipIdVerified = true; + + // Write data in headerData buffer. + return esp_ota_write(imageProcessor->mOTAUpdateHandle, headerData, IMG_HEADER_LEN); + } + } + + esp_err_t err = esp_ota_write(imageProcessor->mOTAUpdateHandle, buf + index, size - index); + if (err != ESP_OK) + { + ESP_LOGE(TAG, "esp_ota_write failed (%s)!", esp_err_to_name(err)); + } + + return err; +} +#endif // CONFIG_ENABLE_DELTA_OTA + void OTAImageProcessorImpl::HandlePrepareDownload(intptr_t context) { auto * imageProcessor = reinterpret_cast(context); @@ -142,13 +299,32 @@ void OTAImageProcessorImpl::HandlePrepareDownload(intptr_t context) ChipLogError(SoftwareUpdate, "OTA partition not found"); return; } +#ifdef CONFIG_ENABLE_DELTA_OTA + // New image size is unknown for delta OTA, so we use OTA_SIZE_UNKNOWN flag. + esp_err_t err = esp_ota_begin(imageProcessor->mOTAUpdatePartition, OTA_SIZE_UNKNOWN, &(imageProcessor->mOTAUpdateHandle)); +#else esp_err_t err = esp_ota_begin(imageProcessor->mOTAUpdatePartition, OTA_WITH_SEQUENTIAL_WRITES, &(imageProcessor->mOTAUpdateHandle)); +#endif // CONFIG_ENABLE_DELTA_OTA + if (err != ESP_OK) { imageProcessor->mDownloader->OnPreparedForDownload(ESP32Utils::MapError(err)); return; } +#ifdef CONFIG_ENABLE_DELTA_OTA + imageProcessor->deltaOtaCfg.user_data = imageProcessor, + imageProcessor->deltaOtaCfg.read_cb = &(imageProcessor->DeltaOTAReadCallback), + imageProcessor->deltaOtaCfg.write_cb_with_user_data = &(imageProcessor->DeltaOTAWriteCallback), + + imageProcessor->mDeltaOTAUpdateHandle = esp_delta_ota_init(&imageProcessor->deltaOtaCfg); + if (imageProcessor->mDeltaOTAUpdateHandle == NULL) + { + ChipLogError(SoftwareUpdate, "esp_delta_ota_init failed"); + imageProcessor->mDownloader->OnPreparedForDownload(CHIP_ERROR_INTERNAL); + return; + } +#endif // CONFIG_ENABLE_DELTA_OTA #ifdef CONFIG_ENABLE_ENCRYPTED_OTA CHIP_ERROR chipError = imageProcessor->DecryptStart(); @@ -182,7 +358,30 @@ void OTAImageProcessorImpl::HandleFinalize(intptr_t context) } #endif // CONFIG_ENABLE_ENCRYPTED_OTA +#ifdef CONFIG_ENABLE_DELTA_OTA + esp_err_t err = esp_delta_ota_finalize(imageProcessor->mDeltaOTAUpdateHandle); + if (err != ESP_OK) + { + ESP_LOGE(TAG, "esp_delta_ota_finalize() failed (%s)!", esp_err_to_name(err)); + esp_ota_abort(imageProcessor->mOTAUpdateHandle); + imageProcessor->ReleaseBlock(); + PostOTAStateChangeEvent(DeviceLayer::kOtaDownloadFailed); + } + + err = esp_delta_ota_deinit(imageProcessor->mDeltaOTAUpdateHandle); + if (err != ESP_OK) + { + ESP_LOGE(TAG, "esp_delta_ota_deinit() failed (%s)!", esp_err_to_name(err)); + esp_ota_abort(imageProcessor->mOTAUpdateHandle); + imageProcessor->ReleaseBlock(); + PostOTAStateChangeEvent(DeviceLayer::kOtaDownloadFailed); + } + + err = esp_ota_end(imageProcessor->mOTAUpdateHandle); + DeltaOTACleanUp(reinterpret_cast(imageProcessor)); +#else esp_err_t err = esp_ota_end(imageProcessor->mOTAUpdateHandle); +#endif // CONFIG_ENABLE_DELTA_OTA if (err != ESP_OK) { if (err == ESP_ERR_OTA_VALIDATE_FAILED) @@ -217,6 +416,10 @@ void OTAImageProcessorImpl::HandleAbort(intptr_t context) imageProcessor->DecryptAbort(); #endif // CONFIG_ENABLE_ENCRYPTED_OTA +#ifdef CONFIG_ENABLE_DELTA_OTA + DeltaOTACleanUp(reinterpret_cast(imageProcessor)); +#endif // CONFIG_ENABLE_DELTA_OTA + if (esp_ota_abort(imageProcessor->mOTAUpdateHandle) != ESP_OK) { ESP_LOGE(TAG, "ESP OTA abort failed"); @@ -264,7 +467,24 @@ void OTAImageProcessorImpl::HandleProcessBlock(intptr_t context) } #endif // CONFIG_ENABLE_ENCRYPTED_OTA - err = esp_ota_write(imageProcessor->mOTAUpdateHandle, blockToWrite.data(), blockToWrite.size()); +#ifdef CONFIG_ENABLE_DELTA_OTA + + int index = 0; + err = imageProcessor->VerifyHeaderData(blockToWrite.data(), blockToWrite.size(), &index); + + if (err != ESP_OK) + { + ESP_LOGE(TAG, "Header data verification failed (%s)", esp_err_to_name(err)); + imageProcessor->mDownloader->EndDownload(CHIP_ERROR_INVALID_SIGNATURE); + PostOTAStateChangeEvent(DeviceLayer::kOtaDownloadFailed); + return; + } + + // Apply the patch and writes that data to the passive partition. + err = esp_delta_ota_feed_patch(imageProcessor->mDeltaOTAUpdateHandle, blockToWrite.data() + index, blockToWrite.size() - index); +#else + err = esp_ota_write(imageProcessor->mOTAUpdateHandle, blockToWrite.data(), blockToWrite.size()); +#endif // CONFIG_ENABLE_DELTA_OTA #ifdef CONFIG_ENABLE_ENCRYPTED_OTA free((void *) (blockToWrite.data())); diff --git a/src/platform/ESP32/OTAImageProcessorImpl.h b/src/platform/ESP32/OTAImageProcessorImpl.h index c33407dad7..3414f90b42 100644 --- a/src/platform/ESP32/OTAImageProcessorImpl.h +++ b/src/platform/ESP32/OTAImageProcessorImpl.h @@ -27,6 +27,12 @@ #include #endif // CONFIG_ENABLE_ENCRYPTED_OTA +#ifdef CONFIG_ENABLE_DELTA_OTA +#include "esp_app_format.h" +#include +#define IMG_HEADER_LEN sizeof(esp_image_header_t) +#endif // CONFIG_ENABLE_DELTA_OTA + namespace chip { class OTAImageProcessorImpl : public OTAImageProcessorInterface @@ -64,6 +70,19 @@ class OTAImageProcessorImpl : public OTAImageProcessorInterface MutableByteSpan mBlock; const esp_partition_t * mOTAUpdatePartition = nullptr; esp_ota_handle_t mOTAUpdateHandle; +#ifdef CONFIG_ENABLE_DELTA_OTA + esp_delta_ota_handle_t mDeltaOTAUpdateHandle; + esp_delta_ota_cfg_t deltaOtaCfg; + bool patchHeaderVerified = false; + bool chipIdVerified = false; + + static void DeltaOTACleanUp(intptr_t context); + static bool VerifyChipId(esp_chip_id_t chipId); + static bool VerifyPatchHeader(void * imgHeaderData); + esp_err_t VerifyHeaderData(const uint8_t * buf, size_t size, int * index); + static esp_err_t DeltaOTAReadCallback(uint8_t * buf_p, size_t size, int src_offset); + static esp_err_t DeltaOTAWriteCallback(const uint8_t * buf_p, size_t size, void * arg); +#endif // CONFIG_ENABLE_DELTA_OTA OTAImageHeaderParser mHeaderParser; #ifdef CONFIG_ENABLE_ENCRYPTED_OTA From e994cbfa73da18120938a2342f587ec125510819 Mon Sep 17 00:00:00 2001 From: Andrei Litvin Date: Mon, 12 Aug 2024 12:42:00 -0400 Subject: [PATCH 019/165] Fix typo in NXP dockerfile: missing backslash (#34931) --- integrations/docker/images/stage-2/chip-build-k32w/Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/integrations/docker/images/stage-2/chip-build-k32w/Dockerfile b/integrations/docker/images/stage-2/chip-build-k32w/Dockerfile index d1b162e66c..d70fcd4bb2 100644 --- a/integrations/docker/images/stage-2/chip-build-k32w/Dockerfile +++ b/integrations/docker/images/stage-2/chip-build-k32w/Dockerfile @@ -28,7 +28,7 @@ RUN set -x \ RUN set -x \ && mkdir -p k32w1/repo \ - && cd k32w1/repo + && cd k32w1/repo \ && west init -m https://github.com/nxp-mcuxpresso/mcux-sdk --mr "MCUX_2.16.000" \ && west update -o=--depth=1 -n -f smart \ && cd - \ From 25f879f7c4c4989f43fae3ec4087f3273807f532 Mon Sep 17 00:00:00 2001 From: William Date: Mon, 12 Aug 2024 19:09:08 +0100 Subject: [PATCH 020/165] Fixed test 1.6 and updated the scripts to work in CI. (#34918) * Fixed test 1.6 and updated the scripts to work in CI. * Restyled by autopep8 --------- Co-authored-by: Restyled.io --- src/python_testing/TC_SEAR_1_6.py | 28 +++++++++++++++++++--------- 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/src/python_testing/TC_SEAR_1_6.py b/src/python_testing/TC_SEAR_1_6.py index 02a0fcdd33..aaa6ac788d 100644 --- a/src/python_testing/TC_SEAR_1_6.py +++ b/src/python_testing/TC_SEAR_1_6.py @@ -52,7 +52,7 @@ async def read_supported_areas(self, step): self.print_step(step, "Read SupportedAreas attribute") supported_areas = await self.read_sear_attribute_expect_success( endpoint=self.endpoint, attribute=Clusters.ServiceArea.Attributes.SupportedAreas) - logging.info("SupportedAreas: %s" % (supported_areas)) + logging.info("SupportedAreas: %s" % supported_areas) return [a.areaID for a in supported_areas] @@ -77,7 +77,7 @@ def write_to_app_pipe(self, command): with open(self.app_pipe, "w") as app_pipe: app_pipe.write(command + "\n") # Allow some time for the command to take effect. - # This removes the test flakyness which is very annoying for everyone in CI. + # This removes the test flakiness which is very annoying for everyone in CI. sleep(0.001) def TC_SEAR_1_6(self) -> list[str]: @@ -102,7 +102,10 @@ async def test_TC_SEAR_1_6(self): test_step = "Manually intervene to put the device in the idle state and ensure SupportedAreas and SelectedAreas are not empty" self.print_step("2", test_step) - if not self.is_ci: + if self.is_ci: + await self.send_single_cmd(cmd=Clusters.Objects.ServiceArea.Commands.SelectAreas(newAreas=[7, 1234567]), + endpoint=self.endpoint) + else: self.wait_for_user_input(prompt_msg=f"{test_step}, and press Enter when done.\n") supported_area_ids = await self.read_supported_areas(step=3) @@ -113,7 +116,10 @@ async def test_TC_SEAR_1_6(self): test_step = "Manually intervene to put the device in the operating state" self.print_step("5", test_step) - if not self.is_ci: + if self.is_ci: + await self.send_single_cmd(cmd=Clusters.Objects.RvcRunMode.Commands.ChangeToMode(newMode=1), + endpoint=self.endpoint) + else: self.wait_for_user_input(prompt_msg=f"{test_step}, and press Enter when done.\n") progress_list_operating = await self.read_progress(step=6) @@ -122,16 +128,20 @@ async def test_TC_SEAR_1_6(self): for p in progress_list_operating: asserts.assert_true(p.areaID in selected_areas, f"Progress entry with unknown AreaID({p.areaID})") - asserts.assert_true(p.status in (Clusters.ServiceArea.OperationalStatusEnum.kPending, - Clusters.ServiceArea.OperationalStatusEnum.kOperating), + asserts.assert_true(p.status in (Clusters.ServiceArea.Enums.OperationalStatusEnum.kPending, + Clusters.ServiceArea.Enums.OperationalStatusEnum.kOperating), f"Progress entry with unexpected Status({p.status})") - asserts.assert_true(p.TotalOperationalTime is NullValue, "Progress entry with non-null TotalOperationalTime") + asserts.assert_true(type(p.totalOperationalTime) in [type(None), type( + NullValue)], "Progress.TotalOperationalTime has a value") test_step = "While all entries in Progress show the Pending or Operating status (i.e. \ before any area is skipped or completed), manually intervene to put the device \ in the idle state, by ending the operation unexpectedly (e.g. force an error)" self.print_step("7", test_step) - if not self.is_ci: + if self.is_ci: + await self.send_single_cmd(cmd=Clusters.Objects.RvcRunMode.Commands.ChangeToMode(newMode=0), + endpoint=self.endpoint) + else: self.wait_for_user_input(prompt_msg=f"{test_step}, and press Enter when done.\n") progress_list_idle = await self.read_progress(step=8) @@ -140,7 +150,7 @@ async def test_TC_SEAR_1_6(self): for p in progress_list_idle: asserts.assert_true(p.areaID in selected_areas, f"Progress entry with unknown AreaID({p.areaID})") - asserts.assert_true(p.status == Clusters.ServiceArea.OperationalStatusEnum.kSkipped, + asserts.assert_true(p.status == Clusters.ServiceArea.Enums.OperationalStatusEnum.kSkipped, f"Progress entry with unexpected Status({p.status})") From 354464e4444e712df559ee3cece4872fe00f84b6 Mon Sep 17 00:00:00 2001 From: Marius Tache <102153746+marius-alex-tache@users.noreply.github.com> Date: Mon, 12 Aug 2024 21:23:27 +0300 Subject: [PATCH 021/165] [NXP][k32w1] Fix docker image (#34935) Create a separate folder for each west workspace. Signed-off-by: marius-alex-tache --- .../docker/images/stage-2/chip-build-k32w/Dockerfile | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/integrations/docker/images/stage-2/chip-build-k32w/Dockerfile b/integrations/docker/images/stage-2/chip-build-k32w/Dockerfile index d70fcd4bb2..9b222355fb 100644 --- a/integrations/docker/images/stage-2/chip-build-k32w/Dockerfile +++ b/integrations/docker/images/stage-2/chip-build-k32w/Dockerfile @@ -19,24 +19,24 @@ RUN set -x \ RUN set -x \ && west init -m https://github.com/nxp-mcuxpresso/mcux-sdk --mr "MCUX_2.6.14_K32W0" \ - && west update \ + && west update -o=--depth=1 -n -f smart \ && chmod +x core/tools/imagetool/sign_images.sh \ && ln -sf ../rtos core \ && ln -sf ../middleware core \ && cp -R examples/* core/boards && rm -rf examples \ && : # last line +WORKDIR /opt/k32w1_sdk + RUN set -x \ - && mkdir -p k32w1/repo \ - && cd k32w1/repo \ && west init -m https://github.com/nxp-mcuxpresso/mcux-sdk --mr "MCUX_2.16.000" \ && west update -o=--depth=1 -n -f smart \ - && cd - \ && : # last line FROM ghcr.io/project-chip/chip-build:${VERSION} COPY --from=build /opt/sdk/ /opt/sdk/ +COPY --from=build /opt/k32w1_sdk/ /opt/k32w1_sdk/ ENV NXP_K32W0_SDK_ROOT=/opt/sdk/core -ENV NXP_SDK_ROOT=/opt/sdk/k32w1/repo +ENV NXP_SDK_ROOT=/opt/k32w1_sdk From 10531e1cd18be7a288798a8b5e4e7a985586e311 Mon Sep 17 00:00:00 2001 From: Justin Wood Date: Mon, 12 Aug 2024 15:07:25 -0700 Subject: [PATCH 022/165] Checking third party deps doesn't pass after someone fixes it (#34872) * Fixing this to stop breaking PRs * Qualifying as expression * Making this more readable now that it's an expression --- .github/workflows/third-party-check.yaml | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/.github/workflows/third-party-check.yaml b/.github/workflows/third-party-check.yaml index 575e7e3c9c..beda0af41b 100644 --- a/.github/workflows/third-party-check.yaml +++ b/.github/workflows/third-party-check.yaml @@ -17,7 +17,7 @@ name: Check for Unintentional Submodule Updates on: pull_request: branches-ignore: - - 'dependabot/**' + - "dependabot/**" paths: - "third_party/**" - ".gitmodules" @@ -26,9 +26,14 @@ jobs: check-submodule-update-label: name: Check For Submodule Update Label runs-on: ubuntu-latest - if: "!contains(github.event.pull_request.labels.*.name, 'changing-submodules-on-purpose')" steps: - - name: Error Message - run: echo This pull request attempts to update submodules without the changing-submodules-on-purpose label. Please apply that label if the changes are intentional, or remove those changes. - - name: Fail Job - run: exit 1 + - if: ${{ !contains(github.event.pull_request.labels.*.name, 'changing-submodules-on-purpose') }} + name: Fail + run: | + echo This pull request attempts to update submodules without the changing-submodules-on-purpose label. Please apply that label if the changes are intentional, or remove those changes. + exit 1 + - if: ${{ contains(github.event.pull_request.labels.*.name, 'changing-submodules-on-purpose') }} + name: Success + run: | + echo PR looks good. + exit 0 From 20d6857cf5f3c67ffe24cba02f67ff1b372bab29 Mon Sep 17 00:00:00 2001 From: Youngho Yoon <34558998+yhoyoon@users.noreply.github.com> Date: Tue, 13 Aug 2024 08:49:39 +0900 Subject: [PATCH 023/165] Implement the AndroidChipLogging (#34899) * Refine android log priority based on category This change adds ANDROID_LOG_INFO priority for kLogCategory_Progress. Refine android log priorities to enhance debugging efficiency and prepare an environment where lower-priority logs can be controlled and excluded using the log filter function. Signed-off-by: Youngho Yoon <34558998+yhoyoon@users.noreply.github.com> * Implement the AndroidChipLogging Implemented the AndroidChipLogging.setLogFilter to enhance the logging mechanism. This method allows for the filtering out of unnecessary or redundant log messages, significantly reducing noise in the logs. To use the log filter, call AndroidChipLogging.setLogFilter with the appropriate filter criteria. The arg is log level in android.util.Log. Example: AndroidChipLogging.setLogFilter(android.util.Log.ERROR) Signed-off-by: Youngho Yoon <34558998+yhoyoon@users.noreply.github.com> * Restyled by google-java-format --------- Signed-off-by: Youngho Yoon <34558998+yhoyoon@users.noreply.github.com> Co-authored-by: Restyled.io --- .../android/AndroidChipPlatform-JNI.cpp | 29 +++++++++++++++++++ src/platform/android/BUILD.gn | 1 + src/platform/android/CHIPPlatformConfig.h | 2 +- src/platform/android/Logging.cpp | 16 +++++++++- .../chip/platform/AndroidChipLogging.java | 23 +++++++++++++++ 5 files changed, 69 insertions(+), 2 deletions(-) create mode 100644 src/platform/android/java/chip/platform/AndroidChipLogging.java diff --git a/src/platform/android/AndroidChipPlatform-JNI.cpp b/src/platform/android/AndroidChipPlatform-JNI.cpp index a5863a0c73..45f54835d4 100644 --- a/src/platform/android/AndroidChipPlatform-JNI.cpp +++ b/src/platform/android/AndroidChipPlatform-JNI.cpp @@ -28,12 +28,15 @@ #include #include #include +#include #include #include #include #include #include +#include + #include "AndroidChipPlatform-JNI.h" #include "BLEManagerImpl.h" #include "BleConnectCallback-JNI.h" @@ -45,6 +48,8 @@ using namespace chip; #define JNI_METHOD(RETURN, METHOD_NAME) extern "C" JNIEXPORT RETURN JNICALL Java_chip_platform_AndroidChipPlatform_##METHOD_NAME +#define JNI_LOGGING_METHOD(RETURN, METHOD_NAME) \ + extern "C" JNIEXPORT RETURN JNICALL Java_chip_platform_AndroidChipLogging_##METHOD_NAME #define JNI_MDNSCALLBACK_METHOD(RETURN, METHOD_NAME) \ extern "C" JNIEXPORT RETURN JNICALL Java_chip_platform_ChipMdnsCallbackImpl_##METHOD_NAME @@ -245,6 +250,30 @@ JNI_METHOD(void, nativeSetDnssdDelegates)(JNIEnv * env, jclass self, jobject res chip::Dnssd::InitializeWithObjects(resolver, browser, chipMdnsCallback); } +JNI_LOGGING_METHOD(void, setLogFilter)(JNIEnv * env, jclass clazz, jint level) +{ + using namespace chip::Logging; + + uint8_t category = kLogCategory_Detail; + switch (level) + { + case ANDROID_LOG_VERBOSE: + case ANDROID_LOG_DEBUG: + category = kLogCategory_Detail; + break; + case ANDROID_LOG_INFO: + category = kLogCategory_Progress; + break; + case ANDROID_LOG_WARN: + case ANDROID_LOG_ERROR: + category = kLogCategory_Error; + break; + default: + break; + } + SetLogFilter(category); +} + JNI_MDNSCALLBACK_METHOD(void, handleServiceResolve) (JNIEnv * env, jclass self, jstring instanceName, jstring serviceType, jstring hostName, jstring address, jint port, jobject attributes, jlong callbackHandle, jlong contextHandle) diff --git a/src/platform/android/BUILD.gn b/src/platform/android/BUILD.gn index aa6f59ab51..640b524900 100644 --- a/src/platform/android/BUILD.gn +++ b/src/platform/android/BUILD.gn @@ -114,6 +114,7 @@ android_library("java") { sources = [ "java/chip/platform/AndroidBleManager.java", + "java/chip/platform/AndroidChipLogging.java", "java/chip/platform/AndroidChipPlatform.java", "java/chip/platform/AndroidChipPlatformException.java", "java/chip/platform/BleCallback.java", diff --git a/src/platform/android/CHIPPlatformConfig.h b/src/platform/android/CHIPPlatformConfig.h index 19ba3d1135..352dc41f41 100644 --- a/src/platform/android/CHIPPlatformConfig.h +++ b/src/platform/android/CHIPPlatformConfig.h @@ -48,7 +48,7 @@ using CHIP_CONFIG_PERSISTED_STORAGE_KEY_TYPE = const char *; #endif // CHIP_CONFIG_MAX_EXCHANGE_CONTEXTS #ifndef CHIP_LOG_FILTERING -#define CHIP_LOG_FILTERING 0 +#define CHIP_LOG_FILTERING 1 #endif // CHIP_LOG_FILTERING #ifndef CHIP_CONFIG_BDX_MAX_NUM_TRANSFERS diff --git a/src/platform/android/Logging.cpp b/src/platform/android/Logging.cpp index 404c76f803..ccdaa8dffc 100644 --- a/src/platform/android/Logging.cpp +++ b/src/platform/android/Logging.cpp @@ -12,7 +12,21 @@ namespace Platform { void LogV(const char * module, uint8_t category, const char * msg, va_list v) { - int priority = (category == kLogCategory_Error) ? ANDROID_LOG_ERROR : ANDROID_LOG_DEBUG; + int priority = ANDROID_LOG_DEBUG; + switch (category) + { + case kLogCategory_Error: + priority = ANDROID_LOG_ERROR; + break; + case kLogCategory_Progress: + priority = ANDROID_LOG_INFO; + break; + case kLogCategory_Detail: + priority = ANDROID_LOG_DEBUG; + break; + default: + break; + } __android_log_vprint(priority, module, msg, v); } diff --git a/src/platform/android/java/chip/platform/AndroidChipLogging.java b/src/platform/android/java/chip/platform/AndroidChipLogging.java new file mode 100644 index 0000000000..4f41b21b78 --- /dev/null +++ b/src/platform/android/java/chip/platform/AndroidChipLogging.java @@ -0,0 +1,23 @@ +/* + * 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. + * + */ +package chip.platform; + +public class AndroidChipLogging { + // logging level is in android.util.Log class + public static native void setLogFilter(int level); +} From 8eccf68b82022881dfeded94259156433e072183 Mon Sep 17 00:00:00 2001 From: Karsten Sperling <113487422+ksperling-apple@users.noreply.github.com> Date: Tue, 13 Aug 2024 23:20:47 +1200 Subject: [PATCH 024/165] Syslog and logging tweaks (#34941) * Make syslog ident and facility overridable and tweak options * Linux: Be a little less verbose when writing settings --- src/platform/Linux/CHIPLinuxStorageIni.cpp | 6 +----- src/platform/logging/impl/Syslog.cpp | 10 +++++++++- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/src/platform/Linux/CHIPLinuxStorageIni.cpp b/src/platform/Linux/CHIPLinuxStorageIni.cpp index 1a96887628..7186fe3d47 100644 --- a/src/platform/Linux/CHIPLinuxStorageIni.cpp +++ b/src/platform/Linux/CHIPLinuxStorageIni.cpp @@ -98,17 +98,13 @@ CHIP_ERROR ChipLinuxStorageIni::CommitConfig(const std::string & configFile) if (fd != -1) { std::ofstream ofs; - - ChipLogProgress(DeviceLayer, "writing settings to file (%s)", tmpPath.c_str()); - ofs.open(tmpPath, std::ofstream::out | std::ofstream::trunc); mConfigStore.generate(ofs); - close(fd); if (rename(tmpPath.c_str(), configFile.c_str()) == 0) { - ChipLogProgress(DeviceLayer, "renamed tmp file to file (%s)", configFile.c_str()); + ChipLogDetail(DeviceLayer, "wrote settings to %s", configFile.c_str()); } else { diff --git a/src/platform/logging/impl/Syslog.cpp b/src/platform/logging/impl/Syslog.cpp index 163e6d7398..638cffeb94 100644 --- a/src/platform/logging/impl/Syslog.cpp +++ b/src/platform/logging/impl/Syslog.cpp @@ -23,6 +23,14 @@ #include #include +#ifndef CHIP_SYSLOG_IDENT +#define CHIP_SYSLOG_IDENT nullptr +#endif + +#ifndef CHIP_SYSLOG_FACILITY +#define CHIP_SYSLOG_FACILITY LOG_DAEMON +#endif + namespace chip { namespace Logging { namespace Platform { @@ -51,7 +59,7 @@ void LogV(const char * module, uint8_t category, const char * msg, va_list v) if (!sInitialized) { - openlog(nullptr, 0, LOG_DAEMON); + openlog(CHIP_SYSLOG_IDENT, LOG_CONS | LOG_PID, CHIP_SYSLOG_FACILITY); sInitialized = true; } From ddf44dc121b1e3973e4d7f8d53fd78a3680c0022 Mon Sep 17 00:00:00 2001 From: William Date: Tue, 13 Aug 2024 12:22:19 +0100 Subject: [PATCH 025/165] Add out-of-band msgs to add and remove Supported Areas and Maps (#34930) * update the status field of progress elements at the end of a clean. * Added some style suggestions from the review of PR 34887. * update the readme. * Added a simple message to add a map. * Added an out-of-band message to add a supported area. * Added out-of-band messages to remove supported maps and supported areas. * Updated the rvc-app PICS values. Updated TC-SEAR-1.2 to include the necessary out-of-band messages to run the test in CI. * refactored to improve readability. * Restyled by clang-format * Restyled by prettier-markdown * Removed oddly duplicated method. * Fixed the json value conversion types. --------- Co-authored-by: Restyled.io --- examples/rvc-app/README.md | 37 ++++- .../rvc-app/linux/RvcAppCommandDelegate.cpp | 88 ++++++++++++ .../rvc-app/linux/RvcAppCommandDelegate.h | 8 ++ .../rvc-app/rvc-common/include/rvc-device.h | 8 ++ .../include/rvc-service-area-delegate.h | 16 ++- .../rvc-common/pics/rvc-app-pics-values | 8 +- .../rvc-app/rvc-common/src/rvc-device.cpp | 22 +++ .../src/rvc-service-area-delegate.cpp | 126 +++++++++++++++++- src/python_testing/TC_SEAR_1_2.py | 16 ++- 9 files changed, 317 insertions(+), 12 deletions(-) diff --git a/examples/rvc-app/README.md b/examples/rvc-app/README.md index 8cc6e7308b..da9317f508 100644 --- a/examples/rvc-app/README.md +++ b/examples/rvc-app/README.md @@ -20,7 +20,42 @@ must have a `"Name"` key that contains the command name. This name is shown in the state machine diagram above. Example `echo '{"Name": "Charged"}' > /tmp/chip_rvc_fifo_42`. -### `AreaComplete` message +### ServiceArea related messages + +#### `AddMap` message + +This message adds a map to the SupportedMaps attribute of the Service Area +cluster. This message requires the following extra keys. + +- `MapId` This is an `int` setting the ID of the new map. +- `MapName` This is a `string` setting the name of the new map. + +#### `AddArea` message + +This message adds a new area to the SupportedAreas attribute of the Service Area +cluster. This message requires the following extra keys, most of which are +optional. Consult the `SupportedAreas` attribute spec for more information on +what are valid areas. + +- `AreaId` This is an `int` setting the ID of the area. +- `MapId` This is an `int` sitting the map ID the area is associated with. +- `LocationName` This is a `string` setting the location's name. +- `FloorNumber` This is an `int` setting the floor number of the area. +- `AreaType` This is an `int` setting the area type tag. +- `LandmarkTag` This is an `int` setting the landmark tag. +- `PositianTag` This is an `int` setting the position tag. + +#### `RemoveMap` message + +This message removes a map with the given map ID. This message requires the +`int` key `MapId`. + +#### `RemoveArea` message + +This message removes an area with the given area ID. This message requires the +`int` key `AreaId`. + +#### `AreaComplete` message This indicates that the area currently being serviced as indicated by the service area cluster is now complete. diff --git a/examples/rvc-app/linux/RvcAppCommandDelegate.cpp b/examples/rvc-app/linux/RvcAppCommandDelegate.cpp index 5a08dc6c9f..791df4d482 100644 --- a/examples/rvc-app/linux/RvcAppCommandDelegate.cpp +++ b/examples/rvc-app/linux/RvcAppCommandDelegate.cpp @@ -17,6 +17,7 @@ */ #include "RvcAppCommandDelegate.h" +#include #include #include "rvc-device.h" @@ -24,6 +25,7 @@ #include using namespace chip; +using namespace chip::app; using namespace chip::app::Clusters; RvcAppCommandHandler * RvcAppCommandHandler::FromJSON(const char * json) @@ -87,6 +89,25 @@ void RvcAppCommandHandler::HandleCommand(intptr_t context) { self->OnAreaCompleteHandler(); } + else if (name == "AddMap") + { + self->OnAddServiceAreaMap(self->mJsonValue); + } + else if (name == "AddArea") + { + VerifyOrExit(self->mJsonValue.isMember("AreaId"), ChipLogError(NotSpecified, "RVC App: AreaId key is missing")); + self->OnAddServiceAreaArea(self->mJsonValue); + } + else if (name == "RemoveMap") + { + VerifyOrExit(self->mJsonValue.isMember("MapId"), ChipLogError(NotSpecified, "RVC App: MapId key is missing")); + self->OnRemoveServiceAreaMap(self->mJsonValue["MapId"].asUInt()); + } + else if (name == "RemoveArea") + { + VerifyOrExit(self->mJsonValue.isMember("AreaId"), ChipLogError(NotSpecified, "RVC App: AreaId key is missing")); + self->OnRemoveServiceAreaArea(self->mJsonValue["AreaId"].asUInt()); + } else if (name == "ErrorEvent") { std::string error = self->mJsonValue["Error"].asString(); @@ -149,6 +170,73 @@ void RvcAppCommandHandler::OnAreaCompleteHandler() mRvcDevice->HandleAreaCompletedEvent(); } +void RvcAppCommandHandler::OnAddServiceAreaMap(Json::Value jsonValue) +{ + // Find if self->mJsonValue has the MapId and MapName Keys + if (jsonValue.isMember("MapId") && jsonValue.isMember("MapName")) + { + uint32_t mapId = jsonValue["MapId"].asUInt(); + std::string mapName = jsonValue["MapName"].asString(); + mRvcDevice->HandleAddServiceAreaMap(mapId, CharSpan(mapName.data(), mapName.size())); + } + else + { + ChipLogError(NotSpecified, "RVC App: MapId and MapName keys are missing"); + } +} + +void RvcAppCommandHandler::OnAddServiceAreaArea(Json::Value jsonValue) +{ + ServiceArea::AreaStructureWrapper area; + area.SetAreaId(jsonValue["AreaId"].asUInt()); + if (jsonValue.isMember("MapId")) + { + area.SetMapId(jsonValue["MapId"].asUInt()); + } + + // Set the location info + if (jsonValue.isMember("LocationName") || jsonValue.isMember("FloorNumber") || jsonValue.isMember("AreaType")) + { + DataModel::Nullable floorNumber = DataModel::NullNullable; + if (jsonValue.isMember("FloorNumber")) + { + floorNumber = jsonValue["FloorNumber"].asInt(); + } + DataModel::Nullable areaType = DataModel::NullNullable; + if (jsonValue.isMember("AreaType")) + { + areaType = Globals::AreaTypeTag(jsonValue["AreaType"].asUInt()); + } + auto locationName = jsonValue["LocationName"].asString(); + + area.SetLocationInfo(CharSpan(locationName.data(), locationName.size()), floorNumber, areaType); + } + + // Set landmark info + if (jsonValue.isMember("LandmarkTag")) + { + DataModel::Nullable relativePositionTag = DataModel::NullNullable; + if (jsonValue.isMember("PositionTag")) + { + relativePositionTag = Globals::RelativePositionTag(jsonValue["PositionTag"].asUInt()); + } + + area.SetLandmarkInfo(Globals::LandmarkTag(jsonValue["LandmarkTag"].asUInt()), relativePositionTag); + } + + mRvcDevice->HandleAddServiceAreaArea(area); +} + +void RvcAppCommandHandler::OnRemoveServiceAreaMap(uint32_t mapId) +{ + mRvcDevice->HandleRemoveServiceAreaMap(mapId); +} + +void RvcAppCommandHandler::OnRemoveServiceAreaArea(uint32_t areaId) +{ + mRvcDevice->HandleRemoveServiceAreaArea(areaId); +} + void RvcAppCommandHandler::OnErrorEventHandler(const std::string & error) { mRvcDevice->HandleErrorEvent(error); diff --git a/examples/rvc-app/linux/RvcAppCommandDelegate.h b/examples/rvc-app/linux/RvcAppCommandDelegate.h index e8dc404de2..6f896641da 100644 --- a/examples/rvc-app/linux/RvcAppCommandDelegate.h +++ b/examples/rvc-app/linux/RvcAppCommandDelegate.h @@ -57,6 +57,14 @@ class RvcAppCommandHandler void OnAreaCompleteHandler(); + void OnAddServiceAreaMap(Json::Value jsonValue); + + void OnAddServiceAreaArea(Json::Value jsonValue); + + void OnRemoveServiceAreaMap(uint32_t mapId); + + void OnRemoveServiceAreaArea(uint32_t areaId); + void OnErrorEventHandler(const std::string & error); void OnClearErrorHandler(); diff --git a/examples/rvc-app/rvc-common/include/rvc-device.h b/examples/rvc-app/rvc-common/include/rvc-device.h index 40a5232966..b66ce3251f 100644 --- a/examples/rvc-app/rvc-common/include/rvc-device.h +++ b/examples/rvc-app/rvc-common/include/rvc-device.h @@ -127,6 +127,14 @@ class RvcDevice void HandleAreaCompletedEvent(); + void HandleAddServiceAreaMap(uint32_t mapId, const CharSpan & mapName); + + void HandleAddServiceAreaArea(ServiceArea::AreaStructureWrapper & area); + + void HandleRemoveServiceAreaMap(uint32_t mapId); + + void HandleRemoveServiceAreaArea(uint32_t areaId); + /** * Sets the device to an error state with the error state ID matching the error name given. * @param error The error name. Could be one of UnableToStartOrResume, UnableToCompleteOperation, CommandInvalidInState, diff --git a/examples/rvc-app/rvc-common/include/rvc-service-area-delegate.h b/examples/rvc-app/rvc-common/include/rvc-service-area-delegate.h index 4d065782dc..4c13fcd493 100644 --- a/examples/rvc-app/rvc-common/include/rvc-service-area-delegate.h +++ b/examples/rvc-app/rvc-common/include/rvc-service-area-delegate.h @@ -63,6 +63,7 @@ class RvcServiceAreaDelegate : public Delegate const uint32_t supportedAreaID_C = 10050; const uint32_t supportedAreaID_D = 0x88888888; +public: /** * Set the SupportedMaps and SupportedAreas where the SupportedMaps is not null. */ @@ -73,7 +74,6 @@ class RvcServiceAreaDelegate : public Delegate */ void SetNoMapTopology(); -public: CHIP_ERROR Init() override; // command support @@ -101,6 +101,18 @@ class RvcServiceAreaDelegate : public Delegate bool ClearSupportedAreas() override; + /** + * This is a more sophisticated way of ensuring that we all attributes are still valid when a supported area is removed. + * Rather than clearing all the attributes that depend on the supported aeras, we only remove the elements that point to + * the removed supported areas. + */ + void HandleSupportedAreasUpdated() override; + + /** + * Note: Call the HandleSupportedAreasUpdated() method when finished removing supported areas. + */ + bool RemoveSupportedArea(uint32_t areaId); + //************************************************************************* // Supported Maps accessors @@ -118,6 +130,8 @@ class RvcServiceAreaDelegate : public Delegate bool ClearSupportedMaps() override; + bool RemoveSupportedMap(uint32_t mapId); + //************************************************************************* // Selected Areas accessors diff --git a/examples/rvc-app/rvc-common/pics/rvc-app-pics-values b/examples/rvc-app/rvc-common/pics/rvc-app-pics-values index 24558915f6..c38f0c1b7e 100644 --- a/examples/rvc-app/rvc-common/pics/rvc-app-pics-values +++ b/examples/rvc-app/rvc-common/pics/rvc-app-pics-values @@ -65,10 +65,10 @@ SEAR.S.C00.Rsp=1 SEAR.S.C02.Rsp=1 SEAR.S.C01.Tx=1 SEAR.S.C03.Tx=1 -SEAR.S.M.REMOVE_AREA=0 -SEAR.S.M.ADD_AREA=0 -SEAR.S.M.REMOVE_MAP=0 -SEAR.S.M.ADD_MAP=0 +SEAR.S.M.REMOVE_AREA=1 +SEAR.S.M.ADD_AREA=1 +SEAR.S.M.REMOVE_MAP=1 +SEAR.S.M.ADD_MAP=1 SEAR.S.M.INVALID_STATE_FOR_SELECT_AREAS=1 SEAR.S.M.VALID_STATE_FOR_SELECT_AREAS=0 SEAR.S.M.SELECT_AREAS_WHILE_NON_IDLE=1 diff --git a/examples/rvc-app/rvc-common/src/rvc-device.cpp b/examples/rvc-app/rvc-common/src/rvc-device.cpp index 8619d28ff4..623c95963f 100644 --- a/examples/rvc-app/rvc-common/src/rvc-device.cpp +++ b/examples/rvc-app/rvc-common/src/rvc-device.cpp @@ -327,6 +327,26 @@ void RvcDevice::HandleAreaCompletedEvent() } } +void RvcDevice::HandleAddServiceAreaMap(uint32_t mapId, const CharSpan & mapName) +{ + mServiceAreaInstance.AddSupportedMap(mapId, mapName); +} + +void RvcDevice::HandleAddServiceAreaArea(ServiceArea::AreaStructureWrapper & area) +{ + mServiceAreaInstance.AddSupportedArea(area); +} + +void RvcDevice::HandleRemoveServiceAreaMap(uint32_t mapId) +{ + mServiceAreaDelegate.RemoveSupportedMap(mapId); +} + +void RvcDevice::HandleRemoveServiceAreaArea(uint32_t areaId) +{ + mServiceAreaDelegate.RemoveSupportedArea(areaId); +} + void RvcDevice::HandleErrorEvent(const std::string & error) { detail::Structs::ErrorStateStruct::Type err; @@ -406,6 +426,8 @@ void RvcDevice::HandleResetMessage() mServiceAreaInstance.ClearProgress(); mServiceAreaInstance.SetCurrentArea(DataModel::NullNullable); mServiceAreaInstance.SetEstimatedEndTime(DataModel::NullNullable); + + mServiceAreaDelegate.SetMapTopology(); } void RvcDevice::UpdateServiceAreaProgressOnExit() diff --git a/examples/rvc-app/rvc-common/src/rvc-service-area-delegate.cpp b/examples/rvc-app/rvc-common/src/rvc-service-area-delegate.cpp index f7e17aa49a..984472977a 100644 --- a/examples/rvc-app/rvc-common/src/rvc-service-area-delegate.cpp +++ b/examples/rvc-app/rvc-common/src/rvc-service-area-delegate.cpp @@ -25,7 +25,7 @@ using namespace chip::app::Clusters::ServiceArea; void RvcServiceAreaDelegate::SetMapTopology() { - ClearSupportedMaps(); + GetInstance()->ClearSupportedMaps(); GetInstance()->AddSupportedMap(supportedMapId_XX, "My Map XX"_span); GetInstance()->AddSupportedMap(supportedMapId_YY, "My Map YY"_span); @@ -65,7 +65,7 @@ void RvcServiceAreaDelegate::SetMapTopology() void RvcServiceAreaDelegate::SetNoMapTopology() { - ClearSupportedMaps(); + GetInstance()->ClearSupportedMaps(); // Area A has name, floor number. auto areaA = @@ -279,6 +279,20 @@ bool RvcServiceAreaDelegate::ClearSupportedAreas() return false; } +bool RvcServiceAreaDelegate::RemoveSupportedArea(uint32_t areaId) +{ + for (auto it = mSupportedAreas.begin(); it != mSupportedAreas.end(); ++it) + { + if (it->areaID == areaId) + { + mSupportedAreas.erase(it); + return true; + } + } + + return false; +} + //************************************************************************* // Supported Maps accessors @@ -372,6 +386,114 @@ bool RvcServiceAreaDelegate::ClearSupportedMaps() return false; } +void RvcServiceAreaDelegate::HandleSupportedAreasUpdated() +{ + // Get a list of supported area IDs as `supportedAreaIDs` + std::vector supportedAreaIDs; + for (const auto & supportedArea : mSupportedAreas) + { + supportedAreaIDs.push_back(supportedArea.areaID); + } + + if (supportedAreaIDs.empty()) + { + // Clear all selected areas, current area, and progress if there are no supported areas. + GetInstance()->ClearSelectedAreas(); + GetInstance()->SetCurrentArea(DataModel::NullNullable); + GetInstance()->ClearProgress(); + return; + } + + // Remove mSelectedArea elements that do not exist is `supportedAreaIDs` + { + for (auto it = mSelectedAreas.begin(); it != mSelectedAreas.end();) + { + if (std::find(supportedAreaIDs.begin(), supportedAreaIDs.end(), *it) == supportedAreaIDs.end()) + { + it = mSelectedAreas.erase(it); + } + else + { + ++it; + } + } + } + + // Set current Area to null if current area is not in `supportedAreaIDs` + { + auto currentAreaId = GetInstance()->GetCurrentArea(); + if (!currentAreaId.IsNull() && + std::find(supportedAreaIDs.begin(), supportedAreaIDs.end(), currentAreaId.Value()) == supportedAreaIDs.end()) + { + GetInstance()->SetCurrentArea(DataModel::NullNullable); + } + } + + // Remove mProgress elements that do not exist is `supportedAreaIDs` + { + for (auto it = mProgressList.begin(); it != mProgressList.end();) + { + if (std::find(supportedAreaIDs.begin(), supportedAreaIDs.end(), it->areaID) == supportedAreaIDs.end()) + { + it = mProgressList.erase(it); + } + else + { + ++it; + } + } + } +} + +bool RvcServiceAreaDelegate::RemoveSupportedMap(uint32_t mapId) +{ + bool removedEntry = false; + for (auto it = mSupportedMaps.begin(); it != mSupportedMaps.end(); ++it) + { + if (it->mapID == mapId) + { + mSupportedMaps.erase(it); + removedEntry = true; + } + } + + if (!removedEntry) + { + return false; + } + + // If there are no supported maps left, none of the supported areas are vaild and their MapID needs to be null. + if (GetNumberOfSupportedMaps() == 0) + { + ClearSupportedAreas(); + return true; + } + + // Get the supported area IDs where the map ID matches the removed map ID + std::vector supportedAreaIds; + { + for (const auto & supportedArea : mSupportedAreas) + { + if (supportedArea.mapID == mapId) + { + supportedAreaIds.push_back(supportedArea.areaID); + } + } + } + + // Remove the supported areas with the matching map ID + if (!supportedAreaIds.empty()) + { + for (const auto & supportedAreaId : supportedAreaIds) + { + RemoveSupportedArea(supportedAreaId); + } + HandleSupportedAreasUpdated(); + } + + return true; +} + //************************************************************************* // Selected areas accessors diff --git a/src/python_testing/TC_SEAR_1_2.py b/src/python_testing/TC_SEAR_1_2.py index 939f4be638..083533277a 100644 --- a/src/python_testing/TC_SEAR_1_2.py +++ b/src/python_testing/TC_SEAR_1_2.py @@ -245,7 +245,9 @@ async def test_TC_SEAR_1_2(self): test_step = "Manually intervene to remove one or more entries in the SupportedMaps list" self.print_step("10", test_step) - if not self.is_ci: + if self.is_ci: + self.write_to_app_pipe('{"Name": "RemoveMap", "MapId": 3}') + else: self.wait_for_user_input(prompt_msg=f"{test_step}, and press Enter when done.\n") await self.read_and_validate_supported_maps(step=11) @@ -278,7 +280,9 @@ async def test_TC_SEAR_1_2(self): test_step = "Manually intervene to add one or more entries to the SupportedMaps list" self.print_step("14", test_step) - if not self.is_ci: + if self.is_ci: + self.write_to_app_pipe('{"Name": "AddMap", "MapId": 1, "MapName": "NewTestMap1"}') + else: self.wait_for_user_input(prompt_msg=f"{test_step}, and press Enter when done.\n") await self.read_and_validate_supported_maps(step=15) @@ -311,7 +315,9 @@ async def test_TC_SEAR_1_2(self): test_step = "Manually intervene to remove one or more entries from the SupportedAreas list" self.print_step("18", test_step) - if not self.is_ci: + if self.is_ci: + self.write_to_app_pipe('{"Name": "RemoveArea", "AreaId": 10050}') + else: self.wait_for_user_input(prompt_msg=f"{test_step}, and press Enter when done.\n") await self.read_and_validate_supported_areas(step=19) @@ -343,7 +349,9 @@ async def test_TC_SEAR_1_2(self): test_step = "Manually intervene to add one or more entries to the SupportedAreas list" self.print_step("22", test_step) - if not self.is_ci: + if self.is_ci: + self.write_to_app_pipe('{"Name": "AddArea", "AreaId": 42, "MapId": 1, "LocationName": "NewTestArea1"}') + else: self.wait_for_user_input(prompt_msg=f"{test_step}, and press Enter when done.\n") await self.read_and_validate_supported_areas(step=23) From 13c45d5b48418835ad66d65bb71f6a8b0e48e6ab Mon Sep 17 00:00:00 2001 From: jamesharrow <93921463+jamesharrow@users.noreply.github.com> Date: Tue, 13 Aug 2024 15:01:02 +0100 Subject: [PATCH 026/165] Restructured folders in chip-energy-management-app - no code change (#34879) * Refactored file location for chip-energy-management-app. Updated esp32 and linux build files. * Updated some all-clusters-app build and CMakeLists (linux, esp32, psoc6) * Updated remaining build and CMakefiles with new folders. * Fixed unit tests BUILD.gn * Restyled by gn * Missed Ameba .cmake * Missed all-clusters-minimal-app/esp32/main/CMakeLists.txt --------- Co-authored-by: Restyled.io --- .../all-clusters-app/ameba/chip_main.cmake | 23 +++++----- examples/all-clusters-app/asr/BUILD.gn | 23 +++++----- .../all-clusters-app/cc13x4_26x4/BUILD.gn | 23 +++++----- .../esp32/main/CMakeLists.txt | 10 ++++- .../all-clusters-app/infineon/psoc6/BUILD.gn | 24 +++++----- examples/all-clusters-app/linux/BUILD.gn | 27 ++++++----- examples/all-clusters-app/mbed/CMakeLists.txt | 23 +++++----- .../nrfconnect/CMakeLists.txt | 23 +++++----- examples/all-clusters-app/nxp/mw320/BUILD.gn | 24 +++++----- .../openiotsdk/CMakeLists.txt | 23 +++++----- .../all-clusters-app/telink/CMakeLists.txt | 23 +++++----- examples/all-clusters-app/tizen/BUILD.gn | 24 +++++----- .../esp32/main/CMakeLists.txt | 5 ++- .../EnergyManagementAppCmdLineOptions.h | 0 .../{ => common}/src/EnergyTimeUtils.cpp | 0 .../include/DEMManufacturerDelegate.h | 0 .../DeviceEnergyManagementDelegateImpl.h | 0 .../include/DeviceEnergyManagementManager.h | 0 .../include/device-energy-management-modes.h | 0 .../src/DEMTestEventTriggers.cpp | 0 .../DeviceEnergyManagementDelegateImpl.cpp | 0 .../src/DeviceEnergyManagementManager.cpp | 0 .../src/device-energy-management-mode.cpp | 0 .../include/ChargingTargetsMemMgr.h | 0 .../{ => energy-evse}/include/EVSECallbacks.h | 0 .../include/EVSEManufacturerImpl.h | 0 .../include/EnergyEvseDelegateImpl.h | 0 .../include/EnergyEvseMain.h | 0 .../include/EnergyEvseManager.h | 0 .../include/EnergyEvseTargetsStore.h | 0 .../include/EnergyTimeUtils.h | 0 .../include/energy-evse-modes.h | 0 .../src/ChargingTargetsMemMgr.cpp | 0 .../src/EVSEManufacturerImpl.cpp | 0 .../src/EnergyEvseDelegateImpl.cpp | 0 .../src/EnergyEvseEventTriggers.cpp | 0 .../{ => energy-evse}/src/EnergyEvseMain.cpp | 0 .../src/EnergyEvseManager.cpp | 0 .../src/EnergyEvseTargetsStore.cpp | 0 .../src/energy-evse-mode.cpp | 0 .../ElectricalPowerMeasurementDelegate.h | 0 .../include/FakeReadings.h | 0 .../include/PowerTopologyDelegate.h | 0 .../ElectricalPowerMeasurementDelegate.cpp | 0 .../src/EnergyReportingEventTriggers.cpp | 0 .../src/FakeReadings.cpp | 0 .../src/PowerTopologyDelegate.cpp | 0 .../energy-management-common/tests/BUILD.gn | 2 +- .../esp32/main/CMakeLists.txt | 10 ++++- examples/energy-management-app/linux/BUILD.gn | 45 ++++++++++--------- examples/shell/shell_common/BUILD.gn | 24 +++++----- 51 files changed, 207 insertions(+), 149 deletions(-) rename examples/energy-management-app/energy-management-common/{ => common}/include/EnergyManagementAppCmdLineOptions.h (100%) rename examples/energy-management-app/energy-management-common/{ => common}/src/EnergyTimeUtils.cpp (100%) rename examples/energy-management-app/energy-management-common/{ => device-energy-management}/include/DEMManufacturerDelegate.h (100%) rename examples/energy-management-app/energy-management-common/{ => device-energy-management}/include/DeviceEnergyManagementDelegateImpl.h (100%) rename examples/energy-management-app/energy-management-common/{ => device-energy-management}/include/DeviceEnergyManagementManager.h (100%) rename examples/energy-management-app/energy-management-common/{ => device-energy-management}/include/device-energy-management-modes.h (100%) rename examples/energy-management-app/energy-management-common/{ => device-energy-management}/src/DEMTestEventTriggers.cpp (100%) rename examples/energy-management-app/energy-management-common/{ => device-energy-management}/src/DeviceEnergyManagementDelegateImpl.cpp (100%) rename examples/energy-management-app/energy-management-common/{ => device-energy-management}/src/DeviceEnergyManagementManager.cpp (100%) rename examples/energy-management-app/energy-management-common/{ => device-energy-management}/src/device-energy-management-mode.cpp (100%) rename examples/energy-management-app/energy-management-common/{ => energy-evse}/include/ChargingTargetsMemMgr.h (100%) rename examples/energy-management-app/energy-management-common/{ => energy-evse}/include/EVSECallbacks.h (100%) rename examples/energy-management-app/energy-management-common/{ => energy-evse}/include/EVSEManufacturerImpl.h (100%) rename examples/energy-management-app/energy-management-common/{ => energy-evse}/include/EnergyEvseDelegateImpl.h (100%) rename examples/energy-management-app/energy-management-common/{ => energy-evse}/include/EnergyEvseMain.h (100%) rename examples/energy-management-app/energy-management-common/{ => energy-evse}/include/EnergyEvseManager.h (100%) rename examples/energy-management-app/energy-management-common/{ => energy-evse}/include/EnergyEvseTargetsStore.h (100%) rename examples/energy-management-app/energy-management-common/{ => energy-evse}/include/EnergyTimeUtils.h (100%) rename examples/energy-management-app/energy-management-common/{ => energy-evse}/include/energy-evse-modes.h (100%) rename examples/energy-management-app/energy-management-common/{ => energy-evse}/src/ChargingTargetsMemMgr.cpp (100%) rename examples/energy-management-app/energy-management-common/{ => energy-evse}/src/EVSEManufacturerImpl.cpp (100%) rename examples/energy-management-app/energy-management-common/{ => energy-evse}/src/EnergyEvseDelegateImpl.cpp (100%) rename examples/energy-management-app/energy-management-common/{ => energy-evse}/src/EnergyEvseEventTriggers.cpp (100%) rename examples/energy-management-app/energy-management-common/{ => energy-evse}/src/EnergyEvseMain.cpp (100%) rename examples/energy-management-app/energy-management-common/{ => energy-evse}/src/EnergyEvseManager.cpp (100%) rename examples/energy-management-app/energy-management-common/{ => energy-evse}/src/EnergyEvseTargetsStore.cpp (100%) rename examples/energy-management-app/energy-management-common/{ => energy-evse}/src/energy-evse-mode.cpp (100%) rename examples/energy-management-app/energy-management-common/{ => energy-reporting}/include/ElectricalPowerMeasurementDelegate.h (100%) rename examples/energy-management-app/energy-management-common/{ => energy-reporting}/include/FakeReadings.h (100%) rename examples/energy-management-app/energy-management-common/{ => energy-reporting}/include/PowerTopologyDelegate.h (100%) rename examples/energy-management-app/energy-management-common/{ => energy-reporting}/src/ElectricalPowerMeasurementDelegate.cpp (100%) rename examples/energy-management-app/energy-management-common/{ => energy-reporting}/src/EnergyReportingEventTriggers.cpp (100%) rename examples/energy-management-app/energy-management-common/{ => energy-reporting}/src/FakeReadings.cpp (100%) rename examples/energy-management-app/energy-management-common/{ => energy-reporting}/src/PowerTopologyDelegate.cpp (100%) diff --git a/examples/all-clusters-app/ameba/chip_main.cmake b/examples/all-clusters-app/ameba/chip_main.cmake index e6e9ee19a8..363b01e05a 100644 --- a/examples/all-clusters-app/ameba/chip_main.cmake +++ b/examples/all-clusters-app/ameba/chip_main.cmake @@ -187,15 +187,15 @@ list( ${chip_dir}/examples/microwave-oven-app/microwave-oven-common/src/microwave-oven-device.cpp - ${chip_dir}/examples/energy-management-app/energy-management-common/src/ChargingTargetsMemMgr.cpp - ${chip_dir}/examples/energy-management-app/energy-management-common/src/DeviceEnergyManagementDelegateImpl.cpp - ${chip_dir}/examples/energy-management-app/energy-management-common/src/DeviceEnergyManagementManager.cpp - ${chip_dir}/examples/energy-management-app/energy-management-common/src/EVSEManufacturerImpl.cpp - ${chip_dir}/examples/energy-management-app/energy-management-common/src/ElectricalPowerMeasurementDelegate.cpp - ${chip_dir}/examples/energy-management-app/energy-management-common/src/EnergyEvseDelegateImpl.cpp - ${chip_dir}/examples/energy-management-app/energy-management-common/src/EnergyEvseManager.cpp - ${chip_dir}/examples/energy-management-app/energy-management-common/src/EnergyEvseTargetsStore.cpp - ${chip_dir}/examples/energy-management-app/energy-management-common/src/EnergyTimeUtils.cpp + ${chip_dir}/examples/energy-management-app/energy-management-common/common/src/EnergyTimeUtils.cpp + ${chip_dir}/examples/energy-management-app/energy-management-common/device-energy-management/src/DeviceEnergyManagementDelegateImpl.cpp + ${chip_dir}/examples/energy-management-app/energy-management-common/device-energy-management/src/DeviceEnergyManagementManager.cpp + ${chip_dir}/examples/energy-management-app/energy-management-common/energy-evse/src/ChargingTargetsMemMgr.cpp + ${chip_dir}/examples/energy-management-app/energy-management-common/energy-evse/src/EVSEManufacturerImpl.cpp + ${chip_dir}/examples/energy-management-app/energy-management-common/energy-evse/src/EnergyEvseDelegateImpl.cpp + ${chip_dir}/examples/energy-management-app/energy-management-common/energy-evse/src/EnergyEvseManager.cpp + ${chip_dir}/examples/energy-management-app/energy-management-common/energy-evse/src/EnergyEvseTargetsStore.cpp + ${chip_dir}/examples/energy-management-app/energy-management-common/energy-reporting/src/ElectricalPowerMeasurementDelegate.cpp ${chip_dir}/examples/platform/ameba/route_hook/ameba_route_hook.c ${chip_dir}/examples/platform/ameba/route_hook/ameba_route_table.c @@ -243,7 +243,10 @@ target_include_directories( ${chip_dir}/examples/all-clusters-app/all-clusters-common/include ${chip_dir}/examples/microwave-oven-app/microwave-oven-common ${chip_dir}/examples/microwave-oven-app/microwave-oven-common/include - ${chip_dir}/examples/energy-management-app/energy-management-common/include + ${chip_dir}/examples/energy-management-app/energy-management-common/common/include + ${chip_dir}/examples/energy-management-app/energy-management-common/device-energy-management/include + ${chip_dir}/examples/energy-management-app/energy-management-common/energy-evse/include + ${chip_dir}/examples/energy-management-app/energy-management-common/energy-reporting/include ${chip_dir}/examples/all-clusters-app/ameba/main/include ${chip_dir}/examples/platform/ameba ${chip_dir}/examples/platform/ameba/route_hook diff --git a/examples/all-clusters-app/asr/BUILD.gn b/examples/all-clusters-app/asr/BUILD.gn index fc7ad9037b..e27884810c 100644 --- a/examples/all-clusters-app/asr/BUILD.gn +++ b/examples/all-clusters-app/asr/BUILD.gn @@ -82,15 +82,15 @@ asr_executable("clusters_app") { "${chip_root}/examples/all-clusters-app/all-clusters-common/src/smco-stub.cpp", "${chip_root}/examples/all-clusters-app/all-clusters-common/src/static-supported-modes-manager.cpp", "${chip_root}/examples/all-clusters-app/all-clusters-common/src/static-supported-temperature-levels.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/ChargingTargetsMemMgr.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/DeviceEnergyManagementDelegateImpl.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/DeviceEnergyManagementManager.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/EVSEManufacturerImpl.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/ElectricalPowerMeasurementDelegate.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/EnergyEvseDelegateImpl.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/EnergyEvseManager.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/EnergyEvseTargetsStore.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/EnergyTimeUtils.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/common/src/EnergyTimeUtils.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/device-energy-management/src/DeviceEnergyManagementDelegateImpl.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/device-energy-management/src/DeviceEnergyManagementManager.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/src/ChargingTargetsMemMgr.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/src/EVSEManufacturerImpl.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/src/EnergyEvseDelegateImpl.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/src/EnergyEvseManager.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/src/EnergyEvseTargetsStore.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-reporting/src/ElectricalPowerMeasurementDelegate.cpp", "${examples_plat_dir}/ButtonHandler.cpp", "${examples_plat_dir}/CHIPDeviceManager.cpp", "${examples_plat_dir}/LEDWidget.cpp", @@ -121,7 +121,10 @@ asr_executable("clusters_app") { "${examples_plat_dir}", "${asr_project_dir}/include", "${chip_root}/examples/all-clusters-app/all-clusters-common/include", - "${chip_root}/examples/energy-management-app/energy-management-common/include", + "${chip_root}/examples/energy-management-app/energy-management-common/common/include", + "${chip_root}/examples/energy-management-app/energy-management-common/device-energy-management/include", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/include", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-reporting/include", "${chip_root}/src", "${chip_root}/src/lib", "${chip_root}/src/lib/support", diff --git a/examples/all-clusters-app/cc13x4_26x4/BUILD.gn b/examples/all-clusters-app/cc13x4_26x4/BUILD.gn index c1cb81a972..bda63caa38 100644 --- a/examples/all-clusters-app/cc13x4_26x4/BUILD.gn +++ b/examples/all-clusters-app/cc13x4_26x4/BUILD.gn @@ -72,15 +72,15 @@ ti_simplelink_executable("all-clusters-app") { "${chip_root}/examples/all-clusters-app/all-clusters-common/src/smco-stub.cpp", "${chip_root}/examples/all-clusters-app/all-clusters-common/src/static-supported-modes-manager.cpp", "${chip_root}/examples/all-clusters-app/all-clusters-common/src/static-supported-temperature-levels.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/ChargingTargetsMemMgr.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/DeviceEnergyManagementDelegateImpl.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/DeviceEnergyManagementManager.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/EVSEManufacturerImpl.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/ElectricalPowerMeasurementDelegate.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/EnergyEvseDelegateImpl.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/EnergyEvseManager.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/EnergyEvseTargetsStore.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/EnergyTimeUtils.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/common/src/EnergyTimeUtils.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/device-energy-management/src/DeviceEnergyManagementDelegateImpl.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/device-energy-management/src/DeviceEnergyManagementManager.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/src/ChargingTargetsMemMgr.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/src/EVSEManufacturerImpl.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/src/EnergyEvseDelegateImpl.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/src/EnergyEvseManager.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/src/EnergyEvseTargetsStore.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-reporting/src/ElectricalPowerMeasurementDelegate.cpp", "${chip_root}/examples/providers/DeviceInfoProviderImpl.cpp", "${chip_root}/src/app/clusters/general-diagnostics-server/GenericFaultTestEventTriggerHandler.cpp", "${project_dir}/main/AppTask.cpp", @@ -116,7 +116,10 @@ ti_simplelink_executable("all-clusters-app") { "${project_dir}", "${project_dir}/main", "${chip_root}/examples/all-clusters-app/all-clusters-common/include", - "${chip_root}/examples/energy-management-app/energy-management-common/include", + "${chip_root}/examples/energy-management-app/energy-management-common/common/include", + "${chip_root}/examples/energy-management-app/energy-management-common/device-energy-management/include", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/include", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-reporting/include", "${chip_root}/examples/providers/", ] diff --git a/examples/all-clusters-app/esp32/main/CMakeLists.txt b/examples/all-clusters-app/esp32/main/CMakeLists.txt index 7fd1d54860..3e80b995c5 100644 --- a/examples/all-clusters-app/esp32/main/CMakeLists.txt +++ b/examples/all-clusters-app/esp32/main/CMakeLists.txt @@ -18,7 +18,10 @@ # The list of src and include dirs must be in sync with that in all-clusters-app/esp32/main/component.mk set(PRIV_INCLUDE_DIRS_LIST "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/all-clusters-app/all-clusters-common/include" - "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/energy-management-app/energy-management-common/include" + "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/energy-management-app/energy-management-common/common/include" + "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/energy-management-app/energy-management-common/device-energy-management/include" + "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/energy-management-app/energy-management-common/energy-evse/include" + "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/energy-management-app/energy-management-common/energy-reporting/include" "${CMAKE_CURRENT_LIST_DIR}/include" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/providers" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/platform/esp32" @@ -29,7 +32,10 @@ set(SRC_DIRS_LIST "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/zzz_generated/app-common/app-common/zap-generated/attributes" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/zzz_generated/app-common/app-common/zap-generated" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/all-clusters-app/all-clusters-common/src" - "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/energy-management-app/energy-management-common/src" + "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/energy-management-app/energy-management-common/common/src" + "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/energy-management-app/energy-management-common/device-energy-management/src" + "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/energy-management-app/energy-management-common/energy-evse/src" + "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/energy-management-app/energy-management-common/energy-reporting/src" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/providers" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/platform/esp32/ota" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/platform/esp32/common" diff --git a/examples/all-clusters-app/infineon/psoc6/BUILD.gn b/examples/all-clusters-app/infineon/psoc6/BUILD.gn index 9be0689134..aeb1fa0b6f 100644 --- a/examples/all-clusters-app/infineon/psoc6/BUILD.gn +++ b/examples/all-clusters-app/infineon/psoc6/BUILD.gn @@ -124,15 +124,16 @@ psoc6_executable("clusters_app") { "${chip_root}/examples/all-clusters-app/all-clusters-common/src/smco-stub.cpp", "${chip_root}/examples/all-clusters-app/all-clusters-common/src/static-supported-modes-manager.cpp", "${chip_root}/examples/all-clusters-app/all-clusters-common/src/static-supported-temperature-levels.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/ChargingTargetsMemMgr.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/DeviceEnergyManagementDelegateImpl.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/DeviceEnergyManagementManager.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/EVSEManufacturerImpl.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/ElectricalPowerMeasurementDelegate.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/EnergyEvseDelegateImpl.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/EnergyEvseManager.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/EnergyEvseTargetsStore.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/EnergyTimeUtils.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/common/src/EnergyTimeUtils.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/device-energy-management/src/DeviceEnergyManagementDelegateImpl.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/device-energy-management/src/DeviceEnergyManagementManager.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/src/ChargingTargetsMemMgr.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/src/EVSEManufacturerImpl.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/src/EnergyEvseDelegateImpl.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/src/EnergyEvseManager.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/src/EnergyEvseTargetsStore.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/src/energy-evse-mode.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-reporting/src/ElectricalPowerMeasurementDelegate.cpp", "${examples_plat_dir}/LEDWidget.cpp", "${examples_plat_dir}/init_psoc6Platform.cpp", "src/AppTask.cpp", @@ -157,7 +158,10 @@ psoc6_executable("clusters_app") { "${examples_plat_dir}", "${psoc6_project_dir}/include", "${chip_root}/examples/all-clusters-app/all-clusters-common/include", - "${chip_root}/examples/energy-management-app/energy-management-common/include", + "${chip_root}/examples/energy-management-app/energy-management-common/common/include", + "${chip_root}/examples/energy-management-app/energy-management-common/device-energy-management/include", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/include", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-reporting/include", ] defines = [] diff --git a/examples/all-clusters-app/linux/BUILD.gn b/examples/all-clusters-app/linux/BUILD.gn index c7c5fb0f14..ed228b51b2 100644 --- a/examples/all-clusters-app/linux/BUILD.gn +++ b/examples/all-clusters-app/linux/BUILD.gn @@ -64,17 +64,17 @@ source_set("chip-all-clusters-common") { "${chip_root}/examples/all-clusters-app/all-clusters-common/src/tcc-mode.cpp", "${chip_root}/examples/all-clusters-app/all-clusters-common/src/water-heater-mode.cpp", "${chip_root}/examples/all-clusters-app/linux/diagnostic-logs-provider-delegate-impl.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/ChargingTargetsMemMgr.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/DeviceEnergyManagementDelegateImpl.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/DeviceEnergyManagementManager.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/EVSEManufacturerImpl.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/ElectricalPowerMeasurementDelegate.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/EnergyEvseDelegateImpl.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/EnergyEvseManager.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/EnergyEvseTargetsStore.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/EnergyTimeUtils.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/device-energy-management-mode.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/energy-evse-mode.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/common/src/EnergyTimeUtils.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/device-energy-management/src/DeviceEnergyManagementDelegateImpl.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/device-energy-management/src/DeviceEnergyManagementManager.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/device-energy-management/src/device-energy-management-mode.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/src/ChargingTargetsMemMgr.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/src/EVSEManufacturerImpl.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/src/EnergyEvseDelegateImpl.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/src/EnergyEvseManager.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/src/EnergyEvseTargetsStore.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/src/energy-evse-mode.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-reporting/src/ElectricalPowerMeasurementDelegate.cpp", "${chip_root}/examples/thermostat/linux/thermostat-delegate-impl.cpp", "AllClustersCommandDelegate.cpp", "AllClustersCommandDelegate.h", @@ -98,7 +98,10 @@ source_set("chip-all-clusters-common") { include_dirs = [ "${chip_root}/examples/all-clusters-app/all-clusters-common/include", - "${chip_root}/examples/energy-management-app/energy-management-common/include", + "${chip_root}/examples/energy-management-app/energy-management-common/common/include", + "${chip_root}/examples/energy-management-app/energy-management-common/device-energy-management/include", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/include", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-reporting/include", "${chip_root}/examples/thermostat/linux/include", ] diff --git a/examples/all-clusters-app/mbed/CMakeLists.txt b/examples/all-clusters-app/mbed/CMakeLists.txt index 427517aff9..b2e54ed28a 100644 --- a/examples/all-clusters-app/mbed/CMakeLists.txt +++ b/examples/all-clusters-app/mbed/CMakeLists.txt @@ -50,7 +50,10 @@ target_include_directories(${APP_TARGET} PRIVATE main/include/ ${MBED_COMMON}/util/include ${ALL_CLUSTERS_COMMON}/include - ${ENERGY_MANAGEMENT_COMMON}/include + ${ENERGY_MANAGEMENT_COMMON}/common/include + ${ENERGY_MANAGEMENT_COMMON}/device-energy-management/include + ${ENERGY_MANAGEMENT_COMMON}/energy-evse/include + ${ENERGY_MANAGEMENT_COMMON}/energy-reporting/include ${GEN_DIR}/app-common ${GEN_DIR}/all-clusters-app ${NLIO_ROOT} @@ -72,15 +75,15 @@ target_sources(${APP_TARGET} PRIVATE ${ALL_CLUSTERS_COMMON}/src/smco-stub.cpp ${ALL_CLUSTERS_COMMON}/src/static-supported-modes-manager.cpp ${ALL_CLUSTERS_COMMON}/src/static-supported-temperature-levels.cpp - ${ENERGY_MANAGEMENT_COMMON}/src/ChargingTargetsMemMgr.cpp - ${ENERGY_MANAGEMENT_COMMON}/src/DeviceEnergyManagementDelegateImpl.cpp - ${ENERGY_MANAGEMENT_COMMON}/src/DeviceEnergyManagementManager.cpp - ${ENERGY_MANAGEMENT_COMMON}/src/EVSEManufacturerImpl.cpp - ${ENERGY_MANAGEMENT_COMMON}/src/ElectricalPowerMeasurementDelegate.cpp - ${ENERGY_MANAGEMENT_COMMON}/src/EnergyEvseDelegateImpl.cpp - ${ENERGY_MANAGEMENT_COMMON}/src/EnergyEvseManager.cpp - ${ENERGY_MANAGEMENT_COMMON}/src/EnergyEvseTargetsStore.cpp - ${ENERGY_MANAGEMENT_COMMON}/src/EnergyTimeUtils.cpp + ${ENERGY_MANAGEMENT_COMMON}/common/src/EnergyTimeUtils.cpp + ${ENERGY_MANAGEMENT_COMMON}/device-energy-management/src/DeviceEnergyManagementDelegateImpl.cpp + ${ENERGY_MANAGEMENT_COMMON}/device-energy-management/src/DeviceEnergyManagementManager.cpp + ${ENERGY_MANAGEMENT_COMMON}/energy-evse/src/ChargingTargetsMemMgr.cpp + ${ENERGY_MANAGEMENT_COMMON}/energy-evse/src/EVSEManufacturerImpl.cpp + ${ENERGY_MANAGEMENT_COMMON}/energy-evse/src/EnergyEvseDelegateImpl.cpp + ${ENERGY_MANAGEMENT_COMMON}/energy-evse/src/EnergyEvseManager.cpp + ${ENERGY_MANAGEMENT_COMMON}/energy-evse/src/EnergyEvseTargetsStore.cpp + ${ENERGY_MANAGEMENT_COMMON}/energy-reporting/src/ElectricalPowerMeasurementDelegate.cpp ) chip_configure_data_model(${APP_TARGET} diff --git a/examples/all-clusters-app/nrfconnect/CMakeLists.txt b/examples/all-clusters-app/nrfconnect/CMakeLists.txt index e11dcbd143..bed8169e40 100644 --- a/examples/all-clusters-app/nrfconnect/CMakeLists.txt +++ b/examples/all-clusters-app/nrfconnect/CMakeLists.txt @@ -42,7 +42,10 @@ include(${CHIP_ROOT}/src/app/chip_data_model.cmake) target_include_directories(app PRIVATE main/include ${ALL_CLUSTERS_COMMON_DIR}/include - ${ENERGY_MANAGEMENT_COMMON_DIR}/include + ${ENERGY_MANAGEMENT_COMMON_DIR}/common/include + ${ENERGY_MANAGEMENT_COMMON_DIR}/device-energy-management/include + ${ENERGY_MANAGEMENT_COMMON_DIR}/energy-evse/include + ${ENERGY_MANAGEMENT_COMMON_DIR}/energy-reporting/include ${GEN_DIR}/app-common ${GEN_DIR}/all-clusters-app ${NRFCONNECT_COMMON}/util/include) @@ -62,15 +65,15 @@ target_sources(app PRIVATE ${ALL_CLUSTERS_COMMON_DIR}/src/air-quality-instance.cpp ${ALL_CLUSTERS_COMMON_DIR}/src/concentration-measurement-instances.cpp ${ALL_CLUSTERS_COMMON_DIR}/src/resource-monitoring-delegates.cpp - ${ENERGY_MANAGEMENT_COMMON_DIR}/src/ChargingTargetsMemMgr.cpp - ${ENERGY_MANAGEMENT_COMMON_DIR}/src/DeviceEnergyManagementDelegateImpl.cpp - ${ENERGY_MANAGEMENT_COMMON_DIR}/src/DeviceEnergyManagementManager.cpp - ${ENERGY_MANAGEMENT_COMMON_DIR}/src/EVSEManufacturerImpl.cpp - ${ENERGY_MANAGEMENT_COMMON_DIR}/src/ElectricalPowerMeasurementDelegate.cpp - ${ENERGY_MANAGEMENT_COMMON_DIR}/src/EnergyEvseDelegateImpl.cpp - ${ENERGY_MANAGEMENT_COMMON_DIR}/src/EnergyEvseManager.cpp - ${ENERGY_MANAGEMENT_COMMON_DIR}/src/EnergyEvseTargetsStore.cpp - ${ENERGY_MANAGEMENT_COMMON_DIR}/src/EnergyTimeUtils.cpp + ${ENERGY_MANAGEMENT_COMMON_DIR}/common/src/EnergyTimeUtils.cpp + ${ENERGY_MANAGEMENT_COMMON_DIR}/device-energy-management/src/DeviceEnergyManagementDelegateImpl.cpp + ${ENERGY_MANAGEMENT_COMMON_DIR}/device-energy-management/src/DeviceEnergyManagementManager.cpp + ${ENERGY_MANAGEMENT_COMMON_DIR}/energy-evse/src/ChargingTargetsMemMgr.cpp + ${ENERGY_MANAGEMENT_COMMON_DIR}/energy-evse/src/EVSEManufacturerImpl.cpp + ${ENERGY_MANAGEMENT_COMMON_DIR}/energy-evse/src/EnergyEvseDelegateImpl.cpp + ${ENERGY_MANAGEMENT_COMMON_DIR}/energy-evse/src/EnergyEvseManager.cpp + ${ENERGY_MANAGEMENT_COMMON_DIR}/energy-evse/src/EnergyEvseTargetsStore.cpp + ${ENERGY_MANAGEMENT_COMMON_DIR}/energy-reporting/src/ElectricalPowerMeasurementDelegate.cpp ${NRFCONNECT_COMMON}/util/LEDWidget.cpp) chip_configure_data_model(app diff --git a/examples/all-clusters-app/nxp/mw320/BUILD.gn b/examples/all-clusters-app/nxp/mw320/BUILD.gn index e5e3671143..89ba7f2497 100644 --- a/examples/all-clusters-app/nxp/mw320/BUILD.gn +++ b/examples/all-clusters-app/nxp/mw320/BUILD.gn @@ -74,7 +74,10 @@ mw320_executable("shell_mw320") { "${chip_root}/src", "${chip_root}/src/app/util", "${chip_root}/examples/all-clusters-app/all-clusters-common/include", - "${chip_root}/examples/energy-management-app/energy-management-common/include", + "${chip_root}/examples/energy-management-app/energy-management-common/common/include", + "${chip_root}/examples/energy-management-app/energy-management-common/device-energy-management/include", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/include", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-reporting/include", "${chip_root}/examples/all-clusters-app/nxp/mw320/include", ] sources = [ @@ -89,15 +92,16 @@ mw320_executable("shell_mw320") { "${chip_root}/examples/all-clusters-app/all-clusters-common/src/smco-stub.cpp", "${chip_root}/examples/all-clusters-app/all-clusters-common/src/static-supported-modes-manager.cpp", "${chip_root}/examples/all-clusters-app/all-clusters-common/src/static-supported-temperature-levels.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/ChargingTargetsMemMgr.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/DeviceEnergyManagementDelegateImpl.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/DeviceEnergyManagementManager.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/EVSEManufacturerImpl.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/ElectricalPowerMeasurementDelegate.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/EnergyEvseDelegateImpl.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/EnergyEvseManager.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/EnergyEvseTargetsStore.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/EnergyTimeUtils.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/common/src/EnergyTimeUtils.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/device-energy-management/src/DeviceEnergyManagementDelegateImpl.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/device-energy-management/src/DeviceEnergyManagementManager.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/src/ChargingTargetsMemMgr.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/src/EVSEManufacturerImpl.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/src/EnergyEvseDelegateImpl.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/src/EnergyEvseManager.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/src/EnergyEvseTargetsStore.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/src/energy-evse-mode.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-reporting/src/ElectricalPowerMeasurementDelegate.cpp", "${chip_root}/src/lib/shell/streamer_mw320.cpp", "binding-handler.cpp", "include/CHIPProjectConfig.h", diff --git a/examples/all-clusters-app/openiotsdk/CMakeLists.txt b/examples/all-clusters-app/openiotsdk/CMakeLists.txt index 9db62a3df7..c568ec2b19 100644 --- a/examples/all-clusters-app/openiotsdk/CMakeLists.txt +++ b/examples/all-clusters-app/openiotsdk/CMakeLists.txt @@ -48,7 +48,10 @@ target_include_directories(${APP_TARGET} PRIVATE main/include ${ALL_CLUSTERS_COMMON}/include - ${ENERGY_MANAGEMENT_COMMON}/include + ${ENERGY_MANAGEMENT_COMMON}/common/include + ${ENERGY_MANAGEMENT_COMMON}/device-energy-management/include + ${ENERGY_MANAGEMENT_COMMON}/energy-evse/include + ${ENERGY_MANAGEMENT_COMMON}/energy-reporting/include ) target_sources(${APP_TARGET} @@ -65,15 +68,15 @@ target_sources(${APP_TARGET} ${ALL_CLUSTERS_COMMON}/src/resource-monitoring-delegates.cpp ${ALL_CLUSTERS_COMMON}/src/static-supported-modes-manager.cpp ${ALL_CLUSTERS_COMMON}/src/binding-handler.cpp - ${ENERGY_MANAGEMENT_COMMON}/src/ChargingTargetsMemMgr.cpp - ${ENERGY_MANAGEMENT_COMMON}/src/DeviceEnergyManagementDelegateImpl.cpp - ${ENERGY_MANAGEMENT_COMMON}/src/DeviceEnergyManagementManager.cpp - ${ENERGY_MANAGEMENT_COMMON}/src/EVSEManufacturerImpl.cpp - ${ENERGY_MANAGEMENT_COMMON}/src/ElectricalPowerMeasurementDelegate.cpp - ${ENERGY_MANAGEMENT_COMMON}/src/EnergyEvseDelegateImpl.cpp - ${ENERGY_MANAGEMENT_COMMON}/src/EnergyEvseManager.cpp - ${ENERGY_MANAGEMENT_COMMON}/src/EnergyEvseTargetsStore.cpp - ${ENERGY_MANAGEMENT_COMMON}/src/EnergyTimeUtils.cpp + ${ENERGY_MANAGEMENT_COMMON}/common/src/EnergyTimeUtils.cpp + ${ENERGY_MANAGEMENT_COMMON}/device-energy-management/src/DeviceEnergyManagementDelegateImpl.cpp + ${ENERGY_MANAGEMENT_COMMON}/device-energy-management/src/DeviceEnergyManagementManager.cpp + ${ENERGY_MANAGEMENT_COMMON}/energy-evse/src/ChargingTargetsMemMgr.cpp + ${ENERGY_MANAGEMENT_COMMON}/energy-evse/src/EVSEManufacturerImpl.cpp + ${ENERGY_MANAGEMENT_COMMON}/energy-evse/src/EnergyEvseDelegateImpl.cpp + ${ENERGY_MANAGEMENT_COMMON}/energy-evse/src/EnergyEvseManager.cpp + ${ENERGY_MANAGEMENT_COMMON}/energy-evse/src/EnergyEvseTargetsStore.cpp + ${ENERGY_MANAGEMENT_COMMON}/energy-reporting/src/ElectricalPowerMeasurementDelegate.cpp ) target_link_libraries(${APP_TARGET} diff --git a/examples/all-clusters-app/telink/CMakeLists.txt b/examples/all-clusters-app/telink/CMakeLists.txt index 675ea4d9eb..1eba507269 100644 --- a/examples/all-clusters-app/telink/CMakeLists.txt +++ b/examples/all-clusters-app/telink/CMakeLists.txt @@ -31,7 +31,10 @@ project(chip-telink-all-clusters-app-example) target_include_directories(app PRIVATE include ${ALL_CLUSTERS_COMMON_DIR}/include - ${ENERGY_MANAGEMENT_COMMON_DIR}/include + ${ENERGY_MANAGEMENT_COMMON_DIR}/common/include + ${ENERGY_MANAGEMENT_COMMON_DIR}/device-energy-management/include + ${ENERGY_MANAGEMENT_COMMON_DIR}/energy-evse/include + ${ENERGY_MANAGEMENT_COMMON_DIR}/energy-reporting/include ${GEN_DIR}/app-common ${GEN_DIR}/all-clusters-app ${TELINK_COMMON}/common/include @@ -51,15 +54,15 @@ target_sources(app PRIVATE ${ALL_CLUSTERS_COMMON_DIR}/src/device-energy-management-stub.cpp ${ALL_CLUSTERS_COMMON_DIR}/src/energy-evse-stub.cpp ${ALL_CLUSTERS_COMMON_DIR}/src/resource-monitoring-delegates.cpp - ${ENERGY_MANAGEMENT_COMMON_DIR}/src/ChargingTargetsMemMgr.cpp - ${ENERGY_MANAGEMENT_COMMON_DIR}/src/DeviceEnergyManagementDelegateImpl.cpp - ${ENERGY_MANAGEMENT_COMMON_DIR}/src/DeviceEnergyManagementManager.cpp - ${ENERGY_MANAGEMENT_COMMON_DIR}/src/EVSEManufacturerImpl.cpp - ${ENERGY_MANAGEMENT_COMMON_DIR}/src/ElectricalPowerMeasurementDelegate.cpp - ${ENERGY_MANAGEMENT_COMMON_DIR}/src/EnergyEvseDelegateImpl.cpp - ${ENERGY_MANAGEMENT_COMMON_DIR}/src/EnergyEvseManager.cpp - ${ENERGY_MANAGEMENT_COMMON_DIR}/src/EnergyEvseTargetsStore.cpp - ${ENERGY_MANAGEMENT_COMMON_DIR}/src/EnergyTimeUtils.cpp + ${ENERGY_MANAGEMENT_COMMON_DIR}/common/src/EnergyTimeUtils.cpp + ${ENERGY_MANAGEMENT_COMMON_DIR}/device-energy-management/src/DeviceEnergyManagementDelegateImpl.cpp + ${ENERGY_MANAGEMENT_COMMON_DIR}/device-energy-management/src/DeviceEnergyManagementManager.cpp + ${ENERGY_MANAGEMENT_COMMON_DIR}/energy-evse/src/ChargingTargetsMemMgr.cpp + ${ENERGY_MANAGEMENT_COMMON_DIR}/energy-evse/src/EVSEManufacturerImpl.cpp + ${ENERGY_MANAGEMENT_COMMON_DIR}/energy-evse/src/EnergyEvseDelegateImpl.cpp + ${ENERGY_MANAGEMENT_COMMON_DIR}/energy-evse/src/EnergyEvseManager.cpp + ${ENERGY_MANAGEMENT_COMMON_DIR}/energy-evse/src/EnergyEvseTargetsStore.cpp + ${ENERGY_MANAGEMENT_COMMON_DIR}/energy-reporting/src/ElectricalPowerMeasurementDelegate.cpp ${TELINK_COMMON}/common/src/mainCommon.cpp ${TELINK_COMMON}/common/src/AppTaskCommon.cpp ${TELINK_COMMON}/util/src/LEDManager.cpp diff --git a/examples/all-clusters-app/tizen/BUILD.gn b/examples/all-clusters-app/tizen/BUILD.gn index 855416c044..332b03cbeb 100644 --- a/examples/all-clusters-app/tizen/BUILD.gn +++ b/examples/all-clusters-app/tizen/BUILD.gn @@ -38,15 +38,16 @@ source_set("chip-all-clusters-common") { "${chip_root}/examples/all-clusters-app/all-clusters-common/src/smco-stub.cpp", "${chip_root}/examples/all-clusters-app/all-clusters-common/src/static-supported-modes-manager.cpp", "${chip_root}/examples/all-clusters-app/all-clusters-common/src/static-supported-temperature-levels.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/ChargingTargetsMemMgr.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/DeviceEnergyManagementDelegateImpl.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/DeviceEnergyManagementManager.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/EVSEManufacturerImpl.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/ElectricalPowerMeasurementDelegate.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/EnergyEvseDelegateImpl.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/EnergyEvseManager.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/EnergyEvseTargetsStore.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/EnergyTimeUtils.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/common/src/EnergyTimeUtils.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/device-energy-management/src/DeviceEnergyManagementDelegateImpl.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/device-energy-management/src/DeviceEnergyManagementManager.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/src/ChargingTargetsMemMgr.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/src/EVSEManufacturerImpl.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/src/EnergyEvseDelegateImpl.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/src/EnergyEvseManager.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/src/EnergyEvseTargetsStore.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/src/energy-evse-mode.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-reporting/src/ElectricalPowerMeasurementDelegate.cpp", ] deps = [ @@ -57,7 +58,10 @@ source_set("chip-all-clusters-common") { include_dirs = [ "${chip_root}/examples/all-clusters-app/all-clusters-common/include", - "${chip_root}/examples/energy-management-app/energy-management-common/include", + "${chip_root}/examples/energy-management-app/energy-management-common/common/include", + "${chip_root}/examples/energy-management-app/energy-management-common/device-energy-management/include", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/include", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-reporting/include", ] } diff --git a/examples/all-clusters-minimal-app/esp32/main/CMakeLists.txt b/examples/all-clusters-minimal-app/esp32/main/CMakeLists.txt index 7178945c7e..06916c32c6 100644 --- a/examples/all-clusters-minimal-app/esp32/main/CMakeLists.txt +++ b/examples/all-clusters-minimal-app/esp32/main/CMakeLists.txt @@ -19,7 +19,10 @@ # The list of src and include dirs must be in sync with that in all-clusters-minimal-app/esp32/main/component.mk set(PRIV_INCLUDE_DIRS_LIST "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/all-clusters-app/all-clusters-common/include" - "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/energy-management-app/energy-management-common/include" + "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/energy-management-app/energy-management-common/common/include" + "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/energy-management-app/energy-management-common/device-energy-management/include" + "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/energy-management-app/energy-management-common/energy-evse/include" + "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/energy-management-app/energy-management-common/energy-reporting/include" "${CMAKE_CURRENT_LIST_DIR}/include" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/providers" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/platform/esp32" diff --git a/examples/energy-management-app/energy-management-common/include/EnergyManagementAppCmdLineOptions.h b/examples/energy-management-app/energy-management-common/common/include/EnergyManagementAppCmdLineOptions.h similarity index 100% rename from examples/energy-management-app/energy-management-common/include/EnergyManagementAppCmdLineOptions.h rename to examples/energy-management-app/energy-management-common/common/include/EnergyManagementAppCmdLineOptions.h diff --git a/examples/energy-management-app/energy-management-common/src/EnergyTimeUtils.cpp b/examples/energy-management-app/energy-management-common/common/src/EnergyTimeUtils.cpp similarity index 100% rename from examples/energy-management-app/energy-management-common/src/EnergyTimeUtils.cpp rename to examples/energy-management-app/energy-management-common/common/src/EnergyTimeUtils.cpp diff --git a/examples/energy-management-app/energy-management-common/include/DEMManufacturerDelegate.h b/examples/energy-management-app/energy-management-common/device-energy-management/include/DEMManufacturerDelegate.h similarity index 100% rename from examples/energy-management-app/energy-management-common/include/DEMManufacturerDelegate.h rename to examples/energy-management-app/energy-management-common/device-energy-management/include/DEMManufacturerDelegate.h diff --git a/examples/energy-management-app/energy-management-common/include/DeviceEnergyManagementDelegateImpl.h b/examples/energy-management-app/energy-management-common/device-energy-management/include/DeviceEnergyManagementDelegateImpl.h similarity index 100% rename from examples/energy-management-app/energy-management-common/include/DeviceEnergyManagementDelegateImpl.h rename to examples/energy-management-app/energy-management-common/device-energy-management/include/DeviceEnergyManagementDelegateImpl.h diff --git a/examples/energy-management-app/energy-management-common/include/DeviceEnergyManagementManager.h b/examples/energy-management-app/energy-management-common/device-energy-management/include/DeviceEnergyManagementManager.h similarity index 100% rename from examples/energy-management-app/energy-management-common/include/DeviceEnergyManagementManager.h rename to examples/energy-management-app/energy-management-common/device-energy-management/include/DeviceEnergyManagementManager.h diff --git a/examples/energy-management-app/energy-management-common/include/device-energy-management-modes.h b/examples/energy-management-app/energy-management-common/device-energy-management/include/device-energy-management-modes.h similarity index 100% rename from examples/energy-management-app/energy-management-common/include/device-energy-management-modes.h rename to examples/energy-management-app/energy-management-common/device-energy-management/include/device-energy-management-modes.h diff --git a/examples/energy-management-app/energy-management-common/src/DEMTestEventTriggers.cpp b/examples/energy-management-app/energy-management-common/device-energy-management/src/DEMTestEventTriggers.cpp similarity index 100% rename from examples/energy-management-app/energy-management-common/src/DEMTestEventTriggers.cpp rename to examples/energy-management-app/energy-management-common/device-energy-management/src/DEMTestEventTriggers.cpp diff --git a/examples/energy-management-app/energy-management-common/src/DeviceEnergyManagementDelegateImpl.cpp b/examples/energy-management-app/energy-management-common/device-energy-management/src/DeviceEnergyManagementDelegateImpl.cpp similarity index 100% rename from examples/energy-management-app/energy-management-common/src/DeviceEnergyManagementDelegateImpl.cpp rename to examples/energy-management-app/energy-management-common/device-energy-management/src/DeviceEnergyManagementDelegateImpl.cpp diff --git a/examples/energy-management-app/energy-management-common/src/DeviceEnergyManagementManager.cpp b/examples/energy-management-app/energy-management-common/device-energy-management/src/DeviceEnergyManagementManager.cpp similarity index 100% rename from examples/energy-management-app/energy-management-common/src/DeviceEnergyManagementManager.cpp rename to examples/energy-management-app/energy-management-common/device-energy-management/src/DeviceEnergyManagementManager.cpp diff --git a/examples/energy-management-app/energy-management-common/src/device-energy-management-mode.cpp b/examples/energy-management-app/energy-management-common/device-energy-management/src/device-energy-management-mode.cpp similarity index 100% rename from examples/energy-management-app/energy-management-common/src/device-energy-management-mode.cpp rename to examples/energy-management-app/energy-management-common/device-energy-management/src/device-energy-management-mode.cpp diff --git a/examples/energy-management-app/energy-management-common/include/ChargingTargetsMemMgr.h b/examples/energy-management-app/energy-management-common/energy-evse/include/ChargingTargetsMemMgr.h similarity index 100% rename from examples/energy-management-app/energy-management-common/include/ChargingTargetsMemMgr.h rename to examples/energy-management-app/energy-management-common/energy-evse/include/ChargingTargetsMemMgr.h diff --git a/examples/energy-management-app/energy-management-common/include/EVSECallbacks.h b/examples/energy-management-app/energy-management-common/energy-evse/include/EVSECallbacks.h similarity index 100% rename from examples/energy-management-app/energy-management-common/include/EVSECallbacks.h rename to examples/energy-management-app/energy-management-common/energy-evse/include/EVSECallbacks.h diff --git a/examples/energy-management-app/energy-management-common/include/EVSEManufacturerImpl.h b/examples/energy-management-app/energy-management-common/energy-evse/include/EVSEManufacturerImpl.h similarity index 100% rename from examples/energy-management-app/energy-management-common/include/EVSEManufacturerImpl.h rename to examples/energy-management-app/energy-management-common/energy-evse/include/EVSEManufacturerImpl.h diff --git a/examples/energy-management-app/energy-management-common/include/EnergyEvseDelegateImpl.h b/examples/energy-management-app/energy-management-common/energy-evse/include/EnergyEvseDelegateImpl.h similarity index 100% rename from examples/energy-management-app/energy-management-common/include/EnergyEvseDelegateImpl.h rename to examples/energy-management-app/energy-management-common/energy-evse/include/EnergyEvseDelegateImpl.h diff --git a/examples/energy-management-app/energy-management-common/include/EnergyEvseMain.h b/examples/energy-management-app/energy-management-common/energy-evse/include/EnergyEvseMain.h similarity index 100% rename from examples/energy-management-app/energy-management-common/include/EnergyEvseMain.h rename to examples/energy-management-app/energy-management-common/energy-evse/include/EnergyEvseMain.h diff --git a/examples/energy-management-app/energy-management-common/include/EnergyEvseManager.h b/examples/energy-management-app/energy-management-common/energy-evse/include/EnergyEvseManager.h similarity index 100% rename from examples/energy-management-app/energy-management-common/include/EnergyEvseManager.h rename to examples/energy-management-app/energy-management-common/energy-evse/include/EnergyEvseManager.h diff --git a/examples/energy-management-app/energy-management-common/include/EnergyEvseTargetsStore.h b/examples/energy-management-app/energy-management-common/energy-evse/include/EnergyEvseTargetsStore.h similarity index 100% rename from examples/energy-management-app/energy-management-common/include/EnergyEvseTargetsStore.h rename to examples/energy-management-app/energy-management-common/energy-evse/include/EnergyEvseTargetsStore.h diff --git a/examples/energy-management-app/energy-management-common/include/EnergyTimeUtils.h b/examples/energy-management-app/energy-management-common/energy-evse/include/EnergyTimeUtils.h similarity index 100% rename from examples/energy-management-app/energy-management-common/include/EnergyTimeUtils.h rename to examples/energy-management-app/energy-management-common/energy-evse/include/EnergyTimeUtils.h diff --git a/examples/energy-management-app/energy-management-common/include/energy-evse-modes.h b/examples/energy-management-app/energy-management-common/energy-evse/include/energy-evse-modes.h similarity index 100% rename from examples/energy-management-app/energy-management-common/include/energy-evse-modes.h rename to examples/energy-management-app/energy-management-common/energy-evse/include/energy-evse-modes.h diff --git a/examples/energy-management-app/energy-management-common/src/ChargingTargetsMemMgr.cpp b/examples/energy-management-app/energy-management-common/energy-evse/src/ChargingTargetsMemMgr.cpp similarity index 100% rename from examples/energy-management-app/energy-management-common/src/ChargingTargetsMemMgr.cpp rename to examples/energy-management-app/energy-management-common/energy-evse/src/ChargingTargetsMemMgr.cpp diff --git a/examples/energy-management-app/energy-management-common/src/EVSEManufacturerImpl.cpp b/examples/energy-management-app/energy-management-common/energy-evse/src/EVSEManufacturerImpl.cpp similarity index 100% rename from examples/energy-management-app/energy-management-common/src/EVSEManufacturerImpl.cpp rename to examples/energy-management-app/energy-management-common/energy-evse/src/EVSEManufacturerImpl.cpp diff --git a/examples/energy-management-app/energy-management-common/src/EnergyEvseDelegateImpl.cpp b/examples/energy-management-app/energy-management-common/energy-evse/src/EnergyEvseDelegateImpl.cpp similarity index 100% rename from examples/energy-management-app/energy-management-common/src/EnergyEvseDelegateImpl.cpp rename to examples/energy-management-app/energy-management-common/energy-evse/src/EnergyEvseDelegateImpl.cpp diff --git a/examples/energy-management-app/energy-management-common/src/EnergyEvseEventTriggers.cpp b/examples/energy-management-app/energy-management-common/energy-evse/src/EnergyEvseEventTriggers.cpp similarity index 100% rename from examples/energy-management-app/energy-management-common/src/EnergyEvseEventTriggers.cpp rename to examples/energy-management-app/energy-management-common/energy-evse/src/EnergyEvseEventTriggers.cpp diff --git a/examples/energy-management-app/energy-management-common/src/EnergyEvseMain.cpp b/examples/energy-management-app/energy-management-common/energy-evse/src/EnergyEvseMain.cpp similarity index 100% rename from examples/energy-management-app/energy-management-common/src/EnergyEvseMain.cpp rename to examples/energy-management-app/energy-management-common/energy-evse/src/EnergyEvseMain.cpp diff --git a/examples/energy-management-app/energy-management-common/src/EnergyEvseManager.cpp b/examples/energy-management-app/energy-management-common/energy-evse/src/EnergyEvseManager.cpp similarity index 100% rename from examples/energy-management-app/energy-management-common/src/EnergyEvseManager.cpp rename to examples/energy-management-app/energy-management-common/energy-evse/src/EnergyEvseManager.cpp diff --git a/examples/energy-management-app/energy-management-common/src/EnergyEvseTargetsStore.cpp b/examples/energy-management-app/energy-management-common/energy-evse/src/EnergyEvseTargetsStore.cpp similarity index 100% rename from examples/energy-management-app/energy-management-common/src/EnergyEvseTargetsStore.cpp rename to examples/energy-management-app/energy-management-common/energy-evse/src/EnergyEvseTargetsStore.cpp diff --git a/examples/energy-management-app/energy-management-common/src/energy-evse-mode.cpp b/examples/energy-management-app/energy-management-common/energy-evse/src/energy-evse-mode.cpp similarity index 100% rename from examples/energy-management-app/energy-management-common/src/energy-evse-mode.cpp rename to examples/energy-management-app/energy-management-common/energy-evse/src/energy-evse-mode.cpp diff --git a/examples/energy-management-app/energy-management-common/include/ElectricalPowerMeasurementDelegate.h b/examples/energy-management-app/energy-management-common/energy-reporting/include/ElectricalPowerMeasurementDelegate.h similarity index 100% rename from examples/energy-management-app/energy-management-common/include/ElectricalPowerMeasurementDelegate.h rename to examples/energy-management-app/energy-management-common/energy-reporting/include/ElectricalPowerMeasurementDelegate.h diff --git a/examples/energy-management-app/energy-management-common/include/FakeReadings.h b/examples/energy-management-app/energy-management-common/energy-reporting/include/FakeReadings.h similarity index 100% rename from examples/energy-management-app/energy-management-common/include/FakeReadings.h rename to examples/energy-management-app/energy-management-common/energy-reporting/include/FakeReadings.h diff --git a/examples/energy-management-app/energy-management-common/include/PowerTopologyDelegate.h b/examples/energy-management-app/energy-management-common/energy-reporting/include/PowerTopologyDelegate.h similarity index 100% rename from examples/energy-management-app/energy-management-common/include/PowerTopologyDelegate.h rename to examples/energy-management-app/energy-management-common/energy-reporting/include/PowerTopologyDelegate.h diff --git a/examples/energy-management-app/energy-management-common/src/ElectricalPowerMeasurementDelegate.cpp b/examples/energy-management-app/energy-management-common/energy-reporting/src/ElectricalPowerMeasurementDelegate.cpp similarity index 100% rename from examples/energy-management-app/energy-management-common/src/ElectricalPowerMeasurementDelegate.cpp rename to examples/energy-management-app/energy-management-common/energy-reporting/src/ElectricalPowerMeasurementDelegate.cpp diff --git a/examples/energy-management-app/energy-management-common/src/EnergyReportingEventTriggers.cpp b/examples/energy-management-app/energy-management-common/energy-reporting/src/EnergyReportingEventTriggers.cpp similarity index 100% rename from examples/energy-management-app/energy-management-common/src/EnergyReportingEventTriggers.cpp rename to examples/energy-management-app/energy-management-common/energy-reporting/src/EnergyReportingEventTriggers.cpp diff --git a/examples/energy-management-app/energy-management-common/src/FakeReadings.cpp b/examples/energy-management-app/energy-management-common/energy-reporting/src/FakeReadings.cpp similarity index 100% rename from examples/energy-management-app/energy-management-common/src/FakeReadings.cpp rename to examples/energy-management-app/energy-management-common/energy-reporting/src/FakeReadings.cpp diff --git a/examples/energy-management-app/energy-management-common/src/PowerTopologyDelegate.cpp b/examples/energy-management-app/energy-management-common/energy-reporting/src/PowerTopologyDelegate.cpp similarity index 100% rename from examples/energy-management-app/energy-management-common/src/PowerTopologyDelegate.cpp rename to examples/energy-management-app/energy-management-common/energy-reporting/src/PowerTopologyDelegate.cpp diff --git a/examples/energy-management-app/energy-management-common/tests/BUILD.gn b/examples/energy-management-app/energy-management-common/tests/BUILD.gn index b55340a527..c11d783194 100644 --- a/examples/energy-management-app/energy-management-common/tests/BUILD.gn +++ b/examples/energy-management-app/energy-management-common/tests/BUILD.gn @@ -18,7 +18,7 @@ import("//build_overrides/chip.gni") import("${chip_root}/build/chip/chip_test_suite.gni") config("tests_config") { - include_dirs = [ "${chip_root}/examples/energy-management-app/energy-management-common/include" ] + include_dirs = [ "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/include" ] } chip_test_suite("tests") { diff --git a/examples/energy-management-app/esp32/main/CMakeLists.txt b/examples/energy-management-app/esp32/main/CMakeLists.txt index cce09303b5..03b8234625 100644 --- a/examples/energy-management-app/esp32/main/CMakeLists.txt +++ b/examples/energy-management-app/esp32/main/CMakeLists.txt @@ -19,7 +19,10 @@ set(PRIV_INCLUDE_DIRS_LIST "${APP_GEN_DIR}" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/providers" - "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/energy-management-app/energy-management-common/include" + "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/energy-management-app/energy-management-common/common/include" + "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/energy-management-app/energy-management-common/device-energy-management/include" + "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/energy-management-app/energy-management-common/energy-evse/include" + "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/energy-management-app/energy-management-common/energy-reporting/include" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/energy-management-app/esp32/main/include" "${CMAKE_CURRENT_LIST_DIR}/include" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/platform/esp32" @@ -29,7 +32,10 @@ set(SRC_DIRS_LIST "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/zzz_generated/app-common/app-common/zap-generated/attributes" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/zzz_generated/app-common/app-common/zap-generated" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/providers" - "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/energy-management-app/energy-management-common/src" + "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/energy-management-app/energy-management-common/common/src" + "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/energy-management-app/energy-management-common/device-energy-management/src" + "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/energy-management-app/energy-management-common/energy-evse/src" + "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/energy-management-app/energy-management-common/energy-reporting/src" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/platform/esp32/ota" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/platform/esp32/common" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/platform/esp32/time" diff --git a/examples/energy-management-app/linux/BUILD.gn b/examples/energy-management-app/linux/BUILD.gn index 1a6e2d287f..d2633c67c8 100644 --- a/examples/energy-management-app/linux/BUILD.gn +++ b/examples/energy-management-app/linux/BUILD.gn @@ -34,23 +34,23 @@ config("includes") { executable("chip-energy-management-app") { sources = [ - "${chip_root}/examples/energy-management-app/energy-management-common/src/ChargingTargetsMemMgr.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/DEMTestEventTriggers.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/DeviceEnergyManagementDelegateImpl.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/DeviceEnergyManagementManager.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/EVSEManufacturerImpl.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/ElectricalPowerMeasurementDelegate.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/EnergyEvseDelegateImpl.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/EnergyEvseEventTriggers.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/EnergyEvseMain.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/EnergyEvseManager.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/EnergyEvseTargetsStore.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/EnergyReportingEventTriggers.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/EnergyTimeUtils.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/FakeReadings.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/PowerTopologyDelegate.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/device-energy-management-mode.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/energy-evse-mode.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/common/src/EnergyTimeUtils.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/device-energy-management/src/DEMTestEventTriggers.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/device-energy-management/src/DeviceEnergyManagementDelegateImpl.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/device-energy-management/src/DeviceEnergyManagementManager.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/device-energy-management/src/device-energy-management-mode.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/src/ChargingTargetsMemMgr.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/src/EVSEManufacturerImpl.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/src/EnergyEvseDelegateImpl.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/src/EnergyEvseEventTriggers.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/src/EnergyEvseMain.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/src/EnergyEvseManager.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/src/EnergyEvseTargetsStore.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/src/energy-evse-mode.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-reporting/src/ElectricalPowerMeasurementDelegate.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-reporting/src/EnergyReportingEventTriggers.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-reporting/src/FakeReadings.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-reporting/src/PowerTopologyDelegate.cpp", "include/CHIPProjectAppConfig.h", "main.cpp", ] @@ -71,7 +71,10 @@ executable("chip-energy-management-app") { include_dirs = [ "include", - "${chip_root}/examples/energy-management-app/energy-management-common/include", + "${chip_root}/examples/energy-management-app/energy-management-common/common/include", + "${chip_root}/examples/energy-management-app/energy-management-common/device-energy-management/include", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/include", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-reporting/include", ] if (chip_enable_pw_rpc) { @@ -129,13 +132,13 @@ executable("chip-energy-management-app") { source_set("test-evse-targets-store") { sources = [ - "${chip_root}/examples/energy-management-app/energy-management-common/src/ChargingTargetsMemMgr.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/EnergyEvseTargetsStore.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/src/ChargingTargetsMemMgr.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/src/EnergyEvseTargetsStore.cpp", ] include_dirs = [ "include", - "${chip_root}/examples/energy-management-app/energy-management-common/include", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/include", ] deps = [ diff --git a/examples/shell/shell_common/BUILD.gn b/examples/shell/shell_common/BUILD.gn index 470f81b5d2..e4aa2973f8 100644 --- a/examples/shell/shell_common/BUILD.gn +++ b/examples/shell/shell_common/BUILD.gn @@ -70,20 +70,24 @@ static_library("shell_common") { "${chip_root}/examples/all-clusters-app/all-clusters-common/src/smco-stub.cpp", "${chip_root}/examples/all-clusters-app/all-clusters-common/src/static-supported-modes-manager.cpp", "${chip_root}/examples/all-clusters-app/all-clusters-common/src/static-supported-temperature-levels.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/ChargingTargetsMemMgr.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/DeviceEnergyManagementDelegateImpl.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/DeviceEnergyManagementManager.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/EVSEManufacturerImpl.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/ElectricalPowerMeasurementDelegate.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/EnergyEvseDelegateImpl.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/EnergyEvseManager.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/EnergyEvseTargetsStore.cpp", - "${chip_root}/examples/energy-management-app/energy-management-common/src/EnergyTimeUtils.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/common/src/EnergyTimeUtils.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/device-energy-management/src/DeviceEnergyManagementDelegateImpl.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/device-energy-management/src/DeviceEnergyManagementManager.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/src/ChargingTargetsMemMgr.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/src/EVSEManufacturerImpl.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/src/EnergyEvseDelegateImpl.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/src/EnergyEvseManager.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/src/EnergyEvseTargetsStore.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/src/energy-evse-mode.cpp", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-reporting/src/ElectricalPowerMeasurementDelegate.cpp", ] include_dirs = [ "${chip_root}/examples/all-clusters-app/all-clusters-common/include", - "${chip_root}/examples/energy-management-app/energy-management-common/include", + "${chip_root}/examples/energy-management-app/energy-management-common/common/include", + "${chip_root}/examples/energy-management-app/energy-management-common/device-energy-management/include", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/include", + "${chip_root}/examples/energy-management-app/energy-management-common/energy-reporting/include", "${chip_root}/src/app/clusters/device-energy-management-server", ] From 62139bf0ab19c4c5d0b8a4d2282a6b8cf3405aac Mon Sep 17 00:00:00 2001 From: dinabenamar <108664279+dinabenamar@users.noreply.github.com> Date: Tue, 13 Aug 2024 16:01:50 +0200 Subject: [PATCH 027/165] [NXP][config] Adding CMake support to build CHIP libs for NXP FreeRTOS platforms (#34901) * [NXP][config][freertos] Adding support to build Matter lib and port files with cmake on NXP freertos platforms Signed-off-by: Dina Benamar * [NXP][config][common] Create common .cmake file to include common configs between freertos & zephyr Signed-off-by: Dina Benamar * [NXP][config][zephyr] Include common.cmake which adds common options to zephyr & freertos Signed-off-by: Dina Benamar * [NXP][config][freertos] Updates to align with new flag introduction "chip_enable_secure_whole_factory_data" Signed-off-by: Dina Benamar * [NXP][config][freertos] Set build_matter_standalone_lib to true to support building CHIP libs with CMake in matter-over-thread configuration Signed-off-by: Dina Benamar --------- Signed-off-by: Dina Benamar --- config/nxp/chip-cmake-freertos/CMakeLists.txt | 62 +++++++++++++++++ config/nxp/chip-gn-freertos/.gn | 29 ++++++++ config/nxp/chip-gn-freertos/BUILD.gn | 42 +++++++++++ config/nxp/chip-gn-freertos/args.gni | 31 +++++++++ config/nxp/chip-module/CMakeLists.txt | 42 +---------- config/nxp/cmake/common.cmake | 69 +++++++++++++++++++ 6 files changed, 234 insertions(+), 41 deletions(-) create mode 100644 config/nxp/chip-cmake-freertos/CMakeLists.txt create mode 100644 config/nxp/chip-gn-freertos/.gn create mode 100644 config/nxp/chip-gn-freertos/BUILD.gn create mode 100644 config/nxp/chip-gn-freertos/args.gni create mode 100644 config/nxp/cmake/common.cmake diff --git a/config/nxp/chip-cmake-freertos/CMakeLists.txt b/config/nxp/chip-cmake-freertos/CMakeLists.txt new file mode 100644 index 0000000000..b639e23ff6 --- /dev/null +++ b/config/nxp/chip-cmake-freertos/CMakeLists.txt @@ -0,0 +1,62 @@ +# +# 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(ExternalProject) + +if(NOT CHIP_ROOT) + get_filename_component(CHIP_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/../../.. REALPATH) +endif() + +get_filename_component(GN_ROOT_TARGET ${CHIP_ROOT}/config/nxp/chip-gn-freertos REALPATH) + +include(${CHIP_ROOT}/config/nxp/cmake/common.cmake) +include(${CHIP_ROOT}/src/app/chip_data_model.cmake) + +# Prepare compiler flags +matter_add_cflags(${CMAKE_C_FLAGS}) +matter_add_cxxflags(${CMAKE_CXX_FLAGS}) + +matter_get_compiler_flags_from_targets("${CONFIG_CHIP_EXTERNAL_TARGETS}") + +# ============================================================================== +# Generate configuration for CHIP GN build system +# ============================================================================== +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_common_gn_args( + DEBUG CONFIG_DEBUG + LIB_SHELL CONFIG_CHIP_LIB_SHELL + LIB_TESTS CONFIG_CHIP_BUILD_TESTS + 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 +) + +matter_generate_args_tmp_file() + +# ============================================================================== +# Build chip library +# ============================================================================== +matter_build(chip + LIB_SHELL ${CONFIG_CHIP_LIB_SHELL} + LIB_TESTS ${CONFIG_CHIP_BUILD_TESTS} + DEVICE_INFO_EXAMPLE_PROVIDER ${CONFIG_CHIP_EXAMPLE_DEVICE_INFO_PROVIDER} + GN_DEPENDENCIES ${CONFIG_GN_DEPENDENCIES} +) diff --git a/config/nxp/chip-gn-freertos/.gn b/config/nxp/chip-gn-freertos/.gn new file mode 100644 index 0000000000..15dde062d8 --- /dev/null +++ b/config/nxp/chip-gn-freertos/.gn @@ -0,0 +1,29 @@ +# 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") + +# The location of the build configuration file. +buildconfig = "//build/config/BUILDCONFIG.gn" + +# CHIP uses angle bracket includes. +check_system_includes = true + +default_args = { + target_cpu = "arm" + target_os = "freertos" + + import("${chip_root}/config/nxp/chip-gn-freertos/args.gni") +} diff --git a/config/nxp/chip-gn-freertos/BUILD.gn b/config/nxp/chip-gn-freertos/BUILD.gn new file mode 100644 index 0000000000..3c508666c8 --- /dev/null +++ b/config/nxp/chip-gn-freertos/BUILD.gn @@ -0,0 +1,42 @@ +# 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("${chip_root}/build/chip/tests.gni") + +assert(current_os == "freertos") + +declare_args() { + chip_build_example_providers = false + chip_enable_ethernet = false + chip_malloc_sys_heap = false +} + +group("nxp_freertos") { + deps = [ "${chip_root}/src/lib" ] + + if (chip_build_tests) { + deps += [ "${chip_root}/src:tests" ] + } + + if (chip_build_example_providers) { + deps += [ "${chip_root}/examples/providers:device_info_provider" ] + } +} + +group("default") { + deps = [ ":nxp_freertos" ] +} diff --git a/config/nxp/chip-gn-freertos/args.gni b/config/nxp/chip-gn-freertos/args.gni new file mode 100644 index 0000000000..be31f22fcb --- /dev/null +++ b/config/nxp/chip-gn-freertos/args.gni @@ -0,0 +1,31 @@ +# 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/nxp_sdk.gni") + +nxp_external_sdk = true +nxp_build_matter_standalone_lib = true +chip_device_platform = "nxp" +lwip_platform = "nxp" + +# project config files +chip_device_project_config_include = "" +chip_project_config_include = "" +chip_inet_project_config_include = "" +chip_system_project_config_include = "" +chip_ble_project_config_include = "" + +# mbedtls is built as part of the NXP SDK build process +mbedtls_target = "${nxp_sdk_build_root}:nxp_mbedtls" diff --git a/config/nxp/chip-module/CMakeLists.txt b/config/nxp/chip-module/CMakeLists.txt index 6b8266970d..32a85a606c 100644 --- a/config/nxp/chip-module/CMakeLists.txt +++ b/config/nxp/chip-module/CMakeLists.txt @@ -42,12 +42,8 @@ if (NOT CHIP_ROOT) get_filename_component(CHIP_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/../../.. REALPATH) endif() get_filename_component(GN_ROOT_TARGET ${CHIP_ROOT}/config/nxp/chip-gn REALPATH) -get_filename_component(COMMON_CMAKE_SOURCE_DIR ${CHIP_ROOT}/config/common/cmake REALPATH) -# Get common Cmake sources - -include(${COMMON_CMAKE_SOURCE_DIR}/chip_gn_args.cmake) -include(${COMMON_CMAKE_SOURCE_DIR}/chip_gn.cmake) +include(${CHIP_ROOT}/config/nxp/cmake/common.cmake) # Prepare compiler flags if (CHIP_CFLAGS) @@ -109,30 +105,6 @@ matter_common_gn_args( matter_add_gn_arg_string("zephyr_ar" ${CMAKE_AR}) matter_add_gn_arg_string("zephyr_cc" ${CMAKE_C_COMPILER}) matter_add_gn_arg_string("zephyr_cxx" ${CMAKE_CXX_COMPILER}) -matter_add_gn_arg_bool ("chip_logging" CONFIG_LOG) -matter_add_gn_arg_bool ("chip_enable_openthread" CONFIG_NET_L2_OPENTHREAD) -matter_add_gn_arg_bool ("chip_openthread_ftd" CONFIG_OPENTHREAD_FTD) -matter_add_gn_arg_bool ("chip_config_network_layer_ble" CONFIG_BT) -matter_add_gn_arg_bool ("chip_inet_config_enable_ipv4" CONFIG_CHIP_IPV4) -matter_add_gn_arg_bool ("chip_persist_subscriptions" CONFIG_CHIP_PERSISTENT_SUBSCRIPTIONS) -matter_add_gn_arg_bool ("chip_monolithic_tests" CONFIG_CHIP_BUILD_TESTS) -matter_add_gn_arg_bool ("chip_inet_config_enable_tcp_endpoint" CONFIG_CHIP_BUILD_TESTS) -matter_add_gn_arg_bool ("chip_error_logging" CONFIG_MATTER_LOG_LEVEL GREATER_EQUAL 1) -matter_add_gn_arg_bool ("chip_progress_logging" CONFIG_MATTER_LOG_LEVEL GREATER_EQUAL 3) -matter_add_gn_arg_bool ("chip_detail_logging" CONFIG_MATTER_LOG_LEVEL GREATER_EQUAL 4) -matter_add_gn_arg_bool ("chip_automation_logging" FALSE) -matter_add_gn_arg_bool ("chip_malloc_sys_heap" CONFIG_CHIP_MALLOC_SYS_HEAP) -matter_add_gn_arg_bool ("chip_enable_wifi" CONFIG_CHIP_WIFI) -matter_add_gn_arg_bool ("chip_system_config_provide_statistics" CONFIG_CHIP_STATISTICS) -matter_add_gn_arg_bool ("chip_enable_icd_server" CONFIG_CHIP_ENABLE_ICD_SUPPORT) -matter_add_gn_arg_bool ("enable_eventlist_attribute" TRUE) -matter_add_gn_arg_bool ("chip_enable_ota_requestor" CONFIG_CHIP_OTA_REQUESTOR) - -if(CONFIG_DEBUG) - matter_add_gn_arg_bool("optimize_debug" true) - matter_add_gn_arg_string("optimize_debug_level" "0") - matter_add_gn_arg_string("symbol_level" "2") -endif() if (CONFIG_CHIP_FACTORY_DATA) matter_add_gn_arg_bool("chip_use_transitional_commissionable_data_provider" FALSE) @@ -141,11 +113,6 @@ elseif (CONFIG_CHIP_FACTORY_DATA_CUSTOM_BACKEND) matter_add_gn_arg_bool("chip_use_transitional_commissionable_data_provider" FALSE) endif() -if (CONFIG_CHIP_ROTATING_DEVICE_ID) - matter_add_gn_arg_bool("chip_enable_rotating_device_id" TRUE) - matter_add_gn_arg_bool("chip_enable_additional_data_advertising" TRUE) -endif() - if (CONFIG_NET_L2_OPENTHREAD) matter_add_gn_arg_string("chip_mdns" "platform") elseif(CONFIG_WIFI_NXP) @@ -154,9 +121,6 @@ else() matter_add_gn_arg_string("chip_mdns" "none") endif() -if (CONFIG_CHIP_CRYPTO_PSA) - matter_add_gn_arg_string("chip_crypto" "psa") -endif() # if (BOARD STREQUAL "native_posix") # matter_add_gn_arg_string("target_cpu" "x86") @@ -164,10 +128,6 @@ endif() # matter_add_gn_arg_string("target_cpu" "x64") # endif() -if (NOT CONFIG_CHIP_DEBUG_SYMBOLS) - matter_add_gn_arg_string("symbol_level" "0") -endif() - # if (CHIP_COMPILER_LAUNCHER) # matter_add_gn_arg_string("pw_command_launcher" ${CHIP_COMPILER_LAUNCHER}) # endif() diff --git a/config/nxp/cmake/common.cmake b/config/nxp/cmake/common.cmake new file mode 100644 index 0000000000..8b0f379f50 --- /dev/null +++ b/config/nxp/cmake/common.cmake @@ -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. +# + +# +# @file +# CMake for CHIP library configuration common to NXP platforms +# + +include(${CHIP_ROOT}/config/nxp/chip-module/generate_factory_data.cmake) + +get_filename_component(COMMON_CMAKE_SOURCE_DIR ${CHIP_ROOT}/config/common/cmake REALPATH) + +# Get common Cmake sources +include(${COMMON_CMAKE_SOURCE_DIR}/chip_gn_args.cmake) +include(${COMMON_CMAKE_SOURCE_DIR}/chip_gn.cmake) + +# ============================================================================== +# Generate configuration for CHIP GN build system +# ============================================================================== +matter_add_gn_arg_bool ("chip_logging" CONFIG_LOG) +matter_add_gn_arg_bool ("chip_enable_openthread" CONFIG_NET_L2_OPENTHREAD) +matter_add_gn_arg_bool ("chip_openthread_ftd" CONFIG_OPENTHREAD_FTD) +matter_add_gn_arg_bool ("chip_config_network_layer_ble" CONFIG_BT) +matter_add_gn_arg_bool ("chip_inet_config_enable_ipv4" CONFIG_CHIP_IPV4) +matter_add_gn_arg_bool ("chip_persist_subscriptions" CONFIG_CHIP_PERSISTENT_SUBSCRIPTIONS) +matter_add_gn_arg_bool ("chip_monolithic_tests" CONFIG_CHIP_BUILD_TESTS) +matter_add_gn_arg_bool ("chip_inet_config_enable_tcp_endpoint" CONFIG_CHIP_BUILD_TESTS) +matter_add_gn_arg_bool ("chip_error_logging" CONFIG_MATTER_LOG_LEVEL GREATER_EQUAL 1) +matter_add_gn_arg_bool ("chip_progress_logging" CONFIG_MATTER_LOG_LEVEL GREATER_EQUAL 3) +matter_add_gn_arg_bool ("chip_detail_logging" CONFIG_MATTER_LOG_LEVEL GREATER_EQUAL 4) +matter_add_gn_arg_bool ("chip_automation_logging" FALSE) +matter_add_gn_arg_bool ("chip_malloc_sys_heap" CONFIG_CHIP_MALLOC_SYS_HEAP) +matter_add_gn_arg_bool ("chip_enable_wifi" CONFIG_CHIP_WIFI) +matter_add_gn_arg_bool ("chip_system_config_provide_statistics" CONFIG_CHIP_STATISTICS) +matter_add_gn_arg_bool ("chip_enable_icd_server" CONFIG_CHIP_ENABLE_ICD_SUPPORT) +matter_add_gn_arg_bool ("enable_eventlist_attribute" TRUE) +matter_add_gn_arg_bool ("chip_enable_ota_requestor" CONFIG_CHIP_OTA_REQUESTOR) + +if(CONFIG_DEBUG) + matter_add_gn_arg_bool("optimize_debug" true) + matter_add_gn_arg_string("optimize_debug_level" "0") + matter_add_gn_arg_string("symbol_level" "2") +endif() + +if (CONFIG_CHIP_ROTATING_DEVICE_ID) + matter_add_gn_arg_bool("chip_enable_rotating_device_id" TRUE) + matter_add_gn_arg_bool("chip_enable_additional_data_advertising" TRUE) +endif() + +if (CONFIG_CHIP_CRYPTO_PSA) + matter_add_gn_arg_string("chip_crypto" "psa") +endif() + +if (NOT CONFIG_CHIP_DEBUG_SYMBOLS) + matter_add_gn_arg_string("symbol_level" "0") +endif() From f485e4acb75e048b78aeda92b556927abb5a9ef1 Mon Sep 17 00:00:00 2001 From: Yufeng Wang Date: Tue, 13 Aug 2024 09:03:41 -0700 Subject: [PATCH 028/165] [chip-tool] Adjust the maximum value of 'discriminator' to align with spec (#34940) --- .../chip-tool/commands/pairing/OpenCommissioningWindowCommand.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/chip-tool/commands/pairing/OpenCommissioningWindowCommand.h b/examples/chip-tool/commands/pairing/OpenCommissioningWindowCommand.h index 3a19974560..9da6e937ee 100644 --- a/examples/chip-tool/commands/pairing/OpenCommissioningWindowCommand.h +++ b/examples/chip-tool/commands/pairing/OpenCommissioningWindowCommand.h @@ -38,7 +38,7 @@ class OpenCommissioningWindowCommand : public CHIPCommand "Time, in seconds, before the commissioning window closes."); AddArgument("iteration", chip::Crypto::kSpake2p_Min_PBKDF_Iterations, chip::Crypto::kSpake2p_Max_PBKDF_Iterations, &mIteration, "Number of PBKDF iterations to use to derive the verifier. Ignored if 'option' is 0."); - AddArgument("discriminator", 0, 4096, &mDiscriminator, "Discriminator to use for advertising. Ignored if 'option' is 0."); + AddArgument("discriminator", 0, 4095, &mDiscriminator, "Discriminator to use for advertising. Ignored if 'option' is 0."); AddArgument("timeout", 0, UINT16_MAX, &mTimeout, "Time, in seconds, before this command is considered to have timed out."); } From b1e41b9db649537f09238ee61497953e488c18b7 Mon Sep 17 00:00:00 2001 From: andrei-menzopol <96489227+andrei-menzopol@users.noreply.github.com> Date: Tue, 13 Aug 2024 21:49:24 +0300 Subject: [PATCH 029/165] [examples][lock-common] Remove iostream include (#34952) * iostream adds a lot of unnecessary functions when lock-app is compiled for non-linux platforms, increasing ram and flash consumption. * linux lock-app compiles without it Signed-off-by: Andrei Menzopol --- examples/lock-app/lock-common/src/LockManager.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/examples/lock-app/lock-common/src/LockManager.cpp b/examples/lock-app/lock-common/src/LockManager.cpp index 8af6605188..cb7011899c 100644 --- a/examples/lock-app/lock-common/src/LockManager.cpp +++ b/examples/lock-app/lock-common/src/LockManager.cpp @@ -18,7 +18,6 @@ #include "LockManager.h" -#include #include #include From 4e30ae817e3f92e4dcaf6a9cf1a94b9d52198c99 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mi=C5=82osz=20Tomkiel?= Date: Tue, 13 Aug 2024 20:52:22 +0200 Subject: [PATCH 030/165] Fixed devcontainer creation for huge user ids (#34948) --- .devcontainer/Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile index 4c8a11fd42..da4e2c4171 100644 --- a/.devcontainer/Dockerfile +++ b/.devcontainer/Dockerfile @@ -43,7 +43,7 @@ RUN apt-get update \ && : RUN groupadd -g $USER_GID $USERNAME \ - && useradd -s /bin/bash -u $USER_UID -g $USER_GID -G docker,sudo -m $USERNAME \ + && useradd --no-log-init -s /bin/bash -u $USER_UID -g $USER_GID -G docker,sudo -m $USERNAME \ && echo $USERNAME ALL=\(root\) NOPASSWD:ALL > /etc/sudoers.d/$USERNAME \ && chmod 0440 /etc/sudoers.d/$USERNAME \ && : From 1d2ddd4131f3b6a10092d93a74ea58f0fe09510b Mon Sep 17 00:00:00 2001 From: Justin Wood Date: Tue, 13 Aug 2024 11:58:06 -0700 Subject: [PATCH 031/165] Enabling this for macOS Catalyst apps (#34956) --- src/darwin/Framework/Matter.xcodeproj/project.pbxproj | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/darwin/Framework/Matter.xcodeproj/project.pbxproj b/src/darwin/Framework/Matter.xcodeproj/project.pbxproj index 10884a64f4..bb5a8ce180 100644 --- a/src/darwin/Framework/Matter.xcodeproj/project.pbxproj +++ b/src/darwin/Framework/Matter.xcodeproj/project.pbxproj @@ -2319,6 +2319,7 @@ INSTALLHDRS_SCRIPT_PHASE = YES; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; IPHONEOS_DEPLOYMENT_TARGET = 14.0; + IS_ZIPPERED = YES; LIBRARY_SEARCH_PATHS = "$(TEMP_DIR)/out/lib"; OTHER_CFLAGS = "-fmacro-prefix-map=$(SRCROOT)/CHIP/="; OTHER_CPLUSPLUSFLAGS = ( @@ -2488,6 +2489,7 @@ INSTALLHDRS_SCRIPT_PHASE = YES; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; IPHONEOS_DEPLOYMENT_TARGET = 14.0; + IS_ZIPPERED = YES; LIBRARY_SEARCH_PATHS = "$(TEMP_DIR)/out/lib"; OTHER_CFLAGS = "-fmacro-prefix-map=$(SRCROOT)/CHIP/="; OTHER_CPLUSPLUSFLAGS = ( From 3884820327714eb16396da7e837b66a162375646 Mon Sep 17 00:00:00 2001 From: Martin Girardot <165289184+Martin-NXP@users.noreply.github.com> Date: Tue, 13 Aug 2024 21:21:14 +0200 Subject: [PATCH 032/165] Add new common NXP dockerfile (#34947) * [NXP][docker image] Add new common NXP docker image for next SDK version Signed-off-by: Martin Girardot * [NXP][docker image] remove k32w1 SDK clone as it will use common NXP SDK Signed-off-by: Martin Girardot --------- Signed-off-by: Martin Girardot --- .../docker/images/base/chip-build/version | 2 +- .../images/stage-2/chip-build-k32w/Dockerfile | 9 -------- .../images/stage-2/chip-build-nxp/Dockerfile | 23 +++++++++++++++++++ .../images/stage-2/chip-build-nxp/build.sh | 1 + .../images/stage-2/chip-build-nxp/run.sh | 1 + .../images/stage-2/chip-build-nxp/version | 1 + .../vscode/chip-build-vscode/Dockerfile | 4 ++++ 7 files changed, 31 insertions(+), 10 deletions(-) create mode 100644 integrations/docker/images/stage-2/chip-build-nxp/Dockerfile create mode 120000 integrations/docker/images/stage-2/chip-build-nxp/build.sh create mode 120000 integrations/docker/images/stage-2/chip-build-nxp/run.sh create mode 120000 integrations/docker/images/stage-2/chip-build-nxp/version diff --git a/integrations/docker/images/base/chip-build/version b/integrations/docker/images/base/chip-build/version index 0d78b8e5f7..5b9870bc97 100644 --- a/integrations/docker/images/base/chip-build/version +++ b/integrations/docker/images/base/chip-build/version @@ -1 +1 @@ -70 : [NXP] Update k32w1 SDK +71 : [NXP] Update k32w1 SDK as it will use common NXP SDK diff --git a/integrations/docker/images/stage-2/chip-build-k32w/Dockerfile b/integrations/docker/images/stage-2/chip-build-k32w/Dockerfile index 9b222355fb..c4cf71927d 100644 --- a/integrations/docker/images/stage-2/chip-build-k32w/Dockerfile +++ b/integrations/docker/images/stage-2/chip-build-k32w/Dockerfile @@ -26,17 +26,8 @@ RUN set -x \ && cp -R examples/* core/boards && rm -rf examples \ && : # last line -WORKDIR /opt/k32w1_sdk - -RUN set -x \ - && west init -m https://github.com/nxp-mcuxpresso/mcux-sdk --mr "MCUX_2.16.000" \ - && west update -o=--depth=1 -n -f smart \ - && : # last line - FROM ghcr.io/project-chip/chip-build:${VERSION} COPY --from=build /opt/sdk/ /opt/sdk/ -COPY --from=build /opt/k32w1_sdk/ /opt/k32w1_sdk/ ENV NXP_K32W0_SDK_ROOT=/opt/sdk/core -ENV NXP_SDK_ROOT=/opt/k32w1_sdk diff --git a/integrations/docker/images/stage-2/chip-build-nxp/Dockerfile b/integrations/docker/images/stage-2/chip-build-nxp/Dockerfile new file mode 100644 index 0000000000..537919fb77 --- /dev/null +++ b/integrations/docker/images/stage-2/chip-build-nxp/Dockerfile @@ -0,0 +1,23 @@ +ARG VERSION=1 +FROM ghcr.io/project-chip/chip-build:${VERSION} AS build +LABEL org.opencontainers.image.source=https://github.com/project-chip/connectedhomeip + +RUN set -x \ + && apt-get update \ + && DEBIAN_FRONTEND=noninteractive apt-get install -fy --no-install-recommends \ + xz-utils \ + && : # last line + +WORKDIR /opt/nxp/ + +RUN set -x \ + && git clone --branch v1.4.0-pvw1 https://github.com/NXP/nxp_matter_support.git \ + && pip3 install --break-system-packages -U --no-cache-dir west \ + && ./nxp_matter_support/scripts/update_nxp_sdk.py --platform common \ + && : # last line + +FROM ghcr.io/project-chip/chip-build:${VERSION} + +COPY --from=build /opt/nxp/ /opt/nxp/ + +ENV NXP_UPDATE_SDK_SCRIPT_DOCKER=/opt/nxp/nxp_matter_support/scripts/update_nxp_sdk.py diff --git a/integrations/docker/images/stage-2/chip-build-nxp/build.sh b/integrations/docker/images/stage-2/chip-build-nxp/build.sh new file mode 120000 index 0000000000..46b2031346 --- /dev/null +++ b/integrations/docker/images/stage-2/chip-build-nxp/build.sh @@ -0,0 +1 @@ +../../../build.sh \ No newline at end of file diff --git a/integrations/docker/images/stage-2/chip-build-nxp/run.sh b/integrations/docker/images/stage-2/chip-build-nxp/run.sh new file mode 120000 index 0000000000..9bbfad86d4 --- /dev/null +++ b/integrations/docker/images/stage-2/chip-build-nxp/run.sh @@ -0,0 +1 @@ +../../../run.sh \ No newline at end of file diff --git a/integrations/docker/images/stage-2/chip-build-nxp/version b/integrations/docker/images/stage-2/chip-build-nxp/version new file mode 120000 index 0000000000..a40ba48b01 --- /dev/null +++ b/integrations/docker/images/stage-2/chip-build-nxp/version @@ -0,0 +1 @@ +../../base/chip-build/version \ No newline at end of file diff --git a/integrations/docker/images/vscode/chip-build-vscode/Dockerfile b/integrations/docker/images/vscode/chip-build-vscode/Dockerfile index 4dda050b9c..9d6e24b1d2 100644 --- a/integrations/docker/images/vscode/chip-build-vscode/Dockerfile +++ b/integrations/docker/images/vscode/chip-build-vscode/Dockerfile @@ -11,6 +11,7 @@ FROM ghcr.io/project-chip/chip-build-crosscompile:${VERSION} AS crosscompile FROM ghcr.io/project-chip/chip-build-ameba:${VERSION} AS ameba FROM ghcr.io/project-chip/chip-build-k32w:${VERSION} AS k32w FROM ghcr.io/project-chip/chip-build-rw61x:${VERSION} AS rw61x +FROM ghcr.io/project-chip/chip-build-nxp:${VERSION} AS nxp FROM ghcr.io/project-chip/chip-build-nxp-zephyr:${VERSION} AS nxpzephyr FROM ghcr.io/project-chip/chip-build-imx:${VERSION} AS imx FROM ghcr.io/project-chip/chip-build-ti:${VERSION} AS ti @@ -51,6 +52,8 @@ COPY --from=k32w /opt/sdk /opt/k32w COPY --from=rw61x /opt/sdk /opt/nxp-sdk +COPY --from=nxp /opt/nxp /opt/nxp + COPY --from=nxpzephyr /opt/nxp-zephyr/zephyr-sdk-0.16.5/ /opt/nxp-zephyr/zephyr-sdk-0.16.5/ COPY --from=nxpzephyr /opt/nxp-zephyr/zephyrproject/ /opt/nxp-zephyr/zephyrproject/ @@ -139,6 +142,7 @@ ENV ZEPHYR_SDK_INSTALL_DIR=/opt/NordicSemiconductor/nRF5_tools/zephyr-sdk-0.16.5 ENV ZEPHYR_TOOLCHAIN_VARIANT=gnuarmemb ENV ZEPHYR_NXP_BASE=/opt/nxp-zephyr/zephyrproject/zephyr ENV ZEPHYR_NXP_SDK_INSTALL_DIR=/opt/nxp-zephyr/zephyr-sdk-0.16.5 +ENV NXP_UPDATE_SDK_SCRIPT_DOCKER=/opt/nxp/nxp_matter_support/scripts/update_nxp_sdk.py ENV TIZEN_VERSION 7.0 ENV TIZEN_SDK_ROOT /opt/tizen-sdk From 74b8ce19ade75de7f6562d70f375a47024b40e0e Mon Sep 17 00:00:00 2001 From: Andrei Litvin Date: Tue, 13 Aug 2024 15:22:57 -0400 Subject: [PATCH 033/165] Use timedInteraction for RevokeCommissioning in CCTRL_2_2 (#34957) Co-authored-by: Andrei Litvin --- src/python_testing/TC_CCTRL_2_2.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/python_testing/TC_CCTRL_2_2.py b/src/python_testing/TC_CCTRL_2_2.py index 8e1c8c5adb..18416d4c29 100644 --- a/src/python_testing/TC_CCTRL_2_2.py +++ b/src/python_testing/TC_CCTRL_2_2.py @@ -161,7 +161,7 @@ async def test_TC_CCTRL_2_2(self): self.step(9) cmd = Clusters.AdministratorCommissioning.Commands.RevokeCommissioning() # If no exception is raised, this is success - await self.send_single_cmd(cmd) + await self.send_single_cmd(cmd, timedRequestTimeoutMs=5000) self.step(10) if not events: From 128c37afaa94643ba7c7d992d7d48dd350902a65 Mon Sep 17 00:00:00 2001 From: Yufeng Wang Date: Tue, 13 Aug 2024 12:34:30 -0700 Subject: [PATCH 034/165] [Fabric-Admin] Fix 'fabricsync sync-device' command always fails (#34938) * [Fabric-Admin] Fix 'fabricsync sync-device' command always fails * Use default random salt * Update examples/fabric-admin/commands/pairing/OpenCommissioningWindowCommand.h Co-authored-by: Abdul Samad * Address review comments --------- Co-authored-by: Abdul Samad --- examples/fabric-admin/commands/common/CHIPCommand.h | 2 +- .../commands/fabric-sync/FabricSyncCommand.cpp | 2 ++ .../pairing/OpenCommissioningWindowCommand.cpp | 1 + .../pairing/OpenCommissioningWindowCommand.h | 4 +++- .../fabric-admin/device_manager/DeviceManager.cpp | 13 +++++++++---- 5 files changed, 16 insertions(+), 6 deletions(-) diff --git a/examples/fabric-admin/commands/common/CHIPCommand.h b/examples/fabric-admin/commands/common/CHIPCommand.h index a02adbfbb5..6711b3e4f9 100644 --- a/examples/fabric-admin/commands/common/CHIPCommand.h +++ b/examples/fabric-admin/commands/common/CHIPCommand.h @@ -51,7 +51,7 @@ inline constexpr char kIdentityGamma[] = "gamma"; // (CASE) communcation. inline constexpr char kIdentityNull[] = "null-fabric-commissioner"; -constexpr uint16_t kMaxCommandSize = 128; +constexpr uint16_t kMaxCommandSize = 384; class CHIPCommand : public Command { diff --git a/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.cpp b/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.cpp index efb7cfd222..dade5932fb 100644 --- a/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.cpp +++ b/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.cpp @@ -163,6 +163,8 @@ CHIP_ERROR FabricSyncRemoveBridgeCommand::RunCommand() void FabricSyncDeviceCommand::OnCommissioningWindowOpened(NodeId deviceId, CHIP_ERROR err, chip::SetupPayload payload) { + ChipLogProgress(NotSpecified, "FabricSyncDeviceCommand::OnCommissioningWindowOpened"); + if (err == CHIP_NO_ERROR) { char payloadBuffer[kMaxManaulCodeLength + 1]; diff --git a/examples/fabric-admin/commands/pairing/OpenCommissioningWindowCommand.cpp b/examples/fabric-admin/commands/pairing/OpenCommissioningWindowCommand.cpp index b2d811fdc8..5307316010 100644 --- a/examples/fabric-admin/commands/pairing/OpenCommissioningWindowCommand.cpp +++ b/examples/fabric-admin/commands/pairing/OpenCommissioningWindowCommand.cpp @@ -55,6 +55,7 @@ CHIP_ERROR OpenCommissioningWindowCommand::RunCommand() .SetTimeout(mCommissioningWindowTimeout) .SetIteration(mIteration) .SetDiscriminator(mDiscriminator) + .SetSetupPIN(mSetupPIN) .SetSalt(mSalt) .SetReadVIDPIDAttributes(true) .SetCallback(&mOnOpenCommissioningWindowCallback), diff --git a/examples/fabric-admin/commands/pairing/OpenCommissioningWindowCommand.h b/examples/fabric-admin/commands/pairing/OpenCommissioningWindowCommand.h index 0978850721..7edcdba711 100644 --- a/examples/fabric-admin/commands/pairing/OpenCommissioningWindowCommand.h +++ b/examples/fabric-admin/commands/pairing/OpenCommissioningWindowCommand.h @@ -46,8 +46,9 @@ class OpenCommissioningWindowCommand : public CHIPCommand "Time, in seconds, before the commissioning window closes."); AddArgument("iteration", chip::Crypto::kSpake2p_Min_PBKDF_Iterations, chip::Crypto::kSpake2p_Max_PBKDF_Iterations, &mIteration, "Number of PBKDF iterations to use to derive the verifier. Ignored if 'option' is 0."); - AddArgument("discriminator", 0, 4096, &mDiscriminator, "Discriminator to use for advertising. Ignored if 'option' is 0."); + AddArgument("discriminator", 0, 4095, &mDiscriminator, "Discriminator to use for advertising. Ignored if 'option' is 0."); AddArgument("timeout", 0, UINT16_MAX, &mTimeout, "Time, in seconds, before this command is considered to have timed out."); + AddArgument("setup-pin", 1, chip::kSetupPINCodeMaximumValue, &mSetupPIN, "The setup PIN (Passcode) to use."); AddArgument("salt", &mSalt, "Salt payload encoded in hexadecimal. Random salt will be generated if absent. " "This needs to be present if verifier is provided, corresponding to salt used for generating verifier"); @@ -76,6 +77,7 @@ class OpenCommissioningWindowCommand : public CHIPCommand uint16_t mDiscriminator; chip::Optional mTimeout; + chip::Optional mSetupPIN; chip::Optional mSalt; chip::Optional mVerifier; diff --git a/examples/fabric-admin/device_manager/DeviceManager.cpp b/examples/fabric-admin/device_manager/DeviceManager.cpp index aea9722bc8..4207378670 100644 --- a/examples/fabric-admin/device_manager/DeviceManager.cpp +++ b/examples/fabric-admin/device_manager/DeviceManager.cpp @@ -33,12 +33,12 @@ namespace { // Constants constexpr uint32_t kSetupPinCode = 20202021; constexpr uint16_t kRemoteBridgePort = 5540; -constexpr uint16_t kDiscriminator = 3840; constexpr uint16_t kWindowTimeout = 300; constexpr uint16_t kIteration = 1000; constexpr uint16_t kSubscribeMinInterval = 0; constexpr uint16_t kSubscribeMaxInterval = 60; constexpr uint16_t kAggragatorEndpointId = 1; +constexpr uint16_t kMaxDiscriminatorLength = 4095; constexpr uint8_t kEnhancedCommissioningMethod = 1; } // namespace @@ -118,7 +118,7 @@ void DeviceManager::OpenDeviceCommissioningWindow(NodeId nodeId, uint32_t commis uint32_t discriminator, const char * saltHex, const char * verifierHex) { // Open the commissioning window of a device within its own fabric. - StringBuilder<512> commandBuilder; + StringBuilder commandBuilder; commandBuilder.Add("pairing open-commissioning-window "); commandBuilder.AddFormat("%lu %d %d %d %d %d --salt hex:%s --verifier hex:%s", nodeId, kRootEndpointId, @@ -132,11 +132,16 @@ void DeviceManager::OpenRemoteDeviceCommissioningWindow(EndpointId remoteEndpoin // Open the commissioning window of a device from another fabric via its fabric bridge. // This method constructs and sends a command to open the commissioning window for a device // that is part of a different fabric, accessed through a fabric bridge. - StringBuilder commandBuilder; + StringBuilder<512> commandBuilder; + + // Use random discriminator to have less chance of collission. + uint16_t discriminator = + Crypto::GetRandU16() % (kMaxDiscriminatorLength + 1); // Include the upper limit kMaxDiscriminatorLength commandBuilder.Add("pairing open-commissioning-window "); commandBuilder.AddFormat("%lu %d %d %d %d %d", mRemoteBridgeNodeId, remoteEndpointId, kEnhancedCommissioningMethod, - kWindowTimeout, kIteration, kDiscriminator); + kWindowTimeout, kIteration, discriminator); + commandBuilder.Add(" --setup-pin 20202021"); PushCommand(commandBuilder.c_str()); } From 6165b62d5b103bf84dcd46baf4eb5130e3d16f03 Mon Sep 17 00:00:00 2001 From: Andrei Litvin Date: Wed, 14 Aug 2024 00:51:38 -0400 Subject: [PATCH 035/165] Fix user_params usage (#34964) --- src/python_testing/TC_MCORE_FS_1_1.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/python_testing/TC_MCORE_FS_1_1.py b/src/python_testing/TC_MCORE_FS_1_1.py index 629dae67fc..b72039834c 100755 --- a/src/python_testing/TC_MCORE_FS_1_1.py +++ b/src/python_testing/TC_MCORE_FS_1_1.py @@ -37,7 +37,7 @@ class TC_MCORE_FS_1_1(MatterBaseTest): async def setup_class(self): super().setup_class() # TODO: confirm whether we can open processes like this on the TH - app = self.matter_test_config.user_params.get("th_server_app_path", None) + app = self.user_params.get("th_server_app_path", None) if not app: asserts.fail('This test requires a TH_SERVER app. Specify app path with --string-arg th_server_app_path:') From 5e8a9ec562c986edd9b71062707c1cc2a89ea3ec Mon Sep 17 00:00:00 2001 From: shripad621git <79364691+shripad621git@users.noreply.github.com> Date: Wed, 14 Aug 2024 11:07:14 +0530 Subject: [PATCH 036/165] Fixed the discovery mode in esp32 factory script to a bitmap value instead of enum (#34900) --- scripts/tools/generate_esp32_chip_factory_bin.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/scripts/tools/generate_esp32_chip_factory_bin.py b/scripts/tools/generate_esp32_chip_factory_bin.py index b19748ca31..892f060992 100755 --- a/scripts/tools/generate_esp32_chip_factory_bin.py +++ b/scripts/tools/generate_esp32_chip_factory_bin.py @@ -276,6 +276,7 @@ def validate_args(args): check_int_range(args.product_id, 0x0000, 0xFFFF, 'Product id') check_int_range(args.vendor_id, 0x0000, 0xFFFF, 'Vendor id') check_int_range(args.hw_ver, 0x0000, 0xFFFF, 'Hardware version') + check_int_range(args.discovery_mode, 0b000, 0b111, 'Discovery-Mode') check_str_range(args.serial_num, 1, 32, 'Serial number') check_str_range(args.vendor_name, 1, 32, 'Vendor name') @@ -566,9 +567,10 @@ def any_base_int(s): return int(s, 0) parser.add_argument('-cf', '--commissioning-flow', type=any_base_int, default=0, help='Device commissioning flow, 0:Standard, 1:User-Intent, 2:Custom. \ Default is 0.', choices=[0, 1, 2]) - parser.add_argument('-dm', '--discovery-mode', type=any_base_int, default=1, - help='Commissionable device discovery networking technology. \ - 0:WiFi-SoftAP, 1:BLE, 2:On-network. Default is BLE.', choices=[0, 1, 2]) + parser.add_argument('-dm', '--discovery-mode', type=any_base_int, default=2, + help='3-bit bitmap representing discovery modes for commissionable device discovery \ + Bit 0:WiFi-SoftAP, Bit 1:BLE, Bit 2:On-network. Default is BLE. Specify values between 0-7') + parser.set_defaults(generate_bin=True) return parser.parse_args() From 0ea43c9bcd2d662245b46b7d662d15261fdfa4ca Mon Sep 17 00:00:00 2001 From: Andrei Litvin Date: Wed, 14 Aug 2024 02:39:34 -0400 Subject: [PATCH 037/165] Fix typo in wait_for_user_input (#34965) --- src/python_testing/TC_CCTRL_2_2.py | 4 ++-- src/python_testing/TC_MCORE_FS_1_1.py | 2 +- src/python_testing/TC_MCORE_FS_1_2.py | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/python_testing/TC_CCTRL_2_2.py b/src/python_testing/TC_CCTRL_2_2.py index 18416d4c29..a2d209f054 100644 --- a/src/python_testing/TC_CCTRL_2_2.py +++ b/src/python_testing/TC_CCTRL_2_2.py @@ -182,7 +182,7 @@ async def test_TC_CCTRL_2_2(self): self.step(12) if not self.is_ci: - self.wait_for_use_input("Approve Commissioning approval request using manufacturer specified mechanism") + self.wait_for_user_input("Approve Commissioning approval request using manufacturer specified mechanism") self.step(13) if not events: @@ -257,7 +257,7 @@ async def test_TC_CCTRL_2_2(self): self.step(23) if not self.is_ci: - self.wait_for_use_input("Approve Commissioning approval request using manufacturer specified mechanism") + self.wait_for_user_input("Approve Commissioning approval request using manufacturer specified mechanism") self.step(24) events = new_event diff --git a/src/python_testing/TC_MCORE_FS_1_1.py b/src/python_testing/TC_MCORE_FS_1_1.py index b72039834c..50f4dc55c7 100755 --- a/src/python_testing/TC_MCORE_FS_1_1.py +++ b/src/python_testing/TC_MCORE_FS_1_1.py @@ -102,7 +102,7 @@ async def test_TC_MCORE_FS_1_1(self): await self.send_single_cmd(cmd, endpoint=dut_commissioning_control_endpoint) if not self.is_ci: - self.wait_for_use_input("Approve Commissioning approval request on DUT using manufacturer specified mechanism") + self.wait_for_user_input("Approve Commissioning approval request on DUT using manufacturer specified mechanism") if not events: new_event = await self.default_controller.ReadEvent(nodeid=self.dut_node_id, events=event_path) diff --git a/src/python_testing/TC_MCORE_FS_1_2.py b/src/python_testing/TC_MCORE_FS_1_2.py index 0af8cbedb3..1085b0fac0 100644 --- a/src/python_testing/TC_MCORE_FS_1_2.py +++ b/src/python_testing/TC_MCORE_FS_1_2.py @@ -118,7 +118,7 @@ async def test_TC_MCORE_FS_1_2(self): self.step(4) if not self.is_ci: - self.wait_for_use_input( + self.wait_for_user_input( "Commission TH_SED_DUT onto DUT_FSA’s fabric using the manufacturer specified mechanism. (ensure Synchronization is enabled.)") else: logging.info("Stopping after step 3 while running in CI to avoid manual steps.") From 927f99a2a2629078187d6d4f1500f664293feae0 Mon Sep 17 00:00:00 2001 From: Stefan Bauer-Schwan <62264998+bauerschwan@users.noreply.github.com> Date: Wed, 14 Aug 2024 13:36:44 +0200 Subject: [PATCH 038/165] Remove wrong dependency to attribute id 82 (#34975) This was a left-over attribute id before a spec change where attributes got removed. After that the attribute id 82dec is SetpointHoldExpiryTimestamp which has nothing to do with Presets --- src/app/tests/suites/certification/Test_TC_TSTAT_1_1.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/app/tests/suites/certification/Test_TC_TSTAT_1_1.yaml b/src/app/tests/suites/certification/Test_TC_TSTAT_1_1.yaml index 789f477667..194babe282 100644 --- a/src/app/tests/suites/certification/Test_TC_TSTAT_1_1.yaml +++ b/src/app/tests/suites/certification/Test_TC_TSTAT_1_1.yaml @@ -575,7 +575,7 @@ tests: response: constraints: type: list - contains: [72, 74, 78, 80, 82] + contains: [72, 74, 78, 80] - label: "Step 5: TH reads EventList attribute from the DUT." PICS: PICS_EVENT_LIST_ENABLED From 6ed81117bce8f4563242f635413e8ab5c7a4e291 Mon Sep 17 00:00:00 2001 From: Amine Alami <43780877+Alami-Amine@users.noreply.github.com> Date: Wed, 14 Aug 2024 16:10:02 +0200 Subject: [PATCH 039/165] replacing "stringcase" python package with internal implementation + generated java and kotlin code (#34949) * changing matter_idl functions * changing yaml runner functions * removing stringcase from config and requirement files * restyle * improve string handling * fixing generated java and kotlin code * regenerate idl golden image for test_generators.py * adding unit test * restyle * adding unit test to build.GN --- .../stage-2/chip-build-efr32/requirements.txt | 1 - scripts/py_matter_idl/BUILD.gn | 1 + .../matter_idl/generators/filters.py | 83 +- .../matter_idl/generators/java/__init__.py | 14 +- .../matter_idl/generators/kotlin/__init__.py | 14 +- .../matter_idl/test_case_conversion.py | 61 ++ .../several_clusters/java/ChipStructs.java | 18 +- .../SecondClusterFabricDescriptorStruct.kt | 18 +- scripts/py_matter_idl/setup.cfg | 1 - scripts/setup/constraints.txt | 2 - scripts/setup/requirements.build.txt | 1 - .../chip/devicecontroller/ChipClusters.java | 798 +++++++++--------- .../devicecontroller/ChipEventStructs.java | 126 +-- .../chip/devicecontroller/ChipStructs.java | 270 +++--- ...olClusterAccessControlEntryChangedEvent.kt | 20 +- ...usterAccessControlExtensionChangedEvent.kt | 20 +- ...usterFabricRestrictionReviewUpdateEvent.kt | 10 +- .../ActionsClusterActionFailedEvent.kt | 12 +- .../ActionsClusterStateChangedEvent.kt | 12 +- ...lusterLoadControlEventStatusChangeEvent.kt | 6 +- .../EnergyEvseClusterEVConnectedEvent.kt | 6 +- .../EnergyEvseClusterEVNotDetectedEvent.kt | 6 +- ...gyEvseClusterEnergyTransferStartedEvent.kt | 6 +- ...gyEvseClusterEnergyTransferStoppedEvent.kt | 6 +- .../EnergyEvseClusterFaultEvent.kt | 10 +- .../MessagesClusterMessageCompleteEvent.kt | 18 +- .../MessagesClusterMessagePresentedEvent.kt | 6 +- .../MessagesClusterMessageQueuedEvent.kt | 6 +- ...dateRequestorClusterVersionAppliedEvent.kt | 6 +- ...imeSynchronizationClusterDSTStatusEvent.kt | 6 +- .../structs/ActionsClusterActionStruct.kt | 12 +- .../ActionsClusterEndpointListStruct.kt | 6 +- ...pplicationBasicClusterApplicationStruct.kt | 12 +- ...icationLauncherClusterApplicationStruct.kt | 12 +- .../structs/ChannelClusterProgramStruct.kt | 8 +- .../ContentLauncherClusterParameterStruct.kt | 8 +- ...ntLauncherClusterStyleInformationStruct.kt | 8 +- ...oadControlClusterLoadControlEventStruct.kt | 16 +- ...dControlClusterLoadControlProgramStruct.kt | 6 +- .../DescriptorClusterSemanticTagStruct.kt | 6 +- ...ceEnergyManagementClusterForecastStruct.kt | 6 +- ...DeviceEnergyManagementClusterSlotStruct.kt | 8 +- ...formationClusterEcosystemLocationStruct.kt | 6 +- ...upKeyManagementClusterGroupKeyMapStruct.kt | 6 +- ...upKeyManagementClusterGroupKeySetStruct.kt | 6 +- ...mentClusterMonitoringRegistrationStruct.kt | 6 +- ...sagesClusterMessageResponseOptionStruct.kt | 8 +- .../structs/MessagesClusterMessageStruct.kt | 6 +- ...rkCommissioningClusterNetworkInfoStruct.kt | 6 +- ...redentialsClusterFabricDescriptorStruct.kt | 18 +- ...OperationalStateClusterErrorStateStruct.kt | 6 +- ...ionalStateClusterOperationalStateStruct.kt | 6 +- ...eUpdateRequestorClusterProviderLocation.kt | 6 +- ...OperationalStateClusterErrorStateStruct.kt | 6 +- ...ionalStateClusterOperationalStateStruct.kt | 6 +- ...OperationalStateClusterErrorStateStruct.kt | 6 +- ...ionalStateClusterOperationalStateStruct.kt | 6 +- ...nagementClusterAttributeValuePairStruct.kt | 6 +- ...cenesManagementClusterExtensionFieldSet.kt | 6 +- .../structs/ServiceAreaClusterAreaStruct.kt | 16 +- .../structs/ServiceAreaClusterMapStruct.kt | 6 +- .../ServiceAreaClusterProgressStruct.kt | 6 +- ...ostatClusterAtomicAttributeStatusStruct.kt | 6 +- ...tworkDiagnosticsClusterRouteTableStruct.kt | 12 +- ...workDirectoryClusterThreadNetworkStruct.kt | 6 +- ...sterFabricScopedTrustedTimeSourceStruct.kt | 6 +- ...onizationClusterTrustedTimeSourceStruct.kt | 6 +- .../cluster/clusters/AccountLoginCluster.kt | 8 +- .../cluster/clusters/ActionsCluster.kt | 96 +-- .../AdministratorCommissioningCluster.kt | 4 +- .../cluster/clusters/ChannelCluster.kt | 12 +- .../clusters/CommissionerControlCluster.kt | 4 +- .../cluster/clusters/ContentControlCluster.kt | 16 +- .../clusters/ContentLauncherCluster.kt | 4 +- .../DemandResponseLoadControlCluster.kt | 8 +- .../clusters/DeviceEnergyManagementCluster.kt | 4 +- .../cluster/clusters/DiagnosticLogsCluster.kt | 4 +- .../cluster/clusters/DoorLockCluster.kt | 24 +- .../clusters/GeneralCommissioningCluster.kt | 8 +- .../clusters/GroupKeyManagementCluster.kt | 8 +- .../cluster/clusters/GroupsCluster.kt | 28 +- .../cluster/clusters/IcdManagementCluster.kt | 12 +- .../cluster/clusters/MediaPlaybackCluster.kt | 8 +- .../cluster/clusters/MessagesCluster.kt | 4 +- .../clusters/NetworkCommissioningCluster.kt | 12 +- .../clusters/OperationalCredentialsCluster.kt | 36 +- .../OtaSoftwareUpdateProviderCluster.kt | 12 +- .../OtaSoftwareUpdateRequestorCluster.kt | 8 +- .../clusters/ScenesManagementCluster.kt | 88 +- .../clusters/ThreadNetworkDirectoryCluster.kt | 8 +- .../clusters/TimeSynchronizationCluster.kt | 16 +- ...olClusterAccessControlEntryChangedEvent.kt | 20 +- ...usterAccessControlExtensionChangedEvent.kt | 20 +- ...usterFabricRestrictionReviewUpdateEvent.kt | 10 +- .../ActionsClusterActionFailedEvent.kt | 12 +- .../ActionsClusterStateChangedEvent.kt | 12 +- ...lusterLoadControlEventStatusChangeEvent.kt | 6 +- .../EnergyEvseClusterEVConnectedEvent.kt | 6 +- .../EnergyEvseClusterEVNotDetectedEvent.kt | 6 +- ...gyEvseClusterEnergyTransferStartedEvent.kt | 6 +- ...gyEvseClusterEnergyTransferStoppedEvent.kt | 6 +- .../EnergyEvseClusterFaultEvent.kt | 10 +- .../MessagesClusterMessageCompleteEvent.kt | 18 +- .../MessagesClusterMessagePresentedEvent.kt | 6 +- .../MessagesClusterMessageQueuedEvent.kt | 6 +- ...dateRequestorClusterVersionAppliedEvent.kt | 6 +- ...imeSynchronizationClusterDSTStatusEvent.kt | 6 +- .../structs/ActionsClusterActionStruct.kt | 12 +- .../ActionsClusterEndpointListStruct.kt | 6 +- ...pplicationBasicClusterApplicationStruct.kt | 12 +- ...icationLauncherClusterApplicationStruct.kt | 12 +- .../structs/ChannelClusterProgramStruct.kt | 8 +- .../ContentLauncherClusterParameterStruct.kt | 8 +- ...ntLauncherClusterStyleInformationStruct.kt | 8 +- ...oadControlClusterLoadControlEventStruct.kt | 16 +- ...dControlClusterLoadControlProgramStruct.kt | 6 +- .../DescriptorClusterSemanticTagStruct.kt | 6 +- ...ceEnergyManagementClusterForecastStruct.kt | 6 +- ...DeviceEnergyManagementClusterSlotStruct.kt | 8 +- ...formationClusterEcosystemLocationStruct.kt | 6 +- ...upKeyManagementClusterGroupKeyMapStruct.kt | 6 +- ...upKeyManagementClusterGroupKeySetStruct.kt | 6 +- ...mentClusterMonitoringRegistrationStruct.kt | 6 +- ...sagesClusterMessageResponseOptionStruct.kt | 8 +- .../structs/MessagesClusterMessageStruct.kt | 6 +- ...rkCommissioningClusterNetworkInfoStruct.kt | 6 +- ...redentialsClusterFabricDescriptorStruct.kt | 18 +- ...OperationalStateClusterErrorStateStruct.kt | 6 +- ...ionalStateClusterOperationalStateStruct.kt | 6 +- ...eUpdateRequestorClusterProviderLocation.kt | 6 +- ...OperationalStateClusterErrorStateStruct.kt | 6 +- ...ionalStateClusterOperationalStateStruct.kt | 6 +- ...OperationalStateClusterErrorStateStruct.kt | 6 +- ...ionalStateClusterOperationalStateStruct.kt | 6 +- ...nagementClusterAttributeValuePairStruct.kt | 6 +- ...cenesManagementClusterExtensionFieldSet.kt | 6 +- .../structs/ServiceAreaClusterAreaStruct.kt | 16 +- .../structs/ServiceAreaClusterMapStruct.kt | 6 +- .../ServiceAreaClusterProgressStruct.kt | 6 +- ...ostatClusterAtomicAttributeStatusStruct.kt | 6 +- ...tworkDiagnosticsClusterRouteTableStruct.kt | 12 +- ...workDirectoryClusterThreadNetworkStruct.kt | 6 +- ...sterFabricScopedTrustedTimeSourceStruct.kt | 6 +- ...onizationClusterTrustedTimeSourceStruct.kt | 6 +- src/controller/python/chip/yaml/runner.py | 20 +- 145 files changed, 1437 insertions(+), 1311 deletions(-) create mode 100644 scripts/py_matter_idl/matter_idl/test_case_conversion.py diff --git a/integrations/docker/images/stage-2/chip-build-efr32/requirements.txt b/integrations/docker/images/stage-2/chip-build-efr32/requirements.txt index dc05bcd645..5c9ae9889f 100644 --- a/integrations/docker/images/stage-2/chip-build-efr32/requirements.txt +++ b/integrations/docker/images/stage-2/chip-build-efr32/requirements.txt @@ -1,7 +1,6 @@ # codegen.py build requirements Jinja2==3.1.3 lark==1.1.7 -stringcase==1.2.0 # Sphinx dependencies (for slc-cli) linkify-it-py==2.0.2 myst-parser==2.0.0 diff --git a/scripts/py_matter_idl/BUILD.gn b/scripts/py_matter_idl/BUILD.gn index 29e6becb4e..c0493e8fb7 100644 --- a/scripts/py_matter_idl/BUILD.gn +++ b/scripts/py_matter_idl/BUILD.gn @@ -53,6 +53,7 @@ pw_python_package("matter_idl") { tests = [ "matter_idl/test_backwards_compatibility.py", + "matter_idl/test_case_conversion.py", "matter_idl/test_data_model_xml.py", "matter_idl/test_matter_idl_parser.py", "matter_idl/test_generators.py", diff --git a/scripts/py_matter_idl/matter_idl/generators/filters.py b/scripts/py_matter_idl/matter_idl/generators/filters.py index b1ea94a7cd..8f81c2013c 100644 --- a/scripts/py_matter_idl/matter_idl/generators/filters.py +++ b/scripts/py_matter_idl/matter_idl/generators/filters.py @@ -12,7 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -import stringcase +import re def normalize_acronyms(s: str) -> str: @@ -49,6 +49,75 @@ def lowfirst_except_acronym(s: str) -> str: return lowfirst(s) +def to_snake_case(s: str) -> str: + """convert to snake case; all words are seperated by underscore and are lower case + examples: + FooBarBaz --> foo_bar_baz + foo BarBaz --> foo_bar_baz + FOOBarBaz --> foo_bar_baz + _fooBar_Baz_ --> foo_bar_baz + """ + s = "" if s is None else str(s) + + s = re.sub(r'([A-Z]+)([A-Z][a-z])', r'\1_\2', s) + s = re.sub(r'([a-z\d])([A-Z])', r'\1_\2', s) + s = re.sub(r'[\s\-]+', '_', s) + + snake_case = s.lower() + return snake_case.strip('_') + + +def to_constant_case(s: str) -> str: + """convert to constant case; all words are seperated by underscore and are upper case + similar to a snake case but with upper case + examples: + FooBarBaz --> FOO_BAR_BAZ + foo BarBaz --> FOO_BAR_BAZ + FOOBarBaz --> FOO_BAR_BAZ + """ + snake_case = to_snake_case(s) + constant_case = snake_case.upper() + return constant_case + + +def to_spinal_case(s: str) -> str: + """convert to spinal case; all words sperated by hypen and are lower case + similar to a snake case but with hyphen seperator instead of underscore + examples: + FooBarBaz --> foo-bar-baz + foo BarBaz --> foo-bar-baz + FOOBarBaz --> foo-bar-baz + """ + snake_case = to_snake_case(s) + return snake_case.replace('_', '-') + + +def to_pascal_case(s: str) -> str: + """convert to pascal case; with no spaces or underscore between words, first letter of all words is uppercase + examples: + fooBarBaz --> FooBarBaz + foo BarBaz --> FooBarBaz + FOOBar_Baz --> FooBarBaz + """ + + snake_case = to_snake_case(s) + snake_case_split = snake_case.split('_') + pascal_case = ''.join(word.capitalize() for word in snake_case_split) + + return pascal_case + + +def to_camel_case(s) -> str: + """convert to camel case; with no spaces or underscore between words, first word all lowercase and following words are uppercase + same as pascal case but first letter is lower case + examples: + FooBarBaz --> fooBarBaz + foo BarBaz --> fooBarBaz + FOOBarBaz --> fooBarBaz + """ + return lowfirst(to_pascal_case(s)) + + def RegisterCommonFilters(filtermap): """ Register filters that are NOT considered platform-generator specific. @@ -59,12 +128,12 @@ def RegisterCommonFilters(filtermap): """ # General casing for output naming - filtermap['camelcase'] = stringcase.camelcase - filtermap['capitalcase'] = stringcase.capitalcase - filtermap['constcase'] = stringcase.constcase - filtermap['pascalcase'] = stringcase.pascalcase - filtermap['snakecase'] = stringcase.snakecase - filtermap['spinalcase'] = stringcase.spinalcase + filtermap['camelcase'] = to_camel_case + filtermap['capitalcase'] = upfirst + filtermap['constcase'] = to_constant_case + filtermap['pascalcase'] = to_pascal_case + filtermap['snakecase'] = to_snake_case + filtermap['spinalcase'] = to_spinal_case filtermap['normalize_acronyms'] = normalize_acronyms filtermap['lowfirst'] = lowfirst diff --git a/scripts/py_matter_idl/matter_idl/generators/java/__init__.py b/scripts/py_matter_idl/matter_idl/generators/java/__init__.py index 96fa37c1a2..d21107653d 100644 --- a/scripts/py_matter_idl/matter_idl/generators/java/__init__.py +++ b/scripts/py_matter_idl/matter_idl/generators/java/__init__.py @@ -20,11 +20,11 @@ from typing import List, Optional, Set from matter_idl.generators import CodeGenerator, GeneratorStorage +from matter_idl.generators.filters import upfirst from matter_idl.generators.type_definitions import (BasicInteger, BasicString, FundamentalType, IdlBitmapType, IdlEnumType, IdlType, ParseDataType, TypeLookupContext) from matter_idl.matter_idl_types import (Attribute, Cluster, Command, DataType, Field, FieldQuality, Idl, Struct, StructQuality, StructTag) -from stringcase import capitalcase @dataclasses.dataclass @@ -199,7 +199,7 @@ def DelegatedCallbackName(attr: Attribute, context: TypeLookupContext) -> str: if global_name: return 'Delegated{}AttributeCallback'.format(GlobalNameToJavaName(global_name)) - return 'Delegated{}Cluster{}AttributeCallback'.format(context.cluster.name, capitalcase(attr.definition.name)) + return 'Delegated{}Cluster{}AttributeCallback'.format(context.cluster.name, upfirst(attr.definition.name)) def ChipClustersCallbackName(attr: Attribute, context: TypeLookupContext) -> str: @@ -212,7 +212,7 @@ def ChipClustersCallbackName(attr: Attribute, context: TypeLookupContext) -> str if global_name: return 'ChipClusters.{}AttributeCallback'.format(GlobalNameToJavaName(global_name)) - return 'ChipClusters.{}Cluster.{}AttributeCallback'.format(context.cluster.name, capitalcase(attr.definition.name)) + return 'ChipClusters.{}Cluster.{}AttributeCallback'.format(context.cluster.name, upfirst(attr.definition.name)) def CallbackName(attr: Attribute, context: TypeLookupContext) -> str: @@ -228,11 +228,11 @@ def CallbackName(attr: Attribute, context: TypeLookupContext) -> str: global_name = FieldToGlobalName(attr.definition, context) if global_name: - return 'CHIP{}AttributeCallback'.format(capitalcase(global_name)) + return 'CHIP{}AttributeCallback'.format(upfirst(global_name)) return 'CHIP{}{}AttributeCallback'.format( - capitalcase(context.cluster.name), - capitalcase(attr.definition.name) + upfirst(context.cluster.name), + upfirst(attr.definition.name) ) @@ -262,7 +262,7 @@ def JavaAttributeCallbackName(attr: Attribute, context: TypeLookupContext) -> st if global_name: return '{}AttributeCallback'.format(GlobalNameToJavaName(global_name)) - return '{}AttributeCallback'.format(capitalcase(attr.definition.name)) + return '{}AttributeCallback'.format(upfirst(attr.definition.name)) def IsFieldGlobalName(field: Field, context: TypeLookupContext) -> bool: diff --git a/scripts/py_matter_idl/matter_idl/generators/kotlin/__init__.py b/scripts/py_matter_idl/matter_idl/generators/kotlin/__init__.py index 17e5136e16..405f505a09 100644 --- a/scripts/py_matter_idl/matter_idl/generators/kotlin/__init__.py +++ b/scripts/py_matter_idl/matter_idl/generators/kotlin/__init__.py @@ -20,11 +20,11 @@ from typing import List, Optional, Set from matter_idl.generators import CodeGenerator, GeneratorStorage +from matter_idl.generators.filters import upfirst from matter_idl.generators.type_definitions import (BasicInteger, BasicString, FundamentalType, IdlBitmapType, IdlEnumType, IdlType, ParseDataType, TypeLookupContext) from matter_idl.matter_idl_types import (Attribute, Cluster, Command, DataType, Field, FieldQuality, Idl, Struct, StructQuality, StructTag) -from stringcase import capitalcase @dataclasses.dataclass @@ -160,7 +160,7 @@ def DelegatedCallbackName(attr: Attribute, context: TypeLookupContext) -> str: if global_name: return 'Delegated{}AttributeCallback'.format(GlobalNameToJavaName(global_name)) - return 'Delegated{}Cluster{}AttributeCallback'.format(context.cluster.name, capitalcase(attr.definition.name)) + return 'Delegated{}Cluster{}AttributeCallback'.format(context.cluster.name, upfirst(attr.definition.name)) def ChipClustersCallbackName(attr: Attribute, context: TypeLookupContext) -> str: @@ -173,7 +173,7 @@ def ChipClustersCallbackName(attr: Attribute, context: TypeLookupContext) -> str if global_name: return 'ChipClusters.{}AttributeCallback'.format(GlobalNameToJavaName(global_name)) - return 'ChipClusters.{}Cluster.{}AttributeCallback'.format(context.cluster.name, capitalcase(attr.definition.name)) + return 'ChipClusters.{}Cluster.{}AttributeCallback'.format(context.cluster.name, upfirst(attr.definition.name)) def CallbackName(attr: Attribute, context: TypeLookupContext) -> str: @@ -189,11 +189,11 @@ def CallbackName(attr: Attribute, context: TypeLookupContext) -> str: global_name = FieldToGlobalName(attr.definition, context) if global_name: - return 'CHIP{}AttributeCallback'.format(capitalcase(global_name)) + return 'CHIP{}AttributeCallback'.format(upfirst(global_name)) return 'CHIP{}{}AttributeCallback'.format( - capitalcase(context.cluster.name), - capitalcase(attr.definition.name) + upfirst(context.cluster.name), + upfirst(attr.definition.name) ) @@ -223,7 +223,7 @@ def JavaAttributeCallbackName(attr: Attribute, context: TypeLookupContext) -> st if global_name: return '{}'.format(GlobalNameToJavaName(global_name)) - return '{}Attribute'.format(capitalcase(attr.definition.name)) + return '{}Attribute'.format(upfirst(attr.definition.name)) def IsFieldGlobalName(field: Field, context: TypeLookupContext) -> bool: diff --git a/scripts/py_matter_idl/matter_idl/test_case_conversion.py b/scripts/py_matter_idl/matter_idl/test_case_conversion.py new file mode 100644 index 0000000000..7d8381530a --- /dev/null +++ b/scripts/py_matter_idl/matter_idl/test_case_conversion.py @@ -0,0 +1,61 @@ + +import unittest + +import matter_idl.generators.filters as case_convert + +''' +This file contains tests for checking five of the case conversion functions, notably: snake_case, CONSTANT_CASE, spinal-case, PascalCase and camelCase. + + +''' +inputs = [ + "FooBarBaz", + "FOOBarBaz", + "FOOBarBAZ", + "fooBARBaz", + "fooBarBAZ", + "foo BarBaz", + " FooBarBaz ", + "foo_bar_baz", + "FOO-bar-baz", + "FOO_BAR_BAZ", + "__FooBarBaz__", + "_fooBar_Baz_", + "foo_Bar Baz" +] + + +class TestSnakeCase(unittest.TestCase): + def test_snake_case(self): + expected = "foo_bar_baz" + for input in inputs: + converted = case_convert.to_snake_case(input) + self.assertEqual(converted, expected, "they are not equal") + + def test_constant_case(self): + expected = "FOO_BAR_BAZ" + for input in inputs: + converted = case_convert.to_constant_case(input) + self.assertEqual(converted, expected, "they are not equal") + + def test_spinal_case(self): + expected = "foo-bar-baz" + for input in inputs: + converted = case_convert.to_spinal_case(input) + self.assertEqual(converted, expected, "they are not equal") + + def test_pascal_case(self): + expected = "FooBarBaz" + for input in inputs: + converted = case_convert.to_pascal_case(input) + self.assertEqual(converted, expected, "they are not equal") + + def test_camel_case(self): + expected = "fooBarBaz" + for input in inputs: + converted = case_convert.to_camel_case(input) + self.assertEqual(converted, expected, "they are not equal") + + +if __name__ == '__main__': + unittest.main() diff --git a/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/java/ChipStructs.java b/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/java/ChipStructs.java index d3cf1f0c7d..70c8bf0e64 100644 --- a/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/java/ChipStructs.java +++ b/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/java/ChipStructs.java @@ -32,9 +32,9 @@ public static class SecondClusterFabricDescriptorStruct { public String label; public Integer fabricIndex; private static final long ROOT_PUBLIC_KEY_ID = 1L; - private static final long VENDOR_I_D_ID = 2L; - private static final long FABRIC_I_D_ID = 3L; - private static final long NODE_I_D_ID = 4L; + private static final long VENDOR_ID_ID = 2L; + private static final long FABRIC_ID_ID = 3L; + private static final long NODE_ID_ID = 4L; private static final long LABEL_ID = 5L; private static final long FABRIC_INDEX_ID = 254L; @@ -57,9 +57,9 @@ public SecondClusterFabricDescriptorStruct( public StructType encodeTlv() { ArrayList values = new ArrayList<>(); values.add(new StructElement(ROOT_PUBLIC_KEY_ID, new ByteArrayType(rootPublicKey))); - values.add(new StructElement(VENDOR_I_D_ID, new UIntType(vendorID))); - values.add(new StructElement(FABRIC_I_D_ID, new UIntType(fabricID))); - values.add(new StructElement(NODE_I_D_ID, new UIntType(nodeID))); + values.add(new StructElement(VENDOR_ID_ID, new UIntType(vendorID))); + values.add(new StructElement(FABRIC_ID_ID, new UIntType(fabricID))); + values.add(new StructElement(NODE_ID_ID, new UIntType(nodeID))); values.add(new StructElement(LABEL_ID, new StringType(label))); values.add(new StructElement(FABRIC_INDEX_ID, new UIntType(fabricIndex))); @@ -82,17 +82,17 @@ public static SecondClusterFabricDescriptorStruct decodeTlv(BaseTLVType tlvValue ByteArrayType castingValue = element.value(ByteArrayType.class); rootPublicKey = castingValue.value(byte[].class); } - } else if (element.contextTagNum() == VENDOR_I_D_ID) { + } else if (element.contextTagNum() == VENDOR_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); vendorID = castingValue.value(Integer.class); } - } else if (element.contextTagNum() == FABRIC_I_D_ID) { + } else if (element.contextTagNum() == FABRIC_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); fabricID = castingValue.value(Long.class); } - } else if (element.contextTagNum() == NODE_I_D_ID) { + } else if (element.contextTagNum() == NODE_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); nodeID = castingValue.value(Long.class); diff --git a/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/java/SecondClusterFabricDescriptorStruct.kt b/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/java/SecondClusterFabricDescriptorStruct.kt index 52c46471ae..cb225d96fd 100644 --- a/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/java/SecondClusterFabricDescriptorStruct.kt +++ b/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/java/SecondClusterFabricDescriptorStruct.kt @@ -48,9 +48,9 @@ class SecondClusterFabricDescriptorStruct ( tlvWriter.apply { startStructure(tlvTag) put(ContextSpecificTag(TAG_ROOT_PUBLIC_KEY), rootPublicKey) - put(ContextSpecificTag(TAG_VENDOR_I_D), vendorID) - put(ContextSpecificTag(TAG_FABRIC_I_D), fabricID) - put(ContextSpecificTag(TAG_NODE_I_D), nodeID) + put(ContextSpecificTag(TAG_VENDOR_ID), vendorID) + put(ContextSpecificTag(TAG_FABRIC_ID), fabricID) + put(ContextSpecificTag(TAG_NODE_ID), nodeID) put(ContextSpecificTag(TAG_LABEL), label) put(ContextSpecificTag(TAG_FABRIC_INDEX), fabricIndex) endStructure() @@ -59,18 +59,18 @@ class SecondClusterFabricDescriptorStruct ( companion object { private const val TAG_ROOT_PUBLIC_KEY = 1 - private const val TAG_VENDOR_I_D = 2 - private const val TAG_FABRIC_I_D = 3 - private const val TAG_NODE_I_D = 4 + private const val TAG_VENDOR_ID = 2 + private const val TAG_FABRIC_ID = 3 + private const val TAG_NODE_ID = 4 private const val TAG_LABEL = 5 private const val TAG_FABRIC_INDEX = 254 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader) : SecondClusterFabricDescriptorStruct { tlvReader.enterStructure(tlvTag) val rootPublicKey = tlvReader.getByteArray(ContextSpecificTag(TAG_ROOT_PUBLIC_KEY)) - val vendorID = tlvReader.getUInt(ContextSpecificTag(TAG_VENDOR_I_D)) - val fabricID = tlvReader.getULong(ContextSpecificTag(TAG_FABRIC_I_D)) - val nodeID = tlvReader.getULong(ContextSpecificTag(TAG_NODE_I_D)) + val vendorID = tlvReader.getUInt(ContextSpecificTag(TAG_VENDOR_ID)) + val fabricID = tlvReader.getULong(ContextSpecificTag(TAG_FABRIC_ID)) + val nodeID = tlvReader.getULong(ContextSpecificTag(TAG_NODE_ID)) val label = tlvReader.getString(ContextSpecificTag(TAG_LABEL)) val fabricIndex = tlvReader.getUInt(ContextSpecificTag(TAG_FABRIC_INDEX)) diff --git a/scripts/py_matter_idl/setup.cfg b/scripts/py_matter_idl/setup.cfg index 6fed9ed20f..25f7f6d3bf 100644 --- a/scripts/py_matter_idl/setup.cfg +++ b/scripts/py_matter_idl/setup.cfg @@ -24,7 +24,6 @@ zip_safe = False install_requires= lark jinja2 - stringcase [options.package_data] matter_idl = diff --git a/scripts/setup/constraints.txt b/scripts/setup/constraints.txt index 3f396a83c7..1b52443141 100644 --- a/scripts/setup/constraints.txt +++ b/scripts/setup/constraints.txt @@ -245,8 +245,6 @@ six==1.16.0 # requests-file stack-data==0.6.2 # via ipython -stringcase==1.2.0 - # via -r requirements.build.txt tabulate==0.9.0 # via -r requirements.memory.txt tornado==6.2 diff --git a/scripts/setup/requirements.build.txt b/scripts/setup/requirements.build.txt index c9e8bad323..e95c4587b9 100644 --- a/scripts/setup/requirements.build.txt +++ b/scripts/setup/requirements.build.txt @@ -11,4 +11,3 @@ click # scripts/py_matter_idl/matter_idl jinja2 lark -stringcase diff --git a/src/controller/java/generated/java/chip/devicecontroller/ChipClusters.java b/src/controller/java/generated/java/chip/devicecontroller/ChipClusters.java index 8b112f53c6..6f3e6f62d3 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/ChipClusters.java +++ b/src/controller/java/generated/java/chip/devicecontroller/ChipClusters.java @@ -3963,7 +3963,7 @@ public static class AccessControlCluster extends BaseChipCluster { private static final long SUBJECTS_PER_ACCESS_CONTROL_ENTRY_ATTRIBUTE_ID = 2L; private static final long TARGETS_PER_ACCESS_CONTROL_ENTRY_ATTRIBUTE_ID = 3L; private static final long ACCESS_CONTROL_ENTRIES_PER_FABRIC_ATTRIBUTE_ID = 4L; - private static final long COMMISSIONING_A_R_L_ATTRIBUTE_ID = 5L; + private static final long COMMISSIONING_ARL_ATTRIBUTE_ID = 5L; private static final long ARL_ATTRIBUTE_ID = 6L; private static final long GENERATED_COMMAND_LIST_ATTRIBUTE_ID = 65528L; private static final long ACCEPTED_COMMAND_LIST_ATTRIBUTE_ID = 65529L; @@ -4194,7 +4194,7 @@ public void onSuccess(byte[] tlv) { public void readCommissioningARLAttribute( CommissioningARLAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, COMMISSIONING_A_R_L_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, COMMISSIONING_ARL_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -4202,12 +4202,12 @@ public void onSuccess(byte[] tlv) { List value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, COMMISSIONING_A_R_L_ATTRIBUTE_ID, true); + }, COMMISSIONING_ARL_ATTRIBUTE_ID, true); } public void subscribeCommissioningARLAttribute( CommissioningARLAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, COMMISSIONING_A_R_L_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, COMMISSIONING_ARL_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -4215,7 +4215,7 @@ public void onSuccess(byte[] tlv) { List value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, COMMISSIONING_A_R_L_ATTRIBUTE_ID, minInterval, maxInterval); + }, COMMISSIONING_ARL_ATTRIBUTE_ID, minInterval, maxInterval); } public void readArlAttribute( @@ -4411,7 +4411,7 @@ public static class ActionsCluster extends BaseChipCluster { private static final long ACTION_LIST_ATTRIBUTE_ID = 0L; private static final long ENDPOINT_LISTS_ATTRIBUTE_ID = 1L; - private static final long SETUP_U_R_L_ATTRIBUTE_ID = 2L; + private static final long SETUP_URL_ATTRIBUTE_ID = 2L; 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; @@ -4815,7 +4815,7 @@ public void onSuccess(byte[] tlv) { public void readSetupURLAttribute( CharStringAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, SETUP_U_R_L_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, SETUP_URL_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -4823,12 +4823,12 @@ public void onSuccess(byte[] tlv) { String value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, SETUP_U_R_L_ATTRIBUTE_ID, true); + }, SETUP_URL_ATTRIBUTE_ID, true); } public void subscribeSetupURLAttribute( CharStringAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, SETUP_U_R_L_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, SETUP_URL_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -4836,7 +4836,7 @@ public void onSuccess(byte[] tlv) { String value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, SETUP_U_R_L_ATTRIBUTE_ID, minInterval, maxInterval); + }, SETUP_URL_ATTRIBUTE_ID, minInterval, maxInterval); } public void readGeneratedCommandListAttribute( @@ -5001,9 +5001,9 @@ public static class BasicInformationCluster extends BaseChipCluster { private static final long DATA_MODEL_REVISION_ATTRIBUTE_ID = 0L; private static final long VENDOR_NAME_ATTRIBUTE_ID = 1L; - private static final long VENDOR_I_D_ATTRIBUTE_ID = 2L; + private static final long VENDOR_ID_ATTRIBUTE_ID = 2L; private static final long PRODUCT_NAME_ATTRIBUTE_ID = 3L; - private static final long PRODUCT_I_D_ATTRIBUTE_ID = 4L; + private static final long PRODUCT_ID_ATTRIBUTE_ID = 4L; private static final long NODE_LABEL_ATTRIBUTE_ID = 5L; private static final long LOCATION_ATTRIBUTE_ID = 6L; private static final long HARDWARE_VERSION_ATTRIBUTE_ID = 7L; @@ -5012,12 +5012,12 @@ public static class BasicInformationCluster extends BaseChipCluster { private static final long SOFTWARE_VERSION_STRING_ATTRIBUTE_ID = 10L; private static final long MANUFACTURING_DATE_ATTRIBUTE_ID = 11L; private static final long PART_NUMBER_ATTRIBUTE_ID = 12L; - private static final long PRODUCT_U_R_L_ATTRIBUTE_ID = 13L; + private static final long PRODUCT_URL_ATTRIBUTE_ID = 13L; private static final long PRODUCT_LABEL_ATTRIBUTE_ID = 14L; private static final long SERIAL_NUMBER_ATTRIBUTE_ID = 15L; private static final long LOCAL_CONFIG_DISABLED_ATTRIBUTE_ID = 16L; private static final long REACHABLE_ATTRIBUTE_ID = 17L; - private static final long UNIQUE_I_D_ATTRIBUTE_ID = 18L; + private static final long UNIQUE_ID_ATTRIBUTE_ID = 18L; private static final long CAPABILITY_MINIMA_ATTRIBUTE_ID = 19L; private static final long PRODUCT_APPEARANCE_ATTRIBUTE_ID = 20L; private static final long SPECIFICATION_VERSION_ATTRIBUTE_ID = 21L; @@ -5133,7 +5133,7 @@ public void onSuccess(byte[] tlv) { public void readVendorIDAttribute( IntegerAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, VENDOR_I_D_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, VENDOR_ID_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -5141,12 +5141,12 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, VENDOR_I_D_ATTRIBUTE_ID, true); + }, VENDOR_ID_ATTRIBUTE_ID, true); } public void subscribeVendorIDAttribute( IntegerAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, VENDOR_I_D_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, VENDOR_ID_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -5154,7 +5154,7 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, VENDOR_I_D_ATTRIBUTE_ID, minInterval, maxInterval); + }, VENDOR_ID_ATTRIBUTE_ID, minInterval, maxInterval); } public void readProductNameAttribute( @@ -5185,7 +5185,7 @@ public void onSuccess(byte[] tlv) { public void readProductIDAttribute( IntegerAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, PRODUCT_I_D_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, PRODUCT_ID_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -5193,12 +5193,12 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, PRODUCT_I_D_ATTRIBUTE_ID, true); + }, PRODUCT_ID_ATTRIBUTE_ID, true); } public void subscribeProductIDAttribute( IntegerAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, PRODUCT_I_D_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, PRODUCT_ID_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -5206,7 +5206,7 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, PRODUCT_I_D_ATTRIBUTE_ID, minInterval, maxInterval); + }, PRODUCT_ID_ATTRIBUTE_ID, minInterval, maxInterval); } public void readNodeLabelAttribute( @@ -5437,7 +5437,7 @@ public void onSuccess(byte[] tlv) { public void readProductURLAttribute( CharStringAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, PRODUCT_U_R_L_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, PRODUCT_URL_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -5445,12 +5445,12 @@ public void onSuccess(byte[] tlv) { String value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, PRODUCT_U_R_L_ATTRIBUTE_ID, true); + }, PRODUCT_URL_ATTRIBUTE_ID, true); } public void subscribeProductURLAttribute( CharStringAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, PRODUCT_U_R_L_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, PRODUCT_URL_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -5458,7 +5458,7 @@ public void onSuccess(byte[] tlv) { String value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, PRODUCT_U_R_L_ATTRIBUTE_ID, minInterval, maxInterval); + }, PRODUCT_URL_ATTRIBUTE_ID, minInterval, maxInterval); } public void readProductLabelAttribute( @@ -5576,7 +5576,7 @@ public void onSuccess(byte[] tlv) { public void readUniqueIDAttribute( CharStringAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, UNIQUE_I_D_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, UNIQUE_ID_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -5584,12 +5584,12 @@ public void onSuccess(byte[] tlv) { String value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, UNIQUE_I_D_ATTRIBUTE_ID, true); + }, UNIQUE_ID_ATTRIBUTE_ID, true); } public void subscribeUniqueIDAttribute( CharStringAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, UNIQUE_I_D_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, UNIQUE_ID_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -5597,7 +5597,7 @@ public void onSuccess(byte[] tlv) { String value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, UNIQUE_I_D_ATTRIBUTE_ID, minInterval, maxInterval); + }, UNIQUE_ID_ATTRIBUTE_ID, minInterval, maxInterval); } public void readCapabilityMinimaAttribute( @@ -6237,7 +6237,7 @@ public void onSuccess(byte[] tlv) { public static class OtaSoftwareUpdateRequestorCluster extends BaseChipCluster { public static final long CLUSTER_ID = 42L; - private static final long DEFAULT_O_T_A_PROVIDERS_ATTRIBUTE_ID = 0L; + private static final long DEFAULT_OTA_PROVIDERS_ATTRIBUTE_ID = 0L; private static final long UPDATE_POSSIBLE_ATTRIBUTE_ID = 1L; private static final long UPDATE_STATE_ATTRIBUTE_ID = 2L; private static final long UPDATE_STATE_PROGRESS_ATTRIBUTE_ID = 3L; @@ -6325,7 +6325,7 @@ public void readDefaultOTAProvidersAttribute( public void readDefaultOTAProvidersAttributeWithFabricFilter( DefaultOTAProvidersAttributeCallback callback, boolean isFabricFiltered) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, DEFAULT_O_T_A_PROVIDERS_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, DEFAULT_OTA_PROVIDERS_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -6333,7 +6333,7 @@ public void onSuccess(byte[] tlv) { List value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, DEFAULT_O_T_A_PROVIDERS_ATTRIBUTE_ID, isFabricFiltered); + }, DEFAULT_OTA_PROVIDERS_ATTRIBUTE_ID, isFabricFiltered); } public void writeDefaultOTAProvidersAttribute(DefaultClusterCallback callback, ArrayList value) { @@ -6342,12 +6342,12 @@ public void writeDefaultOTAProvidersAttribute(DefaultClusterCallback callback, A public void writeDefaultOTAProvidersAttribute(DefaultClusterCallback callback, ArrayList value, int timedWriteTimeoutMs) { BaseTLVType tlvValue = ArrayType.generateArrayType(value, (elementvalue) -> elementvalue.encodeTlv()); - writeAttribute(new WriteAttributesCallbackImpl(callback), DEFAULT_O_T_A_PROVIDERS_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); + writeAttribute(new WriteAttributesCallbackImpl(callback), DEFAULT_OTA_PROVIDERS_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); } public void subscribeDefaultOTAProvidersAttribute( DefaultOTAProvidersAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, DEFAULT_O_T_A_PROVIDERS_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, DEFAULT_OTA_PROVIDERS_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -6355,7 +6355,7 @@ public void onSuccess(byte[] tlv) { List value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, DEFAULT_O_T_A_PROVIDERS_ATTRIBUTE_ID, minInterval, maxInterval); + }, DEFAULT_OTA_PROVIDERS_ATTRIBUTE_ID, minInterval, maxInterval); } public void readUpdatePossibleAttribute( @@ -7626,8 +7626,8 @@ public static class PowerSourceCluster extends BaseChipCluster { private static final long ACTIVE_BAT_FAULTS_ATTRIBUTE_ID = 18L; private static final long BAT_REPLACEMENT_DESCRIPTION_ATTRIBUTE_ID = 19L; private static final long BAT_COMMON_DESIGNATION_ATTRIBUTE_ID = 20L; - private static final long BAT_A_N_S_I_DESIGNATION_ATTRIBUTE_ID = 21L; - private static final long BAT_I_E_C_DESIGNATION_ATTRIBUTE_ID = 22L; + private static final long BAT_ANSI_DESIGNATION_ATTRIBUTE_ID = 21L; + private static final long BAT_IEC_DESIGNATION_ATTRIBUTE_ID = 22L; private static final long BAT_APPROVED_CHEMISTRY_ATTRIBUTE_ID = 23L; private static final long BAT_CAPACITY_ATTRIBUTE_ID = 24L; private static final long BAT_QUANTITY_ATTRIBUTE_ID = 25L; @@ -8266,7 +8266,7 @@ public void onSuccess(byte[] tlv) { public void readBatANSIDesignationAttribute( CharStringAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, BAT_A_N_S_I_DESIGNATION_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, BAT_ANSI_DESIGNATION_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -8274,12 +8274,12 @@ public void onSuccess(byte[] tlv) { String value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, BAT_A_N_S_I_DESIGNATION_ATTRIBUTE_ID, true); + }, BAT_ANSI_DESIGNATION_ATTRIBUTE_ID, true); } public void subscribeBatANSIDesignationAttribute( CharStringAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, BAT_A_N_S_I_DESIGNATION_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, BAT_ANSI_DESIGNATION_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -8287,12 +8287,12 @@ public void onSuccess(byte[] tlv) { String value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, BAT_A_N_S_I_DESIGNATION_ATTRIBUTE_ID, minInterval, maxInterval); + }, BAT_ANSI_DESIGNATION_ATTRIBUTE_ID, minInterval, maxInterval); } public void readBatIECDesignationAttribute( CharStringAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, BAT_I_E_C_DESIGNATION_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, BAT_IEC_DESIGNATION_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -8300,12 +8300,12 @@ public void onSuccess(byte[] tlv) { String value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, BAT_I_E_C_DESIGNATION_ATTRIBUTE_ID, true); + }, BAT_IEC_DESIGNATION_ATTRIBUTE_ID, true); } public void subscribeBatIECDesignationAttribute( CharStringAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, BAT_I_E_C_DESIGNATION_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, BAT_IEC_DESIGNATION_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -8313,7 +8313,7 @@ public void onSuccess(byte[] tlv) { String value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, BAT_I_E_C_DESIGNATION_ATTRIBUTE_ID, minInterval, maxInterval); + }, BAT_IEC_DESIGNATION_ATTRIBUTE_ID, minInterval, maxInterval); } public void readBatApprovedChemistryAttribute( @@ -8715,10 +8715,10 @@ public static class GeneralCommissioningCluster extends BaseChipCluster { private static final long REGULATORY_CONFIG_ATTRIBUTE_ID = 2L; private static final long LOCATION_CAPABILITY_ATTRIBUTE_ID = 3L; private static final long SUPPORTS_CONCURRENT_CONNECTION_ATTRIBUTE_ID = 4L; - private static final long T_C_ACCEPTED_VERSION_ATTRIBUTE_ID = 5L; - private static final long T_C_MIN_REQUIRED_VERSION_ATTRIBUTE_ID = 6L; - private static final long T_C_ACKNOWLEDGEMENTS_ATTRIBUTE_ID = 7L; - private static final long T_C_ACKNOWLEDGEMENTS_REQUIRED_ATTRIBUTE_ID = 8L; + private static final long TC_ACCEPTED_VERSION_ATTRIBUTE_ID = 5L; + private static final long TC_MIN_REQUIRED_VERSION_ATTRIBUTE_ID = 6L; + private static final long TC_ACKNOWLEDGEMENTS_ATTRIBUTE_ID = 7L; + private static final long TC_ACKNOWLEDGEMENTS_REQUIRED_ATTRIBUTE_ID = 8L; 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; @@ -9066,7 +9066,7 @@ public void onSuccess(byte[] tlv) { public void readTCAcceptedVersionAttribute( IntegerAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, T_C_ACCEPTED_VERSION_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, TC_ACCEPTED_VERSION_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -9074,12 +9074,12 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, T_C_ACCEPTED_VERSION_ATTRIBUTE_ID, true); + }, TC_ACCEPTED_VERSION_ATTRIBUTE_ID, true); } public void subscribeTCAcceptedVersionAttribute( IntegerAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, T_C_ACCEPTED_VERSION_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, TC_ACCEPTED_VERSION_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -9087,12 +9087,12 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, T_C_ACCEPTED_VERSION_ATTRIBUTE_ID, minInterval, maxInterval); + }, TC_ACCEPTED_VERSION_ATTRIBUTE_ID, minInterval, maxInterval); } public void readTCMinRequiredVersionAttribute( IntegerAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, T_C_MIN_REQUIRED_VERSION_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, TC_MIN_REQUIRED_VERSION_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -9100,12 +9100,12 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, T_C_MIN_REQUIRED_VERSION_ATTRIBUTE_ID, true); + }, TC_MIN_REQUIRED_VERSION_ATTRIBUTE_ID, true); } public void subscribeTCMinRequiredVersionAttribute( IntegerAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, T_C_MIN_REQUIRED_VERSION_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, TC_MIN_REQUIRED_VERSION_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -9113,12 +9113,12 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, T_C_MIN_REQUIRED_VERSION_ATTRIBUTE_ID, minInterval, maxInterval); + }, TC_MIN_REQUIRED_VERSION_ATTRIBUTE_ID, minInterval, maxInterval); } public void readTCAcknowledgementsAttribute( IntegerAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, T_C_ACKNOWLEDGEMENTS_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, TC_ACKNOWLEDGEMENTS_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -9126,12 +9126,12 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, T_C_ACKNOWLEDGEMENTS_ATTRIBUTE_ID, true); + }, TC_ACKNOWLEDGEMENTS_ATTRIBUTE_ID, true); } public void subscribeTCAcknowledgementsAttribute( IntegerAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, T_C_ACKNOWLEDGEMENTS_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, TC_ACKNOWLEDGEMENTS_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -9139,12 +9139,12 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, T_C_ACKNOWLEDGEMENTS_ATTRIBUTE_ID, minInterval, maxInterval); + }, TC_ACKNOWLEDGEMENTS_ATTRIBUTE_ID, minInterval, maxInterval); } public void readTCAcknowledgementsRequiredAttribute( BooleanAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, T_C_ACKNOWLEDGEMENTS_REQUIRED_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, TC_ACKNOWLEDGEMENTS_REQUIRED_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -9152,12 +9152,12 @@ public void onSuccess(byte[] tlv) { Boolean value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, T_C_ACKNOWLEDGEMENTS_REQUIRED_ATTRIBUTE_ID, true); + }, TC_ACKNOWLEDGEMENTS_REQUIRED_ATTRIBUTE_ID, true); } public void subscribeTCAcknowledgementsRequiredAttribute( BooleanAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, T_C_ACKNOWLEDGEMENTS_REQUIRED_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, TC_ACKNOWLEDGEMENTS_REQUIRED_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -9165,7 +9165,7 @@ public void onSuccess(byte[] tlv) { Boolean value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, T_C_ACKNOWLEDGEMENTS_REQUIRED_ATTRIBUTE_ID, minInterval, maxInterval); + }, TC_ACKNOWLEDGEMENTS_REQUIRED_ATTRIBUTE_ID, minInterval, maxInterval); } public void readGeneratedCommandListAttribute( @@ -9334,7 +9334,7 @@ public static class NetworkCommissioningCluster extends BaseChipCluster { private static final long CONNECT_MAX_TIME_SECONDS_ATTRIBUTE_ID = 3L; private static final long INTERFACE_ENABLED_ATTRIBUTE_ID = 4L; private static final long LAST_NETWORKING_STATUS_ATTRIBUTE_ID = 5L; - private static final long LAST_NETWORK_I_D_ATTRIBUTE_ID = 6L; + private static final long LAST_NETWORK_ID_ATTRIBUTE_ID = 6L; private static final long LAST_CONNECT_ERROR_VALUE_ATTRIBUTE_ID = 7L; private static final long SUPPORTED_WI_FI_BANDS_ATTRIBUTE_ID = 8L; private static final long SUPPORTED_THREAD_FEATURES_ATTRIBUTE_ID = 9L; @@ -9987,7 +9987,7 @@ public void onSuccess(byte[] tlv) { public void readLastNetworkIDAttribute( LastNetworkIDAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, LAST_NETWORK_I_D_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, LAST_NETWORK_ID_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -9995,12 +9995,12 @@ public void onSuccess(byte[] tlv) { @Nullable byte[] value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, LAST_NETWORK_I_D_ATTRIBUTE_ID, true); + }, LAST_NETWORK_ID_ATTRIBUTE_ID, true); } public void subscribeLastNetworkIDAttribute( LastNetworkIDAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, LAST_NETWORK_I_D_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, LAST_NETWORK_ID_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -10008,7 +10008,7 @@ public void onSuccess(byte[] tlv) { @Nullable byte[] value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, LAST_NETWORK_I_D_ATTRIBUTE_ID, minInterval, maxInterval); + }, LAST_NETWORK_ID_ATTRIBUTE_ID, minInterval, maxInterval); } public void readLastConnectErrorValueAttribute( @@ -14009,7 +14009,7 @@ public void onSuccess(byte[] tlv) { public static class EthernetNetworkDiagnosticsCluster extends BaseChipCluster { public static final long CLUSTER_ID = 55L; - private static final long P_H_Y_RATE_ATTRIBUTE_ID = 0L; + private static final long PHY_RATE_ATTRIBUTE_ID = 0L; private static final long FULL_DUPLEX_ATTRIBUTE_ID = 1L; private static final long PACKET_RX_COUNT_ATTRIBUTE_ID = 2L; private static final long PACKET_TX_COUNT_ATTRIBUTE_ID = 3L; @@ -14081,7 +14081,7 @@ public interface AttributeListAttributeCallback extends BaseAttributeCallback { public void readPHYRateAttribute( PHYRateAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, P_H_Y_RATE_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, PHY_RATE_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -14089,12 +14089,12 @@ public void onSuccess(byte[] tlv) { @Nullable Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, P_H_Y_RATE_ATTRIBUTE_ID, true); + }, PHY_RATE_ATTRIBUTE_ID, true); } public void subscribePHYRateAttribute( PHYRateAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, P_H_Y_RATE_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, PHY_RATE_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -14102,7 +14102,7 @@ public void onSuccess(byte[] tlv) { @Nullable Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, P_H_Y_RATE_ATTRIBUTE_ID, minInterval, maxInterval); + }, PHY_RATE_ATTRIBUTE_ID, minInterval, maxInterval); } public void readFullDuplexAttribute( @@ -14473,19 +14473,19 @@ public void onSuccess(byte[] tlv) { public static class TimeSynchronizationCluster extends BaseChipCluster { public static final long CLUSTER_ID = 56L; - private static final long U_T_C_TIME_ATTRIBUTE_ID = 0L; + private static final long UTC_TIME_ATTRIBUTE_ID = 0L; private static final long GRANULARITY_ATTRIBUTE_ID = 1L; private static final long TIME_SOURCE_ATTRIBUTE_ID = 2L; private static final long TRUSTED_TIME_SOURCE_ATTRIBUTE_ID = 3L; - private static final long DEFAULT_N_T_P_ATTRIBUTE_ID = 4L; + private static final long DEFAULT_NTP_ATTRIBUTE_ID = 4L; private static final long TIME_ZONE_ATTRIBUTE_ID = 5L; - private static final long D_S_T_OFFSET_ATTRIBUTE_ID = 6L; + private static final long DST_OFFSET_ATTRIBUTE_ID = 6L; private static final long LOCAL_TIME_ATTRIBUTE_ID = 7L; private static final long TIME_ZONE_DATABASE_ATTRIBUTE_ID = 8L; - private static final long N_T_P_SERVER_AVAILABLE_ATTRIBUTE_ID = 9L; + private static final long NTP_SERVER_AVAILABLE_ATTRIBUTE_ID = 9L; private static final long TIME_ZONE_LIST_MAX_SIZE_ATTRIBUTE_ID = 10L; - private static final long D_S_T_OFFSET_LIST_MAX_SIZE_ATTRIBUTE_ID = 11L; - private static final long SUPPORTS_D_N_S_RESOLVE_ATTRIBUTE_ID = 12L; + private static final long DST_OFFSET_LIST_MAX_SIZE_ATTRIBUTE_ID = 11L; + private static final long SUPPORTS_DNS_RESOLVE_ATTRIBUTE_ID = 12L; 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; @@ -14667,7 +14667,7 @@ public interface AttributeListAttributeCallback extends BaseAttributeCallback { public void readUTCTimeAttribute( UTCTimeAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, U_T_C_TIME_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, UTC_TIME_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -14675,12 +14675,12 @@ public void onSuccess(byte[] tlv) { @Nullable Long value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, U_T_C_TIME_ATTRIBUTE_ID, true); + }, UTC_TIME_ATTRIBUTE_ID, true); } public void subscribeUTCTimeAttribute( UTCTimeAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, U_T_C_TIME_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, UTC_TIME_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -14688,7 +14688,7 @@ public void onSuccess(byte[] tlv) { @Nullable Long value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, U_T_C_TIME_ATTRIBUTE_ID, minInterval, maxInterval); + }, UTC_TIME_ATTRIBUTE_ID, minInterval, maxInterval); } public void readGranularityAttribute( @@ -14771,7 +14771,7 @@ public void onSuccess(byte[] tlv) { public void readDefaultNTPAttribute( DefaultNTPAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, DEFAULT_N_T_P_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, DEFAULT_NTP_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -14779,12 +14779,12 @@ public void onSuccess(byte[] tlv) { @Nullable String value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, DEFAULT_N_T_P_ATTRIBUTE_ID, true); + }, DEFAULT_NTP_ATTRIBUTE_ID, true); } public void subscribeDefaultNTPAttribute( DefaultNTPAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, DEFAULT_N_T_P_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, DEFAULT_NTP_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -14792,7 +14792,7 @@ public void onSuccess(byte[] tlv) { @Nullable String value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, DEFAULT_N_T_P_ATTRIBUTE_ID, minInterval, maxInterval); + }, DEFAULT_NTP_ATTRIBUTE_ID, minInterval, maxInterval); } public void readTimeZoneAttribute( @@ -14823,7 +14823,7 @@ public void onSuccess(byte[] tlv) { public void readDSTOffsetAttribute( DSTOffsetAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, D_S_T_OFFSET_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, DST_OFFSET_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -14831,12 +14831,12 @@ public void onSuccess(byte[] tlv) { List value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, D_S_T_OFFSET_ATTRIBUTE_ID, true); + }, DST_OFFSET_ATTRIBUTE_ID, true); } public void subscribeDSTOffsetAttribute( DSTOffsetAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, D_S_T_OFFSET_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, DST_OFFSET_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -14844,7 +14844,7 @@ public void onSuccess(byte[] tlv) { List value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, D_S_T_OFFSET_ATTRIBUTE_ID, minInterval, maxInterval); + }, DST_OFFSET_ATTRIBUTE_ID, minInterval, maxInterval); } public void readLocalTimeAttribute( @@ -14901,7 +14901,7 @@ public void onSuccess(byte[] tlv) { public void readNTPServerAvailableAttribute( BooleanAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, N_T_P_SERVER_AVAILABLE_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, NTP_SERVER_AVAILABLE_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -14909,12 +14909,12 @@ public void onSuccess(byte[] tlv) { Boolean value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, N_T_P_SERVER_AVAILABLE_ATTRIBUTE_ID, true); + }, NTP_SERVER_AVAILABLE_ATTRIBUTE_ID, true); } public void subscribeNTPServerAvailableAttribute( BooleanAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, N_T_P_SERVER_AVAILABLE_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, NTP_SERVER_AVAILABLE_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -14922,7 +14922,7 @@ public void onSuccess(byte[] tlv) { Boolean value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, N_T_P_SERVER_AVAILABLE_ATTRIBUTE_ID, minInterval, maxInterval); + }, NTP_SERVER_AVAILABLE_ATTRIBUTE_ID, minInterval, maxInterval); } public void readTimeZoneListMaxSizeAttribute( @@ -14953,7 +14953,7 @@ public void onSuccess(byte[] tlv) { public void readDSTOffsetListMaxSizeAttribute( IntegerAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, D_S_T_OFFSET_LIST_MAX_SIZE_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, DST_OFFSET_LIST_MAX_SIZE_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -14961,12 +14961,12 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, D_S_T_OFFSET_LIST_MAX_SIZE_ATTRIBUTE_ID, true); + }, DST_OFFSET_LIST_MAX_SIZE_ATTRIBUTE_ID, true); } public void subscribeDSTOffsetListMaxSizeAttribute( IntegerAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, D_S_T_OFFSET_LIST_MAX_SIZE_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, DST_OFFSET_LIST_MAX_SIZE_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -14974,12 +14974,12 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, D_S_T_OFFSET_LIST_MAX_SIZE_ATTRIBUTE_ID, minInterval, maxInterval); + }, DST_OFFSET_LIST_MAX_SIZE_ATTRIBUTE_ID, minInterval, maxInterval); } public void readSupportsDNSResolveAttribute( BooleanAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, SUPPORTS_D_N_S_RESOLVE_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, SUPPORTS_DNS_RESOLVE_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -14987,12 +14987,12 @@ public void onSuccess(byte[] tlv) { Boolean value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, SUPPORTS_D_N_S_RESOLVE_ATTRIBUTE_ID, true); + }, SUPPORTS_DNS_RESOLVE_ATTRIBUTE_ID, true); } public void subscribeSupportsDNSResolveAttribute( BooleanAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, SUPPORTS_D_N_S_RESOLVE_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, SUPPORTS_DNS_RESOLVE_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -15000,7 +15000,7 @@ public void onSuccess(byte[] tlv) { Boolean value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, SUPPORTS_D_N_S_RESOLVE_ATTRIBUTE_ID, minInterval, maxInterval); + }, SUPPORTS_DNS_RESOLVE_ATTRIBUTE_ID, minInterval, maxInterval); } public void readGeneratedCommandListAttribute( @@ -15164,9 +15164,9 @@ public static class BridgedDeviceBasicInformationCluster extends BaseChipCluster public static final long CLUSTER_ID = 57L; private static final long VENDOR_NAME_ATTRIBUTE_ID = 1L; - private static final long VENDOR_I_D_ATTRIBUTE_ID = 2L; + private static final long VENDOR_ID_ATTRIBUTE_ID = 2L; private static final long PRODUCT_NAME_ATTRIBUTE_ID = 3L; - private static final long PRODUCT_I_D_ATTRIBUTE_ID = 4L; + private static final long PRODUCT_ID_ATTRIBUTE_ID = 4L; private static final long NODE_LABEL_ATTRIBUTE_ID = 5L; private static final long HARDWARE_VERSION_ATTRIBUTE_ID = 7L; private static final long HARDWARE_VERSION_STRING_ATTRIBUTE_ID = 8L; @@ -15174,11 +15174,11 @@ public static class BridgedDeviceBasicInformationCluster extends BaseChipCluster private static final long SOFTWARE_VERSION_STRING_ATTRIBUTE_ID = 10L; private static final long MANUFACTURING_DATE_ATTRIBUTE_ID = 11L; private static final long PART_NUMBER_ATTRIBUTE_ID = 12L; - private static final long PRODUCT_U_R_L_ATTRIBUTE_ID = 13L; + private static final long PRODUCT_URL_ATTRIBUTE_ID = 13L; private static final long PRODUCT_LABEL_ATTRIBUTE_ID = 14L; private static final long SERIAL_NUMBER_ATTRIBUTE_ID = 15L; private static final long REACHABLE_ATTRIBUTE_ID = 17L; - private static final long UNIQUE_I_D_ATTRIBUTE_ID = 18L; + private static final long UNIQUE_ID_ATTRIBUTE_ID = 18L; private static final long PRODUCT_APPEARANCE_ATTRIBUTE_ID = 20L; private static final long GENERATED_COMMAND_LIST_ATTRIBUTE_ID = 65528L; private static final long ACCEPTED_COMMAND_LIST_ATTRIBUTE_ID = 65529L; @@ -15265,7 +15265,7 @@ public void onSuccess(byte[] tlv) { public void readVendorIDAttribute( IntegerAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, VENDOR_I_D_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, VENDOR_ID_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -15273,12 +15273,12 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, VENDOR_I_D_ATTRIBUTE_ID, true); + }, VENDOR_ID_ATTRIBUTE_ID, true); } public void subscribeVendorIDAttribute( IntegerAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, VENDOR_I_D_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, VENDOR_ID_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -15286,7 +15286,7 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, VENDOR_I_D_ATTRIBUTE_ID, minInterval, maxInterval); + }, VENDOR_ID_ATTRIBUTE_ID, minInterval, maxInterval); } public void readProductNameAttribute( @@ -15317,7 +15317,7 @@ public void onSuccess(byte[] tlv) { public void readProductIDAttribute( IntegerAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, PRODUCT_I_D_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, PRODUCT_ID_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -15325,12 +15325,12 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, PRODUCT_I_D_ATTRIBUTE_ID, true); + }, PRODUCT_ID_ATTRIBUTE_ID, true); } public void subscribeProductIDAttribute( IntegerAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, PRODUCT_I_D_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, PRODUCT_ID_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -15338,7 +15338,7 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, PRODUCT_I_D_ATTRIBUTE_ID, minInterval, maxInterval); + }, PRODUCT_ID_ATTRIBUTE_ID, minInterval, maxInterval); } public void readNodeLabelAttribute( @@ -15534,7 +15534,7 @@ public void onSuccess(byte[] tlv) { public void readProductURLAttribute( CharStringAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, PRODUCT_U_R_L_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, PRODUCT_URL_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -15542,12 +15542,12 @@ public void onSuccess(byte[] tlv) { String value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, PRODUCT_U_R_L_ATTRIBUTE_ID, true); + }, PRODUCT_URL_ATTRIBUTE_ID, true); } public void subscribeProductURLAttribute( CharStringAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, PRODUCT_U_R_L_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, PRODUCT_URL_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -15555,7 +15555,7 @@ public void onSuccess(byte[] tlv) { String value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, PRODUCT_U_R_L_ATTRIBUTE_ID, minInterval, maxInterval); + }, PRODUCT_URL_ATTRIBUTE_ID, minInterval, maxInterval); } public void readProductLabelAttribute( @@ -15638,7 +15638,7 @@ public void onSuccess(byte[] tlv) { public void readUniqueIDAttribute( CharStringAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, UNIQUE_I_D_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, UNIQUE_ID_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -15646,12 +15646,12 @@ public void onSuccess(byte[] tlv) { String value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, UNIQUE_I_D_ATTRIBUTE_ID, true); + }, UNIQUE_ID_ATTRIBUTE_ID, true); } public void subscribeUniqueIDAttribute( CharStringAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, UNIQUE_I_D_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, UNIQUE_ID_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -15659,7 +15659,7 @@ public void onSuccess(byte[] tlv) { String value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, UNIQUE_I_D_ATTRIBUTE_ID, minInterval, maxInterval); + }, UNIQUE_ID_ATTRIBUTE_ID, minInterval, maxInterval); } public void readProductAppearanceAttribute( @@ -16467,7 +16467,7 @@ public void onSuccess(byte[] tlv) { public static class OperationalCredentialsCluster extends BaseChipCluster { public static final long CLUSTER_ID = 62L; - private static final long N_O_CS_ATTRIBUTE_ID = 0L; + private static final long NO_CS_ATTRIBUTE_ID = 0L; private static final long FABRICS_ATTRIBUTE_ID = 1L; private static final long SUPPORTED_FABRICS_ATTRIBUTE_ID = 2L; private static final long COMMISSIONED_FABRICS_ATTRIBUTE_ID = 3L; @@ -16865,7 +16865,7 @@ public void readNOCsAttribute( public void readNOCsAttributeWithFabricFilter( NOCsAttributeCallback callback, boolean isFabricFiltered) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, N_O_CS_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, NO_CS_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -16873,12 +16873,12 @@ public void onSuccess(byte[] tlv) { List value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, N_O_CS_ATTRIBUTE_ID, isFabricFiltered); + }, NO_CS_ATTRIBUTE_ID, isFabricFiltered); } public void subscribeNOCsAttribute( NOCsAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, N_O_CS_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, NO_CS_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -16886,7 +16886,7 @@ public void onSuccess(byte[] tlv) { List value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, N_O_CS_ATTRIBUTE_ID, minInterval, maxInterval); + }, NO_CS_ATTRIBUTE_ID, minInterval, maxInterval); } public void readFabricsAttribute( @@ -18876,7 +18876,7 @@ public static class IcdManagementCluster extends BaseChipCluster { private static final long ACTIVE_MODE_DURATION_ATTRIBUTE_ID = 1L; private static final long ACTIVE_MODE_THRESHOLD_ATTRIBUTE_ID = 2L; private static final long REGISTERED_CLIENTS_ATTRIBUTE_ID = 3L; - private static final long I_C_D_COUNTER_ATTRIBUTE_ID = 4L; + private static final long ICD_COUNTER_ATTRIBUTE_ID = 4L; private static final long CLIENTS_SUPPORTED_PER_FABRIC_ATTRIBUTE_ID = 5L; private static final long USER_ACTIVE_MODE_TRIGGER_HINT_ATTRIBUTE_ID = 6L; private static final long USER_ACTIVE_MODE_TRIGGER_INSTRUCTION_ATTRIBUTE_ID = 7L; @@ -19138,7 +19138,7 @@ public void onSuccess(byte[] tlv) { public void readICDCounterAttribute( LongAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, I_C_D_COUNTER_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, ICD_COUNTER_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -19146,12 +19146,12 @@ public void onSuccess(byte[] tlv) { Long value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, I_C_D_COUNTER_ATTRIBUTE_ID, true); + }, ICD_COUNTER_ATTRIBUTE_ID, true); } public void subscribeICDCounterAttribute( LongAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, I_C_D_COUNTER_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, ICD_COUNTER_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -19159,7 +19159,7 @@ public void onSuccess(byte[] tlv) { Long value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, I_C_D_COUNTER_ATTRIBUTE_ID, minInterval, maxInterval); + }, ICD_COUNTER_ATTRIBUTE_ID, minInterval, maxInterval); } public void readClientsSupportedPerFabricAttribute( @@ -24240,14 +24240,14 @@ public static class SmokeCoAlarmCluster extends BaseChipCluster { private static final long EXPRESSED_STATE_ATTRIBUTE_ID = 0L; private static final long SMOKE_STATE_ATTRIBUTE_ID = 1L; - private static final long C_O_STATE_ATTRIBUTE_ID = 2L; + private static final long CO_STATE_ATTRIBUTE_ID = 2L; private static final long BATTERY_ALERT_ATTRIBUTE_ID = 3L; private static final long DEVICE_MUTED_ATTRIBUTE_ID = 4L; private static final long TEST_IN_PROGRESS_ATTRIBUTE_ID = 5L; private static final long HARDWARE_FAULT_ALERT_ATTRIBUTE_ID = 6L; private static final long END_OF_SERVICE_ALERT_ATTRIBUTE_ID = 7L; private static final long INTERCONNECT_SMOKE_ALARM_ATTRIBUTE_ID = 8L; - private static final long INTERCONNECT_C_O_ALARM_ATTRIBUTE_ID = 9L; + private static final long INTERCONNECT_CO_ALARM_ATTRIBUTE_ID = 9L; private static final long CONTAMINATION_STATE_ATTRIBUTE_ID = 10L; private static final long SMOKE_SENSITIVITY_LEVEL_ATTRIBUTE_ID = 11L; private static final long EXPIRY_DATE_ATTRIBUTE_ID = 12L; @@ -24354,7 +24354,7 @@ public void onSuccess(byte[] tlv) { public void readCOStateAttribute( IntegerAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, C_O_STATE_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, CO_STATE_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -24362,12 +24362,12 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, C_O_STATE_ATTRIBUTE_ID, true); + }, CO_STATE_ATTRIBUTE_ID, true); } public void subscribeCOStateAttribute( IntegerAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, C_O_STATE_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, CO_STATE_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -24375,7 +24375,7 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, C_O_STATE_ATTRIBUTE_ID, minInterval, maxInterval); + }, CO_STATE_ATTRIBUTE_ID, minInterval, maxInterval); } public void readBatteryAlertAttribute( @@ -24536,7 +24536,7 @@ public void onSuccess(byte[] tlv) { public void readInterconnectCOAlarmAttribute( IntegerAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, INTERCONNECT_C_O_ALARM_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, INTERCONNECT_CO_ALARM_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -24544,12 +24544,12 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, INTERCONNECT_C_O_ALARM_ATTRIBUTE_ID, true); + }, INTERCONNECT_CO_ALARM_ATTRIBUTE_ID, true); } public void subscribeInterconnectCOAlarmAttribute( IntegerAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, INTERCONNECT_C_O_ALARM_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, INTERCONNECT_CO_ALARM_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -24557,7 +24557,7 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, INTERCONNECT_C_O_ALARM_ATTRIBUTE_ID, minInterval, maxInterval); + }, INTERCONNECT_CO_ALARM_ATTRIBUTE_ID, minInterval, maxInterval); } public void readContaminationStateAttribute( @@ -29376,9 +29376,9 @@ public static class ElectricalPowerMeasurementCluster extends BaseChipCluster { private static final long ACTIVE_POWER_ATTRIBUTE_ID = 8L; private static final long REACTIVE_POWER_ATTRIBUTE_ID = 9L; private static final long APPARENT_POWER_ATTRIBUTE_ID = 10L; - private static final long R_M_S_VOLTAGE_ATTRIBUTE_ID = 11L; - private static final long R_M_S_CURRENT_ATTRIBUTE_ID = 12L; - private static final long R_M_S_POWER_ATTRIBUTE_ID = 13L; + private static final long RMS_VOLTAGE_ATTRIBUTE_ID = 11L; + private static final long RMS_CURRENT_ATTRIBUTE_ID = 12L; + private static final long RMS_POWER_ATTRIBUTE_ID = 13L; private static final long FREQUENCY_ATTRIBUTE_ID = 14L; private static final long HARMONIC_CURRENTS_ATTRIBUTE_ID = 15L; private static final long HARMONIC_PHASES_ATTRIBUTE_ID = 16L; @@ -29773,7 +29773,7 @@ public void onSuccess(byte[] tlv) { public void readRMSVoltageAttribute( RMSVoltageAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, R_M_S_VOLTAGE_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, RMS_VOLTAGE_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -29781,12 +29781,12 @@ public void onSuccess(byte[] tlv) { @Nullable Long value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, R_M_S_VOLTAGE_ATTRIBUTE_ID, true); + }, RMS_VOLTAGE_ATTRIBUTE_ID, true); } public void subscribeRMSVoltageAttribute( RMSVoltageAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, R_M_S_VOLTAGE_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, RMS_VOLTAGE_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -29794,12 +29794,12 @@ public void onSuccess(byte[] tlv) { @Nullable Long value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, R_M_S_VOLTAGE_ATTRIBUTE_ID, minInterval, maxInterval); + }, RMS_VOLTAGE_ATTRIBUTE_ID, minInterval, maxInterval); } public void readRMSCurrentAttribute( RMSCurrentAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, R_M_S_CURRENT_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, RMS_CURRENT_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -29807,12 +29807,12 @@ public void onSuccess(byte[] tlv) { @Nullable Long value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, R_M_S_CURRENT_ATTRIBUTE_ID, true); + }, RMS_CURRENT_ATTRIBUTE_ID, true); } public void subscribeRMSCurrentAttribute( RMSCurrentAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, R_M_S_CURRENT_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, RMS_CURRENT_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -29820,12 +29820,12 @@ public void onSuccess(byte[] tlv) { @Nullable Long value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, R_M_S_CURRENT_ATTRIBUTE_ID, minInterval, maxInterval); + }, RMS_CURRENT_ATTRIBUTE_ID, minInterval, maxInterval); } public void readRMSPowerAttribute( RMSPowerAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, R_M_S_POWER_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, RMS_POWER_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -29833,12 +29833,12 @@ public void onSuccess(byte[] tlv) { @Nullable Long value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, R_M_S_POWER_ATTRIBUTE_ID, true); + }, RMS_POWER_ATTRIBUTE_ID, true); } public void subscribeRMSPowerAttribute( RMSPowerAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, R_M_S_POWER_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, RMS_POWER_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -29846,7 +29846,7 @@ public void onSuccess(byte[] tlv) { @Nullable Long value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, R_M_S_POWER_ATTRIBUTE_ID, minInterval, maxInterval); + }, RMS_POWER_ATTRIBUTE_ID, minInterval, maxInterval); } public void readFrequencyAttribute( @@ -31767,9 +31767,9 @@ public void onSuccess(byte[] tlv) { public static class DeviceEnergyManagementCluster extends BaseChipCluster { public static final long CLUSTER_ID = 152L; - private static final long E_S_A_TYPE_ATTRIBUTE_ID = 0L; - private static final long E_S_A_CAN_GENERATE_ATTRIBUTE_ID = 1L; - private static final long E_S_A_STATE_ATTRIBUTE_ID = 2L; + private static final long ESA_TYPE_ATTRIBUTE_ID = 0L; + private static final long ESA_CAN_GENERATE_ATTRIBUTE_ID = 1L; + private static final long ESA_STATE_ATTRIBUTE_ID = 2L; private static final long ABS_MIN_POWER_ATTRIBUTE_ID = 3L; private static final long ABS_MAX_POWER_ATTRIBUTE_ID = 4L; private static final long POWER_ADJUSTMENT_CAPABILITY_ATTRIBUTE_ID = 5L; @@ -31994,7 +31994,7 @@ public interface AttributeListAttributeCallback extends BaseAttributeCallback { public void readESATypeAttribute( IntegerAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, E_S_A_TYPE_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, ESA_TYPE_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -32002,12 +32002,12 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, E_S_A_TYPE_ATTRIBUTE_ID, true); + }, ESA_TYPE_ATTRIBUTE_ID, true); } public void subscribeESATypeAttribute( IntegerAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, E_S_A_TYPE_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, ESA_TYPE_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -32015,12 +32015,12 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, E_S_A_TYPE_ATTRIBUTE_ID, minInterval, maxInterval); + }, ESA_TYPE_ATTRIBUTE_ID, minInterval, maxInterval); } public void readESACanGenerateAttribute( BooleanAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, E_S_A_CAN_GENERATE_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, ESA_CAN_GENERATE_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -32028,12 +32028,12 @@ public void onSuccess(byte[] tlv) { Boolean value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, E_S_A_CAN_GENERATE_ATTRIBUTE_ID, true); + }, ESA_CAN_GENERATE_ATTRIBUTE_ID, true); } public void subscribeESACanGenerateAttribute( BooleanAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, E_S_A_CAN_GENERATE_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, ESA_CAN_GENERATE_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -32041,12 +32041,12 @@ public void onSuccess(byte[] tlv) { Boolean value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, E_S_A_CAN_GENERATE_ATTRIBUTE_ID, minInterval, maxInterval); + }, ESA_CAN_GENERATE_ATTRIBUTE_ID, minInterval, maxInterval); } public void readESAStateAttribute( IntegerAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, E_S_A_STATE_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, ESA_STATE_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -32054,12 +32054,12 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, E_S_A_STATE_ATTRIBUTE_ID, true); + }, ESA_STATE_ATTRIBUTE_ID, true); } public void subscribeESAStateAttribute( IntegerAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, E_S_A_STATE_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, ESA_STATE_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -32067,7 +32067,7 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, E_S_A_STATE_ATTRIBUTE_ID, minInterval, maxInterval); + }, ESA_STATE_ATTRIBUTE_ID, minInterval, maxInterval); } public void readAbsMinPowerAttribute( @@ -32375,11 +32375,11 @@ public static class EnergyEvseCluster extends BaseChipCluster { private static final long NEXT_CHARGE_TARGET_TIME_ATTRIBUTE_ID = 36L; private static final long NEXT_CHARGE_REQUIRED_ENERGY_ATTRIBUTE_ID = 37L; private static final long NEXT_CHARGE_TARGET_SO_C_ATTRIBUTE_ID = 38L; - private static final long APPROXIMATE_E_V_EFFICIENCY_ATTRIBUTE_ID = 39L; + private static final long APPROXIMATE_EV_EFFICIENCY_ATTRIBUTE_ID = 39L; private static final long STATE_OF_CHARGE_ATTRIBUTE_ID = 48L; private static final long BATTERY_CAPACITY_ATTRIBUTE_ID = 49L; - private static final long VEHICLE_I_D_ATTRIBUTE_ID = 50L; - private static final long SESSION_I_D_ATTRIBUTE_ID = 64L; + private static final long VEHICLE_ID_ATTRIBUTE_ID = 50L; + private static final long SESSION_ID_ATTRIBUTE_ID = 64L; private static final long SESSION_DURATION_ATTRIBUTE_ID = 65L; private static final long SESSION_ENERGY_CHARGED_ATTRIBUTE_ID = 66L; private static final long SESSION_ENERGY_DISCHARGED_ATTRIBUTE_ID = 67L; @@ -33015,7 +33015,7 @@ public void onSuccess(byte[] tlv) { public void readApproximateEVEfficiencyAttribute( ApproximateEVEfficiencyAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, APPROXIMATE_E_V_EFFICIENCY_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, APPROXIMATE_EV_EFFICIENCY_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -33023,7 +33023,7 @@ public void onSuccess(byte[] tlv) { @Nullable Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, APPROXIMATE_E_V_EFFICIENCY_ATTRIBUTE_ID, true); + }, APPROXIMATE_EV_EFFICIENCY_ATTRIBUTE_ID, true); } public void writeApproximateEVEfficiencyAttribute(DefaultClusterCallback callback, Integer value) { @@ -33032,12 +33032,12 @@ public void writeApproximateEVEfficiencyAttribute(DefaultClusterCallback callbac public void writeApproximateEVEfficiencyAttribute(DefaultClusterCallback callback, Integer value, int timedWriteTimeoutMs) { BaseTLVType tlvValue = value != null ? new UIntType(value) : new NullType(); - writeAttribute(new WriteAttributesCallbackImpl(callback), APPROXIMATE_E_V_EFFICIENCY_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); + writeAttribute(new WriteAttributesCallbackImpl(callback), APPROXIMATE_EV_EFFICIENCY_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); } public void subscribeApproximateEVEfficiencyAttribute( ApproximateEVEfficiencyAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, APPROXIMATE_E_V_EFFICIENCY_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, APPROXIMATE_EV_EFFICIENCY_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -33045,7 +33045,7 @@ public void onSuccess(byte[] tlv) { @Nullable Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, APPROXIMATE_E_V_EFFICIENCY_ATTRIBUTE_ID, minInterval, maxInterval); + }, APPROXIMATE_EV_EFFICIENCY_ATTRIBUTE_ID, minInterval, maxInterval); } public void readStateOfChargeAttribute( @@ -33102,7 +33102,7 @@ public void onSuccess(byte[] tlv) { public void readVehicleIDAttribute( VehicleIDAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, VEHICLE_I_D_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, VEHICLE_ID_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -33110,12 +33110,12 @@ public void onSuccess(byte[] tlv) { @Nullable String value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, VEHICLE_I_D_ATTRIBUTE_ID, true); + }, VEHICLE_ID_ATTRIBUTE_ID, true); } public void subscribeVehicleIDAttribute( VehicleIDAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, VEHICLE_I_D_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, VEHICLE_ID_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -33123,12 +33123,12 @@ public void onSuccess(byte[] tlv) { @Nullable String value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, VEHICLE_I_D_ATTRIBUTE_ID, minInterval, maxInterval); + }, VEHICLE_ID_ATTRIBUTE_ID, minInterval, maxInterval); } public void readSessionIDAttribute( SessionIDAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, SESSION_I_D_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, SESSION_ID_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -33136,12 +33136,12 @@ public void onSuccess(byte[] tlv) { @Nullable Long value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, SESSION_I_D_ATTRIBUTE_ID, true); + }, SESSION_ID_ATTRIBUTE_ID, true); } public void subscribeSessionIDAttribute( SessionIDAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, SESSION_I_D_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, SESSION_ID_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -33149,7 +33149,7 @@ public void onSuccess(byte[] tlv) { @Nullable Long value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, SESSION_I_D_ATTRIBUTE_ID, minInterval, maxInterval); + }, SESSION_ID_ATTRIBUTE_ID, minInterval, maxInterval); } public void readSessionDurationAttribute( @@ -35127,19 +35127,19 @@ public static class DoorLockCluster extends BaseChipCluster { private static final long DOOR_CLOSED_EVENTS_ATTRIBUTE_ID = 5L; private static final long OPEN_PERIOD_ATTRIBUTE_ID = 6L; private static final long NUMBER_OF_TOTAL_USERS_SUPPORTED_ATTRIBUTE_ID = 17L; - private static final long NUMBER_OF_P_I_N_USERS_SUPPORTED_ATTRIBUTE_ID = 18L; - private static final long NUMBER_OF_R_F_I_D_USERS_SUPPORTED_ATTRIBUTE_ID = 19L; + private static final long NUMBER_OF_PIN_USERS_SUPPORTED_ATTRIBUTE_ID = 18L; + private static final long NUMBER_OF_RFID_USERS_SUPPORTED_ATTRIBUTE_ID = 19L; private static final long NUMBER_OF_WEEK_DAY_SCHEDULES_SUPPORTED_PER_USER_ATTRIBUTE_ID = 20L; private static final long NUMBER_OF_YEAR_DAY_SCHEDULES_SUPPORTED_PER_USER_ATTRIBUTE_ID = 21L; private static final long NUMBER_OF_HOLIDAY_SCHEDULES_SUPPORTED_ATTRIBUTE_ID = 22L; - private static final long MAX_P_I_N_CODE_LENGTH_ATTRIBUTE_ID = 23L; - private static final long MIN_P_I_N_CODE_LENGTH_ATTRIBUTE_ID = 24L; - private static final long MAX_R_F_I_D_CODE_LENGTH_ATTRIBUTE_ID = 25L; - private static final long MIN_R_F_I_D_CODE_LENGTH_ATTRIBUTE_ID = 26L; + private static final long MAX_PIN_CODE_LENGTH_ATTRIBUTE_ID = 23L; + private static final long MIN_PIN_CODE_LENGTH_ATTRIBUTE_ID = 24L; + private static final long MAX_RFID_CODE_LENGTH_ATTRIBUTE_ID = 25L; + private static final long MIN_RFID_CODE_LENGTH_ATTRIBUTE_ID = 26L; private static final long CREDENTIAL_RULES_SUPPORT_ATTRIBUTE_ID = 27L; private static final long NUMBER_OF_CREDENTIALS_SUPPORTED_PER_USER_ATTRIBUTE_ID = 28L; private static final long LANGUAGE_ATTRIBUTE_ID = 33L; - private static final long L_E_D_SETTINGS_ATTRIBUTE_ID = 34L; + private static final long LED_SETTINGS_ATTRIBUTE_ID = 34L; private static final long AUTO_RELOCK_TIME_ATTRIBUTE_ID = 35L; private static final long SOUND_VOLUME_ATTRIBUTE_ID = 36L; private static final long OPERATING_MODE_ATTRIBUTE_ID = 37L; @@ -35147,21 +35147,21 @@ public static class DoorLockCluster extends BaseChipCluster { private static final long DEFAULT_CONFIGURATION_REGISTER_ATTRIBUTE_ID = 39L; private static final long ENABLE_LOCAL_PROGRAMMING_ATTRIBUTE_ID = 40L; private static final long ENABLE_ONE_TOUCH_LOCKING_ATTRIBUTE_ID = 41L; - private static final long ENABLE_INSIDE_STATUS_L_E_D_ATTRIBUTE_ID = 42L; + private static final long ENABLE_INSIDE_STATUS_LED_ATTRIBUTE_ID = 42L; private static final long ENABLE_PRIVACY_MODE_BUTTON_ATTRIBUTE_ID = 43L; private static final long LOCAL_PROGRAMMING_FEATURES_ATTRIBUTE_ID = 44L; private static final long WRONG_CODE_ENTRY_LIMIT_ATTRIBUTE_ID = 48L; private static final long USER_CODE_TEMPORARY_DISABLE_TIME_ATTRIBUTE_ID = 49L; - private static final long SEND_P_I_N_OVER_THE_AIR_ATTRIBUTE_ID = 50L; - private static final long REQUIRE_P_I_NFOR_REMOTE_OPERATION_ATTRIBUTE_ID = 51L; + private static final long SEND_PIN_OVER_THE_AIR_ATTRIBUTE_ID = 50L; + private static final long REQUIRE_PI_NFOR_REMOTE_OPERATION_ATTRIBUTE_ID = 51L; private static final long EXPIRING_USER_TIMEOUT_ATTRIBUTE_ID = 53L; private static final long ALIRO_READER_VERIFICATION_KEY_ATTRIBUTE_ID = 128L; private static final long ALIRO_READER_GROUP_IDENTIFIER_ATTRIBUTE_ID = 129L; private static final long ALIRO_READER_GROUP_SUB_IDENTIFIER_ATTRIBUTE_ID = 130L; private static final long ALIRO_EXPEDITED_TRANSACTION_SUPPORTED_PROTOCOL_VERSIONS_ATTRIBUTE_ID = 131L; private static final long ALIRO_GROUP_RESOLVING_KEY_ATTRIBUTE_ID = 132L; - private static final long ALIRO_SUPPORTED_B_L_E_U_W_B_PROTOCOL_VERSIONS_ATTRIBUTE_ID = 133L; - private static final long ALIRO_B_L_E_ADVERTISING_VERSION_ATTRIBUTE_ID = 134L; + private static final long ALIRO_SUPPORTED_BLEUWB_PROTOCOL_VERSIONS_ATTRIBUTE_ID = 133L; + private static final long ALIRO_BLE_ADVERTISING_VERSION_ATTRIBUTE_ID = 134L; private static final long NUMBER_OF_ALIRO_CREDENTIAL_ISSUER_KEYS_SUPPORTED_ATTRIBUTE_ID = 135L; private static final long NUMBER_OF_ALIRO_ENDPOINT_KEYS_SUPPORTED_ATTRIBUTE_ID = 136L; private static final long GENERATED_COMMAND_LIST_ATTRIBUTE_ID = 65528L; @@ -36266,7 +36266,7 @@ public void onSuccess(byte[] tlv) { public void readNumberOfPINUsersSupportedAttribute( IntegerAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, NUMBER_OF_P_I_N_USERS_SUPPORTED_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, NUMBER_OF_PIN_USERS_SUPPORTED_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -36274,12 +36274,12 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, NUMBER_OF_P_I_N_USERS_SUPPORTED_ATTRIBUTE_ID, true); + }, NUMBER_OF_PIN_USERS_SUPPORTED_ATTRIBUTE_ID, true); } public void subscribeNumberOfPINUsersSupportedAttribute( IntegerAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, NUMBER_OF_P_I_N_USERS_SUPPORTED_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, NUMBER_OF_PIN_USERS_SUPPORTED_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -36287,12 +36287,12 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, NUMBER_OF_P_I_N_USERS_SUPPORTED_ATTRIBUTE_ID, minInterval, maxInterval); + }, NUMBER_OF_PIN_USERS_SUPPORTED_ATTRIBUTE_ID, minInterval, maxInterval); } public void readNumberOfRFIDUsersSupportedAttribute( IntegerAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, NUMBER_OF_R_F_I_D_USERS_SUPPORTED_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, NUMBER_OF_RFID_USERS_SUPPORTED_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -36300,12 +36300,12 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, NUMBER_OF_R_F_I_D_USERS_SUPPORTED_ATTRIBUTE_ID, true); + }, NUMBER_OF_RFID_USERS_SUPPORTED_ATTRIBUTE_ID, true); } public void subscribeNumberOfRFIDUsersSupportedAttribute( IntegerAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, NUMBER_OF_R_F_I_D_USERS_SUPPORTED_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, NUMBER_OF_RFID_USERS_SUPPORTED_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -36313,7 +36313,7 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, NUMBER_OF_R_F_I_D_USERS_SUPPORTED_ATTRIBUTE_ID, minInterval, maxInterval); + }, NUMBER_OF_RFID_USERS_SUPPORTED_ATTRIBUTE_ID, minInterval, maxInterval); } public void readNumberOfWeekDaySchedulesSupportedPerUserAttribute( @@ -36396,7 +36396,7 @@ public void onSuccess(byte[] tlv) { public void readMaxPINCodeLengthAttribute( IntegerAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, MAX_P_I_N_CODE_LENGTH_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, MAX_PIN_CODE_LENGTH_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -36404,12 +36404,12 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, MAX_P_I_N_CODE_LENGTH_ATTRIBUTE_ID, true); + }, MAX_PIN_CODE_LENGTH_ATTRIBUTE_ID, true); } public void subscribeMaxPINCodeLengthAttribute( IntegerAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, MAX_P_I_N_CODE_LENGTH_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, MAX_PIN_CODE_LENGTH_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -36417,12 +36417,12 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, MAX_P_I_N_CODE_LENGTH_ATTRIBUTE_ID, minInterval, maxInterval); + }, MAX_PIN_CODE_LENGTH_ATTRIBUTE_ID, minInterval, maxInterval); } public void readMinPINCodeLengthAttribute( IntegerAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, MIN_P_I_N_CODE_LENGTH_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, MIN_PIN_CODE_LENGTH_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -36430,12 +36430,12 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, MIN_P_I_N_CODE_LENGTH_ATTRIBUTE_ID, true); + }, MIN_PIN_CODE_LENGTH_ATTRIBUTE_ID, true); } public void subscribeMinPINCodeLengthAttribute( IntegerAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, MIN_P_I_N_CODE_LENGTH_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, MIN_PIN_CODE_LENGTH_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -36443,12 +36443,12 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, MIN_P_I_N_CODE_LENGTH_ATTRIBUTE_ID, minInterval, maxInterval); + }, MIN_PIN_CODE_LENGTH_ATTRIBUTE_ID, minInterval, maxInterval); } public void readMaxRFIDCodeLengthAttribute( IntegerAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, MAX_R_F_I_D_CODE_LENGTH_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, MAX_RFID_CODE_LENGTH_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -36456,12 +36456,12 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, MAX_R_F_I_D_CODE_LENGTH_ATTRIBUTE_ID, true); + }, MAX_RFID_CODE_LENGTH_ATTRIBUTE_ID, true); } public void subscribeMaxRFIDCodeLengthAttribute( IntegerAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, MAX_R_F_I_D_CODE_LENGTH_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, MAX_RFID_CODE_LENGTH_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -36469,12 +36469,12 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, MAX_R_F_I_D_CODE_LENGTH_ATTRIBUTE_ID, minInterval, maxInterval); + }, MAX_RFID_CODE_LENGTH_ATTRIBUTE_ID, minInterval, maxInterval); } public void readMinRFIDCodeLengthAttribute( IntegerAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, MIN_R_F_I_D_CODE_LENGTH_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, MIN_RFID_CODE_LENGTH_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -36482,12 +36482,12 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, MIN_R_F_I_D_CODE_LENGTH_ATTRIBUTE_ID, true); + }, MIN_RFID_CODE_LENGTH_ATTRIBUTE_ID, true); } public void subscribeMinRFIDCodeLengthAttribute( IntegerAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, MIN_R_F_I_D_CODE_LENGTH_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, MIN_RFID_CODE_LENGTH_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -36495,7 +36495,7 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, MIN_R_F_I_D_CODE_LENGTH_ATTRIBUTE_ID, minInterval, maxInterval); + }, MIN_RFID_CODE_LENGTH_ATTRIBUTE_ID, minInterval, maxInterval); } public void readCredentialRulesSupportAttribute( @@ -36587,7 +36587,7 @@ public void onSuccess(byte[] tlv) { public void readLEDSettingsAttribute( IntegerAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, L_E_D_SETTINGS_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, LED_SETTINGS_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -36595,7 +36595,7 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, L_E_D_SETTINGS_ATTRIBUTE_ID, true); + }, LED_SETTINGS_ATTRIBUTE_ID, true); } public void writeLEDSettingsAttribute(DefaultClusterCallback callback, Integer value) { @@ -36604,12 +36604,12 @@ public void writeLEDSettingsAttribute(DefaultClusterCallback callback, Integer v public void writeLEDSettingsAttribute(DefaultClusterCallback callback, Integer value, int timedWriteTimeoutMs) { BaseTLVType tlvValue = new UIntType(value); - writeAttribute(new WriteAttributesCallbackImpl(callback), L_E_D_SETTINGS_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); + writeAttribute(new WriteAttributesCallbackImpl(callback), LED_SETTINGS_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); } public void subscribeLEDSettingsAttribute( IntegerAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, L_E_D_SETTINGS_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, LED_SETTINGS_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -36617,7 +36617,7 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, L_E_D_SETTINGS_ATTRIBUTE_ID, minInterval, maxInterval); + }, LED_SETTINGS_ATTRIBUTE_ID, minInterval, maxInterval); } public void readAutoRelockTimeAttribute( @@ -36849,7 +36849,7 @@ public void onSuccess(byte[] tlv) { public void readEnableInsideStatusLEDAttribute( BooleanAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, ENABLE_INSIDE_STATUS_L_E_D_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, ENABLE_INSIDE_STATUS_LED_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -36857,7 +36857,7 @@ public void onSuccess(byte[] tlv) { Boolean value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, ENABLE_INSIDE_STATUS_L_E_D_ATTRIBUTE_ID, true); + }, ENABLE_INSIDE_STATUS_LED_ATTRIBUTE_ID, true); } public void writeEnableInsideStatusLEDAttribute(DefaultClusterCallback callback, Boolean value) { @@ -36866,12 +36866,12 @@ public void writeEnableInsideStatusLEDAttribute(DefaultClusterCallback callback, public void writeEnableInsideStatusLEDAttribute(DefaultClusterCallback callback, Boolean value, int timedWriteTimeoutMs) { BaseTLVType tlvValue = new BooleanType(value); - writeAttribute(new WriteAttributesCallbackImpl(callback), ENABLE_INSIDE_STATUS_L_E_D_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); + writeAttribute(new WriteAttributesCallbackImpl(callback), ENABLE_INSIDE_STATUS_LED_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); } public void subscribeEnableInsideStatusLEDAttribute( BooleanAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, ENABLE_INSIDE_STATUS_L_E_D_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, ENABLE_INSIDE_STATUS_LED_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -36879,7 +36879,7 @@ public void onSuccess(byte[] tlv) { Boolean value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, ENABLE_INSIDE_STATUS_L_E_D_ATTRIBUTE_ID, minInterval, maxInterval); + }, ENABLE_INSIDE_STATUS_LED_ATTRIBUTE_ID, minInterval, maxInterval); } public void readEnablePrivacyModeButtonAttribute( @@ -37024,7 +37024,7 @@ public void onSuccess(byte[] tlv) { public void readSendPINOverTheAirAttribute( BooleanAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, SEND_P_I_N_OVER_THE_AIR_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, SEND_PIN_OVER_THE_AIR_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -37032,7 +37032,7 @@ public void onSuccess(byte[] tlv) { Boolean value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, SEND_P_I_N_OVER_THE_AIR_ATTRIBUTE_ID, true); + }, SEND_PIN_OVER_THE_AIR_ATTRIBUTE_ID, true); } public void writeSendPINOverTheAirAttribute(DefaultClusterCallback callback, Boolean value) { @@ -37041,12 +37041,12 @@ public void writeSendPINOverTheAirAttribute(DefaultClusterCallback callback, Boo public void writeSendPINOverTheAirAttribute(DefaultClusterCallback callback, Boolean value, int timedWriteTimeoutMs) { BaseTLVType tlvValue = new BooleanType(value); - writeAttribute(new WriteAttributesCallbackImpl(callback), SEND_P_I_N_OVER_THE_AIR_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); + writeAttribute(new WriteAttributesCallbackImpl(callback), SEND_PIN_OVER_THE_AIR_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); } public void subscribeSendPINOverTheAirAttribute( BooleanAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, SEND_P_I_N_OVER_THE_AIR_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, SEND_PIN_OVER_THE_AIR_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -37054,12 +37054,12 @@ public void onSuccess(byte[] tlv) { Boolean value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, SEND_P_I_N_OVER_THE_AIR_ATTRIBUTE_ID, minInterval, maxInterval); + }, SEND_PIN_OVER_THE_AIR_ATTRIBUTE_ID, minInterval, maxInterval); } public void readRequirePINforRemoteOperationAttribute( BooleanAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, REQUIRE_P_I_NFOR_REMOTE_OPERATION_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, REQUIRE_PI_NFOR_REMOTE_OPERATION_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -37067,7 +37067,7 @@ public void onSuccess(byte[] tlv) { Boolean value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, REQUIRE_P_I_NFOR_REMOTE_OPERATION_ATTRIBUTE_ID, true); + }, REQUIRE_PI_NFOR_REMOTE_OPERATION_ATTRIBUTE_ID, true); } public void writeRequirePINforRemoteOperationAttribute(DefaultClusterCallback callback, Boolean value) { @@ -37076,12 +37076,12 @@ public void writeRequirePINforRemoteOperationAttribute(DefaultClusterCallback ca public void writeRequirePINforRemoteOperationAttribute(DefaultClusterCallback callback, Boolean value, int timedWriteTimeoutMs) { BaseTLVType tlvValue = new BooleanType(value); - writeAttribute(new WriteAttributesCallbackImpl(callback), REQUIRE_P_I_NFOR_REMOTE_OPERATION_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); + writeAttribute(new WriteAttributesCallbackImpl(callback), REQUIRE_PI_NFOR_REMOTE_OPERATION_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); } public void subscribeRequirePINforRemoteOperationAttribute( BooleanAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, REQUIRE_P_I_NFOR_REMOTE_OPERATION_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, REQUIRE_PI_NFOR_REMOTE_OPERATION_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -37089,7 +37089,7 @@ public void onSuccess(byte[] tlv) { Boolean value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, REQUIRE_P_I_NFOR_REMOTE_OPERATION_ATTRIBUTE_ID, minInterval, maxInterval); + }, REQUIRE_PI_NFOR_REMOTE_OPERATION_ATTRIBUTE_ID, minInterval, maxInterval); } public void readExpiringUserTimeoutAttribute( @@ -37259,7 +37259,7 @@ public void onSuccess(byte[] tlv) { public void readAliroSupportedBLEUWBProtocolVersionsAttribute( AliroSupportedBLEUWBProtocolVersionsAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, ALIRO_SUPPORTED_B_L_E_U_W_B_PROTOCOL_VERSIONS_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, ALIRO_SUPPORTED_BLEUWB_PROTOCOL_VERSIONS_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -37267,12 +37267,12 @@ public void onSuccess(byte[] tlv) { List value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, ALIRO_SUPPORTED_B_L_E_U_W_B_PROTOCOL_VERSIONS_ATTRIBUTE_ID, true); + }, ALIRO_SUPPORTED_BLEUWB_PROTOCOL_VERSIONS_ATTRIBUTE_ID, true); } public void subscribeAliroSupportedBLEUWBProtocolVersionsAttribute( AliroSupportedBLEUWBProtocolVersionsAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, ALIRO_SUPPORTED_B_L_E_U_W_B_PROTOCOL_VERSIONS_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, ALIRO_SUPPORTED_BLEUWB_PROTOCOL_VERSIONS_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -37280,12 +37280,12 @@ public void onSuccess(byte[] tlv) { List value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, ALIRO_SUPPORTED_B_L_E_U_W_B_PROTOCOL_VERSIONS_ATTRIBUTE_ID, minInterval, maxInterval); + }, ALIRO_SUPPORTED_BLEUWB_PROTOCOL_VERSIONS_ATTRIBUTE_ID, minInterval, maxInterval); } public void readAliroBLEAdvertisingVersionAttribute( IntegerAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, ALIRO_B_L_E_ADVERTISING_VERSION_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, ALIRO_BLE_ADVERTISING_VERSION_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -37293,12 +37293,12 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, ALIRO_B_L_E_ADVERTISING_VERSION_ATTRIBUTE_ID, true); + }, ALIRO_BLE_ADVERTISING_VERSION_ATTRIBUTE_ID, true); } public void subscribeAliroBLEAdvertisingVersionAttribute( IntegerAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, ALIRO_B_L_E_ADVERTISING_VERSION_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, ALIRO_BLE_ADVERTISING_VERSION_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -37306,7 +37306,7 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, ALIRO_B_L_E_ADVERTISING_VERSION_ATTRIBUTE_ID, minInterval, maxInterval); + }, ALIRO_BLE_ADVERTISING_VERSION_ATTRIBUTE_ID, minInterval, maxInterval); } public void readNumberOfAliroCredentialIssuerKeysSupportedAttribute( @@ -40420,9 +40420,9 @@ public static class ThermostatCluster extends BaseChipCluster { private static final long ABS_MAX_HEAT_SETPOINT_LIMIT_ATTRIBUTE_ID = 4L; private static final long ABS_MIN_COOL_SETPOINT_LIMIT_ATTRIBUTE_ID = 5L; private static final long ABS_MAX_COOL_SETPOINT_LIMIT_ATTRIBUTE_ID = 6L; - private static final long P_I_COOLING_DEMAND_ATTRIBUTE_ID = 7L; - private static final long P_I_HEATING_DEMAND_ATTRIBUTE_ID = 8L; - private static final long H_V_A_C_SYSTEM_TYPE_CONFIGURATION_ATTRIBUTE_ID = 9L; + private static final long PI_COOLING_DEMAND_ATTRIBUTE_ID = 7L; + private static final long PI_HEATING_DEMAND_ATTRIBUTE_ID = 8L; + private static final long HVAC_SYSTEM_TYPE_CONFIGURATION_ATTRIBUTE_ID = 9L; private static final long LOCAL_TEMPERATURE_CALIBRATION_ATTRIBUTE_ID = 16L; private static final long OCCUPIED_COOLING_SETPOINT_ATTRIBUTE_ID = 17L; private static final long OCCUPIED_HEATING_SETPOINT_ATTRIBUTE_ID = 18L; @@ -40454,14 +40454,14 @@ public static class ThermostatCluster extends BaseChipCluster { private static final long UNOCCUPIED_SETBACK_MIN_ATTRIBUTE_ID = 56L; private static final long UNOCCUPIED_SETBACK_MAX_ATTRIBUTE_ID = 57L; private static final long EMERGENCY_HEAT_DELTA_ATTRIBUTE_ID = 58L; - private static final long A_C_TYPE_ATTRIBUTE_ID = 64L; - private static final long A_C_CAPACITY_ATTRIBUTE_ID = 65L; - private static final long A_C_REFRIGERANT_TYPE_ATTRIBUTE_ID = 66L; - private static final long A_C_COMPRESSOR_TYPE_ATTRIBUTE_ID = 67L; - private static final long A_C_ERROR_CODE_ATTRIBUTE_ID = 68L; - private static final long A_C_LOUVER_POSITION_ATTRIBUTE_ID = 69L; - private static final long A_C_COIL_TEMPERATURE_ATTRIBUTE_ID = 70L; - private static final long A_C_CAPACITYFORMAT_ATTRIBUTE_ID = 71L; + private static final long AC_TYPE_ATTRIBUTE_ID = 64L; + private static final long AC_CAPACITY_ATTRIBUTE_ID = 65L; + private static final long AC_REFRIGERANT_TYPE_ATTRIBUTE_ID = 66L; + private static final long AC_COMPRESSOR_TYPE_ATTRIBUTE_ID = 67L; + private static final long AC_ERROR_CODE_ATTRIBUTE_ID = 68L; + private static final long AC_LOUVER_POSITION_ATTRIBUTE_ID = 69L; + private static final long AC_COIL_TEMPERATURE_ATTRIBUTE_ID = 70L; + private static final long AC_CAPACITYFORMAT_ATTRIBUTE_ID = 71L; private static final long PRESET_TYPES_ATTRIBUTE_ID = 72L; private static final long SCHEDULE_TYPES_ATTRIBUTE_ID = 73L; private static final long NUMBER_OF_PRESETS_ATTRIBUTE_ID = 74L; @@ -40993,7 +40993,7 @@ public void onSuccess(byte[] tlv) { public void readPICoolingDemandAttribute( IntegerAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, P_I_COOLING_DEMAND_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, PI_COOLING_DEMAND_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -41001,12 +41001,12 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, P_I_COOLING_DEMAND_ATTRIBUTE_ID, true); + }, PI_COOLING_DEMAND_ATTRIBUTE_ID, true); } public void subscribePICoolingDemandAttribute( IntegerAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, P_I_COOLING_DEMAND_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, PI_COOLING_DEMAND_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -41014,12 +41014,12 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, P_I_COOLING_DEMAND_ATTRIBUTE_ID, minInterval, maxInterval); + }, PI_COOLING_DEMAND_ATTRIBUTE_ID, minInterval, maxInterval); } public void readPIHeatingDemandAttribute( IntegerAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, P_I_HEATING_DEMAND_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, PI_HEATING_DEMAND_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -41027,12 +41027,12 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, P_I_HEATING_DEMAND_ATTRIBUTE_ID, true); + }, PI_HEATING_DEMAND_ATTRIBUTE_ID, true); } public void subscribePIHeatingDemandAttribute( IntegerAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, P_I_HEATING_DEMAND_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, PI_HEATING_DEMAND_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -41040,12 +41040,12 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, P_I_HEATING_DEMAND_ATTRIBUTE_ID, minInterval, maxInterval); + }, PI_HEATING_DEMAND_ATTRIBUTE_ID, minInterval, maxInterval); } public void readHVACSystemTypeConfigurationAttribute( IntegerAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, H_V_A_C_SYSTEM_TYPE_CONFIGURATION_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, HVAC_SYSTEM_TYPE_CONFIGURATION_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -41053,7 +41053,7 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, H_V_A_C_SYSTEM_TYPE_CONFIGURATION_ATTRIBUTE_ID, true); + }, HVAC_SYSTEM_TYPE_CONFIGURATION_ATTRIBUTE_ID, true); } public void writeHVACSystemTypeConfigurationAttribute(DefaultClusterCallback callback, Integer value) { @@ -41062,12 +41062,12 @@ public void writeHVACSystemTypeConfigurationAttribute(DefaultClusterCallback cal public void writeHVACSystemTypeConfigurationAttribute(DefaultClusterCallback callback, Integer value, int timedWriteTimeoutMs) { BaseTLVType tlvValue = new UIntType(value); - writeAttribute(new WriteAttributesCallbackImpl(callback), H_V_A_C_SYSTEM_TYPE_CONFIGURATION_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); + writeAttribute(new WriteAttributesCallbackImpl(callback), HVAC_SYSTEM_TYPE_CONFIGURATION_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); } public void subscribeHVACSystemTypeConfigurationAttribute( IntegerAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, H_V_A_C_SYSTEM_TYPE_CONFIGURATION_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, HVAC_SYSTEM_TYPE_CONFIGURATION_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -41075,7 +41075,7 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, H_V_A_C_SYSTEM_TYPE_CONFIGURATION_ATTRIBUTE_ID, minInterval, maxInterval); + }, HVAC_SYSTEM_TYPE_CONFIGURATION_ATTRIBUTE_ID, minInterval, maxInterval); } public void readLocalTemperatureCalibrationAttribute( @@ -42057,7 +42057,7 @@ public void onSuccess(byte[] tlv) { public void readACTypeAttribute( IntegerAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, A_C_TYPE_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, AC_TYPE_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -42065,7 +42065,7 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, A_C_TYPE_ATTRIBUTE_ID, true); + }, AC_TYPE_ATTRIBUTE_ID, true); } public void writeACTypeAttribute(DefaultClusterCallback callback, Integer value) { @@ -42074,12 +42074,12 @@ public void writeACTypeAttribute(DefaultClusterCallback callback, Integer value) public void writeACTypeAttribute(DefaultClusterCallback callback, Integer value, int timedWriteTimeoutMs) { BaseTLVType tlvValue = new UIntType(value); - writeAttribute(new WriteAttributesCallbackImpl(callback), A_C_TYPE_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); + writeAttribute(new WriteAttributesCallbackImpl(callback), AC_TYPE_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); } public void subscribeACTypeAttribute( IntegerAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, A_C_TYPE_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, AC_TYPE_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -42087,12 +42087,12 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, A_C_TYPE_ATTRIBUTE_ID, minInterval, maxInterval); + }, AC_TYPE_ATTRIBUTE_ID, minInterval, maxInterval); } public void readACCapacityAttribute( IntegerAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, A_C_CAPACITY_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, AC_CAPACITY_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -42100,7 +42100,7 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, A_C_CAPACITY_ATTRIBUTE_ID, true); + }, AC_CAPACITY_ATTRIBUTE_ID, true); } public void writeACCapacityAttribute(DefaultClusterCallback callback, Integer value) { @@ -42109,12 +42109,12 @@ public void writeACCapacityAttribute(DefaultClusterCallback callback, Integer va public void writeACCapacityAttribute(DefaultClusterCallback callback, Integer value, int timedWriteTimeoutMs) { BaseTLVType tlvValue = new UIntType(value); - writeAttribute(new WriteAttributesCallbackImpl(callback), A_C_CAPACITY_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); + writeAttribute(new WriteAttributesCallbackImpl(callback), AC_CAPACITY_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); } public void subscribeACCapacityAttribute( IntegerAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, A_C_CAPACITY_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, AC_CAPACITY_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -42122,12 +42122,12 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, A_C_CAPACITY_ATTRIBUTE_ID, minInterval, maxInterval); + }, AC_CAPACITY_ATTRIBUTE_ID, minInterval, maxInterval); } public void readACRefrigerantTypeAttribute( IntegerAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, A_C_REFRIGERANT_TYPE_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, AC_REFRIGERANT_TYPE_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -42135,7 +42135,7 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, A_C_REFRIGERANT_TYPE_ATTRIBUTE_ID, true); + }, AC_REFRIGERANT_TYPE_ATTRIBUTE_ID, true); } public void writeACRefrigerantTypeAttribute(DefaultClusterCallback callback, Integer value) { @@ -42144,12 +42144,12 @@ public void writeACRefrigerantTypeAttribute(DefaultClusterCallback callback, Int public void writeACRefrigerantTypeAttribute(DefaultClusterCallback callback, Integer value, int timedWriteTimeoutMs) { BaseTLVType tlvValue = new UIntType(value); - writeAttribute(new WriteAttributesCallbackImpl(callback), A_C_REFRIGERANT_TYPE_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); + writeAttribute(new WriteAttributesCallbackImpl(callback), AC_REFRIGERANT_TYPE_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); } public void subscribeACRefrigerantTypeAttribute( IntegerAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, A_C_REFRIGERANT_TYPE_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, AC_REFRIGERANT_TYPE_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -42157,12 +42157,12 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, A_C_REFRIGERANT_TYPE_ATTRIBUTE_ID, minInterval, maxInterval); + }, AC_REFRIGERANT_TYPE_ATTRIBUTE_ID, minInterval, maxInterval); } public void readACCompressorTypeAttribute( IntegerAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, A_C_COMPRESSOR_TYPE_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, AC_COMPRESSOR_TYPE_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -42170,7 +42170,7 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, A_C_COMPRESSOR_TYPE_ATTRIBUTE_ID, true); + }, AC_COMPRESSOR_TYPE_ATTRIBUTE_ID, true); } public void writeACCompressorTypeAttribute(DefaultClusterCallback callback, Integer value) { @@ -42179,12 +42179,12 @@ public void writeACCompressorTypeAttribute(DefaultClusterCallback callback, Inte public void writeACCompressorTypeAttribute(DefaultClusterCallback callback, Integer value, int timedWriteTimeoutMs) { BaseTLVType tlvValue = new UIntType(value); - writeAttribute(new WriteAttributesCallbackImpl(callback), A_C_COMPRESSOR_TYPE_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); + writeAttribute(new WriteAttributesCallbackImpl(callback), AC_COMPRESSOR_TYPE_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); } public void subscribeACCompressorTypeAttribute( IntegerAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, A_C_COMPRESSOR_TYPE_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, AC_COMPRESSOR_TYPE_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -42192,12 +42192,12 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, A_C_COMPRESSOR_TYPE_ATTRIBUTE_ID, minInterval, maxInterval); + }, AC_COMPRESSOR_TYPE_ATTRIBUTE_ID, minInterval, maxInterval); } public void readACErrorCodeAttribute( LongAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, A_C_ERROR_CODE_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, AC_ERROR_CODE_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -42205,7 +42205,7 @@ public void onSuccess(byte[] tlv) { Long value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, A_C_ERROR_CODE_ATTRIBUTE_ID, true); + }, AC_ERROR_CODE_ATTRIBUTE_ID, true); } public void writeACErrorCodeAttribute(DefaultClusterCallback callback, Long value) { @@ -42214,12 +42214,12 @@ public void writeACErrorCodeAttribute(DefaultClusterCallback callback, Long valu public void writeACErrorCodeAttribute(DefaultClusterCallback callback, Long value, int timedWriteTimeoutMs) { BaseTLVType tlvValue = new UIntType(value); - writeAttribute(new WriteAttributesCallbackImpl(callback), A_C_ERROR_CODE_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); + writeAttribute(new WriteAttributesCallbackImpl(callback), AC_ERROR_CODE_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); } public void subscribeACErrorCodeAttribute( LongAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, A_C_ERROR_CODE_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, AC_ERROR_CODE_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -42227,12 +42227,12 @@ public void onSuccess(byte[] tlv) { Long value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, A_C_ERROR_CODE_ATTRIBUTE_ID, minInterval, maxInterval); + }, AC_ERROR_CODE_ATTRIBUTE_ID, minInterval, maxInterval); } public void readACLouverPositionAttribute( IntegerAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, A_C_LOUVER_POSITION_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, AC_LOUVER_POSITION_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -42240,7 +42240,7 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, A_C_LOUVER_POSITION_ATTRIBUTE_ID, true); + }, AC_LOUVER_POSITION_ATTRIBUTE_ID, true); } public void writeACLouverPositionAttribute(DefaultClusterCallback callback, Integer value) { @@ -42249,12 +42249,12 @@ public void writeACLouverPositionAttribute(DefaultClusterCallback callback, Inte public void writeACLouverPositionAttribute(DefaultClusterCallback callback, Integer value, int timedWriteTimeoutMs) { BaseTLVType tlvValue = new UIntType(value); - writeAttribute(new WriteAttributesCallbackImpl(callback), A_C_LOUVER_POSITION_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); + writeAttribute(new WriteAttributesCallbackImpl(callback), AC_LOUVER_POSITION_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); } public void subscribeACLouverPositionAttribute( IntegerAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, A_C_LOUVER_POSITION_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, AC_LOUVER_POSITION_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -42262,12 +42262,12 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, A_C_LOUVER_POSITION_ATTRIBUTE_ID, minInterval, maxInterval); + }, AC_LOUVER_POSITION_ATTRIBUTE_ID, minInterval, maxInterval); } public void readACCoilTemperatureAttribute( ACCoilTemperatureAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, A_C_COIL_TEMPERATURE_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, AC_COIL_TEMPERATURE_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -42275,12 +42275,12 @@ public void onSuccess(byte[] tlv) { @Nullable Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, A_C_COIL_TEMPERATURE_ATTRIBUTE_ID, true); + }, AC_COIL_TEMPERATURE_ATTRIBUTE_ID, true); } public void subscribeACCoilTemperatureAttribute( ACCoilTemperatureAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, A_C_COIL_TEMPERATURE_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, AC_COIL_TEMPERATURE_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -42288,12 +42288,12 @@ public void onSuccess(byte[] tlv) { @Nullable Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, A_C_COIL_TEMPERATURE_ATTRIBUTE_ID, minInterval, maxInterval); + }, AC_COIL_TEMPERATURE_ATTRIBUTE_ID, minInterval, maxInterval); } public void readACCapacityformatAttribute( IntegerAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, A_C_CAPACITYFORMAT_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, AC_CAPACITYFORMAT_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -42301,7 +42301,7 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, A_C_CAPACITYFORMAT_ATTRIBUTE_ID, true); + }, AC_CAPACITYFORMAT_ATTRIBUTE_ID, true); } public void writeACCapacityformatAttribute(DefaultClusterCallback callback, Integer value) { @@ -42310,12 +42310,12 @@ public void writeACCapacityformatAttribute(DefaultClusterCallback callback, Inte public void writeACCapacityformatAttribute(DefaultClusterCallback callback, Integer value, int timedWriteTimeoutMs) { BaseTLVType tlvValue = new UIntType(value); - writeAttribute(new WriteAttributesCallbackImpl(callback), A_C_CAPACITYFORMAT_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); + writeAttribute(new WriteAttributesCallbackImpl(callback), AC_CAPACITYFORMAT_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); } public void subscribeACCapacityformatAttribute( IntegerAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, A_C_CAPACITYFORMAT_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, AC_CAPACITYFORMAT_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -42323,7 +42323,7 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, A_C_CAPACITYFORMAT_ATTRIBUTE_ID, minInterval, maxInterval); + }, AC_CAPACITYFORMAT_ATTRIBUTE_ID, minInterval, maxInterval); } public void readPresetTypesAttribute( @@ -43729,14 +43729,14 @@ public static class ColorControlCluster extends BaseChipCluster { private static final long PRIMARY6_INTENSITY_ATTRIBUTE_ID = 42L; private static final long WHITE_POINT_X_ATTRIBUTE_ID = 48L; private static final long WHITE_POINT_Y_ATTRIBUTE_ID = 49L; - private static final long COLOR_POINT_R_X_ATTRIBUTE_ID = 50L; - private static final long COLOR_POINT_R_Y_ATTRIBUTE_ID = 51L; + private static final long COLOR_POINT_RX_ATTRIBUTE_ID = 50L; + private static final long COLOR_POINT_RY_ATTRIBUTE_ID = 51L; private static final long COLOR_POINT_R_INTENSITY_ATTRIBUTE_ID = 52L; - private static final long COLOR_POINT_G_X_ATTRIBUTE_ID = 54L; - private static final long COLOR_POINT_G_Y_ATTRIBUTE_ID = 55L; + private static final long COLOR_POINT_GX_ATTRIBUTE_ID = 54L; + private static final long COLOR_POINT_GY_ATTRIBUTE_ID = 55L; private static final long COLOR_POINT_G_INTENSITY_ATTRIBUTE_ID = 56L; - private static final long COLOR_POINT_B_X_ATTRIBUTE_ID = 58L; - private static final long COLOR_POINT_B_Y_ATTRIBUTE_ID = 59L; + private static final long COLOR_POINT_BX_ATTRIBUTE_ID = 58L; + private static final long COLOR_POINT_BY_ATTRIBUTE_ID = 59L; private static final long COLOR_POINT_B_INTENSITY_ATTRIBUTE_ID = 60L; private static final long ENHANCED_CURRENT_HUE_ATTRIBUTE_ID = 16384L; private static final long ENHANCED_COLOR_MODE_ATTRIBUTE_ID = 16385L; @@ -45330,7 +45330,7 @@ public void onSuccess(byte[] tlv) { public void readColorPointRXAttribute( IntegerAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, COLOR_POINT_R_X_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, COLOR_POINT_RX_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -45338,7 +45338,7 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, COLOR_POINT_R_X_ATTRIBUTE_ID, true); + }, COLOR_POINT_RX_ATTRIBUTE_ID, true); } public void writeColorPointRXAttribute(DefaultClusterCallback callback, Integer value) { @@ -45347,12 +45347,12 @@ public void writeColorPointRXAttribute(DefaultClusterCallback callback, Integer public void writeColorPointRXAttribute(DefaultClusterCallback callback, Integer value, int timedWriteTimeoutMs) { BaseTLVType tlvValue = new UIntType(value); - writeAttribute(new WriteAttributesCallbackImpl(callback), COLOR_POINT_R_X_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); + writeAttribute(new WriteAttributesCallbackImpl(callback), COLOR_POINT_RX_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); } public void subscribeColorPointRXAttribute( IntegerAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, COLOR_POINT_R_X_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, COLOR_POINT_RX_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -45360,12 +45360,12 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, COLOR_POINT_R_X_ATTRIBUTE_ID, minInterval, maxInterval); + }, COLOR_POINT_RX_ATTRIBUTE_ID, minInterval, maxInterval); } public void readColorPointRYAttribute( IntegerAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, COLOR_POINT_R_Y_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, COLOR_POINT_RY_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -45373,7 +45373,7 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, COLOR_POINT_R_Y_ATTRIBUTE_ID, true); + }, COLOR_POINT_RY_ATTRIBUTE_ID, true); } public void writeColorPointRYAttribute(DefaultClusterCallback callback, Integer value) { @@ -45382,12 +45382,12 @@ public void writeColorPointRYAttribute(DefaultClusterCallback callback, Integer public void writeColorPointRYAttribute(DefaultClusterCallback callback, Integer value, int timedWriteTimeoutMs) { BaseTLVType tlvValue = new UIntType(value); - writeAttribute(new WriteAttributesCallbackImpl(callback), COLOR_POINT_R_Y_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); + writeAttribute(new WriteAttributesCallbackImpl(callback), COLOR_POINT_RY_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); } public void subscribeColorPointRYAttribute( IntegerAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, COLOR_POINT_R_Y_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, COLOR_POINT_RY_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -45395,7 +45395,7 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, COLOR_POINT_R_Y_ATTRIBUTE_ID, minInterval, maxInterval); + }, COLOR_POINT_RY_ATTRIBUTE_ID, minInterval, maxInterval); } public void readColorPointRIntensityAttribute( @@ -45435,7 +45435,7 @@ public void onSuccess(byte[] tlv) { public void readColorPointGXAttribute( IntegerAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, COLOR_POINT_G_X_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, COLOR_POINT_GX_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -45443,7 +45443,7 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, COLOR_POINT_G_X_ATTRIBUTE_ID, true); + }, COLOR_POINT_GX_ATTRIBUTE_ID, true); } public void writeColorPointGXAttribute(DefaultClusterCallback callback, Integer value) { @@ -45452,12 +45452,12 @@ public void writeColorPointGXAttribute(DefaultClusterCallback callback, Integer public void writeColorPointGXAttribute(DefaultClusterCallback callback, Integer value, int timedWriteTimeoutMs) { BaseTLVType tlvValue = new UIntType(value); - writeAttribute(new WriteAttributesCallbackImpl(callback), COLOR_POINT_G_X_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); + writeAttribute(new WriteAttributesCallbackImpl(callback), COLOR_POINT_GX_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); } public void subscribeColorPointGXAttribute( IntegerAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, COLOR_POINT_G_X_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, COLOR_POINT_GX_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -45465,12 +45465,12 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, COLOR_POINT_G_X_ATTRIBUTE_ID, minInterval, maxInterval); + }, COLOR_POINT_GX_ATTRIBUTE_ID, minInterval, maxInterval); } public void readColorPointGYAttribute( IntegerAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, COLOR_POINT_G_Y_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, COLOR_POINT_GY_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -45478,7 +45478,7 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, COLOR_POINT_G_Y_ATTRIBUTE_ID, true); + }, COLOR_POINT_GY_ATTRIBUTE_ID, true); } public void writeColorPointGYAttribute(DefaultClusterCallback callback, Integer value) { @@ -45487,12 +45487,12 @@ public void writeColorPointGYAttribute(DefaultClusterCallback callback, Integer public void writeColorPointGYAttribute(DefaultClusterCallback callback, Integer value, int timedWriteTimeoutMs) { BaseTLVType tlvValue = new UIntType(value); - writeAttribute(new WriteAttributesCallbackImpl(callback), COLOR_POINT_G_Y_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); + writeAttribute(new WriteAttributesCallbackImpl(callback), COLOR_POINT_GY_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); } public void subscribeColorPointGYAttribute( IntegerAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, COLOR_POINT_G_Y_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, COLOR_POINT_GY_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -45500,7 +45500,7 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, COLOR_POINT_G_Y_ATTRIBUTE_ID, minInterval, maxInterval); + }, COLOR_POINT_GY_ATTRIBUTE_ID, minInterval, maxInterval); } public void readColorPointGIntensityAttribute( @@ -45540,7 +45540,7 @@ public void onSuccess(byte[] tlv) { public void readColorPointBXAttribute( IntegerAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, COLOR_POINT_B_X_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, COLOR_POINT_BX_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -45548,7 +45548,7 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, COLOR_POINT_B_X_ATTRIBUTE_ID, true); + }, COLOR_POINT_BX_ATTRIBUTE_ID, true); } public void writeColorPointBXAttribute(DefaultClusterCallback callback, Integer value) { @@ -45557,12 +45557,12 @@ public void writeColorPointBXAttribute(DefaultClusterCallback callback, Integer public void writeColorPointBXAttribute(DefaultClusterCallback callback, Integer value, int timedWriteTimeoutMs) { BaseTLVType tlvValue = new UIntType(value); - writeAttribute(new WriteAttributesCallbackImpl(callback), COLOR_POINT_B_X_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); + writeAttribute(new WriteAttributesCallbackImpl(callback), COLOR_POINT_BX_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); } public void subscribeColorPointBXAttribute( IntegerAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, COLOR_POINT_B_X_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, COLOR_POINT_BX_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -45570,12 +45570,12 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, COLOR_POINT_B_X_ATTRIBUTE_ID, minInterval, maxInterval); + }, COLOR_POINT_BX_ATTRIBUTE_ID, minInterval, maxInterval); } public void readColorPointBYAttribute( IntegerAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, COLOR_POINT_B_Y_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, COLOR_POINT_BY_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -45583,7 +45583,7 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, COLOR_POINT_B_Y_ATTRIBUTE_ID, true); + }, COLOR_POINT_BY_ATTRIBUTE_ID, true); } public void writeColorPointBYAttribute(DefaultClusterCallback callback, Integer value) { @@ -45592,12 +45592,12 @@ public void writeColorPointBYAttribute(DefaultClusterCallback callback, Integer public void writeColorPointBYAttribute(DefaultClusterCallback callback, Integer value, int timedWriteTimeoutMs) { BaseTLVType tlvValue = new UIntType(value); - writeAttribute(new WriteAttributesCallbackImpl(callback), COLOR_POINT_B_Y_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); + writeAttribute(new WriteAttributesCallbackImpl(callback), COLOR_POINT_BY_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); } public void subscribeColorPointBYAttribute( IntegerAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, COLOR_POINT_B_Y_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, COLOR_POINT_BY_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -45605,7 +45605,7 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, COLOR_POINT_B_Y_ATTRIBUTE_ID, minInterval, maxInterval); + }, COLOR_POINT_BY_ATTRIBUTE_ID, minInterval, maxInterval); } public void readColorPointBIntensityAttribute( @@ -48553,9 +48553,9 @@ public static class OccupancySensingCluster extends BaseChipCluster { private static final long OCCUPANCY_SENSOR_TYPE_BITMAP_ATTRIBUTE_ID = 2L; private static final long HOLD_TIME_ATTRIBUTE_ID = 3L; private static final long HOLD_TIME_LIMITS_ATTRIBUTE_ID = 4L; - private static final long P_I_R_OCCUPIED_TO_UNOCCUPIED_DELAY_ATTRIBUTE_ID = 16L; - private static final long P_I_R_UNOCCUPIED_TO_OCCUPIED_DELAY_ATTRIBUTE_ID = 17L; - private static final long P_I_R_UNOCCUPIED_TO_OCCUPIED_THRESHOLD_ATTRIBUTE_ID = 18L; + private static final long PIR_OCCUPIED_TO_UNOCCUPIED_DELAY_ATTRIBUTE_ID = 16L; + private static final long PIR_UNOCCUPIED_TO_OCCUPIED_DELAY_ATTRIBUTE_ID = 17L; + private static final long PIR_UNOCCUPIED_TO_OCCUPIED_THRESHOLD_ATTRIBUTE_ID = 18L; private static final long ULTRASONIC_OCCUPIED_TO_UNOCCUPIED_DELAY_ATTRIBUTE_ID = 32L; private static final long ULTRASONIC_UNOCCUPIED_TO_OCCUPIED_DELAY_ATTRIBUTE_ID = 33L; private static final long ULTRASONIC_UNOCCUPIED_TO_OCCUPIED_THRESHOLD_ATTRIBUTE_ID = 34L; @@ -48740,7 +48740,7 @@ public void onSuccess(byte[] tlv) { public void readPIROccupiedToUnoccupiedDelayAttribute( IntegerAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, P_I_R_OCCUPIED_TO_UNOCCUPIED_DELAY_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, PIR_OCCUPIED_TO_UNOCCUPIED_DELAY_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -48748,7 +48748,7 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, P_I_R_OCCUPIED_TO_UNOCCUPIED_DELAY_ATTRIBUTE_ID, true); + }, PIR_OCCUPIED_TO_UNOCCUPIED_DELAY_ATTRIBUTE_ID, true); } public void writePIROccupiedToUnoccupiedDelayAttribute(DefaultClusterCallback callback, Integer value) { @@ -48757,12 +48757,12 @@ public void writePIROccupiedToUnoccupiedDelayAttribute(DefaultClusterCallback ca public void writePIROccupiedToUnoccupiedDelayAttribute(DefaultClusterCallback callback, Integer value, int timedWriteTimeoutMs) { BaseTLVType tlvValue = new UIntType(value); - writeAttribute(new WriteAttributesCallbackImpl(callback), P_I_R_OCCUPIED_TO_UNOCCUPIED_DELAY_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); + writeAttribute(new WriteAttributesCallbackImpl(callback), PIR_OCCUPIED_TO_UNOCCUPIED_DELAY_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); } public void subscribePIROccupiedToUnoccupiedDelayAttribute( IntegerAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, P_I_R_OCCUPIED_TO_UNOCCUPIED_DELAY_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, PIR_OCCUPIED_TO_UNOCCUPIED_DELAY_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -48770,12 +48770,12 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, P_I_R_OCCUPIED_TO_UNOCCUPIED_DELAY_ATTRIBUTE_ID, minInterval, maxInterval); + }, PIR_OCCUPIED_TO_UNOCCUPIED_DELAY_ATTRIBUTE_ID, minInterval, maxInterval); } public void readPIRUnoccupiedToOccupiedDelayAttribute( IntegerAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, P_I_R_UNOCCUPIED_TO_OCCUPIED_DELAY_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, PIR_UNOCCUPIED_TO_OCCUPIED_DELAY_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -48783,7 +48783,7 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, P_I_R_UNOCCUPIED_TO_OCCUPIED_DELAY_ATTRIBUTE_ID, true); + }, PIR_UNOCCUPIED_TO_OCCUPIED_DELAY_ATTRIBUTE_ID, true); } public void writePIRUnoccupiedToOccupiedDelayAttribute(DefaultClusterCallback callback, Integer value) { @@ -48792,12 +48792,12 @@ public void writePIRUnoccupiedToOccupiedDelayAttribute(DefaultClusterCallback ca public void writePIRUnoccupiedToOccupiedDelayAttribute(DefaultClusterCallback callback, Integer value, int timedWriteTimeoutMs) { BaseTLVType tlvValue = new UIntType(value); - writeAttribute(new WriteAttributesCallbackImpl(callback), P_I_R_UNOCCUPIED_TO_OCCUPIED_DELAY_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); + writeAttribute(new WriteAttributesCallbackImpl(callback), PIR_UNOCCUPIED_TO_OCCUPIED_DELAY_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); } public void subscribePIRUnoccupiedToOccupiedDelayAttribute( IntegerAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, P_I_R_UNOCCUPIED_TO_OCCUPIED_DELAY_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, PIR_UNOCCUPIED_TO_OCCUPIED_DELAY_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -48805,12 +48805,12 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, P_I_R_UNOCCUPIED_TO_OCCUPIED_DELAY_ATTRIBUTE_ID, minInterval, maxInterval); + }, PIR_UNOCCUPIED_TO_OCCUPIED_DELAY_ATTRIBUTE_ID, minInterval, maxInterval); } public void readPIRUnoccupiedToOccupiedThresholdAttribute( IntegerAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, P_I_R_UNOCCUPIED_TO_OCCUPIED_THRESHOLD_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, PIR_UNOCCUPIED_TO_OCCUPIED_THRESHOLD_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -48818,7 +48818,7 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, P_I_R_UNOCCUPIED_TO_OCCUPIED_THRESHOLD_ATTRIBUTE_ID, true); + }, PIR_UNOCCUPIED_TO_OCCUPIED_THRESHOLD_ATTRIBUTE_ID, true); } public void writePIRUnoccupiedToOccupiedThresholdAttribute(DefaultClusterCallback callback, Integer value) { @@ -48827,12 +48827,12 @@ public void writePIRUnoccupiedToOccupiedThresholdAttribute(DefaultClusterCallbac public void writePIRUnoccupiedToOccupiedThresholdAttribute(DefaultClusterCallback callback, Integer value, int timedWriteTimeoutMs) { BaseTLVType tlvValue = new UIntType(value); - writeAttribute(new WriteAttributesCallbackImpl(callback), P_I_R_UNOCCUPIED_TO_OCCUPIED_THRESHOLD_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); + writeAttribute(new WriteAttributesCallbackImpl(callback), PIR_UNOCCUPIED_TO_OCCUPIED_THRESHOLD_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); } public void subscribePIRUnoccupiedToOccupiedThresholdAttribute( IntegerAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, P_I_R_UNOCCUPIED_TO_OCCUPIED_THRESHOLD_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, PIR_UNOCCUPIED_TO_OCCUPIED_THRESHOLD_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -48840,7 +48840,7 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, P_I_R_UNOCCUPIED_TO_OCCUPIED_THRESHOLD_ATTRIBUTE_ID, minInterval, maxInterval); + }, PIR_UNOCCUPIED_TO_OCCUPIED_THRESHOLD_ATTRIBUTE_ID, minInterval, maxInterval); } public void readUltrasonicOccupiedToUnoccupiedDelayAttribute( @@ -54599,7 +54599,7 @@ public static class ThreadBorderRouterManagementCluster extends BaseChipCluster public static final long CLUSTER_ID = 1106L; private static final long BORDER_ROUTER_NAME_ATTRIBUTE_ID = 0L; - private static final long BORDER_AGENT_I_D_ATTRIBUTE_ID = 1L; + private static final long BORDER_AGENT_ID_ATTRIBUTE_ID = 1L; private static final long THREAD_VERSION_ATTRIBUTE_ID = 2L; private static final long INTERFACE_ENABLED_ATTRIBUTE_ID = 3L; private static final long ACTIVE_DATASET_TIMESTAMP_ATTRIBUTE_ID = 4L; @@ -54773,7 +54773,7 @@ public void onSuccess(byte[] tlv) { public void readBorderAgentIDAttribute( OctetStringAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, BORDER_AGENT_I_D_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, BORDER_AGENT_ID_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -54781,12 +54781,12 @@ public void onSuccess(byte[] tlv) { byte[] value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, BORDER_AGENT_I_D_ATTRIBUTE_ID, true); + }, BORDER_AGENT_ID_ATTRIBUTE_ID, true); } public void subscribeBorderAgentIDAttribute( OctetStringAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, BORDER_AGENT_I_D_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, BORDER_AGENT_ID_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -54794,7 +54794,7 @@ public void onSuccess(byte[] tlv) { byte[] value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, BORDER_AGENT_I_D_ATTRIBUTE_ID, minInterval, maxInterval); + }, BORDER_AGENT_ID_ATTRIBUTE_ID, minInterval, maxInterval); } public void readThreadVersionAttribute( @@ -55061,7 +55061,7 @@ public void onSuccess(byte[] tlv) { public static class ThreadNetworkDirectoryCluster extends BaseChipCluster { public static final long CLUSTER_ID = 1107L; - private static final long PREFERRED_EXTENDED_PAN_I_D_ATTRIBUTE_ID = 0L; + private static final long PREFERRED_EXTENDED_PAN_ID_ATTRIBUTE_ID = 0L; private static final long THREAD_NETWORKS_ATTRIBUTE_ID = 1L; private static final long THREAD_NETWORK_TABLE_SIZE_ATTRIBUTE_ID = 2L; private static final long GENERATED_COMMAND_LIST_ATTRIBUTE_ID = 65528L; @@ -55175,7 +55175,7 @@ public interface AttributeListAttributeCallback extends BaseAttributeCallback { public void readPreferredExtendedPanIDAttribute( PreferredExtendedPanIDAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, PREFERRED_EXTENDED_PAN_I_D_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, PREFERRED_EXTENDED_PAN_ID_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -55183,7 +55183,7 @@ public void onSuccess(byte[] tlv) { @Nullable byte[] value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, PREFERRED_EXTENDED_PAN_I_D_ATTRIBUTE_ID, true); + }, PREFERRED_EXTENDED_PAN_ID_ATTRIBUTE_ID, true); } public void writePreferredExtendedPanIDAttribute(DefaultClusterCallback callback, byte[] value) { @@ -55192,12 +55192,12 @@ public void writePreferredExtendedPanIDAttribute(DefaultClusterCallback callback public void writePreferredExtendedPanIDAttribute(DefaultClusterCallback callback, byte[] value, int timedWriteTimeoutMs) { BaseTLVType tlvValue = value != null ? new ByteArrayType(value) : new NullType(); - writeAttribute(new WriteAttributesCallbackImpl(callback), PREFERRED_EXTENDED_PAN_I_D_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); + writeAttribute(new WriteAttributesCallbackImpl(callback), PREFERRED_EXTENDED_PAN_ID_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); } public void subscribePreferredExtendedPanIDAttribute( PreferredExtendedPanIDAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, PREFERRED_EXTENDED_PAN_I_D_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, PREFERRED_EXTENDED_PAN_ID_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -55205,7 +55205,7 @@ public void onSuccess(byte[] tlv) { @Nullable byte[] value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, PREFERRED_EXTENDED_PAN_I_D_ATTRIBUTE_ID, minInterval, maxInterval); + }, PREFERRED_EXTENDED_PAN_ID_ATTRIBUTE_ID, minInterval, maxInterval); } public void readThreadNetworksAttribute( @@ -55420,7 +55420,7 @@ public void onSuccess(byte[] tlv) { public static class WakeOnLanCluster extends BaseChipCluster { public static final long CLUSTER_ID = 1283L; - private static final long M_A_C_ADDRESS_ATTRIBUTE_ID = 0L; + private static final long MAC_ADDRESS_ATTRIBUTE_ID = 0L; private static final long LINK_LOCAL_ADDRESS_ATTRIBUTE_ID = 1L; private static final long GENERATED_COMMAND_LIST_ATTRIBUTE_ID = 65528L; private static final long ACCEPTED_COMMAND_LIST_ATTRIBUTE_ID = 65529L; @@ -55457,7 +55457,7 @@ public interface AttributeListAttributeCallback extends BaseAttributeCallback { public void readMACAddressAttribute( CharStringAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, M_A_C_ADDRESS_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, MAC_ADDRESS_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -55465,12 +55465,12 @@ public void onSuccess(byte[] tlv) { String value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, M_A_C_ADDRESS_ATTRIBUTE_ID, true); + }, MAC_ADDRESS_ATTRIBUTE_ID, true); } public void subscribeMACAddressAttribute( CharStringAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, M_A_C_ADDRESS_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, MAC_ADDRESS_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -55478,7 +55478,7 @@ public void onSuccess(byte[] tlv) { String value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, M_A_C_ADDRESS_ATTRIBUTE_ID, minInterval, maxInterval); + }, MAC_ADDRESS_ATTRIBUTE_ID, minInterval, maxInterval); } public void readLinkLocalAddressAttribute( @@ -59222,9 +59222,9 @@ public static class ApplicationBasicCluster extends BaseChipCluster { public static final long CLUSTER_ID = 1293L; private static final long VENDOR_NAME_ATTRIBUTE_ID = 0L; - private static final long VENDOR_I_D_ATTRIBUTE_ID = 1L; + private static final long VENDOR_ID_ATTRIBUTE_ID = 1L; private static final long APPLICATION_NAME_ATTRIBUTE_ID = 2L; - private static final long PRODUCT_I_D_ATTRIBUTE_ID = 3L; + private static final long PRODUCT_ID_ATTRIBUTE_ID = 3L; private static final long APPLICATION_ATTRIBUTE_ID = 4L; private static final long STATUS_ATTRIBUTE_ID = 5L; private static final long APPLICATION_VERSION_ATTRIBUTE_ID = 6L; @@ -59298,7 +59298,7 @@ public void onSuccess(byte[] tlv) { public void readVendorIDAttribute( IntegerAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, VENDOR_I_D_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, VENDOR_ID_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -59306,12 +59306,12 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, VENDOR_I_D_ATTRIBUTE_ID, true); + }, VENDOR_ID_ATTRIBUTE_ID, true); } public void subscribeVendorIDAttribute( IntegerAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, VENDOR_I_D_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, VENDOR_ID_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -59319,7 +59319,7 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, VENDOR_I_D_ATTRIBUTE_ID, minInterval, maxInterval); + }, VENDOR_ID_ATTRIBUTE_ID, minInterval, maxInterval); } public void readApplicationNameAttribute( @@ -59350,7 +59350,7 @@ public void onSuccess(byte[] tlv) { public void readProductIDAttribute( IntegerAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, PRODUCT_I_D_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, PRODUCT_ID_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -59358,12 +59358,12 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, PRODUCT_I_D_ATTRIBUTE_ID, true); + }, PRODUCT_ID_ATTRIBUTE_ID, true); } public void subscribeProductIDAttribute( IntegerAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, PRODUCT_I_D_ATTRIBUTE_ID); + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, PRODUCT_ID_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override @@ -59371,7 +59371,7 @@ public void onSuccess(byte[] tlv) { Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, PRODUCT_I_D_ATTRIBUTE_ID, minInterval, maxInterval); + }, PRODUCT_ID_ATTRIBUTE_ID, minInterval, maxInterval); } public void readApplicationAttribute( diff --git a/src/controller/java/generated/java/chip/devicecontroller/ChipEventStructs.java b/src/controller/java/generated/java/chip/devicecontroller/ChipEventStructs.java index 4e3c6ce296..160f29d2cf 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/ChipEventStructs.java +++ b/src/controller/java/generated/java/chip/devicecontroller/ChipEventStructs.java @@ -30,8 +30,8 @@ public static class AccessControlClusterAccessControlEntryChangedEvent { public Integer changeType; public @Nullable ChipStructs.AccessControlClusterAccessControlEntryStruct latestValue; public Integer fabricIndex; - private static final long ADMIN_NODE_I_D_ID = 1L; - private static final long ADMIN_PASSCODE_I_D_ID = 2L; + private static final long ADMIN_NODE_ID_ID = 1L; + private static final long ADMIN_PASSCODE_ID_ID = 2L; private static final long CHANGE_TYPE_ID = 3L; private static final long LATEST_VALUE_ID = 4L; private static final long FABRIC_INDEX_ID = 254L; @@ -52,8 +52,8 @@ public AccessControlClusterAccessControlEntryChangedEvent( public StructType encodeTlv() { ArrayList values = new ArrayList<>(); - values.add(new StructElement(ADMIN_NODE_I_D_ID, adminNodeID != null ? new UIntType(adminNodeID) : new NullType())); - values.add(new StructElement(ADMIN_PASSCODE_I_D_ID, adminPasscodeID != null ? new UIntType(adminPasscodeID) : new NullType())); + values.add(new StructElement(ADMIN_NODE_ID_ID, adminNodeID != null ? new UIntType(adminNodeID) : new NullType())); + values.add(new StructElement(ADMIN_PASSCODE_ID_ID, adminPasscodeID != null ? new UIntType(adminPasscodeID) : new NullType())); values.add(new StructElement(CHANGE_TYPE_ID, new UIntType(changeType))); values.add(new StructElement(LATEST_VALUE_ID, latestValue != null ? latestValue.encodeTlv() : new NullType())); values.add(new StructElement(FABRIC_INDEX_ID, new UIntType(fabricIndex))); @@ -71,12 +71,12 @@ public static AccessControlClusterAccessControlEntryChangedEvent decodeTlv(BaseT @Nullable ChipStructs.AccessControlClusterAccessControlEntryStruct latestValue = null; Integer fabricIndex = null; for (StructElement element: ((StructType)tlvValue).value()) { - if (element.contextTagNum() == ADMIN_NODE_I_D_ID) { + if (element.contextTagNum() == ADMIN_NODE_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); adminNodeID = castingValue.value(Long.class); } - } else if (element.contextTagNum() == ADMIN_PASSCODE_I_D_ID) { + } else if (element.contextTagNum() == ADMIN_PASSCODE_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); adminPasscodeID = castingValue.value(Integer.class); @@ -136,8 +136,8 @@ public static class AccessControlClusterAccessControlExtensionChangedEvent { public Integer changeType; public @Nullable ChipStructs.AccessControlClusterAccessControlExtensionStruct latestValue; public Integer fabricIndex; - private static final long ADMIN_NODE_I_D_ID = 1L; - private static final long ADMIN_PASSCODE_I_D_ID = 2L; + private static final long ADMIN_NODE_ID_ID = 1L; + private static final long ADMIN_PASSCODE_ID_ID = 2L; private static final long CHANGE_TYPE_ID = 3L; private static final long LATEST_VALUE_ID = 4L; private static final long FABRIC_INDEX_ID = 254L; @@ -158,8 +158,8 @@ public AccessControlClusterAccessControlExtensionChangedEvent( public StructType encodeTlv() { ArrayList values = new ArrayList<>(); - values.add(new StructElement(ADMIN_NODE_I_D_ID, adminNodeID != null ? new UIntType(adminNodeID) : new NullType())); - values.add(new StructElement(ADMIN_PASSCODE_I_D_ID, adminPasscodeID != null ? new UIntType(adminPasscodeID) : new NullType())); + values.add(new StructElement(ADMIN_NODE_ID_ID, adminNodeID != null ? new UIntType(adminNodeID) : new NullType())); + values.add(new StructElement(ADMIN_PASSCODE_ID_ID, adminPasscodeID != null ? new UIntType(adminPasscodeID) : new NullType())); values.add(new StructElement(CHANGE_TYPE_ID, new UIntType(changeType))); values.add(new StructElement(LATEST_VALUE_ID, latestValue != null ? latestValue.encodeTlv() : new NullType())); values.add(new StructElement(FABRIC_INDEX_ID, new UIntType(fabricIndex))); @@ -177,12 +177,12 @@ public static AccessControlClusterAccessControlExtensionChangedEvent decodeTlv(B @Nullable ChipStructs.AccessControlClusterAccessControlExtensionStruct latestValue = null; Integer fabricIndex = null; for (StructElement element: ((StructType)tlvValue).value()) { - if (element.contextTagNum() == ADMIN_NODE_I_D_ID) { + if (element.contextTagNum() == ADMIN_NODE_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); adminNodeID = castingValue.value(Long.class); } - } else if (element.contextTagNum() == ADMIN_PASSCODE_I_D_ID) { + } else if (element.contextTagNum() == ADMIN_PASSCODE_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); adminPasscodeID = castingValue.value(Integer.class); @@ -289,7 +289,7 @@ public static class AccessControlClusterFabricRestrictionReviewUpdateEvent { public Integer fabricIndex; private static final long TOKEN_ID = 0L; private static final long INSTRUCTION_ID = 1L; - private static final long REDIRECT_U_R_L_ID = 2L; + private static final long REDIRECT_URL_ID = 2L; private static final long FABRIC_INDEX_ID = 254L; public AccessControlClusterFabricRestrictionReviewUpdateEvent( @@ -308,7 +308,7 @@ public StructType encodeTlv() { ArrayList values = new ArrayList<>(); values.add(new StructElement(TOKEN_ID, new UIntType(token))); values.add(new StructElement(INSTRUCTION_ID, instruction != null ? new StringType(instruction) : new NullType())); - values.add(new StructElement(REDIRECT_U_R_L_ID, redirectURL != null ? new StringType(redirectURL) : new NullType())); + values.add(new StructElement(REDIRECT_URL_ID, redirectURL != null ? new StringType(redirectURL) : new NullType())); values.add(new StructElement(FABRIC_INDEX_ID, new UIntType(fabricIndex))); return new StructType(values); @@ -333,7 +333,7 @@ public static AccessControlClusterFabricRestrictionReviewUpdateEvent decodeTlv(B StringType castingValue = element.value(StringType.class); instruction = castingValue.value(String.class); } - } else if (element.contextTagNum() == REDIRECT_U_R_L_ID) { + } else if (element.contextTagNum() == REDIRECT_URL_ID) { if (element.value(BaseTLVType.class).type() == TLVType.String) { StringType castingValue = element.value(StringType.class); redirectURL = castingValue.value(String.class); @@ -377,8 +377,8 @@ public static class ActionsClusterStateChangedEvent { public Integer actionID; public Long invokeID; public Integer newState; - private static final long ACTION_I_D_ID = 0L; - private static final long INVOKE_I_D_ID = 1L; + private static final long ACTION_ID_ID = 0L; + private static final long INVOKE_ID_ID = 1L; private static final long NEW_STATE_ID = 2L; public ActionsClusterStateChangedEvent( @@ -393,8 +393,8 @@ public ActionsClusterStateChangedEvent( public StructType encodeTlv() { ArrayList values = new ArrayList<>(); - values.add(new StructElement(ACTION_I_D_ID, new UIntType(actionID))); - values.add(new StructElement(INVOKE_I_D_ID, new UIntType(invokeID))); + values.add(new StructElement(ACTION_ID_ID, new UIntType(actionID))); + values.add(new StructElement(INVOKE_ID_ID, new UIntType(invokeID))); values.add(new StructElement(NEW_STATE_ID, new UIntType(newState))); return new StructType(values); @@ -408,12 +408,12 @@ public static ActionsClusterStateChangedEvent decodeTlv(BaseTLVType tlvValue) { Long invokeID = null; Integer newState = null; for (StructElement element: ((StructType)tlvValue).value()) { - if (element.contextTagNum() == ACTION_I_D_ID) { + if (element.contextTagNum() == ACTION_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); actionID = castingValue.value(Integer.class); } - } else if (element.contextTagNum() == INVOKE_I_D_ID) { + } else if (element.contextTagNum() == INVOKE_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); invokeID = castingValue.value(Long.class); @@ -454,8 +454,8 @@ public static class ActionsClusterActionFailedEvent { public Long invokeID; public Integer newState; public Integer error; - private static final long ACTION_I_D_ID = 0L; - private static final long INVOKE_I_D_ID = 1L; + private static final long ACTION_ID_ID = 0L; + private static final long INVOKE_ID_ID = 1L; private static final long NEW_STATE_ID = 2L; private static final long ERROR_ID = 3L; @@ -473,8 +473,8 @@ public ActionsClusterActionFailedEvent( public StructType encodeTlv() { ArrayList values = new ArrayList<>(); - values.add(new StructElement(ACTION_I_D_ID, new UIntType(actionID))); - values.add(new StructElement(INVOKE_I_D_ID, new UIntType(invokeID))); + values.add(new StructElement(ACTION_ID_ID, new UIntType(actionID))); + values.add(new StructElement(INVOKE_ID_ID, new UIntType(invokeID))); values.add(new StructElement(NEW_STATE_ID, new UIntType(newState))); values.add(new StructElement(ERROR_ID, new UIntType(error))); @@ -490,12 +490,12 @@ public static ActionsClusterActionFailedEvent decodeTlv(BaseTLVType tlvValue) { Integer newState = null; Integer error = null; for (StructElement element: ((StructType)tlvValue).value()) { - if (element.contextTagNum() == ACTION_I_D_ID) { + if (element.contextTagNum() == ACTION_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); actionID = castingValue.value(Integer.class); } - } else if (element.contextTagNum() == INVOKE_I_D_ID) { + } else if (element.contextTagNum() == INVOKE_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); invokeID = castingValue.value(Long.class); @@ -801,7 +801,7 @@ public static class OtaSoftwareUpdateRequestorClusterVersionAppliedEvent { public Long softwareVersion; public Integer productID; private static final long SOFTWARE_VERSION_ID = 0L; - private static final long PRODUCT_I_D_ID = 1L; + private static final long PRODUCT_ID_ID = 1L; public OtaSoftwareUpdateRequestorClusterVersionAppliedEvent( Long softwareVersion, @@ -814,7 +814,7 @@ public OtaSoftwareUpdateRequestorClusterVersionAppliedEvent( public StructType encodeTlv() { ArrayList values = new ArrayList<>(); values.add(new StructElement(SOFTWARE_VERSION_ID, new UIntType(softwareVersion))); - values.add(new StructElement(PRODUCT_I_D_ID, new UIntType(productID))); + values.add(new StructElement(PRODUCT_ID_ID, new UIntType(productID))); return new StructType(values); } @@ -831,7 +831,7 @@ public static OtaSoftwareUpdateRequestorClusterVersionAppliedEvent decodeTlv(Bas UIntType castingValue = element.value(UIntType.class); softwareVersion = castingValue.value(Long.class); } - } else if (element.contextTagNum() == PRODUCT_I_D_ID) { + } else if (element.contextTagNum() == PRODUCT_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); productID = castingValue.value(Integer.class); @@ -1727,7 +1727,7 @@ public String toString() { } public static class TimeSynchronizationClusterDSTStatusEvent { public Boolean DSTOffsetActive; - private static final long D_S_T_OFFSET_ACTIVE_ID = 0L; + private static final long DST_OFFSET_ACTIVE_ID = 0L; public TimeSynchronizationClusterDSTStatusEvent( Boolean DSTOffsetActive @@ -1737,7 +1737,7 @@ public TimeSynchronizationClusterDSTStatusEvent( public StructType encodeTlv() { ArrayList values = new ArrayList<>(); - values.add(new StructElement(D_S_T_OFFSET_ACTIVE_ID, new BooleanType(DSTOffsetActive))); + values.add(new StructElement(DST_OFFSET_ACTIVE_ID, new BooleanType(DSTOffsetActive))); return new StructType(values); } @@ -1748,7 +1748,7 @@ public static TimeSynchronizationClusterDSTStatusEvent decodeTlv(BaseTLVType tlv } Boolean DSTOffsetActive = null; for (StructElement element: ((StructType)tlvValue).value()) { - if (element.contextTagNum() == D_S_T_OFFSET_ACTIVE_ID) { + if (element.contextTagNum() == DST_OFFSET_ACTIVE_ID) { if (element.value(BaseTLVType.class).type() == TLVType.Boolean) { BooleanType castingValue = element.value(BooleanType.class); DSTOffsetActive = castingValue.value(Boolean.class); @@ -3893,7 +3893,7 @@ public static class DemandResponseLoadControlClusterLoadControlEventStatusChange public @Nullable Optional dutyCycleControl; public @Nullable Optional powerSavingsControl; public @Nullable Optional heatingSourceControl; - private static final long EVENT_I_D_ID = 0L; + private static final long EVENT_ID_ID = 0L; private static final long TRANSITION_INDEX_ID = 1L; private static final long STATUS_ID = 2L; private static final long CRITICALITY_ID = 3L; @@ -3930,7 +3930,7 @@ public DemandResponseLoadControlClusterLoadControlEventStatusChangeEvent( public StructType encodeTlv() { ArrayList values = new ArrayList<>(); - values.add(new StructElement(EVENT_I_D_ID, new ByteArrayType(eventID))); + values.add(new StructElement(EVENT_ID_ID, new ByteArrayType(eventID))); values.add(new StructElement(TRANSITION_INDEX_ID, transitionIndex != null ? new UIntType(transitionIndex) : new NullType())); values.add(new StructElement(STATUS_ID, new UIntType(status))); values.add(new StructElement(CRITICALITY_ID, new UIntType(criticality))); @@ -3959,7 +3959,7 @@ public static DemandResponseLoadControlClusterLoadControlEventStatusChangeEvent @Nullable Optional powerSavingsControl = null; @Nullable Optional heatingSourceControl = null; for (StructElement element: ((StructType)tlvValue).value()) { - if (element.contextTagNum() == EVENT_I_D_ID) { + if (element.contextTagNum() == EVENT_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.ByteArray) { ByteArrayType castingValue = element.value(ByteArrayType.class); eventID = castingValue.value(byte[].class); @@ -4065,7 +4065,7 @@ public String toString() { } public static class MessagesClusterMessageQueuedEvent { public byte[] messageID; - private static final long MESSAGE_I_D_ID = 0L; + private static final long MESSAGE_ID_ID = 0L; public MessagesClusterMessageQueuedEvent( byte[] messageID @@ -4075,7 +4075,7 @@ public MessagesClusterMessageQueuedEvent( public StructType encodeTlv() { ArrayList values = new ArrayList<>(); - values.add(new StructElement(MESSAGE_I_D_ID, new ByteArrayType(messageID))); + values.add(new StructElement(MESSAGE_ID_ID, new ByteArrayType(messageID))); return new StructType(values); } @@ -4086,7 +4086,7 @@ public static MessagesClusterMessageQueuedEvent decodeTlv(BaseTLVType tlvValue) } byte[] messageID = null; for (StructElement element: ((StructType)tlvValue).value()) { - if (element.contextTagNum() == MESSAGE_I_D_ID) { + if (element.contextTagNum() == MESSAGE_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.ByteArray) { ByteArrayType castingValue = element.value(ByteArrayType.class); messageID = castingValue.value(byte[].class); @@ -4111,7 +4111,7 @@ public String toString() { } public static class MessagesClusterMessagePresentedEvent { public byte[] messageID; - private static final long MESSAGE_I_D_ID = 0L; + private static final long MESSAGE_ID_ID = 0L; public MessagesClusterMessagePresentedEvent( byte[] messageID @@ -4121,7 +4121,7 @@ public MessagesClusterMessagePresentedEvent( public StructType encodeTlv() { ArrayList values = new ArrayList<>(); - values.add(new StructElement(MESSAGE_I_D_ID, new ByteArrayType(messageID))); + values.add(new StructElement(MESSAGE_ID_ID, new ByteArrayType(messageID))); return new StructType(values); } @@ -4132,7 +4132,7 @@ public static MessagesClusterMessagePresentedEvent decodeTlv(BaseTLVType tlvValu } byte[] messageID = null; for (StructElement element: ((StructType)tlvValue).value()) { - if (element.contextTagNum() == MESSAGE_I_D_ID) { + if (element.contextTagNum() == MESSAGE_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.ByteArray) { ByteArrayType castingValue = element.value(ByteArrayType.class); messageID = castingValue.value(byte[].class); @@ -4160,8 +4160,8 @@ public static class MessagesClusterMessageCompleteEvent { public @Nullable Optional responseID; public @Nullable Optional reply; public @Nullable Integer futureMessagesPreference; - private static final long MESSAGE_I_D_ID = 0L; - private static final long RESPONSE_I_D_ID = 1L; + private static final long MESSAGE_ID_ID = 0L; + private static final long RESPONSE_ID_ID = 1L; private static final long REPLY_ID = 2L; private static final long FUTURE_MESSAGES_PREFERENCE_ID = 3L; @@ -4179,8 +4179,8 @@ public MessagesClusterMessageCompleteEvent( public StructType encodeTlv() { ArrayList values = new ArrayList<>(); - values.add(new StructElement(MESSAGE_I_D_ID, new ByteArrayType(messageID))); - values.add(new StructElement(RESPONSE_I_D_ID, responseID != null ? responseID.map((nonOptionalresponseID) -> new UIntType(nonOptionalresponseID)).orElse(new EmptyType()) : new NullType())); + values.add(new StructElement(MESSAGE_ID_ID, new ByteArrayType(messageID))); + values.add(new StructElement(RESPONSE_ID_ID, responseID != null ? responseID.map((nonOptionalresponseID) -> new UIntType(nonOptionalresponseID)).orElse(new EmptyType()) : new NullType())); values.add(new StructElement(REPLY_ID, reply != null ? reply.map((nonOptionalreply) -> new StringType(nonOptionalreply)).orElse(new EmptyType()) : new NullType())); values.add(new StructElement(FUTURE_MESSAGES_PREFERENCE_ID, futureMessagesPreference != null ? new UIntType(futureMessagesPreference) : new NullType())); @@ -4196,12 +4196,12 @@ public static MessagesClusterMessageCompleteEvent decodeTlv(BaseTLVType tlvValue @Nullable Optional reply = null; @Nullable Integer futureMessagesPreference = null; for (StructElement element: ((StructType)tlvValue).value()) { - if (element.contextTagNum() == MESSAGE_I_D_ID) { + if (element.contextTagNum() == MESSAGE_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.ByteArray) { ByteArrayType castingValue = element.value(ByteArrayType.class); messageID = castingValue.value(byte[].class); } - } else if (element.contextTagNum() == RESPONSE_I_D_ID) { + } else if (element.contextTagNum() == RESPONSE_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); responseID = Optional.of(castingValue.value(Long.class)); @@ -4426,7 +4426,7 @@ public String toString() { } public static class EnergyEvseClusterEVConnectedEvent { public Long sessionID; - private static final long SESSION_I_D_ID = 0L; + private static final long SESSION_ID_ID = 0L; public EnergyEvseClusterEVConnectedEvent( Long sessionID @@ -4436,7 +4436,7 @@ public EnergyEvseClusterEVConnectedEvent( public StructType encodeTlv() { ArrayList values = new ArrayList<>(); - values.add(new StructElement(SESSION_I_D_ID, new UIntType(sessionID))); + values.add(new StructElement(SESSION_ID_ID, new UIntType(sessionID))); return new StructType(values); } @@ -4447,7 +4447,7 @@ public static EnergyEvseClusterEVConnectedEvent decodeTlv(BaseTLVType tlvValue) } Long sessionID = null; for (StructElement element: ((StructType)tlvValue).value()) { - if (element.contextTagNum() == SESSION_I_D_ID) { + if (element.contextTagNum() == SESSION_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); sessionID = castingValue.value(Long.class); @@ -4476,7 +4476,7 @@ public static class EnergyEvseClusterEVNotDetectedEvent { public Long sessionDuration; public Long sessionEnergyCharged; public Optional sessionEnergyDischarged; - private static final long SESSION_I_D_ID = 0L; + private static final long SESSION_ID_ID = 0L; private static final long STATE_ID = 1L; private static final long SESSION_DURATION_ID = 2L; private static final long SESSION_ENERGY_CHARGED_ID = 3L; @@ -4498,7 +4498,7 @@ public EnergyEvseClusterEVNotDetectedEvent( public StructType encodeTlv() { ArrayList values = new ArrayList<>(); - values.add(new StructElement(SESSION_I_D_ID, new UIntType(sessionID))); + values.add(new StructElement(SESSION_ID_ID, new UIntType(sessionID))); values.add(new StructElement(STATE_ID, new UIntType(state))); values.add(new StructElement(SESSION_DURATION_ID, new UIntType(sessionDuration))); values.add(new StructElement(SESSION_ENERGY_CHARGED_ID, new IntType(sessionEnergyCharged))); @@ -4517,7 +4517,7 @@ public static EnergyEvseClusterEVNotDetectedEvent decodeTlv(BaseTLVType tlvValue Long sessionEnergyCharged = null; Optional sessionEnergyDischarged = Optional.empty(); for (StructElement element: ((StructType)tlvValue).value()) { - if (element.contextTagNum() == SESSION_I_D_ID) { + if (element.contextTagNum() == SESSION_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); sessionID = castingValue.value(Long.class); @@ -4581,7 +4581,7 @@ public static class EnergyEvseClusterEnergyTransferStartedEvent { public Integer state; public Long maximumCurrent; public Optional maximumDischargeCurrent; - private static final long SESSION_I_D_ID = 0L; + private static final long SESSION_ID_ID = 0L; private static final long STATE_ID = 1L; private static final long MAXIMUM_CURRENT_ID = 2L; private static final long MAXIMUM_DISCHARGE_CURRENT_ID = 3L; @@ -4600,7 +4600,7 @@ public EnergyEvseClusterEnergyTransferStartedEvent( public StructType encodeTlv() { ArrayList values = new ArrayList<>(); - values.add(new StructElement(SESSION_I_D_ID, new UIntType(sessionID))); + values.add(new StructElement(SESSION_ID_ID, new UIntType(sessionID))); values.add(new StructElement(STATE_ID, new UIntType(state))); values.add(new StructElement(MAXIMUM_CURRENT_ID, new IntType(maximumCurrent))); values.add(new StructElement(MAXIMUM_DISCHARGE_CURRENT_ID, maximumDischargeCurrent.map((nonOptionalmaximumDischargeCurrent) -> new IntType(nonOptionalmaximumDischargeCurrent)).orElse(new EmptyType()))); @@ -4617,7 +4617,7 @@ public static EnergyEvseClusterEnergyTransferStartedEvent decodeTlv(BaseTLVType Long maximumCurrent = null; Optional maximumDischargeCurrent = Optional.empty(); for (StructElement element: ((StructType)tlvValue).value()) { - if (element.contextTagNum() == SESSION_I_D_ID) { + if (element.contextTagNum() == SESSION_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); sessionID = castingValue.value(Long.class); @@ -4673,7 +4673,7 @@ public static class EnergyEvseClusterEnergyTransferStoppedEvent { public Integer reason; public Long energyTransferred; public Optional energyDischarged; - private static final long SESSION_I_D_ID = 0L; + private static final long SESSION_ID_ID = 0L; private static final long STATE_ID = 1L; private static final long REASON_ID = 2L; private static final long ENERGY_TRANSFERRED_ID = 4L; @@ -4695,7 +4695,7 @@ public EnergyEvseClusterEnergyTransferStoppedEvent( public StructType encodeTlv() { ArrayList values = new ArrayList<>(); - values.add(new StructElement(SESSION_I_D_ID, new UIntType(sessionID))); + values.add(new StructElement(SESSION_ID_ID, new UIntType(sessionID))); values.add(new StructElement(STATE_ID, new UIntType(state))); values.add(new StructElement(REASON_ID, new UIntType(reason))); values.add(new StructElement(ENERGY_TRANSFERRED_ID, new IntType(energyTransferred))); @@ -4714,7 +4714,7 @@ public static EnergyEvseClusterEnergyTransferStoppedEvent decodeTlv(BaseTLVType Long energyTransferred = null; Optional energyDischarged = Optional.empty(); for (StructElement element: ((StructType)tlvValue).value()) { - if (element.contextTagNum() == SESSION_I_D_ID) { + if (element.contextTagNum() == SESSION_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); sessionID = castingValue.value(Long.class); @@ -4778,7 +4778,7 @@ public static class EnergyEvseClusterFaultEvent { public Integer state; public Integer faultStatePreviousState; public Integer faultStateCurrentState; - private static final long SESSION_I_D_ID = 0L; + private static final long SESSION_ID_ID = 0L; private static final long STATE_ID = 1L; private static final long FAULT_STATE_PREVIOUS_STATE_ID = 2L; private static final long FAULT_STATE_CURRENT_STATE_ID = 4L; @@ -4797,7 +4797,7 @@ public EnergyEvseClusterFaultEvent( public StructType encodeTlv() { ArrayList values = new ArrayList<>(); - values.add(new StructElement(SESSION_I_D_ID, sessionID != null ? new UIntType(sessionID) : new NullType())); + values.add(new StructElement(SESSION_ID_ID, sessionID != null ? new UIntType(sessionID) : new NullType())); values.add(new StructElement(STATE_ID, new UIntType(state))); values.add(new StructElement(FAULT_STATE_PREVIOUS_STATE_ID, new UIntType(faultStatePreviousState))); values.add(new StructElement(FAULT_STATE_CURRENT_STATE_ID, new UIntType(faultStateCurrentState))); @@ -4814,7 +4814,7 @@ public static EnergyEvseClusterFaultEvent decodeTlv(BaseTLVType tlvValue) { Integer faultStatePreviousState = null; Integer faultStateCurrentState = null; for (StructElement element: ((StructType)tlvValue).value()) { - if (element.contextTagNum() == SESSION_I_D_ID) { + if (element.contextTagNum() == SESSION_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); sessionID = castingValue.value(Long.class); diff --git a/src/controller/java/generated/java/chip/devicecontroller/ChipStructs.java b/src/controller/java/generated/java/chip/devicecontroller/ChipStructs.java index 2871071475..70e9ba6b1c 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/ChipStructs.java +++ b/src/controller/java/generated/java/chip/devicecontroller/ChipStructs.java @@ -91,7 +91,7 @@ public static class DescriptorClusterSemanticTagStruct { public Integer tag; public @Nullable Optional label; private static final long MFG_CODE_ID = 0L; - private static final long NAMESPACE_I_D_ID = 1L; + private static final long NAMESPACE_ID_ID = 1L; private static final long TAG_ID = 2L; private static final long LABEL_ID = 3L; @@ -110,7 +110,7 @@ public DescriptorClusterSemanticTagStruct( public StructType encodeTlv() { ArrayList values = new ArrayList<>(); values.add(new StructElement(MFG_CODE_ID, mfgCode != null ? new UIntType(mfgCode) : new NullType())); - values.add(new StructElement(NAMESPACE_I_D_ID, new UIntType(namespaceID))); + values.add(new StructElement(NAMESPACE_ID_ID, new UIntType(namespaceID))); values.add(new StructElement(TAG_ID, new UIntType(tag))); values.add(new StructElement(LABEL_ID, label != null ? label.map((nonOptionallabel) -> new StringType(nonOptionallabel)).orElse(new EmptyType()) : new NullType())); @@ -131,7 +131,7 @@ public static DescriptorClusterSemanticTagStruct decodeTlv(BaseTLVType tlvValue) UIntType castingValue = element.value(UIntType.class); mfgCode = castingValue.value(Integer.class); } - } else if (element.contextTagNum() == NAMESPACE_I_D_ID) { + } else if (element.contextTagNum() == NAMESPACE_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); namespaceID = castingValue.value(Integer.class); @@ -760,10 +760,10 @@ public static class ActionsClusterActionStruct { public Integer endpointListID; public Integer supportedCommands; public Integer state; - private static final long ACTION_I_D_ID = 0L; + private static final long ACTION_ID_ID = 0L; private static final long NAME_ID = 1L; private static final long TYPE_ID = 2L; - private static final long ENDPOINT_LIST_I_D_ID = 3L; + private static final long ENDPOINT_LIST_ID_ID = 3L; private static final long SUPPORTED_COMMANDS_ID = 4L; private static final long STATE_ID = 5L; @@ -785,10 +785,10 @@ public ActionsClusterActionStruct( public StructType encodeTlv() { ArrayList values = new ArrayList<>(); - values.add(new StructElement(ACTION_I_D_ID, new UIntType(actionID))); + values.add(new StructElement(ACTION_ID_ID, new UIntType(actionID))); values.add(new StructElement(NAME_ID, new StringType(name))); values.add(new StructElement(TYPE_ID, new UIntType(type))); - values.add(new StructElement(ENDPOINT_LIST_I_D_ID, new UIntType(endpointListID))); + values.add(new StructElement(ENDPOINT_LIST_ID_ID, new UIntType(endpointListID))); values.add(new StructElement(SUPPORTED_COMMANDS_ID, new UIntType(supportedCommands))); values.add(new StructElement(STATE_ID, new UIntType(state))); @@ -806,7 +806,7 @@ public static ActionsClusterActionStruct decodeTlv(BaseTLVType tlvValue) { Integer supportedCommands = null; Integer state = null; for (StructElement element: ((StructType)tlvValue).value()) { - if (element.contextTagNum() == ACTION_I_D_ID) { + if (element.contextTagNum() == ACTION_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); actionID = castingValue.value(Integer.class); @@ -821,7 +821,7 @@ public static ActionsClusterActionStruct decodeTlv(BaseTLVType tlvValue) { UIntType castingValue = element.value(UIntType.class); type = castingValue.value(Integer.class); } - } else if (element.contextTagNum() == ENDPOINT_LIST_I_D_ID) { + } else if (element.contextTagNum() == ENDPOINT_LIST_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); endpointListID = castingValue.value(Integer.class); @@ -879,7 +879,7 @@ public static class ActionsClusterEndpointListStruct { public String name; public Integer type; public ArrayList endpoints; - private static final long ENDPOINT_LIST_I_D_ID = 0L; + private static final long ENDPOINT_LIST_ID_ID = 0L; private static final long NAME_ID = 1L; private static final long TYPE_ID = 2L; private static final long ENDPOINTS_ID = 3L; @@ -898,7 +898,7 @@ public ActionsClusterEndpointListStruct( public StructType encodeTlv() { ArrayList values = new ArrayList<>(); - values.add(new StructElement(ENDPOINT_LIST_I_D_ID, new UIntType(endpointListID))); + values.add(new StructElement(ENDPOINT_LIST_ID_ID, new UIntType(endpointListID))); values.add(new StructElement(NAME_ID, new StringType(name))); values.add(new StructElement(TYPE_ID, new UIntType(type))); values.add(new StructElement(ENDPOINTS_ID, ArrayType.generateArrayType(endpoints, (elementendpoints) -> new UIntType(elementendpoints)))); @@ -915,7 +915,7 @@ public static ActionsClusterEndpointListStruct decodeTlv(BaseTLVType tlvValue) { Integer type = null; ArrayList endpoints = null; for (StructElement element: ((StructType)tlvValue).value()) { - if (element.contextTagNum() == ENDPOINT_LIST_I_D_ID) { + if (element.contextTagNum() == ENDPOINT_LIST_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); endpointListID = castingValue.value(Integer.class); @@ -1091,7 +1091,7 @@ public static class OtaSoftwareUpdateRequestorClusterProviderLocation { public Long providerNodeID; public Integer endpoint; public Integer fabricIndex; - private static final long PROVIDER_NODE_I_D_ID = 1L; + private static final long PROVIDER_NODE_ID_ID = 1L; private static final long ENDPOINT_ID = 2L; private static final long FABRIC_INDEX_ID = 254L; @@ -1107,7 +1107,7 @@ public OtaSoftwareUpdateRequestorClusterProviderLocation( public StructType encodeTlv() { ArrayList values = new ArrayList<>(); - values.add(new StructElement(PROVIDER_NODE_I_D_ID, new UIntType(providerNodeID))); + values.add(new StructElement(PROVIDER_NODE_ID_ID, new UIntType(providerNodeID))); values.add(new StructElement(ENDPOINT_ID, new UIntType(endpoint))); values.add(new StructElement(FABRIC_INDEX_ID, new UIntType(fabricIndex))); @@ -1122,7 +1122,7 @@ public static OtaSoftwareUpdateRequestorClusterProviderLocation decodeTlv(BaseTL Integer endpoint = null; Integer fabricIndex = null; for (StructElement element: ((StructType)tlvValue).value()) { - if (element.contextTagNum() == PROVIDER_NODE_I_D_ID) { + if (element.contextTagNum() == PROVIDER_NODE_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); providerNodeID = castingValue.value(Long.class); @@ -1412,7 +1412,7 @@ public static class NetworkCommissioningClusterNetworkInfoStruct { public Boolean connected; public @Nullable Optional networkIdentifier; public @Nullable Optional clientIdentifier; - private static final long NETWORK_I_D_ID = 0L; + private static final long NETWORK_ID_ID = 0L; private static final long CONNECTED_ID = 1L; private static final long NETWORK_IDENTIFIER_ID = 2L; private static final long CLIENT_IDENTIFIER_ID = 3L; @@ -1431,7 +1431,7 @@ public NetworkCommissioningClusterNetworkInfoStruct( public StructType encodeTlv() { ArrayList values = new ArrayList<>(); - values.add(new StructElement(NETWORK_I_D_ID, new ByteArrayType(networkID))); + values.add(new StructElement(NETWORK_ID_ID, new ByteArrayType(networkID))); values.add(new StructElement(CONNECTED_ID, new BooleanType(connected))); values.add(new StructElement(NETWORK_IDENTIFIER_ID, networkIdentifier != null ? networkIdentifier.map((nonOptionalnetworkIdentifier) -> new ByteArrayType(nonOptionalnetworkIdentifier)).orElse(new EmptyType()) : new NullType())); values.add(new StructElement(CLIENT_IDENTIFIER_ID, clientIdentifier != null ? clientIdentifier.map((nonOptionalclientIdentifier) -> new ByteArrayType(nonOptionalclientIdentifier)).orElse(new EmptyType()) : new NullType())); @@ -1448,7 +1448,7 @@ public static NetworkCommissioningClusterNetworkInfoStruct decodeTlv(BaseTLVType @Nullable Optional networkIdentifier = null; @Nullable Optional clientIdentifier = null; for (StructElement element: ((StructType)tlvValue).value()) { - if (element.contextTagNum() == NETWORK_I_D_ID) { + if (element.contextTagNum() == NETWORK_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.ByteArray) { ByteArrayType castingValue = element.value(ByteArrayType.class); networkID = castingValue.value(byte[].class); @@ -2495,8 +2495,8 @@ public static class ThreadNetworkDiagnosticsClusterRouteTableStruct { private static final long ROUTER_ID_ID = 2L; private static final long NEXT_HOP_ID = 3L; private static final long PATH_COST_ID = 4L; - private static final long L_Q_I_IN_ID = 5L; - private static final long L_Q_I_OUT_ID = 6L; + private static final long LQI_IN_ID = 5L; + private static final long LQI_OUT_ID = 6L; private static final long AGE_ID = 7L; private static final long ALLOCATED_ID = 8L; private static final long LINK_ESTABLISHED_ID = 9L; @@ -2532,8 +2532,8 @@ public StructType encodeTlv() { values.add(new StructElement(ROUTER_ID_ID, new UIntType(routerId))); values.add(new StructElement(NEXT_HOP_ID, new UIntType(nextHop))); values.add(new StructElement(PATH_COST_ID, new UIntType(pathCost))); - values.add(new StructElement(L_Q_I_IN_ID, new UIntType(LQIIn))); - values.add(new StructElement(L_Q_I_OUT_ID, new UIntType(LQIOut))); + values.add(new StructElement(LQI_IN_ID, new UIntType(LQIIn))); + values.add(new StructElement(LQI_OUT_ID, new UIntType(LQIOut))); values.add(new StructElement(AGE_ID, new UIntType(age))); values.add(new StructElement(ALLOCATED_ID, new BooleanType(allocated))); values.add(new StructElement(LINK_ESTABLISHED_ID, new BooleanType(linkEstablished))); @@ -2581,12 +2581,12 @@ public static ThreadNetworkDiagnosticsClusterRouteTableStruct decodeTlv(BaseTLVT UIntType castingValue = element.value(UIntType.class); pathCost = castingValue.value(Integer.class); } - } else if (element.contextTagNum() == L_Q_I_IN_ID) { + } else if (element.contextTagNum() == LQI_IN_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); LQIIn = castingValue.value(Integer.class); } - } else if (element.contextTagNum() == L_Q_I_OUT_ID) { + } else if (element.contextTagNum() == LQI_OUT_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); LQIOut = castingValue.value(Integer.class); @@ -2800,7 +2800,7 @@ public String toString() { public static class TimeSynchronizationClusterFabricScopedTrustedTimeSourceStruct { public Long nodeID; public Integer endpoint; - private static final long NODE_I_D_ID = 0L; + private static final long NODE_ID_ID = 0L; private static final long ENDPOINT_ID = 1L; public TimeSynchronizationClusterFabricScopedTrustedTimeSourceStruct( @@ -2813,7 +2813,7 @@ public TimeSynchronizationClusterFabricScopedTrustedTimeSourceStruct( public StructType encodeTlv() { ArrayList values = new ArrayList<>(); - values.add(new StructElement(NODE_I_D_ID, new UIntType(nodeID))); + values.add(new StructElement(NODE_ID_ID, new UIntType(nodeID))); values.add(new StructElement(ENDPOINT_ID, new UIntType(endpoint))); return new StructType(values); @@ -2826,7 +2826,7 @@ public static TimeSynchronizationClusterFabricScopedTrustedTimeSourceStruct deco Long nodeID = null; Integer endpoint = null; for (StructElement element: ((StructType)tlvValue).value()) { - if (element.contextTagNum() == NODE_I_D_ID) { + if (element.contextTagNum() == NODE_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); nodeID = castingValue.value(Long.class); @@ -2939,7 +2939,7 @@ public static class TimeSynchronizationClusterTrustedTimeSourceStruct { public Long nodeID; public Integer endpoint; private static final long FABRIC_INDEX_ID = 0L; - private static final long NODE_I_D_ID = 1L; + private static final long NODE_ID_ID = 1L; private static final long ENDPOINT_ID = 2L; public TimeSynchronizationClusterTrustedTimeSourceStruct( @@ -2955,7 +2955,7 @@ public TimeSynchronizationClusterTrustedTimeSourceStruct( public StructType encodeTlv() { ArrayList values = new ArrayList<>(); values.add(new StructElement(FABRIC_INDEX_ID, new UIntType(fabricIndex))); - values.add(new StructElement(NODE_I_D_ID, new UIntType(nodeID))); + values.add(new StructElement(NODE_ID_ID, new UIntType(nodeID))); values.add(new StructElement(ENDPOINT_ID, new UIntType(endpoint))); return new StructType(values); @@ -2974,7 +2974,7 @@ public static TimeSynchronizationClusterTrustedTimeSourceStruct decodeTlv(BaseTL UIntType castingValue = element.value(UIntType.class); fabricIndex = castingValue.value(Integer.class); } - } else if (element.contextTagNum() == NODE_I_D_ID) { + } else if (element.contextTagNum() == NODE_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); nodeID = castingValue.value(Long.class); @@ -3079,9 +3079,9 @@ public static class OperationalCredentialsClusterFabricDescriptorStruct { public String label; public Integer fabricIndex; private static final long ROOT_PUBLIC_KEY_ID = 1L; - private static final long VENDOR_I_D_ID = 2L; - private static final long FABRIC_I_D_ID = 3L; - private static final long NODE_I_D_ID = 4L; + private static final long VENDOR_ID_ID = 2L; + private static final long FABRIC_ID_ID = 3L; + private static final long NODE_ID_ID = 4L; private static final long LABEL_ID = 5L; private static final long FABRIC_INDEX_ID = 254L; @@ -3104,9 +3104,9 @@ public OperationalCredentialsClusterFabricDescriptorStruct( public StructType encodeTlv() { ArrayList values = new ArrayList<>(); values.add(new StructElement(ROOT_PUBLIC_KEY_ID, new ByteArrayType(rootPublicKey))); - values.add(new StructElement(VENDOR_I_D_ID, new UIntType(vendorID))); - values.add(new StructElement(FABRIC_I_D_ID, new UIntType(fabricID))); - values.add(new StructElement(NODE_I_D_ID, new UIntType(nodeID))); + values.add(new StructElement(VENDOR_ID_ID, new UIntType(vendorID))); + values.add(new StructElement(FABRIC_ID_ID, new UIntType(fabricID))); + values.add(new StructElement(NODE_ID_ID, new UIntType(nodeID))); values.add(new StructElement(LABEL_ID, new StringType(label))); values.add(new StructElement(FABRIC_INDEX_ID, new UIntType(fabricIndex))); @@ -3129,17 +3129,17 @@ public static OperationalCredentialsClusterFabricDescriptorStruct decodeTlv(Base ByteArrayType castingValue = element.value(ByteArrayType.class); rootPublicKey = castingValue.value(byte[].class); } - } else if (element.contextTagNum() == VENDOR_I_D_ID) { + } else if (element.contextTagNum() == VENDOR_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); vendorID = castingValue.value(Integer.class); } - } else if (element.contextTagNum() == FABRIC_I_D_ID) { + } else if (element.contextTagNum() == FABRIC_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); fabricID = castingValue.value(Long.class); } - } else if (element.contextTagNum() == NODE_I_D_ID) { + } else if (element.contextTagNum() == NODE_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); nodeID = castingValue.value(Long.class); @@ -3364,7 +3364,7 @@ public static class GroupKeyManagementClusterGroupKeyMapStruct { public Integer groupKeySetID; public Integer fabricIndex; private static final long GROUP_ID_ID = 1L; - private static final long GROUP_KEY_SET_I_D_ID = 2L; + private static final long GROUP_KEY_SET_ID_ID = 2L; private static final long FABRIC_INDEX_ID = 254L; public GroupKeyManagementClusterGroupKeyMapStruct( @@ -3380,7 +3380,7 @@ public GroupKeyManagementClusterGroupKeyMapStruct( public StructType encodeTlv() { ArrayList values = new ArrayList<>(); values.add(new StructElement(GROUP_ID_ID, new UIntType(groupId))); - values.add(new StructElement(GROUP_KEY_SET_I_D_ID, new UIntType(groupKeySetID))); + values.add(new StructElement(GROUP_KEY_SET_ID_ID, new UIntType(groupKeySetID))); values.add(new StructElement(FABRIC_INDEX_ID, new UIntType(fabricIndex))); return new StructType(values); @@ -3399,7 +3399,7 @@ public static GroupKeyManagementClusterGroupKeyMapStruct decodeTlv(BaseTLVType t UIntType castingValue = element.value(UIntType.class); groupId = castingValue.value(Integer.class); } - } else if (element.contextTagNum() == GROUP_KEY_SET_I_D_ID) { + } else if (element.contextTagNum() == GROUP_KEY_SET_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); groupKeySetID = castingValue.value(Integer.class); @@ -3444,7 +3444,7 @@ public static class GroupKeyManagementClusterGroupKeySetStruct { public @Nullable Long epochStartTime1; public @Nullable byte[] epochKey2; public @Nullable Long epochStartTime2; - private static final long GROUP_KEY_SET_I_D_ID = 0L; + private static final long GROUP_KEY_SET_ID_ID = 0L; private static final long GROUP_KEY_SECURITY_POLICY_ID = 1L; private static final long EPOCH_KEY0_ID = 2L; private static final long EPOCH_START_TIME0_ID = 3L; @@ -3475,7 +3475,7 @@ public GroupKeyManagementClusterGroupKeySetStruct( public StructType encodeTlv() { ArrayList values = new ArrayList<>(); - values.add(new StructElement(GROUP_KEY_SET_I_D_ID, new UIntType(groupKeySetID))); + values.add(new StructElement(GROUP_KEY_SET_ID_ID, new UIntType(groupKeySetID))); values.add(new StructElement(GROUP_KEY_SECURITY_POLICY_ID, new UIntType(groupKeySecurityPolicy))); values.add(new StructElement(EPOCH_KEY0_ID, epochKey0 != null ? new ByteArrayType(epochKey0) : new NullType())); values.add(new StructElement(EPOCH_START_TIME0_ID, epochStartTime0 != null ? new UIntType(epochStartTime0) : new NullType())); @@ -3500,7 +3500,7 @@ public static GroupKeyManagementClusterGroupKeySetStruct decodeTlv(BaseTLVType t @Nullable byte[] epochKey2 = null; @Nullable Long epochStartTime2 = null; for (StructElement element: ((StructType)tlvValue).value()) { - if (element.contextTagNum() == GROUP_KEY_SET_I_D_ID) { + if (element.contextTagNum() == GROUP_KEY_SET_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); groupKeySetID = castingValue.value(Integer.class); @@ -3713,7 +3713,7 @@ public static class IcdManagementClusterMonitoringRegistrationStruct { public Long monitoredSubject; public Integer clientType; public Integer fabricIndex; - private static final long CHECK_IN_NODE_I_D_ID = 1L; + private static final long CHECK_IN_NODE_ID_ID = 1L; private static final long MONITORED_SUBJECT_ID = 2L; private static final long CLIENT_TYPE_ID = 4L; private static final long FABRIC_INDEX_ID = 254L; @@ -3732,7 +3732,7 @@ public IcdManagementClusterMonitoringRegistrationStruct( public StructType encodeTlv() { ArrayList values = new ArrayList<>(); - values.add(new StructElement(CHECK_IN_NODE_I_D_ID, new UIntType(checkInNodeID))); + values.add(new StructElement(CHECK_IN_NODE_ID_ID, new UIntType(checkInNodeID))); values.add(new StructElement(MONITORED_SUBJECT_ID, new UIntType(monitoredSubject))); values.add(new StructElement(CLIENT_TYPE_ID, new UIntType(clientType))); values.add(new StructElement(FABRIC_INDEX_ID, new UIntType(fabricIndex))); @@ -3749,7 +3749,7 @@ public static IcdManagementClusterMonitoringRegistrationStruct decodeTlv(BaseTLV Integer clientType = null; Integer fabricIndex = null; for (StructElement element: ((StructType)tlvValue).value()) { - if (element.contextTagNum() == CHECK_IN_NODE_I_D_ID) { + if (element.contextTagNum() == CHECK_IN_NODE_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); checkInNodeID = castingValue.value(Long.class); @@ -3803,7 +3803,7 @@ public static class OvenCavityOperationalStateClusterErrorStateStruct { public Integer errorStateID; public Optional errorStateLabel; public Optional errorStateDetails; - private static final long ERROR_STATE_I_D_ID = 0L; + private static final long ERROR_STATE_ID_ID = 0L; private static final long ERROR_STATE_LABEL_ID = 1L; private static final long ERROR_STATE_DETAILS_ID = 2L; @@ -3819,7 +3819,7 @@ public OvenCavityOperationalStateClusterErrorStateStruct( public StructType encodeTlv() { ArrayList values = new ArrayList<>(); - values.add(new StructElement(ERROR_STATE_I_D_ID, new UIntType(errorStateID))); + values.add(new StructElement(ERROR_STATE_ID_ID, new UIntType(errorStateID))); values.add(new StructElement(ERROR_STATE_LABEL_ID, errorStateLabel.map((nonOptionalerrorStateLabel) -> new StringType(nonOptionalerrorStateLabel)).orElse(new EmptyType()))); values.add(new StructElement(ERROR_STATE_DETAILS_ID, errorStateDetails.map((nonOptionalerrorStateDetails) -> new StringType(nonOptionalerrorStateDetails)).orElse(new EmptyType()))); @@ -3834,7 +3834,7 @@ public static OvenCavityOperationalStateClusterErrorStateStruct decodeTlv(BaseTL Optional errorStateLabel = Optional.empty(); Optional errorStateDetails = Optional.empty(); for (StructElement element: ((StructType)tlvValue).value()) { - if (element.contextTagNum() == ERROR_STATE_I_D_ID) { + if (element.contextTagNum() == ERROR_STATE_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); errorStateID = castingValue.value(Integer.class); @@ -3878,7 +3878,7 @@ public String toString() { public static class OvenCavityOperationalStateClusterOperationalStateStruct { public Integer operationalStateID; public Optional operationalStateLabel; - private static final long OPERATIONAL_STATE_I_D_ID = 0L; + private static final long OPERATIONAL_STATE_ID_ID = 0L; private static final long OPERATIONAL_STATE_LABEL_ID = 1L; public OvenCavityOperationalStateClusterOperationalStateStruct( @@ -3891,7 +3891,7 @@ public OvenCavityOperationalStateClusterOperationalStateStruct( public StructType encodeTlv() { ArrayList values = new ArrayList<>(); - values.add(new StructElement(OPERATIONAL_STATE_I_D_ID, new UIntType(operationalStateID))); + values.add(new StructElement(OPERATIONAL_STATE_ID_ID, new UIntType(operationalStateID))); values.add(new StructElement(OPERATIONAL_STATE_LABEL_ID, operationalStateLabel.map((nonOptionaloperationalStateLabel) -> new StringType(nonOptionaloperationalStateLabel)).orElse(new EmptyType()))); return new StructType(values); @@ -3904,7 +3904,7 @@ public static OvenCavityOperationalStateClusterOperationalStateStruct decodeTlv( Integer operationalStateID = null; Optional operationalStateLabel = Optional.empty(); for (StructElement element: ((StructType)tlvValue).value()) { - if (element.contextTagNum() == OPERATIONAL_STATE_I_D_ID) { + if (element.contextTagNum() == OPERATIONAL_STATE_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); operationalStateID = castingValue.value(Integer.class); @@ -5036,7 +5036,7 @@ public static class OperationalStateClusterErrorStateStruct { public Integer errorStateID; public Optional errorStateLabel; public Optional errorStateDetails; - private static final long ERROR_STATE_I_D_ID = 0L; + private static final long ERROR_STATE_ID_ID = 0L; private static final long ERROR_STATE_LABEL_ID = 1L; private static final long ERROR_STATE_DETAILS_ID = 2L; @@ -5052,7 +5052,7 @@ public OperationalStateClusterErrorStateStruct( public StructType encodeTlv() { ArrayList values = new ArrayList<>(); - values.add(new StructElement(ERROR_STATE_I_D_ID, new UIntType(errorStateID))); + values.add(new StructElement(ERROR_STATE_ID_ID, new UIntType(errorStateID))); values.add(new StructElement(ERROR_STATE_LABEL_ID, errorStateLabel.map((nonOptionalerrorStateLabel) -> new StringType(nonOptionalerrorStateLabel)).orElse(new EmptyType()))); values.add(new StructElement(ERROR_STATE_DETAILS_ID, errorStateDetails.map((nonOptionalerrorStateDetails) -> new StringType(nonOptionalerrorStateDetails)).orElse(new EmptyType()))); @@ -5067,7 +5067,7 @@ public static OperationalStateClusterErrorStateStruct decodeTlv(BaseTLVType tlvV Optional errorStateLabel = Optional.empty(); Optional errorStateDetails = Optional.empty(); for (StructElement element: ((StructType)tlvValue).value()) { - if (element.contextTagNum() == ERROR_STATE_I_D_ID) { + if (element.contextTagNum() == ERROR_STATE_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); errorStateID = castingValue.value(Integer.class); @@ -5111,7 +5111,7 @@ public String toString() { public static class OperationalStateClusterOperationalStateStruct { public Integer operationalStateID; public Optional operationalStateLabel; - private static final long OPERATIONAL_STATE_I_D_ID = 0L; + private static final long OPERATIONAL_STATE_ID_ID = 0L; private static final long OPERATIONAL_STATE_LABEL_ID = 1L; public OperationalStateClusterOperationalStateStruct( @@ -5124,7 +5124,7 @@ public OperationalStateClusterOperationalStateStruct( public StructType encodeTlv() { ArrayList values = new ArrayList<>(); - values.add(new StructElement(OPERATIONAL_STATE_I_D_ID, new UIntType(operationalStateID))); + values.add(new StructElement(OPERATIONAL_STATE_ID_ID, new UIntType(operationalStateID))); values.add(new StructElement(OPERATIONAL_STATE_LABEL_ID, operationalStateLabel.map((nonOptionaloperationalStateLabel) -> new StringType(nonOptionaloperationalStateLabel)).orElse(new EmptyType()))); return new StructType(values); @@ -5137,7 +5137,7 @@ public static OperationalStateClusterOperationalStateStruct decodeTlv(BaseTLVTyp Integer operationalStateID = null; Optional operationalStateLabel = Optional.empty(); for (StructElement element: ((StructType)tlvValue).value()) { - if (element.contextTagNum() == OPERATIONAL_STATE_I_D_ID) { + if (element.contextTagNum() == OPERATIONAL_STATE_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); operationalStateID = castingValue.value(Integer.class); @@ -5173,7 +5173,7 @@ public static class RvcOperationalStateClusterErrorStateStruct { public Integer errorStateID; public Optional errorStateLabel; public Optional errorStateDetails; - private static final long ERROR_STATE_I_D_ID = 0L; + private static final long ERROR_STATE_ID_ID = 0L; private static final long ERROR_STATE_LABEL_ID = 1L; private static final long ERROR_STATE_DETAILS_ID = 2L; @@ -5189,7 +5189,7 @@ public RvcOperationalStateClusterErrorStateStruct( public StructType encodeTlv() { ArrayList values = new ArrayList<>(); - values.add(new StructElement(ERROR_STATE_I_D_ID, new UIntType(errorStateID))); + values.add(new StructElement(ERROR_STATE_ID_ID, new UIntType(errorStateID))); values.add(new StructElement(ERROR_STATE_LABEL_ID, errorStateLabel.map((nonOptionalerrorStateLabel) -> new StringType(nonOptionalerrorStateLabel)).orElse(new EmptyType()))); values.add(new StructElement(ERROR_STATE_DETAILS_ID, errorStateDetails.map((nonOptionalerrorStateDetails) -> new StringType(nonOptionalerrorStateDetails)).orElse(new EmptyType()))); @@ -5204,7 +5204,7 @@ public static RvcOperationalStateClusterErrorStateStruct decodeTlv(BaseTLVType t Optional errorStateLabel = Optional.empty(); Optional errorStateDetails = Optional.empty(); for (StructElement element: ((StructType)tlvValue).value()) { - if (element.contextTagNum() == ERROR_STATE_I_D_ID) { + if (element.contextTagNum() == ERROR_STATE_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); errorStateID = castingValue.value(Integer.class); @@ -5248,7 +5248,7 @@ public String toString() { public static class RvcOperationalStateClusterOperationalStateStruct { public Integer operationalStateID; public Optional operationalStateLabel; - private static final long OPERATIONAL_STATE_I_D_ID = 0L; + private static final long OPERATIONAL_STATE_ID_ID = 0L; private static final long OPERATIONAL_STATE_LABEL_ID = 1L; public RvcOperationalStateClusterOperationalStateStruct( @@ -5261,7 +5261,7 @@ public RvcOperationalStateClusterOperationalStateStruct( public StructType encodeTlv() { ArrayList values = new ArrayList<>(); - values.add(new StructElement(OPERATIONAL_STATE_I_D_ID, new UIntType(operationalStateID))); + values.add(new StructElement(OPERATIONAL_STATE_ID_ID, new UIntType(operationalStateID))); values.add(new StructElement(OPERATIONAL_STATE_LABEL_ID, operationalStateLabel.map((nonOptionaloperationalStateLabel) -> new StringType(nonOptionaloperationalStateLabel)).orElse(new EmptyType()))); return new StructType(values); @@ -5274,7 +5274,7 @@ public static RvcOperationalStateClusterOperationalStateStruct decodeTlv(BaseTLV Integer operationalStateID = null; Optional operationalStateLabel = Optional.empty(); for (StructElement element: ((StructType)tlvValue).value()) { - if (element.contextTagNum() == OPERATIONAL_STATE_I_D_ID) { + if (element.contextTagNum() == OPERATIONAL_STATE_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); operationalStateID = castingValue.value(Integer.class); @@ -5316,7 +5316,7 @@ public static class ScenesManagementClusterAttributeValuePairStruct { public Optional valueSigned32; public Optional valueUnsigned64; public Optional valueSigned64; - private static final long ATTRIBUTE_I_D_ID = 0L; + private static final long ATTRIBUTE_ID_ID = 0L; private static final long VALUE_UNSIGNED8_ID = 1L; private static final long VALUE_SIGNED8_ID = 2L; private static final long VALUE_UNSIGNED16_ID = 3L; @@ -5350,7 +5350,7 @@ public ScenesManagementClusterAttributeValuePairStruct( public StructType encodeTlv() { ArrayList values = new ArrayList<>(); - values.add(new StructElement(ATTRIBUTE_I_D_ID, new UIntType(attributeID))); + values.add(new StructElement(ATTRIBUTE_ID_ID, new UIntType(attributeID))); values.add(new StructElement(VALUE_UNSIGNED8_ID, valueUnsigned8.map((nonOptionalvalueUnsigned8) -> new UIntType(nonOptionalvalueUnsigned8)).orElse(new EmptyType()))); values.add(new StructElement(VALUE_SIGNED8_ID, valueSigned8.map((nonOptionalvalueSigned8) -> new IntType(nonOptionalvalueSigned8)).orElse(new EmptyType()))); values.add(new StructElement(VALUE_UNSIGNED16_ID, valueUnsigned16.map((nonOptionalvalueUnsigned16) -> new UIntType(nonOptionalvalueUnsigned16)).orElse(new EmptyType()))); @@ -5377,7 +5377,7 @@ public static ScenesManagementClusterAttributeValuePairStruct decodeTlv(BaseTLVT Optional valueUnsigned64 = Optional.empty(); Optional valueSigned64 = Optional.empty(); for (StructElement element: ((StructType)tlvValue).value()) { - if (element.contextTagNum() == ATTRIBUTE_I_D_ID) { + if (element.contextTagNum() == ATTRIBUTE_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); attributeID = castingValue.value(Long.class); @@ -5475,7 +5475,7 @@ public String toString() { public static class ScenesManagementClusterExtensionFieldSet { public Long clusterID; public ArrayList attributeValueList; - private static final long CLUSTER_I_D_ID = 0L; + private static final long CLUSTER_ID_ID = 0L; private static final long ATTRIBUTE_VALUE_LIST_ID = 1L; public ScenesManagementClusterExtensionFieldSet( @@ -5488,7 +5488,7 @@ public ScenesManagementClusterExtensionFieldSet( public StructType encodeTlv() { ArrayList values = new ArrayList<>(); - values.add(new StructElement(CLUSTER_I_D_ID, new UIntType(clusterID))); + values.add(new StructElement(CLUSTER_ID_ID, new UIntType(clusterID))); values.add(new StructElement(ATTRIBUTE_VALUE_LIST_ID, ArrayType.generateArrayType(attributeValueList, (elementattributeValueList) -> elementattributeValueList.encodeTlv()))); return new StructType(values); @@ -5501,7 +5501,7 @@ public static ScenesManagementClusterExtensionFieldSet decodeTlv(BaseTLVType tlv Long clusterID = null; ArrayList attributeValueList = null; for (StructElement element: ((StructType)tlvValue).value()) { - if (element.contextTagNum() == CLUSTER_I_D_ID) { + if (element.contextTagNum() == CLUSTER_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); clusterID = castingValue.value(Long.class); @@ -7285,8 +7285,8 @@ public static class DemandResponseLoadControlClusterLoadControlEventStruct { public Integer criticality; public @Nullable Long startTime; public ArrayList transitions; - private static final long EVENT_I_D_ID = 0L; - private static final long PROGRAM_I_D_ID = 1L; + private static final long EVENT_ID_ID = 0L; + private static final long PROGRAM_ID_ID = 1L; private static final long CONTROL_ID = 2L; private static final long DEVICE_CLASS_ID = 3L; private static final long ENROLLMENT_GROUP_ID = 4L; @@ -7316,8 +7316,8 @@ public DemandResponseLoadControlClusterLoadControlEventStruct( public StructType encodeTlv() { ArrayList values = new ArrayList<>(); - values.add(new StructElement(EVENT_I_D_ID, new ByteArrayType(eventID))); - values.add(new StructElement(PROGRAM_I_D_ID, programID != null ? new ByteArrayType(programID) : new NullType())); + values.add(new StructElement(EVENT_ID_ID, new ByteArrayType(eventID))); + values.add(new StructElement(PROGRAM_ID_ID, programID != null ? new ByteArrayType(programID) : new NullType())); values.add(new StructElement(CONTROL_ID, new UIntType(control))); values.add(new StructElement(DEVICE_CLASS_ID, new UIntType(deviceClass))); values.add(new StructElement(ENROLLMENT_GROUP_ID, enrollmentGroup.map((nonOptionalenrollmentGroup) -> new UIntType(nonOptionalenrollmentGroup)).orElse(new EmptyType()))); @@ -7341,12 +7341,12 @@ public static DemandResponseLoadControlClusterLoadControlEventStruct decodeTlv(B @Nullable Long startTime = null; ArrayList transitions = null; for (StructElement element: ((StructType)tlvValue).value()) { - if (element.contextTagNum() == EVENT_I_D_ID) { + if (element.contextTagNum() == EVENT_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.ByteArray) { ByteArrayType castingValue = element.value(ByteArrayType.class); eventID = castingValue.value(byte[].class); } - } else if (element.contextTagNum() == PROGRAM_I_D_ID) { + } else if (element.contextTagNum() == PROGRAM_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.ByteArray) { ByteArrayType castingValue = element.value(ByteArrayType.class); programID = castingValue.value(byte[].class); @@ -7433,7 +7433,7 @@ public static class DemandResponseLoadControlClusterLoadControlProgramStruct { public @Nullable Integer enrollmentGroup; public @Nullable Integer randomStartMinutes; public @Nullable Integer randomDurationMinutes; - private static final long PROGRAM_I_D_ID = 0L; + private static final long PROGRAM_ID_ID = 0L; private static final long NAME_ID = 1L; private static final long ENROLLMENT_GROUP_ID = 2L; private static final long RANDOM_START_MINUTES_ID = 3L; @@ -7455,7 +7455,7 @@ public DemandResponseLoadControlClusterLoadControlProgramStruct( public StructType encodeTlv() { ArrayList values = new ArrayList<>(); - values.add(new StructElement(PROGRAM_I_D_ID, new ByteArrayType(programID))); + values.add(new StructElement(PROGRAM_ID_ID, new ByteArrayType(programID))); values.add(new StructElement(NAME_ID, new StringType(name))); values.add(new StructElement(ENROLLMENT_GROUP_ID, enrollmentGroup != null ? new UIntType(enrollmentGroup) : new NullType())); values.add(new StructElement(RANDOM_START_MINUTES_ID, randomStartMinutes != null ? new UIntType(randomStartMinutes) : new NullType())); @@ -7474,7 +7474,7 @@ public static DemandResponseLoadControlClusterLoadControlProgramStruct decodeTlv @Nullable Integer randomStartMinutes = null; @Nullable Integer randomDurationMinutes = null; for (StructElement element: ((StructType)tlvValue).value()) { - if (element.contextTagNum() == PROGRAM_I_D_ID) { + if (element.contextTagNum() == PROGRAM_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.ByteArray) { ByteArrayType castingValue = element.value(ByteArrayType.class); programID = castingValue.value(byte[].class); @@ -7536,7 +7536,7 @@ public String toString() { public static class MessagesClusterMessageResponseOptionStruct { public Optional messageResponseID; public Optional label; - private static final long MESSAGE_RESPONSE_I_D_ID = 0L; + private static final long MESSAGE_RESPONSE_ID_ID = 0L; private static final long LABEL_ID = 1L; public MessagesClusterMessageResponseOptionStruct( @@ -7549,7 +7549,7 @@ public MessagesClusterMessageResponseOptionStruct( public StructType encodeTlv() { ArrayList values = new ArrayList<>(); - values.add(new StructElement(MESSAGE_RESPONSE_I_D_ID, messageResponseID.map((nonOptionalmessageResponseID) -> new UIntType(nonOptionalmessageResponseID)).orElse(new EmptyType()))); + values.add(new StructElement(MESSAGE_RESPONSE_ID_ID, messageResponseID.map((nonOptionalmessageResponseID) -> new UIntType(nonOptionalmessageResponseID)).orElse(new EmptyType()))); values.add(new StructElement(LABEL_ID, label.map((nonOptionallabel) -> new StringType(nonOptionallabel)).orElse(new EmptyType()))); return new StructType(values); @@ -7562,7 +7562,7 @@ public static MessagesClusterMessageResponseOptionStruct decodeTlv(BaseTLVType t Optional messageResponseID = Optional.empty(); Optional label = Optional.empty(); for (StructElement element: ((StructType)tlvValue).value()) { - if (element.contextTagNum() == MESSAGE_RESPONSE_I_D_ID) { + if (element.contextTagNum() == MESSAGE_RESPONSE_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); messageResponseID = Optional.of(castingValue.value(Long.class)); @@ -7602,7 +7602,7 @@ public static class MessagesClusterMessageStruct { public @Nullable Long duration; public String messageText; public Optional> responses; - private static final long MESSAGE_I_D_ID = 0L; + private static final long MESSAGE_ID_ID = 0L; private static final long PRIORITY_ID = 1L; private static final long MESSAGE_CONTROL_ID = 2L; private static final long START_TIME_ID = 3L; @@ -7630,7 +7630,7 @@ public MessagesClusterMessageStruct( public StructType encodeTlv() { ArrayList values = new ArrayList<>(); - values.add(new StructElement(MESSAGE_I_D_ID, new ByteArrayType(messageID))); + values.add(new StructElement(MESSAGE_ID_ID, new ByteArrayType(messageID))); values.add(new StructElement(PRIORITY_ID, new UIntType(priority))); values.add(new StructElement(MESSAGE_CONTROL_ID, new UIntType(messageControl))); values.add(new StructElement(START_TIME_ID, startTime != null ? new UIntType(startTime) : new NullType())); @@ -7653,7 +7653,7 @@ public static MessagesClusterMessageStruct decodeTlv(BaseTLVType tlvValue) { String messageText = null; Optional> responses = Optional.empty(); for (StructElement element: ((StructType)tlvValue).value()) { - if (element.contextTagNum() == MESSAGE_I_D_ID) { + if (element.contextTagNum() == MESSAGE_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.ByteArray) { ByteArrayType castingValue = element.value(ByteArrayType.class); messageID = castingValue.value(byte[].class); @@ -8000,7 +8000,7 @@ public static class DeviceEnergyManagementClusterSlotStruct { private static final long SLOT_IS_PAUSABLE_ID = 5L; private static final long MIN_PAUSE_DURATION_ID = 6L; private static final long MAX_PAUSE_DURATION_ID = 7L; - private static final long MANUFACTURER_E_S_A_STATE_ID = 8L; + private static final long MANUFACTURER_ESA_STATE_ID = 8L; private static final long NOMINAL_POWER_ID = 9L; private static final long MIN_POWER_ID = 10L; private static final long MAX_POWER_ID = 11L; @@ -8061,7 +8061,7 @@ public StructType encodeTlv() { values.add(new StructElement(SLOT_IS_PAUSABLE_ID, slotIsPausable.map((nonOptionalslotIsPausable) -> new BooleanType(nonOptionalslotIsPausable)).orElse(new EmptyType()))); values.add(new StructElement(MIN_PAUSE_DURATION_ID, minPauseDuration.map((nonOptionalminPauseDuration) -> new UIntType(nonOptionalminPauseDuration)).orElse(new EmptyType()))); values.add(new StructElement(MAX_PAUSE_DURATION_ID, maxPauseDuration.map((nonOptionalmaxPauseDuration) -> new UIntType(nonOptionalmaxPauseDuration)).orElse(new EmptyType()))); - values.add(new StructElement(MANUFACTURER_E_S_A_STATE_ID, manufacturerESAState.map((nonOptionalmanufacturerESAState) -> new UIntType(nonOptionalmanufacturerESAState)).orElse(new EmptyType()))); + values.add(new StructElement(MANUFACTURER_ESA_STATE_ID, manufacturerESAState.map((nonOptionalmanufacturerESAState) -> new UIntType(nonOptionalmanufacturerESAState)).orElse(new EmptyType()))); values.add(new StructElement(NOMINAL_POWER_ID, nominalPower.map((nonOptionalnominalPower) -> new IntType(nonOptionalnominalPower)).orElse(new EmptyType()))); values.add(new StructElement(MIN_POWER_ID, minPower.map((nonOptionalminPower) -> new IntType(nonOptionalminPower)).orElse(new EmptyType()))); values.add(new StructElement(MAX_POWER_ID, maxPower.map((nonOptionalmaxPower) -> new IntType(nonOptionalmaxPower)).orElse(new EmptyType()))); @@ -8138,7 +8138,7 @@ public static DeviceEnergyManagementClusterSlotStruct decodeTlv(BaseTLVType tlvV UIntType castingValue = element.value(UIntType.class); maxPauseDuration = Optional.of(castingValue.value(Long.class)); } - } else if (element.contextTagNum() == MANUFACTURER_E_S_A_STATE_ID) { + } else if (element.contextTagNum() == MANUFACTURER_ESA_STATE_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); manufacturerESAState = Optional.of(castingValue.value(Integer.class)); @@ -8284,7 +8284,7 @@ public static class DeviceEnergyManagementClusterForecastStruct { public Boolean isPausable; public ArrayList slots; public Integer forecastUpdateReason; - private static final long FORECAST_I_D_ID = 0L; + private static final long FORECAST_ID_ID = 0L; private static final long ACTIVE_SLOT_NUMBER_ID = 1L; private static final long START_TIME_ID = 2L; private static final long END_TIME_ID = 3L; @@ -8318,7 +8318,7 @@ public DeviceEnergyManagementClusterForecastStruct( public StructType encodeTlv() { ArrayList values = new ArrayList<>(); - values.add(new StructElement(FORECAST_I_D_ID, new UIntType(forecastID))); + values.add(new StructElement(FORECAST_ID_ID, new UIntType(forecastID))); values.add(new StructElement(ACTIVE_SLOT_NUMBER_ID, activeSlotNumber != null ? new UIntType(activeSlotNumber) : new NullType())); values.add(new StructElement(START_TIME_ID, new UIntType(startTime))); values.add(new StructElement(END_TIME_ID, new UIntType(endTime))); @@ -8345,7 +8345,7 @@ public static DeviceEnergyManagementClusterForecastStruct decodeTlv(BaseTLVType ArrayList slots = null; Integer forecastUpdateReason = null; for (StructElement element: ((StructType)tlvValue).value()) { - if (element.contextTagNum() == FORECAST_I_D_ID) { + if (element.contextTagNum() == FORECAST_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); forecastID = castingValue.value(Long.class); @@ -9418,8 +9418,8 @@ public static class ServiceAreaClusterAreaStruct { public Long areaID; public @Nullable Long mapID; public ChipStructs.ServiceAreaClusterAreaInfoStruct areaDesc; - private static final long AREA_I_D_ID = 0L; - private static final long MAP_I_D_ID = 1L; + private static final long AREA_ID_ID = 0L; + private static final long MAP_ID_ID = 1L; private static final long AREA_DESC_ID = 2L; public ServiceAreaClusterAreaStruct( @@ -9434,8 +9434,8 @@ public ServiceAreaClusterAreaStruct( public StructType encodeTlv() { ArrayList values = new ArrayList<>(); - values.add(new StructElement(AREA_I_D_ID, new UIntType(areaID))); - values.add(new StructElement(MAP_I_D_ID, mapID != null ? new UIntType(mapID) : new NullType())); + values.add(new StructElement(AREA_ID_ID, new UIntType(areaID))); + values.add(new StructElement(MAP_ID_ID, mapID != null ? new UIntType(mapID) : new NullType())); values.add(new StructElement(AREA_DESC_ID, areaDesc.encodeTlv())); return new StructType(values); @@ -9449,12 +9449,12 @@ public static ServiceAreaClusterAreaStruct decodeTlv(BaseTLVType tlvValue) { @Nullable Long mapID = null; ChipStructs.ServiceAreaClusterAreaInfoStruct areaDesc = null; for (StructElement element: ((StructType)tlvValue).value()) { - if (element.contextTagNum() == AREA_I_D_ID) { + if (element.contextTagNum() == AREA_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); areaID = castingValue.value(Long.class); } - } else if (element.contextTagNum() == MAP_I_D_ID) { + } else if (element.contextTagNum() == MAP_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); mapID = castingValue.value(Long.class); @@ -9493,7 +9493,7 @@ public String toString() { public static class ServiceAreaClusterMapStruct { public Long mapID; public String name; - private static final long MAP_I_D_ID = 0L; + private static final long MAP_ID_ID = 0L; private static final long NAME_ID = 1L; public ServiceAreaClusterMapStruct( @@ -9506,7 +9506,7 @@ public ServiceAreaClusterMapStruct( public StructType encodeTlv() { ArrayList values = new ArrayList<>(); - values.add(new StructElement(MAP_I_D_ID, new UIntType(mapID))); + values.add(new StructElement(MAP_ID_ID, new UIntType(mapID))); values.add(new StructElement(NAME_ID, new StringType(name))); return new StructType(values); @@ -9519,7 +9519,7 @@ public static ServiceAreaClusterMapStruct decodeTlv(BaseTLVType tlvValue) { Long mapID = null; String name = null; for (StructElement element: ((StructType)tlvValue).value()) { - if (element.contextTagNum() == MAP_I_D_ID) { + if (element.contextTagNum() == MAP_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); mapID = castingValue.value(Long.class); @@ -9556,7 +9556,7 @@ public static class ServiceAreaClusterProgressStruct { public Integer status; public @Nullable Optional totalOperationalTime; public @Nullable Optional estimatedTime; - private static final long AREA_I_D_ID = 0L; + private static final long AREA_ID_ID = 0L; private static final long STATUS_ID = 1L; private static final long TOTAL_OPERATIONAL_TIME_ID = 2L; private static final long ESTIMATED_TIME_ID = 3L; @@ -9575,7 +9575,7 @@ public ServiceAreaClusterProgressStruct( public StructType encodeTlv() { ArrayList values = new ArrayList<>(); - values.add(new StructElement(AREA_I_D_ID, new UIntType(areaID))); + values.add(new StructElement(AREA_ID_ID, new UIntType(areaID))); values.add(new StructElement(STATUS_ID, new UIntType(status))); values.add(new StructElement(TOTAL_OPERATIONAL_TIME_ID, totalOperationalTime != null ? totalOperationalTime.map((nonOptionaltotalOperationalTime) -> new UIntType(nonOptionaltotalOperationalTime)).orElse(new EmptyType()) : new NullType())); values.add(new StructElement(ESTIMATED_TIME_ID, estimatedTime != null ? estimatedTime.map((nonOptionalestimatedTime) -> new UIntType(nonOptionalestimatedTime)).orElse(new EmptyType()) : new NullType())); @@ -9592,7 +9592,7 @@ public static ServiceAreaClusterProgressStruct decodeTlv(BaseTLVType tlvValue) { @Nullable Optional totalOperationalTime = null; @Nullable Optional estimatedTime = null; for (StructElement element: ((StructType)tlvValue).value()) { - if (element.contextTagNum() == AREA_I_D_ID) { + if (element.contextTagNum() == AREA_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); areaID = castingValue.value(Long.class); @@ -10312,7 +10312,7 @@ public String toString() { public static class ThermostatClusterAtomicAttributeStatusStruct { public Long attributeID; public Integer statusCode; - private static final long ATTRIBUTE_I_D_ID = 0L; + private static final long ATTRIBUTE_ID_ID = 0L; private static final long STATUS_CODE_ID = 1L; public ThermostatClusterAtomicAttributeStatusStruct( @@ -10325,7 +10325,7 @@ public ThermostatClusterAtomicAttributeStatusStruct( public StructType encodeTlv() { ArrayList values = new ArrayList<>(); - values.add(new StructElement(ATTRIBUTE_I_D_ID, new UIntType(attributeID))); + values.add(new StructElement(ATTRIBUTE_ID_ID, new UIntType(attributeID))); values.add(new StructElement(STATUS_CODE_ID, new UIntType(statusCode))); return new StructType(values); @@ -10338,7 +10338,7 @@ public static ThermostatClusterAtomicAttributeStatusStruct decodeTlv(BaseTLVType Long attributeID = null; Integer statusCode = null; for (StructElement element: ((StructType)tlvValue).value()) { - if (element.contextTagNum() == ATTRIBUTE_I_D_ID) { + if (element.contextTagNum() == ATTRIBUTE_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); attributeID = castingValue.value(Long.class); @@ -10451,7 +10451,7 @@ public static class ThreadNetworkDirectoryClusterThreadNetworkStruct { public String networkName; public Integer channel; public Long activeTimestamp; - private static final long EXTENDED_PAN_I_D_ID = 0L; + private static final long EXTENDED_PAN_ID_ID = 0L; private static final long NETWORK_NAME_ID = 1L; private static final long CHANNEL_ID = 2L; private static final long ACTIVE_TIMESTAMP_ID = 3L; @@ -10470,7 +10470,7 @@ public ThreadNetworkDirectoryClusterThreadNetworkStruct( public StructType encodeTlv() { ArrayList values = new ArrayList<>(); - values.add(new StructElement(EXTENDED_PAN_I_D_ID, new ByteArrayType(extendedPanID))); + values.add(new StructElement(EXTENDED_PAN_ID_ID, new ByteArrayType(extendedPanID))); values.add(new StructElement(NETWORK_NAME_ID, new StringType(networkName))); values.add(new StructElement(CHANNEL_ID, new UIntType(channel))); values.add(new StructElement(ACTIVE_TIMESTAMP_ID, new UIntType(activeTimestamp))); @@ -10487,7 +10487,7 @@ public static ThreadNetworkDirectoryClusterThreadNetworkStruct decodeTlv(BaseTLV Integer channel = null; Long activeTimestamp = null; for (StructElement element: ((StructType)tlvValue).value()) { - if (element.contextTagNum() == EXTENDED_PAN_I_D_ID) { + if (element.contextTagNum() == EXTENDED_PAN_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.ByteArray) { ByteArrayType castingValue = element.value(ByteArrayType.class); extendedPanID = castingValue.value(byte[].class); @@ -10894,7 +10894,7 @@ public static class ChannelClusterProgramStruct { private static final long SERIES_INFO_ID = 15L; private static final long CATEGORY_LIST_ID = 16L; private static final long CAST_LIST_ID = 17L; - private static final long EXTERNAL_I_D_LIST_ID = 18L; + private static final long EXTERNAL_ID_LIST_ID = 18L; public ChannelClusterProgramStruct( String identifier, @@ -10958,7 +10958,7 @@ public StructType encodeTlv() { values.add(new StructElement(SERIES_INFO_ID, seriesInfo != null ? seriesInfo.map((nonOptionalseriesInfo) -> nonOptionalseriesInfo.encodeTlv()).orElse(new EmptyType()) : new NullType())); values.add(new StructElement(CATEGORY_LIST_ID, categoryList.map((nonOptionalcategoryList) -> ArrayType.generateArrayType(nonOptionalcategoryList, (elementnonOptionalcategoryList) -> elementnonOptionalcategoryList.encodeTlv())).orElse(new EmptyType()))); values.add(new StructElement(CAST_LIST_ID, castList.map((nonOptionalcastList) -> ArrayType.generateArrayType(nonOptionalcastList, (elementnonOptionalcastList) -> elementnonOptionalcastList.encodeTlv())).orElse(new EmptyType()))); - values.add(new StructElement(EXTERNAL_I_D_LIST_ID, externalIDList.map((nonOptionalexternalIDList) -> ArrayType.generateArrayType(nonOptionalexternalIDList, (elementnonOptionalexternalIDList) -> elementnonOptionalexternalIDList.encodeTlv())).orElse(new EmptyType()))); + values.add(new StructElement(EXTERNAL_ID_LIST_ID, externalIDList.map((nonOptionalexternalIDList) -> ArrayType.generateArrayType(nonOptionalexternalIDList, (elementnonOptionalexternalIDList) -> elementnonOptionalexternalIDList.encodeTlv())).orElse(new EmptyType()))); return new StructType(values); } @@ -11077,7 +11077,7 @@ public static ChannelClusterProgramStruct decodeTlv(BaseTLVType tlvValue) { ArrayType castingValue = element.value(ArrayType.class); castList = Optional.of(castingValue.map((elementcastingValue) -> ChipStructs.ChannelClusterProgramCastStruct.decodeTlv(elementcastingValue))); } - } else if (element.contextTagNum() == EXTERNAL_I_D_LIST_ID) { + } else if (element.contextTagNum() == EXTERNAL_ID_LIST_ID) { if (element.value(BaseTLVType.class).type() == TLVType.Array) { ArrayType castingValue = element.value(ArrayType.class); externalIDList = Optional.of(castingValue.map((elementcastingValue) -> ChipStructs.ChannelClusterProgramCastStruct.decodeTlv(elementcastingValue))); @@ -12091,7 +12091,7 @@ public static class ContentLauncherClusterParameterStruct { public Optional> externalIDList; private static final long TYPE_ID = 0L; private static final long VALUE_ID = 1L; - private static final long EXTERNAL_I_D_LIST_ID = 2L; + private static final long EXTERNAL_ID_LIST_ID = 2L; public ContentLauncherClusterParameterStruct( Integer type, @@ -12107,7 +12107,7 @@ public StructType encodeTlv() { ArrayList values = new ArrayList<>(); values.add(new StructElement(TYPE_ID, new UIntType(type))); values.add(new StructElement(VALUE_ID, new StringType(value))); - values.add(new StructElement(EXTERNAL_I_D_LIST_ID, externalIDList.map((nonOptionalexternalIDList) -> ArrayType.generateArrayType(nonOptionalexternalIDList, (elementnonOptionalexternalIDList) -> elementnonOptionalexternalIDList.encodeTlv())).orElse(new EmptyType()))); + values.add(new StructElement(EXTERNAL_ID_LIST_ID, externalIDList.map((nonOptionalexternalIDList) -> ArrayType.generateArrayType(nonOptionalexternalIDList, (elementnonOptionalexternalIDList) -> elementnonOptionalexternalIDList.encodeTlv())).orElse(new EmptyType()))); return new StructType(values); } @@ -12130,7 +12130,7 @@ public static ContentLauncherClusterParameterStruct decodeTlv(BaseTLVType tlvVal StringType castingValue = element.value(StringType.class); value = castingValue.value(String.class); } - } else if (element.contextTagNum() == EXTERNAL_I_D_LIST_ID) { + } else if (element.contextTagNum() == EXTERNAL_ID_LIST_ID) { if (element.value(BaseTLVType.class).type() == TLVType.Array) { ArrayType castingValue = element.value(ArrayType.class); externalIDList = Optional.of(castingValue.map((elementcastingValue) -> ChipStructs.ContentLauncherClusterAdditionalInfoStruct.decodeTlv(elementcastingValue))); @@ -12211,7 +12211,7 @@ public static class ContentLauncherClusterStyleInformationStruct { public Optional imageURL; public Optional color; public Optional size; - private static final long IMAGE_U_R_L_ID = 0L; + private static final long IMAGE_URL_ID = 0L; private static final long COLOR_ID = 1L; private static final long SIZE_ID = 2L; @@ -12227,7 +12227,7 @@ public ContentLauncherClusterStyleInformationStruct( public StructType encodeTlv() { ArrayList values = new ArrayList<>(); - values.add(new StructElement(IMAGE_U_R_L_ID, imageURL.map((nonOptionalimageURL) -> new StringType(nonOptionalimageURL)).orElse(new EmptyType()))); + values.add(new StructElement(IMAGE_URL_ID, imageURL.map((nonOptionalimageURL) -> new StringType(nonOptionalimageURL)).orElse(new EmptyType()))); values.add(new StructElement(COLOR_ID, color.map((nonOptionalcolor) -> new StringType(nonOptionalcolor)).orElse(new EmptyType()))); values.add(new StructElement(SIZE_ID, size.map((nonOptionalsize) -> nonOptionalsize.encodeTlv()).orElse(new EmptyType()))); @@ -12242,7 +12242,7 @@ public static ContentLauncherClusterStyleInformationStruct decodeTlv(BaseTLVType Optional color = Optional.empty(); Optional size = Optional.empty(); for (StructElement element: ((StructType)tlvValue).value()) { - if (element.contextTagNum() == IMAGE_U_R_L_ID) { + if (element.contextTagNum() == IMAGE_URL_ID) { if (element.value(BaseTLVType.class).type() == TLVType.String) { StringType castingValue = element.value(StringType.class); imageURL = Optional.of(castingValue.value(String.class)); @@ -12483,8 +12483,8 @@ public String toString() { public static class ApplicationLauncherClusterApplicationStruct { public Integer catalogVendorID; public String applicationID; - private static final long CATALOG_VENDOR_I_D_ID = 0L; - private static final long APPLICATION_I_D_ID = 1L; + private static final long CATALOG_VENDOR_ID_ID = 0L; + private static final long APPLICATION_ID_ID = 1L; public ApplicationLauncherClusterApplicationStruct( Integer catalogVendorID, @@ -12496,8 +12496,8 @@ public ApplicationLauncherClusterApplicationStruct( public StructType encodeTlv() { ArrayList values = new ArrayList<>(); - values.add(new StructElement(CATALOG_VENDOR_I_D_ID, new UIntType(catalogVendorID))); - values.add(new StructElement(APPLICATION_I_D_ID, new StringType(applicationID))); + values.add(new StructElement(CATALOG_VENDOR_ID_ID, new UIntType(catalogVendorID))); + values.add(new StructElement(APPLICATION_ID_ID, new StringType(applicationID))); return new StructType(values); } @@ -12509,12 +12509,12 @@ public static ApplicationLauncherClusterApplicationStruct decodeTlv(BaseTLVType Integer catalogVendorID = null; String applicationID = null; for (StructElement element: ((StructType)tlvValue).value()) { - if (element.contextTagNum() == CATALOG_VENDOR_I_D_ID) { + if (element.contextTagNum() == CATALOG_VENDOR_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); catalogVendorID = castingValue.value(Integer.class); } - } else if (element.contextTagNum() == APPLICATION_I_D_ID) { + } else if (element.contextTagNum() == APPLICATION_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.String) { StringType castingValue = element.value(StringType.class); applicationID = castingValue.value(String.class); @@ -12605,8 +12605,8 @@ public String toString() { public static class ApplicationBasicClusterApplicationStruct { public Integer catalogVendorID; public String applicationID; - private static final long CATALOG_VENDOR_I_D_ID = 0L; - private static final long APPLICATION_I_D_ID = 1L; + private static final long CATALOG_VENDOR_ID_ID = 0L; + private static final long APPLICATION_ID_ID = 1L; public ApplicationBasicClusterApplicationStruct( Integer catalogVendorID, @@ -12618,8 +12618,8 @@ public ApplicationBasicClusterApplicationStruct( public StructType encodeTlv() { ArrayList values = new ArrayList<>(); - values.add(new StructElement(CATALOG_VENDOR_I_D_ID, new UIntType(catalogVendorID))); - values.add(new StructElement(APPLICATION_I_D_ID, new StringType(applicationID))); + values.add(new StructElement(CATALOG_VENDOR_ID_ID, new UIntType(catalogVendorID))); + values.add(new StructElement(APPLICATION_ID_ID, new StringType(applicationID))); return new StructType(values); } @@ -12631,12 +12631,12 @@ public static ApplicationBasicClusterApplicationStruct decodeTlv(BaseTLVType tlv Integer catalogVendorID = null; String applicationID = null; for (StructElement element: ((StructType)tlvValue).value()) { - if (element.contextTagNum() == CATALOG_VENDOR_I_D_ID) { + if (element.contextTagNum() == CATALOG_VENDOR_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); catalogVendorID = castingValue.value(Integer.class); } - } else if (element.contextTagNum() == APPLICATION_I_D_ID) { + } else if (element.contextTagNum() == APPLICATION_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.String) { StringType castingValue = element.value(StringType.class); applicationID = castingValue.value(String.class); @@ -12941,7 +12941,7 @@ public static class EcosystemInformationClusterEcosystemLocationStruct { public ChipStructs.EcosystemInformationClusterLocationDescriptorStruct locationDescriptor; public Long locationDescriptorLastEdit; public Integer fabricIndex; - private static final long UNIQUE_LOCATION_I_D_ID = 0L; + private static final long UNIQUE_LOCATION_ID_ID = 0L; private static final long LOCATION_DESCRIPTOR_ID = 1L; private static final long LOCATION_DESCRIPTOR_LAST_EDIT_ID = 2L; private static final long FABRIC_INDEX_ID = 254L; @@ -12960,7 +12960,7 @@ public EcosystemInformationClusterEcosystemLocationStruct( public StructType encodeTlv() { ArrayList values = new ArrayList<>(); - values.add(new StructElement(UNIQUE_LOCATION_I_D_ID, new StringType(uniqueLocationID))); + values.add(new StructElement(UNIQUE_LOCATION_ID_ID, new StringType(uniqueLocationID))); values.add(new StructElement(LOCATION_DESCRIPTOR_ID, locationDescriptor.encodeTlv())); values.add(new StructElement(LOCATION_DESCRIPTOR_LAST_EDIT_ID, new UIntType(locationDescriptorLastEdit))); values.add(new StructElement(FABRIC_INDEX_ID, new UIntType(fabricIndex))); @@ -12977,7 +12977,7 @@ public static EcosystemInformationClusterEcosystemLocationStruct decodeTlv(BaseT Long locationDescriptorLastEdit = null; Integer fabricIndex = null; for (StructElement element: ((StructType)tlvValue).value()) { - if (element.contextTagNum() == UNIQUE_LOCATION_I_D_ID) { + if (element.contextTagNum() == UNIQUE_LOCATION_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.String) { StringType castingValue = element.value(StringType.class); uniqueLocationID = castingValue.value(String.class); diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/AccessControlClusterAccessControlEntryChangedEvent.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/AccessControlClusterAccessControlEntryChangedEvent.kt index 2fb1d22213..7deb482b8b 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/AccessControlClusterAccessControlEntryChangedEvent.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/AccessControlClusterAccessControlEntryChangedEvent.kt @@ -44,14 +44,14 @@ class AccessControlClusterAccessControlEntryChangedEvent( tlvWriter.apply { startStructure(tlvTag) if (adminNodeID != null) { - put(ContextSpecificTag(TAG_ADMIN_NODE_I_D), adminNodeID) + put(ContextSpecificTag(TAG_ADMIN_NODE_ID), adminNodeID) } else { - putNull(ContextSpecificTag(TAG_ADMIN_NODE_I_D)) + putNull(ContextSpecificTag(TAG_ADMIN_NODE_ID)) } if (adminPasscodeID != null) { - put(ContextSpecificTag(TAG_ADMIN_PASSCODE_I_D), adminPasscodeID) + put(ContextSpecificTag(TAG_ADMIN_PASSCODE_ID), adminPasscodeID) } else { - putNull(ContextSpecificTag(TAG_ADMIN_PASSCODE_I_D)) + putNull(ContextSpecificTag(TAG_ADMIN_PASSCODE_ID)) } put(ContextSpecificTag(TAG_CHANGE_TYPE), changeType) if (latestValue != null) { @@ -65,8 +65,8 @@ class AccessControlClusterAccessControlEntryChangedEvent( } companion object { - private const val TAG_ADMIN_NODE_I_D = 1 - private const val TAG_ADMIN_PASSCODE_I_D = 2 + private const val TAG_ADMIN_NODE_ID = 1 + private const val TAG_ADMIN_PASSCODE_ID = 2 private const val TAG_CHANGE_TYPE = 3 private const val TAG_LATEST_VALUE = 4 private const val TAG_FABRIC_INDEX = 254 @@ -78,16 +78,16 @@ class AccessControlClusterAccessControlEntryChangedEvent( tlvReader.enterStructure(tlvTag) val adminNodeID = if (!tlvReader.isNull()) { - tlvReader.getULong(ContextSpecificTag(TAG_ADMIN_NODE_I_D)) + tlvReader.getULong(ContextSpecificTag(TAG_ADMIN_NODE_ID)) } else { - tlvReader.getNull(ContextSpecificTag(TAG_ADMIN_NODE_I_D)) + tlvReader.getNull(ContextSpecificTag(TAG_ADMIN_NODE_ID)) null } val adminPasscodeID = if (!tlvReader.isNull()) { - tlvReader.getUInt(ContextSpecificTag(TAG_ADMIN_PASSCODE_I_D)) + tlvReader.getUInt(ContextSpecificTag(TAG_ADMIN_PASSCODE_ID)) } else { - tlvReader.getNull(ContextSpecificTag(TAG_ADMIN_PASSCODE_I_D)) + tlvReader.getNull(ContextSpecificTag(TAG_ADMIN_PASSCODE_ID)) null } val changeType = tlvReader.getUInt(ContextSpecificTag(TAG_CHANGE_TYPE)) diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/AccessControlClusterAccessControlExtensionChangedEvent.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/AccessControlClusterAccessControlExtensionChangedEvent.kt index 66a3ec9dd0..719690e305 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/AccessControlClusterAccessControlExtensionChangedEvent.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/AccessControlClusterAccessControlExtensionChangedEvent.kt @@ -44,14 +44,14 @@ class AccessControlClusterAccessControlExtensionChangedEvent( tlvWriter.apply { startStructure(tlvTag) if (adminNodeID != null) { - put(ContextSpecificTag(TAG_ADMIN_NODE_I_D), adminNodeID) + put(ContextSpecificTag(TAG_ADMIN_NODE_ID), adminNodeID) } else { - putNull(ContextSpecificTag(TAG_ADMIN_NODE_I_D)) + putNull(ContextSpecificTag(TAG_ADMIN_NODE_ID)) } if (adminPasscodeID != null) { - put(ContextSpecificTag(TAG_ADMIN_PASSCODE_I_D), adminPasscodeID) + put(ContextSpecificTag(TAG_ADMIN_PASSCODE_ID), adminPasscodeID) } else { - putNull(ContextSpecificTag(TAG_ADMIN_PASSCODE_I_D)) + putNull(ContextSpecificTag(TAG_ADMIN_PASSCODE_ID)) } put(ContextSpecificTag(TAG_CHANGE_TYPE), changeType) if (latestValue != null) { @@ -65,8 +65,8 @@ class AccessControlClusterAccessControlExtensionChangedEvent( } companion object { - private const val TAG_ADMIN_NODE_I_D = 1 - private const val TAG_ADMIN_PASSCODE_I_D = 2 + private const val TAG_ADMIN_NODE_ID = 1 + private const val TAG_ADMIN_PASSCODE_ID = 2 private const val TAG_CHANGE_TYPE = 3 private const val TAG_LATEST_VALUE = 4 private const val TAG_FABRIC_INDEX = 254 @@ -78,16 +78,16 @@ class AccessControlClusterAccessControlExtensionChangedEvent( tlvReader.enterStructure(tlvTag) val adminNodeID = if (!tlvReader.isNull()) { - tlvReader.getULong(ContextSpecificTag(TAG_ADMIN_NODE_I_D)) + tlvReader.getULong(ContextSpecificTag(TAG_ADMIN_NODE_ID)) } else { - tlvReader.getNull(ContextSpecificTag(TAG_ADMIN_NODE_I_D)) + tlvReader.getNull(ContextSpecificTag(TAG_ADMIN_NODE_ID)) null } val adminPasscodeID = if (!tlvReader.isNull()) { - tlvReader.getUInt(ContextSpecificTag(TAG_ADMIN_PASSCODE_I_D)) + tlvReader.getUInt(ContextSpecificTag(TAG_ADMIN_PASSCODE_ID)) } else { - tlvReader.getNull(ContextSpecificTag(TAG_ADMIN_PASSCODE_I_D)) + tlvReader.getNull(ContextSpecificTag(TAG_ADMIN_PASSCODE_ID)) null } val changeType = tlvReader.getUInt(ContextSpecificTag(TAG_CHANGE_TYPE)) diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/AccessControlClusterFabricRestrictionReviewUpdateEvent.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/AccessControlClusterFabricRestrictionReviewUpdateEvent.kt index 92934af0a1..7ea3d3fe02 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/AccessControlClusterFabricRestrictionReviewUpdateEvent.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/AccessControlClusterFabricRestrictionReviewUpdateEvent.kt @@ -47,9 +47,9 @@ class AccessControlClusterFabricRestrictionReviewUpdateEvent( putNull(ContextSpecificTag(TAG_INSTRUCTION)) } if (redirectURL != null) { - put(ContextSpecificTag(TAG_REDIRECT_U_R_L), redirectURL) + put(ContextSpecificTag(TAG_REDIRECT_URL), redirectURL) } else { - putNull(ContextSpecificTag(TAG_REDIRECT_U_R_L)) + putNull(ContextSpecificTag(TAG_REDIRECT_URL)) } put(ContextSpecificTag(TAG_FABRIC_INDEX), fabricIndex) endStructure() @@ -59,7 +59,7 @@ class AccessControlClusterFabricRestrictionReviewUpdateEvent( companion object { private const val TAG_TOKEN = 0 private const val TAG_INSTRUCTION = 1 - private const val TAG_REDIRECT_U_R_L = 2 + private const val TAG_REDIRECT_URL = 2 private const val TAG_FABRIC_INDEX = 254 fun fromTlv( @@ -77,9 +77,9 @@ class AccessControlClusterFabricRestrictionReviewUpdateEvent( } val redirectURL = if (!tlvReader.isNull()) { - tlvReader.getString(ContextSpecificTag(TAG_REDIRECT_U_R_L)) + tlvReader.getString(ContextSpecificTag(TAG_REDIRECT_URL)) } else { - tlvReader.getNull(ContextSpecificTag(TAG_REDIRECT_U_R_L)) + tlvReader.getNull(ContextSpecificTag(TAG_REDIRECT_URL)) null } val fabricIndex = tlvReader.getUInt(ContextSpecificTag(TAG_FABRIC_INDEX)) diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/ActionsClusterActionFailedEvent.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/ActionsClusterActionFailedEvent.kt index ac1929f969..16c1a67c5c 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/ActionsClusterActionFailedEvent.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/ActionsClusterActionFailedEvent.kt @@ -40,8 +40,8 @@ class ActionsClusterActionFailedEvent( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_ACTION_I_D), actionID) - put(ContextSpecificTag(TAG_INVOKE_I_D), invokeID) + put(ContextSpecificTag(TAG_ACTION_ID), actionID) + put(ContextSpecificTag(TAG_INVOKE_ID), invokeID) put(ContextSpecificTag(TAG_NEW_STATE), newState) put(ContextSpecificTag(TAG_ERROR), error) endStructure() @@ -49,15 +49,15 @@ class ActionsClusterActionFailedEvent( } companion object { - private const val TAG_ACTION_I_D = 0 - private const val TAG_INVOKE_I_D = 1 + private const val TAG_ACTION_ID = 0 + private const val TAG_INVOKE_ID = 1 private const val TAG_NEW_STATE = 2 private const val TAG_ERROR = 3 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): ActionsClusterActionFailedEvent { tlvReader.enterStructure(tlvTag) - val actionID = tlvReader.getUInt(ContextSpecificTag(TAG_ACTION_I_D)) - val invokeID = tlvReader.getULong(ContextSpecificTag(TAG_INVOKE_I_D)) + val actionID = tlvReader.getUInt(ContextSpecificTag(TAG_ACTION_ID)) + val invokeID = tlvReader.getULong(ContextSpecificTag(TAG_INVOKE_ID)) val newState = tlvReader.getUInt(ContextSpecificTag(TAG_NEW_STATE)) val error = tlvReader.getUInt(ContextSpecificTag(TAG_ERROR)) diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/ActionsClusterStateChangedEvent.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/ActionsClusterStateChangedEvent.kt index d95c5e9d66..cba68b0ed4 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/ActionsClusterStateChangedEvent.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/ActionsClusterStateChangedEvent.kt @@ -34,22 +34,22 @@ class ActionsClusterStateChangedEvent(val actionID: UInt, val invokeID: ULong, v fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_ACTION_I_D), actionID) - put(ContextSpecificTag(TAG_INVOKE_I_D), invokeID) + put(ContextSpecificTag(TAG_ACTION_ID), actionID) + put(ContextSpecificTag(TAG_INVOKE_ID), invokeID) put(ContextSpecificTag(TAG_NEW_STATE), newState) endStructure() } } companion object { - private const val TAG_ACTION_I_D = 0 - private const val TAG_INVOKE_I_D = 1 + private const val TAG_ACTION_ID = 0 + private const val TAG_INVOKE_ID = 1 private const val TAG_NEW_STATE = 2 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): ActionsClusterStateChangedEvent { tlvReader.enterStructure(tlvTag) - val actionID = tlvReader.getUInt(ContextSpecificTag(TAG_ACTION_I_D)) - val invokeID = tlvReader.getULong(ContextSpecificTag(TAG_INVOKE_I_D)) + val actionID = tlvReader.getUInt(ContextSpecificTag(TAG_ACTION_ID)) + val invokeID = tlvReader.getULong(ContextSpecificTag(TAG_INVOKE_ID)) val newState = tlvReader.getUInt(ContextSpecificTag(TAG_NEW_STATE)) tlvReader.exitContainer() diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/DemandResponseLoadControlClusterLoadControlEventStatusChangeEvent.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/DemandResponseLoadControlClusterLoadControlEventStatusChangeEvent.kt index 7c277de07b..1c24da6a70 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/DemandResponseLoadControlClusterLoadControlEventStatusChangeEvent.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/DemandResponseLoadControlClusterLoadControlEventStatusChangeEvent.kt @@ -68,7 +68,7 @@ class DemandResponseLoadControlClusterLoadControlEventStatusChangeEvent( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_EVENT_I_D), eventID) + put(ContextSpecificTag(TAG_EVENT_ID), eventID) if (transitionIndex != null) { put(ContextSpecificTag(TAG_TRANSITION_INDEX), transitionIndex) } else { @@ -122,7 +122,7 @@ class DemandResponseLoadControlClusterLoadControlEventStatusChangeEvent( } companion object { - private const val TAG_EVENT_I_D = 0 + private const val TAG_EVENT_ID = 0 private const val TAG_TRANSITION_INDEX = 1 private const val TAG_STATUS = 2 private const val TAG_CRITICALITY = 3 @@ -138,7 +138,7 @@ class DemandResponseLoadControlClusterLoadControlEventStatusChangeEvent( tlvReader: TlvReader, ): DemandResponseLoadControlClusterLoadControlEventStatusChangeEvent { tlvReader.enterStructure(tlvTag) - val eventID = tlvReader.getByteArray(ContextSpecificTag(TAG_EVENT_I_D)) + val eventID = tlvReader.getByteArray(ContextSpecificTag(TAG_EVENT_ID)) val transitionIndex = if (!tlvReader.isNull()) { tlvReader.getUInt(ContextSpecificTag(TAG_TRANSITION_INDEX)) diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/EnergyEvseClusterEVConnectedEvent.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/EnergyEvseClusterEVConnectedEvent.kt index 37d91a3291..a17f03a6ef 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/EnergyEvseClusterEVConnectedEvent.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/EnergyEvseClusterEVConnectedEvent.kt @@ -32,17 +32,17 @@ class EnergyEvseClusterEVConnectedEvent(val sessionID: ULong) { fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_SESSION_I_D), sessionID) + put(ContextSpecificTag(TAG_SESSION_ID), sessionID) endStructure() } } companion object { - private const val TAG_SESSION_I_D = 0 + private const val TAG_SESSION_ID = 0 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): EnergyEvseClusterEVConnectedEvent { tlvReader.enterStructure(tlvTag) - val sessionID = tlvReader.getULong(ContextSpecificTag(TAG_SESSION_I_D)) + val sessionID = tlvReader.getULong(ContextSpecificTag(TAG_SESSION_ID)) tlvReader.exitContainer() diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/EnergyEvseClusterEVNotDetectedEvent.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/EnergyEvseClusterEVNotDetectedEvent.kt index 17654efa1b..a55f057867 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/EnergyEvseClusterEVNotDetectedEvent.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/EnergyEvseClusterEVNotDetectedEvent.kt @@ -43,7 +43,7 @@ class EnergyEvseClusterEVNotDetectedEvent( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_SESSION_I_D), sessionID) + put(ContextSpecificTag(TAG_SESSION_ID), sessionID) put(ContextSpecificTag(TAG_STATE), state) put(ContextSpecificTag(TAG_SESSION_DURATION), sessionDuration) put(ContextSpecificTag(TAG_SESSION_ENERGY_CHARGED), sessionEnergyCharged) @@ -56,7 +56,7 @@ class EnergyEvseClusterEVNotDetectedEvent( } companion object { - private const val TAG_SESSION_I_D = 0 + private const val TAG_SESSION_ID = 0 private const val TAG_STATE = 1 private const val TAG_SESSION_DURATION = 2 private const val TAG_SESSION_ENERGY_CHARGED = 3 @@ -64,7 +64,7 @@ class EnergyEvseClusterEVNotDetectedEvent( fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): EnergyEvseClusterEVNotDetectedEvent { tlvReader.enterStructure(tlvTag) - val sessionID = tlvReader.getULong(ContextSpecificTag(TAG_SESSION_I_D)) + val sessionID = tlvReader.getULong(ContextSpecificTag(TAG_SESSION_ID)) val state = tlvReader.getUInt(ContextSpecificTag(TAG_STATE)) val sessionDuration = tlvReader.getULong(ContextSpecificTag(TAG_SESSION_DURATION)) val sessionEnergyCharged = tlvReader.getLong(ContextSpecificTag(TAG_SESSION_ENERGY_CHARGED)) diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/EnergyEvseClusterEnergyTransferStartedEvent.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/EnergyEvseClusterEnergyTransferStartedEvent.kt index 345a0aef9f..6e951b49f6 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/EnergyEvseClusterEnergyTransferStartedEvent.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/EnergyEvseClusterEnergyTransferStartedEvent.kt @@ -41,7 +41,7 @@ class EnergyEvseClusterEnergyTransferStartedEvent( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_SESSION_I_D), sessionID) + put(ContextSpecificTag(TAG_SESSION_ID), sessionID) put(ContextSpecificTag(TAG_STATE), state) put(ContextSpecificTag(TAG_MAXIMUM_CURRENT), maximumCurrent) if (maximumDischargeCurrent.isPresent) { @@ -53,14 +53,14 @@ class EnergyEvseClusterEnergyTransferStartedEvent( } companion object { - private const val TAG_SESSION_I_D = 0 + private const val TAG_SESSION_ID = 0 private const val TAG_STATE = 1 private const val TAG_MAXIMUM_CURRENT = 2 private const val TAG_MAXIMUM_DISCHARGE_CURRENT = 3 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): EnergyEvseClusterEnergyTransferStartedEvent { tlvReader.enterStructure(tlvTag) - val sessionID = tlvReader.getULong(ContextSpecificTag(TAG_SESSION_I_D)) + val sessionID = tlvReader.getULong(ContextSpecificTag(TAG_SESSION_ID)) val state = tlvReader.getUInt(ContextSpecificTag(TAG_STATE)) val maximumCurrent = tlvReader.getLong(ContextSpecificTag(TAG_MAXIMUM_CURRENT)) val maximumDischargeCurrent = diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/EnergyEvseClusterEnergyTransferStoppedEvent.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/EnergyEvseClusterEnergyTransferStoppedEvent.kt index b6c3f8cc88..a069eafd10 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/EnergyEvseClusterEnergyTransferStoppedEvent.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/EnergyEvseClusterEnergyTransferStoppedEvent.kt @@ -43,7 +43,7 @@ class EnergyEvseClusterEnergyTransferStoppedEvent( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_SESSION_I_D), sessionID) + put(ContextSpecificTag(TAG_SESSION_ID), sessionID) put(ContextSpecificTag(TAG_STATE), state) put(ContextSpecificTag(TAG_REASON), reason) put(ContextSpecificTag(TAG_ENERGY_TRANSFERRED), energyTransferred) @@ -56,7 +56,7 @@ class EnergyEvseClusterEnergyTransferStoppedEvent( } companion object { - private const val TAG_SESSION_I_D = 0 + private const val TAG_SESSION_ID = 0 private const val TAG_STATE = 1 private const val TAG_REASON = 2 private const val TAG_ENERGY_TRANSFERRED = 4 @@ -64,7 +64,7 @@ class EnergyEvseClusterEnergyTransferStoppedEvent( fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): EnergyEvseClusterEnergyTransferStoppedEvent { tlvReader.enterStructure(tlvTag) - val sessionID = tlvReader.getULong(ContextSpecificTag(TAG_SESSION_I_D)) + val sessionID = tlvReader.getULong(ContextSpecificTag(TAG_SESSION_ID)) val state = tlvReader.getUInt(ContextSpecificTag(TAG_STATE)) val reason = tlvReader.getUInt(ContextSpecificTag(TAG_REASON)) val energyTransferred = tlvReader.getLong(ContextSpecificTag(TAG_ENERGY_TRANSFERRED)) diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/EnergyEvseClusterFaultEvent.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/EnergyEvseClusterFaultEvent.kt index e3c2019af5..cc694c8760 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/EnergyEvseClusterFaultEvent.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/EnergyEvseClusterFaultEvent.kt @@ -41,9 +41,9 @@ class EnergyEvseClusterFaultEvent( tlvWriter.apply { startStructure(tlvTag) if (sessionID != null) { - put(ContextSpecificTag(TAG_SESSION_I_D), sessionID) + put(ContextSpecificTag(TAG_SESSION_ID), sessionID) } else { - putNull(ContextSpecificTag(TAG_SESSION_I_D)) + putNull(ContextSpecificTag(TAG_SESSION_ID)) } put(ContextSpecificTag(TAG_STATE), state) put(ContextSpecificTag(TAG_FAULT_STATE_PREVIOUS_STATE), faultStatePreviousState) @@ -53,7 +53,7 @@ class EnergyEvseClusterFaultEvent( } companion object { - private const val TAG_SESSION_I_D = 0 + private const val TAG_SESSION_ID = 0 private const val TAG_STATE = 1 private const val TAG_FAULT_STATE_PREVIOUS_STATE = 2 private const val TAG_FAULT_STATE_CURRENT_STATE = 4 @@ -62,9 +62,9 @@ class EnergyEvseClusterFaultEvent( tlvReader.enterStructure(tlvTag) val sessionID = if (!tlvReader.isNull()) { - tlvReader.getULong(ContextSpecificTag(TAG_SESSION_I_D)) + tlvReader.getULong(ContextSpecificTag(TAG_SESSION_ID)) } else { - tlvReader.getNull(ContextSpecificTag(TAG_SESSION_I_D)) + tlvReader.getNull(ContextSpecificTag(TAG_SESSION_ID)) null } val state = tlvReader.getUInt(ContextSpecificTag(TAG_STATE)) diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/MessagesClusterMessageCompleteEvent.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/MessagesClusterMessageCompleteEvent.kt index b8524b2018..35b5ca1c11 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/MessagesClusterMessageCompleteEvent.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/MessagesClusterMessageCompleteEvent.kt @@ -41,14 +41,14 @@ class MessagesClusterMessageCompleteEvent( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_MESSAGE_I_D), messageID) + put(ContextSpecificTag(TAG_MESSAGE_ID), messageID) if (responseID != null) { if (responseID.isPresent) { val optresponseID = responseID.get() - put(ContextSpecificTag(TAG_RESPONSE_I_D), optresponseID) + put(ContextSpecificTag(TAG_RESPONSE_ID), optresponseID) } } else { - putNull(ContextSpecificTag(TAG_RESPONSE_I_D)) + putNull(ContextSpecificTag(TAG_RESPONSE_ID)) } if (reply != null) { if (reply.isPresent) { @@ -68,23 +68,23 @@ class MessagesClusterMessageCompleteEvent( } companion object { - private const val TAG_MESSAGE_I_D = 0 - private const val TAG_RESPONSE_I_D = 1 + private const val TAG_MESSAGE_ID = 0 + private const val TAG_RESPONSE_ID = 1 private const val TAG_REPLY = 2 private const val TAG_FUTURE_MESSAGES_PREFERENCE = 3 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): MessagesClusterMessageCompleteEvent { tlvReader.enterStructure(tlvTag) - val messageID = tlvReader.getByteArray(ContextSpecificTag(TAG_MESSAGE_I_D)) + val messageID = tlvReader.getByteArray(ContextSpecificTag(TAG_MESSAGE_ID)) val responseID = if (!tlvReader.isNull()) { - if (tlvReader.isNextTag(ContextSpecificTag(TAG_RESPONSE_I_D))) { - Optional.of(tlvReader.getULong(ContextSpecificTag(TAG_RESPONSE_I_D))) + if (tlvReader.isNextTag(ContextSpecificTag(TAG_RESPONSE_ID))) { + Optional.of(tlvReader.getULong(ContextSpecificTag(TAG_RESPONSE_ID))) } else { Optional.empty() } } else { - tlvReader.getNull(ContextSpecificTag(TAG_RESPONSE_I_D)) + tlvReader.getNull(ContextSpecificTag(TAG_RESPONSE_ID)) null } val reply = diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/MessagesClusterMessagePresentedEvent.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/MessagesClusterMessagePresentedEvent.kt index a2e39882f9..257a121dcc 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/MessagesClusterMessagePresentedEvent.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/MessagesClusterMessagePresentedEvent.kt @@ -32,17 +32,17 @@ class MessagesClusterMessagePresentedEvent(val messageID: ByteArray) { fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_MESSAGE_I_D), messageID) + put(ContextSpecificTag(TAG_MESSAGE_ID), messageID) endStructure() } } companion object { - private const val TAG_MESSAGE_I_D = 0 + private const val TAG_MESSAGE_ID = 0 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): MessagesClusterMessagePresentedEvent { tlvReader.enterStructure(tlvTag) - val messageID = tlvReader.getByteArray(ContextSpecificTag(TAG_MESSAGE_I_D)) + val messageID = tlvReader.getByteArray(ContextSpecificTag(TAG_MESSAGE_ID)) tlvReader.exitContainer() diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/MessagesClusterMessageQueuedEvent.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/MessagesClusterMessageQueuedEvent.kt index db5ed28fae..47b80942b6 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/MessagesClusterMessageQueuedEvent.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/MessagesClusterMessageQueuedEvent.kt @@ -32,17 +32,17 @@ class MessagesClusterMessageQueuedEvent(val messageID: ByteArray) { fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_MESSAGE_I_D), messageID) + put(ContextSpecificTag(TAG_MESSAGE_ID), messageID) endStructure() } } companion object { - private const val TAG_MESSAGE_I_D = 0 + private const val TAG_MESSAGE_ID = 0 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): MessagesClusterMessageQueuedEvent { tlvReader.enterStructure(tlvTag) - val messageID = tlvReader.getByteArray(ContextSpecificTag(TAG_MESSAGE_I_D)) + val messageID = tlvReader.getByteArray(ContextSpecificTag(TAG_MESSAGE_ID)) tlvReader.exitContainer() diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/OtaSoftwareUpdateRequestorClusterVersionAppliedEvent.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/OtaSoftwareUpdateRequestorClusterVersionAppliedEvent.kt index 17cf46b96d..70f0975a0a 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/OtaSoftwareUpdateRequestorClusterVersionAppliedEvent.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/OtaSoftwareUpdateRequestorClusterVersionAppliedEvent.kt @@ -37,14 +37,14 @@ class OtaSoftwareUpdateRequestorClusterVersionAppliedEvent( tlvWriter.apply { startStructure(tlvTag) put(ContextSpecificTag(TAG_SOFTWARE_VERSION), softwareVersion) - put(ContextSpecificTag(TAG_PRODUCT_I_D), productID) + put(ContextSpecificTag(TAG_PRODUCT_ID), productID) endStructure() } } companion object { private const val TAG_SOFTWARE_VERSION = 0 - private const val TAG_PRODUCT_I_D = 1 + private const val TAG_PRODUCT_ID = 1 fun fromTlv( tlvTag: Tag, @@ -52,7 +52,7 @@ class OtaSoftwareUpdateRequestorClusterVersionAppliedEvent( ): OtaSoftwareUpdateRequestorClusterVersionAppliedEvent { tlvReader.enterStructure(tlvTag) val softwareVersion = tlvReader.getULong(ContextSpecificTag(TAG_SOFTWARE_VERSION)) - val productID = tlvReader.getUInt(ContextSpecificTag(TAG_PRODUCT_I_D)) + val productID = tlvReader.getUInt(ContextSpecificTag(TAG_PRODUCT_ID)) tlvReader.exitContainer() diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/TimeSynchronizationClusterDSTStatusEvent.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/TimeSynchronizationClusterDSTStatusEvent.kt index 7564293e97..493128994b 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/TimeSynchronizationClusterDSTStatusEvent.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/eventstructs/TimeSynchronizationClusterDSTStatusEvent.kt @@ -32,17 +32,17 @@ class TimeSynchronizationClusterDSTStatusEvent(val DSTOffsetActive: Boolean) { fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_D_S_T_OFFSET_ACTIVE), DSTOffsetActive) + put(ContextSpecificTag(TAG_DST_OFFSET_ACTIVE), DSTOffsetActive) endStructure() } } companion object { - private const val TAG_D_S_T_OFFSET_ACTIVE = 0 + private const val TAG_DST_OFFSET_ACTIVE = 0 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): TimeSynchronizationClusterDSTStatusEvent { tlvReader.enterStructure(tlvTag) - val DSTOffsetActive = tlvReader.getBoolean(ContextSpecificTag(TAG_D_S_T_OFFSET_ACTIVE)) + val DSTOffsetActive = tlvReader.getBoolean(ContextSpecificTag(TAG_DST_OFFSET_ACTIVE)) tlvReader.exitContainer() diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ActionsClusterActionStruct.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ActionsClusterActionStruct.kt index a20404bb1e..d464c189e4 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ActionsClusterActionStruct.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ActionsClusterActionStruct.kt @@ -44,10 +44,10 @@ class ActionsClusterActionStruct( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_ACTION_I_D), actionID) + put(ContextSpecificTag(TAG_ACTION_ID), actionID) put(ContextSpecificTag(TAG_NAME), name) put(ContextSpecificTag(TAG_TYPE), type) - put(ContextSpecificTag(TAG_ENDPOINT_LIST_I_D), endpointListID) + put(ContextSpecificTag(TAG_ENDPOINT_LIST_ID), endpointListID) put(ContextSpecificTag(TAG_SUPPORTED_COMMANDS), supportedCommands) put(ContextSpecificTag(TAG_STATE), state) endStructure() @@ -55,19 +55,19 @@ class ActionsClusterActionStruct( } companion object { - private const val TAG_ACTION_I_D = 0 + private const val TAG_ACTION_ID = 0 private const val TAG_NAME = 1 private const val TAG_TYPE = 2 - private const val TAG_ENDPOINT_LIST_I_D = 3 + private const val TAG_ENDPOINT_LIST_ID = 3 private const val TAG_SUPPORTED_COMMANDS = 4 private const val TAG_STATE = 5 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): ActionsClusterActionStruct { tlvReader.enterStructure(tlvTag) - val actionID = tlvReader.getUInt(ContextSpecificTag(TAG_ACTION_I_D)) + val actionID = tlvReader.getUInt(ContextSpecificTag(TAG_ACTION_ID)) val name = tlvReader.getString(ContextSpecificTag(TAG_NAME)) val type = tlvReader.getUInt(ContextSpecificTag(TAG_TYPE)) - val endpointListID = tlvReader.getUInt(ContextSpecificTag(TAG_ENDPOINT_LIST_I_D)) + val endpointListID = tlvReader.getUInt(ContextSpecificTag(TAG_ENDPOINT_LIST_ID)) val supportedCommands = tlvReader.getUInt(ContextSpecificTag(TAG_SUPPORTED_COMMANDS)) val state = tlvReader.getUInt(ContextSpecificTag(TAG_STATE)) diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ActionsClusterEndpointListStruct.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ActionsClusterEndpointListStruct.kt index 831224d12c..4f505fcc2f 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ActionsClusterEndpointListStruct.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ActionsClusterEndpointListStruct.kt @@ -41,7 +41,7 @@ class ActionsClusterEndpointListStruct( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_ENDPOINT_LIST_I_D), endpointListID) + put(ContextSpecificTag(TAG_ENDPOINT_LIST_ID), endpointListID) put(ContextSpecificTag(TAG_NAME), name) put(ContextSpecificTag(TAG_TYPE), type) startArray(ContextSpecificTag(TAG_ENDPOINTS)) @@ -54,14 +54,14 @@ class ActionsClusterEndpointListStruct( } companion object { - private const val TAG_ENDPOINT_LIST_I_D = 0 + private const val TAG_ENDPOINT_LIST_ID = 0 private const val TAG_NAME = 1 private const val TAG_TYPE = 2 private const val TAG_ENDPOINTS = 3 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): ActionsClusterEndpointListStruct { tlvReader.enterStructure(tlvTag) - val endpointListID = tlvReader.getUInt(ContextSpecificTag(TAG_ENDPOINT_LIST_I_D)) + val endpointListID = tlvReader.getUInt(ContextSpecificTag(TAG_ENDPOINT_LIST_ID)) val name = tlvReader.getString(ContextSpecificTag(TAG_NAME)) val type = tlvReader.getUInt(ContextSpecificTag(TAG_TYPE)) val endpoints = diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ApplicationBasicClusterApplicationStruct.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ApplicationBasicClusterApplicationStruct.kt index 566b2efdf3..0438c54949 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ApplicationBasicClusterApplicationStruct.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ApplicationBasicClusterApplicationStruct.kt @@ -36,20 +36,20 @@ class ApplicationBasicClusterApplicationStruct( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_CATALOG_VENDOR_I_D), catalogVendorID) - put(ContextSpecificTag(TAG_APPLICATION_I_D), applicationID) + put(ContextSpecificTag(TAG_CATALOG_VENDOR_ID), catalogVendorID) + put(ContextSpecificTag(TAG_APPLICATION_ID), applicationID) endStructure() } } companion object { - private const val TAG_CATALOG_VENDOR_I_D = 0 - private const val TAG_APPLICATION_I_D = 1 + private const val TAG_CATALOG_VENDOR_ID = 0 + private const val TAG_APPLICATION_ID = 1 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): ApplicationBasicClusterApplicationStruct { tlvReader.enterStructure(tlvTag) - val catalogVendorID = tlvReader.getUInt(ContextSpecificTag(TAG_CATALOG_VENDOR_I_D)) - val applicationID = tlvReader.getString(ContextSpecificTag(TAG_APPLICATION_I_D)) + val catalogVendorID = tlvReader.getUInt(ContextSpecificTag(TAG_CATALOG_VENDOR_ID)) + val applicationID = tlvReader.getString(ContextSpecificTag(TAG_APPLICATION_ID)) tlvReader.exitContainer() diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ApplicationLauncherClusterApplicationStruct.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ApplicationLauncherClusterApplicationStruct.kt index 26e76b3c69..33feca6b60 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ApplicationLauncherClusterApplicationStruct.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ApplicationLauncherClusterApplicationStruct.kt @@ -36,20 +36,20 @@ class ApplicationLauncherClusterApplicationStruct( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_CATALOG_VENDOR_I_D), catalogVendorID) - put(ContextSpecificTag(TAG_APPLICATION_I_D), applicationID) + put(ContextSpecificTag(TAG_CATALOG_VENDOR_ID), catalogVendorID) + put(ContextSpecificTag(TAG_APPLICATION_ID), applicationID) endStructure() } } companion object { - private const val TAG_CATALOG_VENDOR_I_D = 0 - private const val TAG_APPLICATION_I_D = 1 + private const val TAG_CATALOG_VENDOR_ID = 0 + private const val TAG_APPLICATION_ID = 1 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): ApplicationLauncherClusterApplicationStruct { tlvReader.enterStructure(tlvTag) - val catalogVendorID = tlvReader.getUInt(ContextSpecificTag(TAG_CATALOG_VENDOR_I_D)) - val applicationID = tlvReader.getString(ContextSpecificTag(TAG_APPLICATION_I_D)) + val catalogVendorID = tlvReader.getUInt(ContextSpecificTag(TAG_CATALOG_VENDOR_ID)) + val applicationID = tlvReader.getString(ContextSpecificTag(TAG_APPLICATION_ID)) tlvReader.exitContainer() diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ChannelClusterProgramStruct.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ChannelClusterProgramStruct.kt index e7e00d9518..10ef68db6a 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ChannelClusterProgramStruct.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ChannelClusterProgramStruct.kt @@ -151,7 +151,7 @@ class ChannelClusterProgramStruct( } if (externalIDList.isPresent) { val optexternalIDList = externalIDList.get() - startArray(ContextSpecificTag(TAG_EXTERNAL_I_D_LIST)) + startArray(ContextSpecificTag(TAG_EXTERNAL_ID_LIST)) for (item in optexternalIDList.iterator()) { item.toTlv(AnonymousTag, this) } @@ -180,7 +180,7 @@ class ChannelClusterProgramStruct( private const val TAG_SERIES_INFO = 15 private const val TAG_CATEGORY_LIST = 16 private const val TAG_CAST_LIST = 17 - private const val TAG_EXTERNAL_I_D_LIST = 18 + private const val TAG_EXTERNAL_ID_LIST = 18 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): ChannelClusterProgramStruct { tlvReader.enterStructure(tlvTag) @@ -308,10 +308,10 @@ class ChannelClusterProgramStruct( Optional.empty() } val externalIDList = - if (tlvReader.isNextTag(ContextSpecificTag(TAG_EXTERNAL_I_D_LIST))) { + if (tlvReader.isNextTag(ContextSpecificTag(TAG_EXTERNAL_ID_LIST))) { Optional.of( buildList { - tlvReader.enterArray(ContextSpecificTag(TAG_EXTERNAL_I_D_LIST)) + tlvReader.enterArray(ContextSpecificTag(TAG_EXTERNAL_ID_LIST)) while (!tlvReader.isEndOfContainer()) { add(ChannelClusterProgramCastStruct.fromTlv(AnonymousTag, tlvReader)) } diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ContentLauncherClusterParameterStruct.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ContentLauncherClusterParameterStruct.kt index 96e28a1c12..2c6df6ee71 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ContentLauncherClusterParameterStruct.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ContentLauncherClusterParameterStruct.kt @@ -44,7 +44,7 @@ class ContentLauncherClusterParameterStruct( put(ContextSpecificTag(TAG_VALUE), value) if (externalIDList.isPresent) { val optexternalIDList = externalIDList.get() - startArray(ContextSpecificTag(TAG_EXTERNAL_I_D_LIST)) + startArray(ContextSpecificTag(TAG_EXTERNAL_ID_LIST)) for (item in optexternalIDList.iterator()) { item.toTlv(AnonymousTag, this) } @@ -57,17 +57,17 @@ class ContentLauncherClusterParameterStruct( companion object { private const val TAG_TYPE = 0 private const val TAG_VALUE = 1 - private const val TAG_EXTERNAL_I_D_LIST = 2 + private const val TAG_EXTERNAL_ID_LIST = 2 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): ContentLauncherClusterParameterStruct { tlvReader.enterStructure(tlvTag) val type = tlvReader.getUInt(ContextSpecificTag(TAG_TYPE)) val value = tlvReader.getString(ContextSpecificTag(TAG_VALUE)) val externalIDList = - if (tlvReader.isNextTag(ContextSpecificTag(TAG_EXTERNAL_I_D_LIST))) { + if (tlvReader.isNextTag(ContextSpecificTag(TAG_EXTERNAL_ID_LIST))) { Optional.of( buildList { - tlvReader.enterArray(ContextSpecificTag(TAG_EXTERNAL_I_D_LIST)) + tlvReader.enterArray(ContextSpecificTag(TAG_EXTERNAL_ID_LIST)) while (!tlvReader.isEndOfContainer()) { add(ContentLauncherClusterAdditionalInfoStruct.fromTlv(AnonymousTag, tlvReader)) } diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ContentLauncherClusterStyleInformationStruct.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ContentLauncherClusterStyleInformationStruct.kt index 9c9da395d5..41ef65fead 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ContentLauncherClusterStyleInformationStruct.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ContentLauncherClusterStyleInformationStruct.kt @@ -41,7 +41,7 @@ class ContentLauncherClusterStyleInformationStruct( startStructure(tlvTag) if (imageURL.isPresent) { val optimageURL = imageURL.get() - put(ContextSpecificTag(TAG_IMAGE_U_R_L), optimageURL) + put(ContextSpecificTag(TAG_IMAGE_URL), optimageURL) } if (color.isPresent) { val optcolor = color.get() @@ -56,15 +56,15 @@ class ContentLauncherClusterStyleInformationStruct( } companion object { - private const val TAG_IMAGE_U_R_L = 0 + private const val TAG_IMAGE_URL = 0 private const val TAG_COLOR = 1 private const val TAG_SIZE = 2 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): ContentLauncherClusterStyleInformationStruct { tlvReader.enterStructure(tlvTag) val imageURL = - if (tlvReader.isNextTag(ContextSpecificTag(TAG_IMAGE_U_R_L))) { - Optional.of(tlvReader.getString(ContextSpecificTag(TAG_IMAGE_U_R_L))) + if (tlvReader.isNextTag(ContextSpecificTag(TAG_IMAGE_URL))) { + Optional.of(tlvReader.getString(ContextSpecificTag(TAG_IMAGE_URL))) } else { Optional.empty() } diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/DemandResponseLoadControlClusterLoadControlEventStruct.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/DemandResponseLoadControlClusterLoadControlEventStruct.kt index 91a2071e0b..5b7a2e7f62 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/DemandResponseLoadControlClusterLoadControlEventStruct.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/DemandResponseLoadControlClusterLoadControlEventStruct.kt @@ -50,11 +50,11 @@ class DemandResponseLoadControlClusterLoadControlEventStruct( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_EVENT_I_D), eventID) + put(ContextSpecificTag(TAG_EVENT_ID), eventID) if (programID != null) { - put(ContextSpecificTag(TAG_PROGRAM_I_D), programID) + put(ContextSpecificTag(TAG_PROGRAM_ID), programID) } else { - putNull(ContextSpecificTag(TAG_PROGRAM_I_D)) + putNull(ContextSpecificTag(TAG_PROGRAM_ID)) } put(ContextSpecificTag(TAG_CONTROL), control) put(ContextSpecificTag(TAG_DEVICE_CLASS), deviceClass) @@ -78,8 +78,8 @@ class DemandResponseLoadControlClusterLoadControlEventStruct( } companion object { - private const val TAG_EVENT_I_D = 0 - private const val TAG_PROGRAM_I_D = 1 + private const val TAG_EVENT_ID = 0 + private const val TAG_PROGRAM_ID = 1 private const val TAG_CONTROL = 2 private const val TAG_DEVICE_CLASS = 3 private const val TAG_ENROLLMENT_GROUP = 4 @@ -92,12 +92,12 @@ class DemandResponseLoadControlClusterLoadControlEventStruct( tlvReader: TlvReader, ): DemandResponseLoadControlClusterLoadControlEventStruct { tlvReader.enterStructure(tlvTag) - val eventID = tlvReader.getByteArray(ContextSpecificTag(TAG_EVENT_I_D)) + val eventID = tlvReader.getByteArray(ContextSpecificTag(TAG_EVENT_ID)) val programID = if (!tlvReader.isNull()) { - tlvReader.getByteArray(ContextSpecificTag(TAG_PROGRAM_I_D)) + tlvReader.getByteArray(ContextSpecificTag(TAG_PROGRAM_ID)) } else { - tlvReader.getNull(ContextSpecificTag(TAG_PROGRAM_I_D)) + tlvReader.getNull(ContextSpecificTag(TAG_PROGRAM_ID)) null } val control = tlvReader.getUInt(ContextSpecificTag(TAG_CONTROL)) diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/DemandResponseLoadControlClusterLoadControlProgramStruct.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/DemandResponseLoadControlClusterLoadControlProgramStruct.kt index 3a71f11aed..766287fcc6 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/DemandResponseLoadControlClusterLoadControlProgramStruct.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/DemandResponseLoadControlClusterLoadControlProgramStruct.kt @@ -42,7 +42,7 @@ class DemandResponseLoadControlClusterLoadControlProgramStruct( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_PROGRAM_I_D), programID) + put(ContextSpecificTag(TAG_PROGRAM_ID), programID) put(ContextSpecificTag(TAG_NAME), name) if (enrollmentGroup != null) { put(ContextSpecificTag(TAG_ENROLLMENT_GROUP), enrollmentGroup) @@ -64,7 +64,7 @@ class DemandResponseLoadControlClusterLoadControlProgramStruct( } companion object { - private const val TAG_PROGRAM_I_D = 0 + private const val TAG_PROGRAM_ID = 0 private const val TAG_NAME = 1 private const val TAG_ENROLLMENT_GROUP = 2 private const val TAG_RANDOM_START_MINUTES = 3 @@ -75,7 +75,7 @@ class DemandResponseLoadControlClusterLoadControlProgramStruct( tlvReader: TlvReader, ): DemandResponseLoadControlClusterLoadControlProgramStruct { tlvReader.enterStructure(tlvTag) - val programID = tlvReader.getByteArray(ContextSpecificTag(TAG_PROGRAM_I_D)) + val programID = tlvReader.getByteArray(ContextSpecificTag(TAG_PROGRAM_ID)) val name = tlvReader.getString(ContextSpecificTag(TAG_NAME)) val enrollmentGroup = if (!tlvReader.isNull()) { diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/DescriptorClusterSemanticTagStruct.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/DescriptorClusterSemanticTagStruct.kt index a3da0980b3..6c13fcab83 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/DescriptorClusterSemanticTagStruct.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/DescriptorClusterSemanticTagStruct.kt @@ -46,7 +46,7 @@ class DescriptorClusterSemanticTagStruct( } else { putNull(ContextSpecificTag(TAG_MFG_CODE)) } - put(ContextSpecificTag(TAG_NAMESPACE_I_D), namespaceID) + put(ContextSpecificTag(TAG_NAMESPACE_ID), namespaceID) put(ContextSpecificTag(TAG_TAG), tag) if (label != null) { if (label.isPresent) { @@ -62,7 +62,7 @@ class DescriptorClusterSemanticTagStruct( companion object { private const val TAG_MFG_CODE = 0 - private const val TAG_NAMESPACE_I_D = 1 + private const val TAG_NAMESPACE_ID = 1 private const val TAG_TAG = 2 private const val TAG_LABEL = 3 @@ -75,7 +75,7 @@ class DescriptorClusterSemanticTagStruct( tlvReader.getNull(ContextSpecificTag(TAG_MFG_CODE)) null } - val namespaceID = tlvReader.getUInt(ContextSpecificTag(TAG_NAMESPACE_I_D)) + val namespaceID = tlvReader.getUInt(ContextSpecificTag(TAG_NAMESPACE_ID)) val tag = tlvReader.getUInt(ContextSpecificTag(TAG_TAG)) val label = if (!tlvReader.isNull()) { diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/DeviceEnergyManagementClusterForecastStruct.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/DeviceEnergyManagementClusterForecastStruct.kt index 2f3b23fc59..c554c72fb8 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/DeviceEnergyManagementClusterForecastStruct.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/DeviceEnergyManagementClusterForecastStruct.kt @@ -52,7 +52,7 @@ class DeviceEnergyManagementClusterForecastStruct( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_FORECAST_I_D), forecastID) + put(ContextSpecificTag(TAG_FORECAST_ID), forecastID) if (activeSlotNumber != null) { put(ContextSpecificTag(TAG_ACTIVE_SLOT_NUMBER), activeSlotNumber) } else { @@ -84,7 +84,7 @@ class DeviceEnergyManagementClusterForecastStruct( } companion object { - private const val TAG_FORECAST_I_D = 0 + private const val TAG_FORECAST_ID = 0 private const val TAG_ACTIVE_SLOT_NUMBER = 1 private const val TAG_START_TIME = 2 private const val TAG_END_TIME = 3 @@ -96,7 +96,7 @@ class DeviceEnergyManagementClusterForecastStruct( fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): DeviceEnergyManagementClusterForecastStruct { tlvReader.enterStructure(tlvTag) - val forecastID = tlvReader.getULong(ContextSpecificTag(TAG_FORECAST_I_D)) + val forecastID = tlvReader.getULong(ContextSpecificTag(TAG_FORECAST_ID)) val activeSlotNumber = if (!tlvReader.isNull()) { tlvReader.getUInt(ContextSpecificTag(TAG_ACTIVE_SLOT_NUMBER)) diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/DeviceEnergyManagementClusterSlotStruct.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/DeviceEnergyManagementClusterSlotStruct.kt index f966446dda..e33cd10f75 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/DeviceEnergyManagementClusterSlotStruct.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/DeviceEnergyManagementClusterSlotStruct.kt @@ -89,7 +89,7 @@ class DeviceEnergyManagementClusterSlotStruct( } if (manufacturerESAState.isPresent) { val optmanufacturerESAState = manufacturerESAState.get() - put(ContextSpecificTag(TAG_MANUFACTURER_E_S_A_STATE), optmanufacturerESAState) + put(ContextSpecificTag(TAG_MANUFACTURER_ESA_STATE), optmanufacturerESAState) } if (nominalPower.isPresent) { val optnominalPower = nominalPower.get() @@ -144,7 +144,7 @@ class DeviceEnergyManagementClusterSlotStruct( private const val TAG_SLOT_IS_PAUSABLE = 5 private const val TAG_MIN_PAUSE_DURATION = 6 private const val TAG_MAX_PAUSE_DURATION = 7 - private const val TAG_MANUFACTURER_E_S_A_STATE = 8 + private const val TAG_MANUFACTURER_ESA_STATE = 8 private const val TAG_NOMINAL_POWER = 9 private const val TAG_MIN_POWER = 10 private const val TAG_MAX_POWER = 11 @@ -181,8 +181,8 @@ class DeviceEnergyManagementClusterSlotStruct( Optional.empty() } val manufacturerESAState = - if (tlvReader.isNextTag(ContextSpecificTag(TAG_MANUFACTURER_E_S_A_STATE))) { - Optional.of(tlvReader.getUInt(ContextSpecificTag(TAG_MANUFACTURER_E_S_A_STATE))) + if (tlvReader.isNextTag(ContextSpecificTag(TAG_MANUFACTURER_ESA_STATE))) { + Optional.of(tlvReader.getUInt(ContextSpecificTag(TAG_MANUFACTURER_ESA_STATE))) } else { Optional.empty() } diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/EcosystemInformationClusterEcosystemLocationStruct.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/EcosystemInformationClusterEcosystemLocationStruct.kt index 5b1b7103aa..bb84dcffef 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/EcosystemInformationClusterEcosystemLocationStruct.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/EcosystemInformationClusterEcosystemLocationStruct.kt @@ -40,7 +40,7 @@ class EcosystemInformationClusterEcosystemLocationStruct( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_UNIQUE_LOCATION_I_D), uniqueLocationID) + put(ContextSpecificTag(TAG_UNIQUE_LOCATION_ID), uniqueLocationID) locationDescriptor.toTlv(ContextSpecificTag(TAG_LOCATION_DESCRIPTOR), this) put(ContextSpecificTag(TAG_LOCATION_DESCRIPTOR_LAST_EDIT), locationDescriptorLastEdit) put(ContextSpecificTag(TAG_FABRIC_INDEX), fabricIndex) @@ -49,7 +49,7 @@ class EcosystemInformationClusterEcosystemLocationStruct( } companion object { - private const val TAG_UNIQUE_LOCATION_I_D = 0 + private const val TAG_UNIQUE_LOCATION_ID = 0 private const val TAG_LOCATION_DESCRIPTOR = 1 private const val TAG_LOCATION_DESCRIPTOR_LAST_EDIT = 2 private const val TAG_FABRIC_INDEX = 254 @@ -59,7 +59,7 @@ class EcosystemInformationClusterEcosystemLocationStruct( tlvReader: TlvReader, ): EcosystemInformationClusterEcosystemLocationStruct { tlvReader.enterStructure(tlvTag) - val uniqueLocationID = tlvReader.getString(ContextSpecificTag(TAG_UNIQUE_LOCATION_I_D)) + val uniqueLocationID = tlvReader.getString(ContextSpecificTag(TAG_UNIQUE_LOCATION_ID)) val locationDescriptor = EcosystemInformationClusterLocationDescriptorStruct.fromTlv( ContextSpecificTag(TAG_LOCATION_DESCRIPTOR), diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/GroupKeyManagementClusterGroupKeyMapStruct.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/GroupKeyManagementClusterGroupKeyMapStruct.kt index ec1ba8a3ef..ddcab454a3 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/GroupKeyManagementClusterGroupKeyMapStruct.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/GroupKeyManagementClusterGroupKeyMapStruct.kt @@ -39,7 +39,7 @@ class GroupKeyManagementClusterGroupKeyMapStruct( tlvWriter.apply { startStructure(tlvTag) put(ContextSpecificTag(TAG_GROUP_ID), groupId) - put(ContextSpecificTag(TAG_GROUP_KEY_SET_I_D), groupKeySetID) + put(ContextSpecificTag(TAG_GROUP_KEY_SET_ID), groupKeySetID) put(ContextSpecificTag(TAG_FABRIC_INDEX), fabricIndex) endStructure() } @@ -47,13 +47,13 @@ class GroupKeyManagementClusterGroupKeyMapStruct( companion object { private const val TAG_GROUP_ID = 1 - private const val TAG_GROUP_KEY_SET_I_D = 2 + private const val TAG_GROUP_KEY_SET_ID = 2 private const val TAG_FABRIC_INDEX = 254 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): GroupKeyManagementClusterGroupKeyMapStruct { tlvReader.enterStructure(tlvTag) val groupId = tlvReader.getUInt(ContextSpecificTag(TAG_GROUP_ID)) - val groupKeySetID = tlvReader.getUInt(ContextSpecificTag(TAG_GROUP_KEY_SET_I_D)) + val groupKeySetID = tlvReader.getUInt(ContextSpecificTag(TAG_GROUP_KEY_SET_ID)) val fabricIndex = tlvReader.getUInt(ContextSpecificTag(TAG_FABRIC_INDEX)) tlvReader.exitContainer() diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/GroupKeyManagementClusterGroupKeySetStruct.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/GroupKeyManagementClusterGroupKeySetStruct.kt index e59269a882..5dd1291b0d 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/GroupKeyManagementClusterGroupKeySetStruct.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/GroupKeyManagementClusterGroupKeySetStruct.kt @@ -48,7 +48,7 @@ class GroupKeyManagementClusterGroupKeySetStruct( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_GROUP_KEY_SET_I_D), groupKeySetID) + put(ContextSpecificTag(TAG_GROUP_KEY_SET_ID), groupKeySetID) put(ContextSpecificTag(TAG_GROUP_KEY_SECURITY_POLICY), groupKeySecurityPolicy) if (epochKey0 != null) { put(ContextSpecificTag(TAG_EPOCH_KEY0), epochKey0) @@ -85,7 +85,7 @@ class GroupKeyManagementClusterGroupKeySetStruct( } companion object { - private const val TAG_GROUP_KEY_SET_I_D = 0 + private const val TAG_GROUP_KEY_SET_ID = 0 private const val TAG_GROUP_KEY_SECURITY_POLICY = 1 private const val TAG_EPOCH_KEY0 = 2 private const val TAG_EPOCH_START_TIME0 = 3 @@ -96,7 +96,7 @@ class GroupKeyManagementClusterGroupKeySetStruct( fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): GroupKeyManagementClusterGroupKeySetStruct { tlvReader.enterStructure(tlvTag) - val groupKeySetID = tlvReader.getUInt(ContextSpecificTag(TAG_GROUP_KEY_SET_I_D)) + val groupKeySetID = tlvReader.getUInt(ContextSpecificTag(TAG_GROUP_KEY_SET_ID)) val groupKeySecurityPolicy = tlvReader.getUInt(ContextSpecificTag(TAG_GROUP_KEY_SECURITY_POLICY)) val epochKey0 = diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/IcdManagementClusterMonitoringRegistrationStruct.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/IcdManagementClusterMonitoringRegistrationStruct.kt index fd60e6d6da..acdcc1643a 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/IcdManagementClusterMonitoringRegistrationStruct.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/IcdManagementClusterMonitoringRegistrationStruct.kt @@ -40,7 +40,7 @@ class IcdManagementClusterMonitoringRegistrationStruct( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_CHECK_IN_NODE_I_D), checkInNodeID) + put(ContextSpecificTag(TAG_CHECK_IN_NODE_ID), checkInNodeID) put(ContextSpecificTag(TAG_MONITORED_SUBJECT), monitoredSubject) put(ContextSpecificTag(TAG_CLIENT_TYPE), clientType) put(ContextSpecificTag(TAG_FABRIC_INDEX), fabricIndex) @@ -49,7 +49,7 @@ class IcdManagementClusterMonitoringRegistrationStruct( } companion object { - private const val TAG_CHECK_IN_NODE_I_D = 1 + private const val TAG_CHECK_IN_NODE_ID = 1 private const val TAG_MONITORED_SUBJECT = 2 private const val TAG_CLIENT_TYPE = 4 private const val TAG_FABRIC_INDEX = 254 @@ -59,7 +59,7 @@ class IcdManagementClusterMonitoringRegistrationStruct( tlvReader: TlvReader, ): IcdManagementClusterMonitoringRegistrationStruct { tlvReader.enterStructure(tlvTag) - val checkInNodeID = tlvReader.getULong(ContextSpecificTag(TAG_CHECK_IN_NODE_I_D)) + val checkInNodeID = tlvReader.getULong(ContextSpecificTag(TAG_CHECK_IN_NODE_ID)) val monitoredSubject = tlvReader.getULong(ContextSpecificTag(TAG_MONITORED_SUBJECT)) val clientType = tlvReader.getUInt(ContextSpecificTag(TAG_CLIENT_TYPE)) val fabricIndex = tlvReader.getUInt(ContextSpecificTag(TAG_FABRIC_INDEX)) diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/MessagesClusterMessageResponseOptionStruct.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/MessagesClusterMessageResponseOptionStruct.kt index b8707df671..0f582c0e9c 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/MessagesClusterMessageResponseOptionStruct.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/MessagesClusterMessageResponseOptionStruct.kt @@ -39,7 +39,7 @@ class MessagesClusterMessageResponseOptionStruct( startStructure(tlvTag) if (messageResponseID.isPresent) { val optmessageResponseID = messageResponseID.get() - put(ContextSpecificTag(TAG_MESSAGE_RESPONSE_I_D), optmessageResponseID) + put(ContextSpecificTag(TAG_MESSAGE_RESPONSE_ID), optmessageResponseID) } if (label.isPresent) { val optlabel = label.get() @@ -50,14 +50,14 @@ class MessagesClusterMessageResponseOptionStruct( } companion object { - private const val TAG_MESSAGE_RESPONSE_I_D = 0 + private const val TAG_MESSAGE_RESPONSE_ID = 0 private const val TAG_LABEL = 1 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): MessagesClusterMessageResponseOptionStruct { tlvReader.enterStructure(tlvTag) val messageResponseID = - if (tlvReader.isNextTag(ContextSpecificTag(TAG_MESSAGE_RESPONSE_I_D))) { - Optional.of(tlvReader.getULong(ContextSpecificTag(TAG_MESSAGE_RESPONSE_I_D))) + if (tlvReader.isNextTag(ContextSpecificTag(TAG_MESSAGE_RESPONSE_ID))) { + Optional.of(tlvReader.getULong(ContextSpecificTag(TAG_MESSAGE_RESPONSE_ID))) } else { Optional.empty() } diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/MessagesClusterMessageStruct.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/MessagesClusterMessageStruct.kt index 6ad4f41ee3..89657c60fd 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/MessagesClusterMessageStruct.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/MessagesClusterMessageStruct.kt @@ -48,7 +48,7 @@ class MessagesClusterMessageStruct( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_MESSAGE_I_D), messageID) + put(ContextSpecificTag(TAG_MESSAGE_ID), messageID) put(ContextSpecificTag(TAG_PRIORITY), priority) put(ContextSpecificTag(TAG_MESSAGE_CONTROL), messageControl) if (startTime != null) { @@ -75,7 +75,7 @@ class MessagesClusterMessageStruct( } companion object { - private const val TAG_MESSAGE_I_D = 0 + private const val TAG_MESSAGE_ID = 0 private const val TAG_PRIORITY = 1 private const val TAG_MESSAGE_CONTROL = 2 private const val TAG_START_TIME = 3 @@ -85,7 +85,7 @@ class MessagesClusterMessageStruct( fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): MessagesClusterMessageStruct { tlvReader.enterStructure(tlvTag) - val messageID = tlvReader.getByteArray(ContextSpecificTag(TAG_MESSAGE_I_D)) + val messageID = tlvReader.getByteArray(ContextSpecificTag(TAG_MESSAGE_ID)) val priority = tlvReader.getUInt(ContextSpecificTag(TAG_PRIORITY)) val messageControl = tlvReader.getUInt(ContextSpecificTag(TAG_MESSAGE_CONTROL)) val startTime = diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/NetworkCommissioningClusterNetworkInfoStruct.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/NetworkCommissioningClusterNetworkInfoStruct.kt index 6d120b2c6e..54bfcc1315 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/NetworkCommissioningClusterNetworkInfoStruct.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/NetworkCommissioningClusterNetworkInfoStruct.kt @@ -41,7 +41,7 @@ class NetworkCommissioningClusterNetworkInfoStruct( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_NETWORK_I_D), networkID) + put(ContextSpecificTag(TAG_NETWORK_ID), networkID) put(ContextSpecificTag(TAG_CONNECTED), connected) if (networkIdentifier != null) { if (networkIdentifier.isPresent) { @@ -64,14 +64,14 @@ class NetworkCommissioningClusterNetworkInfoStruct( } companion object { - private const val TAG_NETWORK_I_D = 0 + private const val TAG_NETWORK_ID = 0 private const val TAG_CONNECTED = 1 private const val TAG_NETWORK_IDENTIFIER = 2 private const val TAG_CLIENT_IDENTIFIER = 3 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): NetworkCommissioningClusterNetworkInfoStruct { tlvReader.enterStructure(tlvTag) - val networkID = tlvReader.getByteArray(ContextSpecificTag(TAG_NETWORK_I_D)) + val networkID = tlvReader.getByteArray(ContextSpecificTag(TAG_NETWORK_ID)) val connected = tlvReader.getBoolean(ContextSpecificTag(TAG_CONNECTED)) val networkIdentifier = if (!tlvReader.isNull()) { diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/OperationalCredentialsClusterFabricDescriptorStruct.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/OperationalCredentialsClusterFabricDescriptorStruct.kt index 5d2af6b686..938092f700 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/OperationalCredentialsClusterFabricDescriptorStruct.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/OperationalCredentialsClusterFabricDescriptorStruct.kt @@ -45,9 +45,9 @@ class OperationalCredentialsClusterFabricDescriptorStruct( tlvWriter.apply { startStructure(tlvTag) put(ContextSpecificTag(TAG_ROOT_PUBLIC_KEY), rootPublicKey) - put(ContextSpecificTag(TAG_VENDOR_I_D), vendorID) - put(ContextSpecificTag(TAG_FABRIC_I_D), fabricID) - put(ContextSpecificTag(TAG_NODE_I_D), nodeID) + put(ContextSpecificTag(TAG_VENDOR_ID), vendorID) + put(ContextSpecificTag(TAG_FABRIC_ID), fabricID) + put(ContextSpecificTag(TAG_NODE_ID), nodeID) put(ContextSpecificTag(TAG_LABEL), label) put(ContextSpecificTag(TAG_FABRIC_INDEX), fabricIndex) endStructure() @@ -56,9 +56,9 @@ class OperationalCredentialsClusterFabricDescriptorStruct( companion object { private const val TAG_ROOT_PUBLIC_KEY = 1 - private const val TAG_VENDOR_I_D = 2 - private const val TAG_FABRIC_I_D = 3 - private const val TAG_NODE_I_D = 4 + private const val TAG_VENDOR_ID = 2 + private const val TAG_FABRIC_ID = 3 + private const val TAG_NODE_ID = 4 private const val TAG_LABEL = 5 private const val TAG_FABRIC_INDEX = 254 @@ -68,9 +68,9 @@ class OperationalCredentialsClusterFabricDescriptorStruct( ): OperationalCredentialsClusterFabricDescriptorStruct { tlvReader.enterStructure(tlvTag) val rootPublicKey = tlvReader.getByteArray(ContextSpecificTag(TAG_ROOT_PUBLIC_KEY)) - val vendorID = tlvReader.getUInt(ContextSpecificTag(TAG_VENDOR_I_D)) - val fabricID = tlvReader.getULong(ContextSpecificTag(TAG_FABRIC_I_D)) - val nodeID = tlvReader.getULong(ContextSpecificTag(TAG_NODE_I_D)) + val vendorID = tlvReader.getUInt(ContextSpecificTag(TAG_VENDOR_ID)) + val fabricID = tlvReader.getULong(ContextSpecificTag(TAG_FABRIC_ID)) + val nodeID = tlvReader.getULong(ContextSpecificTag(TAG_NODE_ID)) val label = tlvReader.getString(ContextSpecificTag(TAG_LABEL)) val fabricIndex = tlvReader.getUInt(ContextSpecificTag(TAG_FABRIC_INDEX)) diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/OperationalStateClusterErrorStateStruct.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/OperationalStateClusterErrorStateStruct.kt index c2a0b9a58d..7f2f4b04d2 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/OperationalStateClusterErrorStateStruct.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/OperationalStateClusterErrorStateStruct.kt @@ -39,7 +39,7 @@ class OperationalStateClusterErrorStateStruct( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_ERROR_STATE_I_D), errorStateID) + put(ContextSpecificTag(TAG_ERROR_STATE_ID), errorStateID) if (errorStateLabel.isPresent) { val opterrorStateLabel = errorStateLabel.get() put(ContextSpecificTag(TAG_ERROR_STATE_LABEL), opterrorStateLabel) @@ -53,13 +53,13 @@ class OperationalStateClusterErrorStateStruct( } companion object { - private const val TAG_ERROR_STATE_I_D = 0 + private const val TAG_ERROR_STATE_ID = 0 private const val TAG_ERROR_STATE_LABEL = 1 private const val TAG_ERROR_STATE_DETAILS = 2 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): OperationalStateClusterErrorStateStruct { tlvReader.enterStructure(tlvTag) - val errorStateID = tlvReader.getUInt(ContextSpecificTag(TAG_ERROR_STATE_I_D)) + val errorStateID = tlvReader.getUInt(ContextSpecificTag(TAG_ERROR_STATE_ID)) val errorStateLabel = if (tlvReader.isNextTag(ContextSpecificTag(TAG_ERROR_STATE_LABEL))) { Optional.of(tlvReader.getString(ContextSpecificTag(TAG_ERROR_STATE_LABEL))) diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/OperationalStateClusterOperationalStateStruct.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/OperationalStateClusterOperationalStateStruct.kt index 558446e081..f07d7ec323 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/OperationalStateClusterOperationalStateStruct.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/OperationalStateClusterOperationalStateStruct.kt @@ -37,7 +37,7 @@ class OperationalStateClusterOperationalStateStruct( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_OPERATIONAL_STATE_I_D), operationalStateID) + put(ContextSpecificTag(TAG_OPERATIONAL_STATE_ID), operationalStateID) if (operationalStateLabel.isPresent) { val optoperationalStateLabel = operationalStateLabel.get() put(ContextSpecificTag(TAG_OPERATIONAL_STATE_LABEL), optoperationalStateLabel) @@ -47,12 +47,12 @@ class OperationalStateClusterOperationalStateStruct( } companion object { - private const val TAG_OPERATIONAL_STATE_I_D = 0 + private const val TAG_OPERATIONAL_STATE_ID = 0 private const val TAG_OPERATIONAL_STATE_LABEL = 1 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): OperationalStateClusterOperationalStateStruct { tlvReader.enterStructure(tlvTag) - val operationalStateID = tlvReader.getUInt(ContextSpecificTag(TAG_OPERATIONAL_STATE_I_D)) + val operationalStateID = tlvReader.getUInt(ContextSpecificTag(TAG_OPERATIONAL_STATE_ID)) val operationalStateLabel = if (tlvReader.isNextTag(ContextSpecificTag(TAG_OPERATIONAL_STATE_LABEL))) { Optional.of(tlvReader.getString(ContextSpecificTag(TAG_OPERATIONAL_STATE_LABEL))) diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/OtaSoftwareUpdateRequestorClusterProviderLocation.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/OtaSoftwareUpdateRequestorClusterProviderLocation.kt index 25e6467fff..a5f1882a6e 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/OtaSoftwareUpdateRequestorClusterProviderLocation.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/OtaSoftwareUpdateRequestorClusterProviderLocation.kt @@ -38,7 +38,7 @@ class OtaSoftwareUpdateRequestorClusterProviderLocation( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_PROVIDER_NODE_I_D), providerNodeID) + put(ContextSpecificTag(TAG_PROVIDER_NODE_ID), providerNodeID) put(ContextSpecificTag(TAG_ENDPOINT), endpoint) put(ContextSpecificTag(TAG_FABRIC_INDEX), fabricIndex) endStructure() @@ -46,7 +46,7 @@ class OtaSoftwareUpdateRequestorClusterProviderLocation( } companion object { - private const val TAG_PROVIDER_NODE_I_D = 1 + private const val TAG_PROVIDER_NODE_ID = 1 private const val TAG_ENDPOINT = 2 private const val TAG_FABRIC_INDEX = 254 @@ -55,7 +55,7 @@ class OtaSoftwareUpdateRequestorClusterProviderLocation( tlvReader: TlvReader, ): OtaSoftwareUpdateRequestorClusterProviderLocation { tlvReader.enterStructure(tlvTag) - val providerNodeID = tlvReader.getULong(ContextSpecificTag(TAG_PROVIDER_NODE_I_D)) + val providerNodeID = tlvReader.getULong(ContextSpecificTag(TAG_PROVIDER_NODE_ID)) val endpoint = tlvReader.getUInt(ContextSpecificTag(TAG_ENDPOINT)) val fabricIndex = tlvReader.getUInt(ContextSpecificTag(TAG_FABRIC_INDEX)) diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/OvenCavityOperationalStateClusterErrorStateStruct.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/OvenCavityOperationalStateClusterErrorStateStruct.kt index 741be20fc8..dbaea8f76b 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/OvenCavityOperationalStateClusterErrorStateStruct.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/OvenCavityOperationalStateClusterErrorStateStruct.kt @@ -39,7 +39,7 @@ class OvenCavityOperationalStateClusterErrorStateStruct( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_ERROR_STATE_I_D), errorStateID) + put(ContextSpecificTag(TAG_ERROR_STATE_ID), errorStateID) if (errorStateLabel.isPresent) { val opterrorStateLabel = errorStateLabel.get() put(ContextSpecificTag(TAG_ERROR_STATE_LABEL), opterrorStateLabel) @@ -53,7 +53,7 @@ class OvenCavityOperationalStateClusterErrorStateStruct( } companion object { - private const val TAG_ERROR_STATE_I_D = 0 + private const val TAG_ERROR_STATE_ID = 0 private const val TAG_ERROR_STATE_LABEL = 1 private const val TAG_ERROR_STATE_DETAILS = 2 @@ -62,7 +62,7 @@ class OvenCavityOperationalStateClusterErrorStateStruct( tlvReader: TlvReader, ): OvenCavityOperationalStateClusterErrorStateStruct { tlvReader.enterStructure(tlvTag) - val errorStateID = tlvReader.getUInt(ContextSpecificTag(TAG_ERROR_STATE_I_D)) + val errorStateID = tlvReader.getUInt(ContextSpecificTag(TAG_ERROR_STATE_ID)) val errorStateLabel = if (tlvReader.isNextTag(ContextSpecificTag(TAG_ERROR_STATE_LABEL))) { Optional.of(tlvReader.getString(ContextSpecificTag(TAG_ERROR_STATE_LABEL))) diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/OvenCavityOperationalStateClusterOperationalStateStruct.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/OvenCavityOperationalStateClusterOperationalStateStruct.kt index b8cc6c5082..7665b08f05 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/OvenCavityOperationalStateClusterOperationalStateStruct.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/OvenCavityOperationalStateClusterOperationalStateStruct.kt @@ -37,7 +37,7 @@ class OvenCavityOperationalStateClusterOperationalStateStruct( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_OPERATIONAL_STATE_I_D), operationalStateID) + put(ContextSpecificTag(TAG_OPERATIONAL_STATE_ID), operationalStateID) if (operationalStateLabel.isPresent) { val optoperationalStateLabel = operationalStateLabel.get() put(ContextSpecificTag(TAG_OPERATIONAL_STATE_LABEL), optoperationalStateLabel) @@ -47,7 +47,7 @@ class OvenCavityOperationalStateClusterOperationalStateStruct( } companion object { - private const val TAG_OPERATIONAL_STATE_I_D = 0 + private const val TAG_OPERATIONAL_STATE_ID = 0 private const val TAG_OPERATIONAL_STATE_LABEL = 1 fun fromTlv( @@ -55,7 +55,7 @@ class OvenCavityOperationalStateClusterOperationalStateStruct( tlvReader: TlvReader, ): OvenCavityOperationalStateClusterOperationalStateStruct { tlvReader.enterStructure(tlvTag) - val operationalStateID = tlvReader.getUInt(ContextSpecificTag(TAG_OPERATIONAL_STATE_I_D)) + val operationalStateID = tlvReader.getUInt(ContextSpecificTag(TAG_OPERATIONAL_STATE_ID)) val operationalStateLabel = if (tlvReader.isNextTag(ContextSpecificTag(TAG_OPERATIONAL_STATE_LABEL))) { Optional.of(tlvReader.getString(ContextSpecificTag(TAG_OPERATIONAL_STATE_LABEL))) diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/RvcOperationalStateClusterErrorStateStruct.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/RvcOperationalStateClusterErrorStateStruct.kt index c9cbcef319..b3d4b1b371 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/RvcOperationalStateClusterErrorStateStruct.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/RvcOperationalStateClusterErrorStateStruct.kt @@ -39,7 +39,7 @@ class RvcOperationalStateClusterErrorStateStruct( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_ERROR_STATE_I_D), errorStateID) + put(ContextSpecificTag(TAG_ERROR_STATE_ID), errorStateID) if (errorStateLabel.isPresent) { val opterrorStateLabel = errorStateLabel.get() put(ContextSpecificTag(TAG_ERROR_STATE_LABEL), opterrorStateLabel) @@ -53,13 +53,13 @@ class RvcOperationalStateClusterErrorStateStruct( } companion object { - private const val TAG_ERROR_STATE_I_D = 0 + private const val TAG_ERROR_STATE_ID = 0 private const val TAG_ERROR_STATE_LABEL = 1 private const val TAG_ERROR_STATE_DETAILS = 2 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): RvcOperationalStateClusterErrorStateStruct { tlvReader.enterStructure(tlvTag) - val errorStateID = tlvReader.getUInt(ContextSpecificTag(TAG_ERROR_STATE_I_D)) + val errorStateID = tlvReader.getUInt(ContextSpecificTag(TAG_ERROR_STATE_ID)) val errorStateLabel = if (tlvReader.isNextTag(ContextSpecificTag(TAG_ERROR_STATE_LABEL))) { Optional.of(tlvReader.getString(ContextSpecificTag(TAG_ERROR_STATE_LABEL))) diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/RvcOperationalStateClusterOperationalStateStruct.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/RvcOperationalStateClusterOperationalStateStruct.kt index d91e485a25..742857e296 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/RvcOperationalStateClusterOperationalStateStruct.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/RvcOperationalStateClusterOperationalStateStruct.kt @@ -37,7 +37,7 @@ class RvcOperationalStateClusterOperationalStateStruct( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_OPERATIONAL_STATE_I_D), operationalStateID) + put(ContextSpecificTag(TAG_OPERATIONAL_STATE_ID), operationalStateID) if (operationalStateLabel.isPresent) { val optoperationalStateLabel = operationalStateLabel.get() put(ContextSpecificTag(TAG_OPERATIONAL_STATE_LABEL), optoperationalStateLabel) @@ -47,7 +47,7 @@ class RvcOperationalStateClusterOperationalStateStruct( } companion object { - private const val TAG_OPERATIONAL_STATE_I_D = 0 + private const val TAG_OPERATIONAL_STATE_ID = 0 private const val TAG_OPERATIONAL_STATE_LABEL = 1 fun fromTlv( @@ -55,7 +55,7 @@ class RvcOperationalStateClusterOperationalStateStruct( tlvReader: TlvReader, ): RvcOperationalStateClusterOperationalStateStruct { tlvReader.enterStructure(tlvTag) - val operationalStateID = tlvReader.getUInt(ContextSpecificTag(TAG_OPERATIONAL_STATE_I_D)) + val operationalStateID = tlvReader.getUInt(ContextSpecificTag(TAG_OPERATIONAL_STATE_ID)) val operationalStateLabel = if (tlvReader.isNextTag(ContextSpecificTag(TAG_OPERATIONAL_STATE_LABEL))) { Optional.of(tlvReader.getString(ContextSpecificTag(TAG_OPERATIONAL_STATE_LABEL))) diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ScenesManagementClusterAttributeValuePairStruct.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ScenesManagementClusterAttributeValuePairStruct.kt index f8526c71f9..80cafb3842 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ScenesManagementClusterAttributeValuePairStruct.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ScenesManagementClusterAttributeValuePairStruct.kt @@ -51,7 +51,7 @@ class ScenesManagementClusterAttributeValuePairStruct( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_ATTRIBUTE_I_D), attributeID) + put(ContextSpecificTag(TAG_ATTRIBUTE_ID), attributeID) if (valueUnsigned8.isPresent) { val optvalueUnsigned8 = valueUnsigned8.get() put(ContextSpecificTag(TAG_VALUE_UNSIGNED8), optvalueUnsigned8) @@ -89,7 +89,7 @@ class ScenesManagementClusterAttributeValuePairStruct( } companion object { - private const val TAG_ATTRIBUTE_I_D = 0 + private const val TAG_ATTRIBUTE_ID = 0 private const val TAG_VALUE_UNSIGNED8 = 1 private const val TAG_VALUE_SIGNED8 = 2 private const val TAG_VALUE_UNSIGNED16 = 3 @@ -104,7 +104,7 @@ class ScenesManagementClusterAttributeValuePairStruct( tlvReader: TlvReader, ): ScenesManagementClusterAttributeValuePairStruct { tlvReader.enterStructure(tlvTag) - val attributeID = tlvReader.getULong(ContextSpecificTag(TAG_ATTRIBUTE_I_D)) + val attributeID = tlvReader.getULong(ContextSpecificTag(TAG_ATTRIBUTE_ID)) val valueUnsigned8 = if (tlvReader.isNextTag(ContextSpecificTag(TAG_VALUE_UNSIGNED8))) { Optional.of(tlvReader.getUInt(ContextSpecificTag(TAG_VALUE_UNSIGNED8))) diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ScenesManagementClusterExtensionFieldSet.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ScenesManagementClusterExtensionFieldSet.kt index a2add79480..31759e0aaa 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ScenesManagementClusterExtensionFieldSet.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ScenesManagementClusterExtensionFieldSet.kt @@ -37,7 +37,7 @@ class ScenesManagementClusterExtensionFieldSet( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_CLUSTER_I_D), clusterID) + put(ContextSpecificTag(TAG_CLUSTER_ID), clusterID) startArray(ContextSpecificTag(TAG_ATTRIBUTE_VALUE_LIST)) for (item in attributeValueList.iterator()) { item.toTlv(AnonymousTag, this) @@ -48,12 +48,12 @@ class ScenesManagementClusterExtensionFieldSet( } companion object { - private const val TAG_CLUSTER_I_D = 0 + private const val TAG_CLUSTER_ID = 0 private const val TAG_ATTRIBUTE_VALUE_LIST = 1 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): ScenesManagementClusterExtensionFieldSet { tlvReader.enterStructure(tlvTag) - val clusterID = tlvReader.getULong(ContextSpecificTag(TAG_CLUSTER_I_D)) + val clusterID = tlvReader.getULong(ContextSpecificTag(TAG_CLUSTER_ID)) val attributeValueList = buildList { tlvReader.enterArray(ContextSpecificTag(TAG_ATTRIBUTE_VALUE_LIST)) diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ServiceAreaClusterAreaStruct.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ServiceAreaClusterAreaStruct.kt index 3f8365d49b..fc6405a96c 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ServiceAreaClusterAreaStruct.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ServiceAreaClusterAreaStruct.kt @@ -38,11 +38,11 @@ class ServiceAreaClusterAreaStruct( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_AREA_I_D), areaID) + put(ContextSpecificTag(TAG_AREA_ID), areaID) if (mapID != null) { - put(ContextSpecificTag(TAG_MAP_I_D), mapID) + put(ContextSpecificTag(TAG_MAP_ID), mapID) } else { - putNull(ContextSpecificTag(TAG_MAP_I_D)) + putNull(ContextSpecificTag(TAG_MAP_ID)) } areaDesc.toTlv(ContextSpecificTag(TAG_AREA_DESC), this) endStructure() @@ -50,18 +50,18 @@ class ServiceAreaClusterAreaStruct( } companion object { - private const val TAG_AREA_I_D = 0 - private const val TAG_MAP_I_D = 1 + private const val TAG_AREA_ID = 0 + private const val TAG_MAP_ID = 1 private const val TAG_AREA_DESC = 2 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): ServiceAreaClusterAreaStruct { tlvReader.enterStructure(tlvTag) - val areaID = tlvReader.getULong(ContextSpecificTag(TAG_AREA_I_D)) + val areaID = tlvReader.getULong(ContextSpecificTag(TAG_AREA_ID)) val mapID = if (!tlvReader.isNull()) { - tlvReader.getULong(ContextSpecificTag(TAG_MAP_I_D)) + tlvReader.getULong(ContextSpecificTag(TAG_MAP_ID)) } else { - tlvReader.getNull(ContextSpecificTag(TAG_MAP_I_D)) + tlvReader.getNull(ContextSpecificTag(TAG_MAP_ID)) null } val areaDesc = diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ServiceAreaClusterMapStruct.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ServiceAreaClusterMapStruct.kt index f00877354d..a245321b6b 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ServiceAreaClusterMapStruct.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ServiceAreaClusterMapStruct.kt @@ -33,19 +33,19 @@ class ServiceAreaClusterMapStruct(val mapID: ULong, val name: String) { fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_MAP_I_D), mapID) + put(ContextSpecificTag(TAG_MAP_ID), mapID) put(ContextSpecificTag(TAG_NAME), name) endStructure() } } companion object { - private const val TAG_MAP_I_D = 0 + private const val TAG_MAP_ID = 0 private const val TAG_NAME = 1 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): ServiceAreaClusterMapStruct { tlvReader.enterStructure(tlvTag) - val mapID = tlvReader.getULong(ContextSpecificTag(TAG_MAP_I_D)) + val mapID = tlvReader.getULong(ContextSpecificTag(TAG_MAP_ID)) val name = tlvReader.getString(ContextSpecificTag(TAG_NAME)) tlvReader.exitContainer() diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ServiceAreaClusterProgressStruct.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ServiceAreaClusterProgressStruct.kt index ddc8238168..684f188058 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ServiceAreaClusterProgressStruct.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ServiceAreaClusterProgressStruct.kt @@ -41,7 +41,7 @@ class ServiceAreaClusterProgressStruct( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_AREA_I_D), areaID) + put(ContextSpecificTag(TAG_AREA_ID), areaID) put(ContextSpecificTag(TAG_STATUS), status) if (totalOperationalTime != null) { if (totalOperationalTime.isPresent) { @@ -64,14 +64,14 @@ class ServiceAreaClusterProgressStruct( } companion object { - private const val TAG_AREA_I_D = 0 + private const val TAG_AREA_ID = 0 private const val TAG_STATUS = 1 private const val TAG_TOTAL_OPERATIONAL_TIME = 2 private const val TAG_ESTIMATED_TIME = 3 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): ServiceAreaClusterProgressStruct { tlvReader.enterStructure(tlvTag) - val areaID = tlvReader.getULong(ContextSpecificTag(TAG_AREA_I_D)) + val areaID = tlvReader.getULong(ContextSpecificTag(TAG_AREA_ID)) val status = tlvReader.getUInt(ContextSpecificTag(TAG_STATUS)) val totalOperationalTime = if (!tlvReader.isNull()) { diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ThermostatClusterAtomicAttributeStatusStruct.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ThermostatClusterAtomicAttributeStatusStruct.kt index 7500a9619d..6073c7c915 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ThermostatClusterAtomicAttributeStatusStruct.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ThermostatClusterAtomicAttributeStatusStruct.kt @@ -33,19 +33,19 @@ class ThermostatClusterAtomicAttributeStatusStruct(val attributeID: ULong, val s fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_ATTRIBUTE_I_D), attributeID) + put(ContextSpecificTag(TAG_ATTRIBUTE_ID), attributeID) put(ContextSpecificTag(TAG_STATUS_CODE), statusCode) endStructure() } } companion object { - private const val TAG_ATTRIBUTE_I_D = 0 + private const val TAG_ATTRIBUTE_ID = 0 private const val TAG_STATUS_CODE = 1 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): ThermostatClusterAtomicAttributeStatusStruct { tlvReader.enterStructure(tlvTag) - val attributeID = tlvReader.getULong(ContextSpecificTag(TAG_ATTRIBUTE_I_D)) + val attributeID = tlvReader.getULong(ContextSpecificTag(TAG_ATTRIBUTE_ID)) val statusCode = tlvReader.getUInt(ContextSpecificTag(TAG_STATUS_CODE)) tlvReader.exitContainer() diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ThreadNetworkDiagnosticsClusterRouteTableStruct.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ThreadNetworkDiagnosticsClusterRouteTableStruct.kt index a5b201c7e1..9ec7421f26 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ThreadNetworkDiagnosticsClusterRouteTableStruct.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ThreadNetworkDiagnosticsClusterRouteTableStruct.kt @@ -57,8 +57,8 @@ class ThreadNetworkDiagnosticsClusterRouteTableStruct( put(ContextSpecificTag(TAG_ROUTER_ID), routerId) put(ContextSpecificTag(TAG_NEXT_HOP), nextHop) put(ContextSpecificTag(TAG_PATH_COST), pathCost) - put(ContextSpecificTag(TAG_L_Q_I_IN), LQIIn) - put(ContextSpecificTag(TAG_L_Q_I_OUT), LQIOut) + put(ContextSpecificTag(TAG_LQI_IN), LQIIn) + put(ContextSpecificTag(TAG_LQI_OUT), LQIOut) put(ContextSpecificTag(TAG_AGE), age) put(ContextSpecificTag(TAG_ALLOCATED), allocated) put(ContextSpecificTag(TAG_LINK_ESTABLISHED), linkEstablished) @@ -72,8 +72,8 @@ class ThreadNetworkDiagnosticsClusterRouteTableStruct( private const val TAG_ROUTER_ID = 2 private const val TAG_NEXT_HOP = 3 private const val TAG_PATH_COST = 4 - private const val TAG_L_Q_I_IN = 5 - private const val TAG_L_Q_I_OUT = 6 + private const val TAG_LQI_IN = 5 + private const val TAG_LQI_OUT = 6 private const val TAG_AGE = 7 private const val TAG_ALLOCATED = 8 private const val TAG_LINK_ESTABLISHED = 9 @@ -88,8 +88,8 @@ class ThreadNetworkDiagnosticsClusterRouteTableStruct( val routerId = tlvReader.getUInt(ContextSpecificTag(TAG_ROUTER_ID)) val nextHop = tlvReader.getUInt(ContextSpecificTag(TAG_NEXT_HOP)) val pathCost = tlvReader.getUInt(ContextSpecificTag(TAG_PATH_COST)) - val LQIIn = tlvReader.getUInt(ContextSpecificTag(TAG_L_Q_I_IN)) - val LQIOut = tlvReader.getUInt(ContextSpecificTag(TAG_L_Q_I_OUT)) + val LQIIn = tlvReader.getUInt(ContextSpecificTag(TAG_LQI_IN)) + val LQIOut = tlvReader.getUInt(ContextSpecificTag(TAG_LQI_OUT)) val age = tlvReader.getUInt(ContextSpecificTag(TAG_AGE)) val allocated = tlvReader.getBoolean(ContextSpecificTag(TAG_ALLOCATED)) val linkEstablished = tlvReader.getBoolean(ContextSpecificTag(TAG_LINK_ESTABLISHED)) diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ThreadNetworkDirectoryClusterThreadNetworkStruct.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ThreadNetworkDirectoryClusterThreadNetworkStruct.kt index ae988738b7..f71764e028 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ThreadNetworkDirectoryClusterThreadNetworkStruct.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ThreadNetworkDirectoryClusterThreadNetworkStruct.kt @@ -40,7 +40,7 @@ class ThreadNetworkDirectoryClusterThreadNetworkStruct( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_EXTENDED_PAN_I_D), extendedPanID) + put(ContextSpecificTag(TAG_EXTENDED_PAN_ID), extendedPanID) put(ContextSpecificTag(TAG_NETWORK_NAME), networkName) put(ContextSpecificTag(TAG_CHANNEL), channel) put(ContextSpecificTag(TAG_ACTIVE_TIMESTAMP), activeTimestamp) @@ -49,7 +49,7 @@ class ThreadNetworkDirectoryClusterThreadNetworkStruct( } companion object { - private const val TAG_EXTENDED_PAN_I_D = 0 + private const val TAG_EXTENDED_PAN_ID = 0 private const val TAG_NETWORK_NAME = 1 private const val TAG_CHANNEL = 2 private const val TAG_ACTIVE_TIMESTAMP = 3 @@ -59,7 +59,7 @@ class ThreadNetworkDirectoryClusterThreadNetworkStruct( tlvReader: TlvReader, ): ThreadNetworkDirectoryClusterThreadNetworkStruct { tlvReader.enterStructure(tlvTag) - val extendedPanID = tlvReader.getByteArray(ContextSpecificTag(TAG_EXTENDED_PAN_I_D)) + val extendedPanID = tlvReader.getByteArray(ContextSpecificTag(TAG_EXTENDED_PAN_ID)) val networkName = tlvReader.getString(ContextSpecificTag(TAG_NETWORK_NAME)) val channel = tlvReader.getUInt(ContextSpecificTag(TAG_CHANNEL)) val activeTimestamp = tlvReader.getULong(ContextSpecificTag(TAG_ACTIVE_TIMESTAMP)) diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/TimeSynchronizationClusterFabricScopedTrustedTimeSourceStruct.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/TimeSynchronizationClusterFabricScopedTrustedTimeSourceStruct.kt index f9eb70cd13..49458e2b72 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/TimeSynchronizationClusterFabricScopedTrustedTimeSourceStruct.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/TimeSynchronizationClusterFabricScopedTrustedTimeSourceStruct.kt @@ -36,14 +36,14 @@ class TimeSynchronizationClusterFabricScopedTrustedTimeSourceStruct( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_NODE_I_D), nodeID) + put(ContextSpecificTag(TAG_NODE_ID), nodeID) put(ContextSpecificTag(TAG_ENDPOINT), endpoint) endStructure() } } companion object { - private const val TAG_NODE_I_D = 0 + private const val TAG_NODE_ID = 0 private const val TAG_ENDPOINT = 1 fun fromTlv( @@ -51,7 +51,7 @@ class TimeSynchronizationClusterFabricScopedTrustedTimeSourceStruct( tlvReader: TlvReader, ): TimeSynchronizationClusterFabricScopedTrustedTimeSourceStruct { tlvReader.enterStructure(tlvTag) - val nodeID = tlvReader.getULong(ContextSpecificTag(TAG_NODE_I_D)) + val nodeID = tlvReader.getULong(ContextSpecificTag(TAG_NODE_ID)) val endpoint = tlvReader.getUInt(ContextSpecificTag(TAG_ENDPOINT)) tlvReader.exitContainer() diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/TimeSynchronizationClusterTrustedTimeSourceStruct.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/TimeSynchronizationClusterTrustedTimeSourceStruct.kt index 6b55677ffd..12dd09376a 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/TimeSynchronizationClusterTrustedTimeSourceStruct.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/TimeSynchronizationClusterTrustedTimeSourceStruct.kt @@ -39,7 +39,7 @@ class TimeSynchronizationClusterTrustedTimeSourceStruct( tlvWriter.apply { startStructure(tlvTag) put(ContextSpecificTag(TAG_FABRIC_INDEX), fabricIndex) - put(ContextSpecificTag(TAG_NODE_I_D), nodeID) + put(ContextSpecificTag(TAG_NODE_ID), nodeID) put(ContextSpecificTag(TAG_ENDPOINT), endpoint) endStructure() } @@ -47,7 +47,7 @@ class TimeSynchronizationClusterTrustedTimeSourceStruct( companion object { private const val TAG_FABRIC_INDEX = 0 - private const val TAG_NODE_I_D = 1 + private const val TAG_NODE_ID = 1 private const val TAG_ENDPOINT = 2 fun fromTlv( @@ -56,7 +56,7 @@ class TimeSynchronizationClusterTrustedTimeSourceStruct( ): TimeSynchronizationClusterTrustedTimeSourceStruct { tlvReader.enterStructure(tlvTag) val fabricIndex = tlvReader.getUInt(ContextSpecificTag(TAG_FABRIC_INDEX)) - val nodeID = tlvReader.getULong(ContextSpecificTag(TAG_NODE_I_D)) + val nodeID = tlvReader.getULong(ContextSpecificTag(TAG_NODE_ID)) val endpoint = tlvReader.getUInt(ContextSpecificTag(TAG_ENDPOINT)) tlvReader.exitContainer() diff --git a/src/controller/java/generated/java/matter/controller/cluster/clusters/AccountLoginCluster.kt b/src/controller/java/generated/java/matter/controller/cluster/clusters/AccountLoginCluster.kt index 2d95215a32..3357ffff9b 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/clusters/AccountLoginCluster.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/clusters/AccountLoginCluster.kt @@ -110,13 +110,13 @@ class AccountLoginCluster( val tlvReader = TlvReader(response.payload) tlvReader.enterStructure(AnonymousTag) - val TAG_SETUP_P_I_N: Int = 0 + val TAG_SETUP_PIN: Int = 0 var setupPIN_decoded: String? = null while (!tlvReader.isEndOfContainer()) { val tag = tlvReader.peekElement().tag - if (tag == ContextSpecificTag(TAG_SETUP_P_I_N)) { + if (tag == ContextSpecificTag(TAG_SETUP_PIN)) { setupPIN_decoded = tlvReader.getString(tag) } else { tlvReader.skipElement() @@ -146,8 +146,8 @@ class AccountLoginCluster( val TAG_TEMP_ACCOUNT_IDENTIFIER_REQ: Int = 0 tlvWriter.put(ContextSpecificTag(TAG_TEMP_ACCOUNT_IDENTIFIER_REQ), tempAccountIdentifier) - val TAG_SETUP_P_I_N_REQ: Int = 1 - tlvWriter.put(ContextSpecificTag(TAG_SETUP_P_I_N_REQ), setupPIN) + val TAG_SETUP_PIN_REQ: Int = 1 + tlvWriter.put(ContextSpecificTag(TAG_SETUP_PIN_REQ), setupPIN) val TAG_NODE_REQ: Int = 2 node?.let { tlvWriter.put(ContextSpecificTag(TAG_NODE_REQ), node) } diff --git a/src/controller/java/generated/java/matter/controller/cluster/clusters/ActionsCluster.kt b/src/controller/java/generated/java/matter/controller/cluster/clusters/ActionsCluster.kt index 2246c4663c..79245c8dc8 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/clusters/ActionsCluster.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/clusters/ActionsCluster.kt @@ -113,11 +113,11 @@ class ActionsCluster(private val controller: MatterController, private val endpo val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_ACTION_I_D_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_ACTION_I_D_REQ), actionID) + val TAG_ACTION_ID_REQ: Int = 0 + tlvWriter.put(ContextSpecificTag(TAG_ACTION_ID_REQ), actionID) - val TAG_INVOKE_I_D_REQ: Int = 1 - invokeID?.let { tlvWriter.put(ContextSpecificTag(TAG_INVOKE_I_D_REQ), invokeID) } + val TAG_INVOKE_ID_REQ: Int = 1 + invokeID?.let { tlvWriter.put(ContextSpecificTag(TAG_INVOKE_ID_REQ), invokeID) } tlvWriter.endStructure() val request: InvokeRequest = @@ -142,11 +142,11 @@ class ActionsCluster(private val controller: MatterController, private val endpo val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_ACTION_I_D_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_ACTION_I_D_REQ), actionID) + val TAG_ACTION_ID_REQ: Int = 0 + tlvWriter.put(ContextSpecificTag(TAG_ACTION_ID_REQ), actionID) - val TAG_INVOKE_I_D_REQ: Int = 1 - invokeID?.let { tlvWriter.put(ContextSpecificTag(TAG_INVOKE_I_D_REQ), invokeID) } + val TAG_INVOKE_ID_REQ: Int = 1 + invokeID?.let { tlvWriter.put(ContextSpecificTag(TAG_INVOKE_ID_REQ), invokeID) } val TAG_TRANSITION_TIME_REQ: Int = 2 tlvWriter.put(ContextSpecificTag(TAG_TRANSITION_TIME_REQ), transitionTime) @@ -169,11 +169,11 @@ class ActionsCluster(private val controller: MatterController, private val endpo val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_ACTION_I_D_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_ACTION_I_D_REQ), actionID) + val TAG_ACTION_ID_REQ: Int = 0 + tlvWriter.put(ContextSpecificTag(TAG_ACTION_ID_REQ), actionID) - val TAG_INVOKE_I_D_REQ: Int = 1 - invokeID?.let { tlvWriter.put(ContextSpecificTag(TAG_INVOKE_I_D_REQ), invokeID) } + val TAG_INVOKE_ID_REQ: Int = 1 + invokeID?.let { tlvWriter.put(ContextSpecificTag(TAG_INVOKE_ID_REQ), invokeID) } tlvWriter.endStructure() val request: InvokeRequest = @@ -198,11 +198,11 @@ class ActionsCluster(private val controller: MatterController, private val endpo val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_ACTION_I_D_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_ACTION_I_D_REQ), actionID) + val TAG_ACTION_ID_REQ: Int = 0 + tlvWriter.put(ContextSpecificTag(TAG_ACTION_ID_REQ), actionID) - val TAG_INVOKE_I_D_REQ: Int = 1 - invokeID?.let { tlvWriter.put(ContextSpecificTag(TAG_INVOKE_I_D_REQ), invokeID) } + val TAG_INVOKE_ID_REQ: Int = 1 + invokeID?.let { tlvWriter.put(ContextSpecificTag(TAG_INVOKE_ID_REQ), invokeID) } val TAG_DURATION_REQ: Int = 2 tlvWriter.put(ContextSpecificTag(TAG_DURATION_REQ), duration) @@ -225,11 +225,11 @@ class ActionsCluster(private val controller: MatterController, private val endpo val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_ACTION_I_D_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_ACTION_I_D_REQ), actionID) + val TAG_ACTION_ID_REQ: Int = 0 + tlvWriter.put(ContextSpecificTag(TAG_ACTION_ID_REQ), actionID) - val TAG_INVOKE_I_D_REQ: Int = 1 - invokeID?.let { tlvWriter.put(ContextSpecificTag(TAG_INVOKE_I_D_REQ), invokeID) } + val TAG_INVOKE_ID_REQ: Int = 1 + invokeID?.let { tlvWriter.put(ContextSpecificTag(TAG_INVOKE_ID_REQ), invokeID) } tlvWriter.endStructure() val request: InvokeRequest = @@ -249,11 +249,11 @@ class ActionsCluster(private val controller: MatterController, private val endpo val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_ACTION_I_D_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_ACTION_I_D_REQ), actionID) + val TAG_ACTION_ID_REQ: Int = 0 + tlvWriter.put(ContextSpecificTag(TAG_ACTION_ID_REQ), actionID) - val TAG_INVOKE_I_D_REQ: Int = 1 - invokeID?.let { tlvWriter.put(ContextSpecificTag(TAG_INVOKE_I_D_REQ), invokeID) } + val TAG_INVOKE_ID_REQ: Int = 1 + invokeID?.let { tlvWriter.put(ContextSpecificTag(TAG_INVOKE_ID_REQ), invokeID) } tlvWriter.endStructure() val request: InvokeRequest = @@ -278,11 +278,11 @@ class ActionsCluster(private val controller: MatterController, private val endpo val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_ACTION_I_D_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_ACTION_I_D_REQ), actionID) + val TAG_ACTION_ID_REQ: Int = 0 + tlvWriter.put(ContextSpecificTag(TAG_ACTION_ID_REQ), actionID) - val TAG_INVOKE_I_D_REQ: Int = 1 - invokeID?.let { tlvWriter.put(ContextSpecificTag(TAG_INVOKE_I_D_REQ), invokeID) } + val TAG_INVOKE_ID_REQ: Int = 1 + invokeID?.let { tlvWriter.put(ContextSpecificTag(TAG_INVOKE_ID_REQ), invokeID) } val TAG_DURATION_REQ: Int = 2 tlvWriter.put(ContextSpecificTag(TAG_DURATION_REQ), duration) @@ -309,11 +309,11 @@ class ActionsCluster(private val controller: MatterController, private val endpo val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_ACTION_I_D_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_ACTION_I_D_REQ), actionID) + val TAG_ACTION_ID_REQ: Int = 0 + tlvWriter.put(ContextSpecificTag(TAG_ACTION_ID_REQ), actionID) - val TAG_INVOKE_I_D_REQ: Int = 1 - invokeID?.let { tlvWriter.put(ContextSpecificTag(TAG_INVOKE_I_D_REQ), invokeID) } + val TAG_INVOKE_ID_REQ: Int = 1 + invokeID?.let { tlvWriter.put(ContextSpecificTag(TAG_INVOKE_ID_REQ), invokeID) } tlvWriter.endStructure() val request: InvokeRequest = @@ -337,11 +337,11 @@ class ActionsCluster(private val controller: MatterController, private val endpo val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_ACTION_I_D_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_ACTION_I_D_REQ), actionID) + val TAG_ACTION_ID_REQ: Int = 0 + tlvWriter.put(ContextSpecificTag(TAG_ACTION_ID_REQ), actionID) - val TAG_INVOKE_I_D_REQ: Int = 1 - invokeID?.let { tlvWriter.put(ContextSpecificTag(TAG_INVOKE_I_D_REQ), invokeID) } + val TAG_INVOKE_ID_REQ: Int = 1 + invokeID?.let { tlvWriter.put(ContextSpecificTag(TAG_INVOKE_ID_REQ), invokeID) } tlvWriter.endStructure() val request: InvokeRequest = @@ -366,11 +366,11 @@ class ActionsCluster(private val controller: MatterController, private val endpo val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_ACTION_I_D_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_ACTION_I_D_REQ), actionID) + val TAG_ACTION_ID_REQ: Int = 0 + tlvWriter.put(ContextSpecificTag(TAG_ACTION_ID_REQ), actionID) - val TAG_INVOKE_I_D_REQ: Int = 1 - invokeID?.let { tlvWriter.put(ContextSpecificTag(TAG_INVOKE_I_D_REQ), invokeID) } + val TAG_INVOKE_ID_REQ: Int = 1 + invokeID?.let { tlvWriter.put(ContextSpecificTag(TAG_INVOKE_ID_REQ), invokeID) } val TAG_DURATION_REQ: Int = 2 tlvWriter.put(ContextSpecificTag(TAG_DURATION_REQ), duration) @@ -397,11 +397,11 @@ class ActionsCluster(private val controller: MatterController, private val endpo val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_ACTION_I_D_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_ACTION_I_D_REQ), actionID) + val TAG_ACTION_ID_REQ: Int = 0 + tlvWriter.put(ContextSpecificTag(TAG_ACTION_ID_REQ), actionID) - val TAG_INVOKE_I_D_REQ: Int = 1 - invokeID?.let { tlvWriter.put(ContextSpecificTag(TAG_INVOKE_I_D_REQ), invokeID) } + val TAG_INVOKE_ID_REQ: Int = 1 + invokeID?.let { tlvWriter.put(ContextSpecificTag(TAG_INVOKE_ID_REQ), invokeID) } tlvWriter.endStructure() val request: InvokeRequest = @@ -426,11 +426,11 @@ class ActionsCluster(private val controller: MatterController, private val endpo val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_ACTION_I_D_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_ACTION_I_D_REQ), actionID) + val TAG_ACTION_ID_REQ: Int = 0 + tlvWriter.put(ContextSpecificTag(TAG_ACTION_ID_REQ), actionID) - val TAG_INVOKE_I_D_REQ: Int = 1 - invokeID?.let { tlvWriter.put(ContextSpecificTag(TAG_INVOKE_I_D_REQ), invokeID) } + val TAG_INVOKE_ID_REQ: Int = 1 + invokeID?.let { tlvWriter.put(ContextSpecificTag(TAG_INVOKE_ID_REQ), invokeID) } val TAG_DURATION_REQ: Int = 2 tlvWriter.put(ContextSpecificTag(TAG_DURATION_REQ), duration) diff --git a/src/controller/java/generated/java/matter/controller/cluster/clusters/AdministratorCommissioningCluster.kt b/src/controller/java/generated/java/matter/controller/cluster/clusters/AdministratorCommissioningCluster.kt index a9ea4c35f0..5ac1e18a20 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/clusters/AdministratorCommissioningCluster.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/clusters/AdministratorCommissioningCluster.kt @@ -120,8 +120,8 @@ class AdministratorCommissioningCluster( val TAG_COMMISSIONING_TIMEOUT_REQ: Int = 0 tlvWriter.put(ContextSpecificTag(TAG_COMMISSIONING_TIMEOUT_REQ), commissioningTimeout) - val TAG_P_A_K_E_PASSCODE_VERIFIER_REQ: Int = 1 - tlvWriter.put(ContextSpecificTag(TAG_P_A_K_E_PASSCODE_VERIFIER_REQ), PAKEPasscodeVerifier) + val TAG_PAKE_PASSCODE_VERIFIER_REQ: Int = 1 + tlvWriter.put(ContextSpecificTag(TAG_PAKE_PASSCODE_VERIFIER_REQ), PAKEPasscodeVerifier) val TAG_DISCRIMINATOR_REQ: Int = 2 tlvWriter.put(ContextSpecificTag(TAG_DISCRIMINATOR_REQ), discriminator) diff --git a/src/controller/java/generated/java/matter/controller/cluster/clusters/ChannelCluster.kt b/src/controller/java/generated/java/matter/controller/cluster/clusters/ChannelCluster.kt index 3bbf5997d1..67eccfdb21 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/clusters/ChannelCluster.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/clusters/ChannelCluster.kt @@ -269,9 +269,9 @@ class ChannelCluster(private val controller: MatterController, private val endpo val TAG_RECORDING_FLAG_REQ: Int = 4 recordingFlag?.let { tlvWriter.put(ContextSpecificTag(TAG_RECORDING_FLAG_REQ), recordingFlag) } - val TAG_EXTERNAL_I_D_LIST_REQ: Int = 5 + val TAG_EXTERNAL_ID_LIST_REQ: Int = 5 externalIDList?.let { - tlvWriter.startArray(ContextSpecificTag(TAG_EXTERNAL_I_D_LIST_REQ)) + tlvWriter.startArray(ContextSpecificTag(TAG_EXTERNAL_ID_LIST_REQ)) for (item in externalIDList.iterator()) { item.toTlv(AnonymousTag, tlvWriter) } @@ -352,8 +352,8 @@ class ChannelCluster(private val controller: MatterController, private val endpo val TAG_SHOULD_RECORD_SERIES_REQ: Int = 1 tlvWriter.put(ContextSpecificTag(TAG_SHOULD_RECORD_SERIES_REQ), shouldRecordSeries) - val TAG_EXTERNAL_I_D_LIST_REQ: Int = 2 - tlvWriter.startArray(ContextSpecificTag(TAG_EXTERNAL_I_D_LIST_REQ)) + val TAG_EXTERNAL_ID_LIST_REQ: Int = 2 + tlvWriter.startArray(ContextSpecificTag(TAG_EXTERNAL_ID_LIST_REQ)) for (item in externalIDList.iterator()) { item.toTlv(AnonymousTag, tlvWriter) } @@ -392,8 +392,8 @@ class ChannelCluster(private val controller: MatterController, private val endpo val TAG_SHOULD_RECORD_SERIES_REQ: Int = 1 tlvWriter.put(ContextSpecificTag(TAG_SHOULD_RECORD_SERIES_REQ), shouldRecordSeries) - val TAG_EXTERNAL_I_D_LIST_REQ: Int = 2 - tlvWriter.startArray(ContextSpecificTag(TAG_EXTERNAL_I_D_LIST_REQ)) + val TAG_EXTERNAL_ID_LIST_REQ: Int = 2 + tlvWriter.startArray(ContextSpecificTag(TAG_EXTERNAL_ID_LIST_REQ)) for (item in externalIDList.iterator()) { item.toTlv(AnonymousTag, tlvWriter) } diff --git a/src/controller/java/generated/java/matter/controller/cluster/clusters/CommissionerControlCluster.kt b/src/controller/java/generated/java/matter/controller/cluster/clusters/CommissionerControlCluster.kt index 6a3d288d56..2daf2b464e 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/clusters/CommissionerControlCluster.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/clusters/CommissionerControlCluster.kt @@ -167,7 +167,7 @@ class CommissionerControlCluster( val TAG_COMMISSIONING_TIMEOUT: Int = 0 var commissioningTimeout_decoded: UShort? = null - val TAG_P_A_K_E_PASSCODE_VERIFIER: Int = 1 + val TAG_PAKE_PASSCODE_VERIFIER: Int = 1 var PAKEPasscodeVerifier_decoded: ByteArray? = null val TAG_DISCRIMINATOR: Int = 2 @@ -186,7 +186,7 @@ class CommissionerControlCluster( commissioningTimeout_decoded = tlvReader.getUShort(tag) } - if (tag == ContextSpecificTag(TAG_P_A_K_E_PASSCODE_VERIFIER)) { + if (tag == ContextSpecificTag(TAG_PAKE_PASSCODE_VERIFIER)) { PAKEPasscodeVerifier_decoded = tlvReader.getByteArray(tag) } diff --git a/src/controller/java/generated/java/matter/controller/cluster/clusters/ContentControlCluster.kt b/src/controller/java/generated/java/matter/controller/cluster/clusters/ContentControlCluster.kt index 9997c5eb20..c2a44834d0 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/clusters/ContentControlCluster.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/clusters/ContentControlCluster.kt @@ -116,11 +116,11 @@ class ContentControlCluster( val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_OLD_P_I_N_REQ: Int = 0 - oldPIN?.let { tlvWriter.put(ContextSpecificTag(TAG_OLD_P_I_N_REQ), oldPIN) } + val TAG_OLD_PIN_REQ: Int = 0 + oldPIN?.let { tlvWriter.put(ContextSpecificTag(TAG_OLD_PIN_REQ), oldPIN) } - val TAG_NEW_P_I_N_REQ: Int = 1 - tlvWriter.put(ContextSpecificTag(TAG_NEW_P_I_N_REQ), newPIN) + val TAG_NEW_PIN_REQ: Int = 1 + tlvWriter.put(ContextSpecificTag(TAG_NEW_PIN_REQ), newPIN) tlvWriter.endStructure() val request: InvokeRequest = @@ -153,13 +153,13 @@ class ContentControlCluster( val tlvReader = TlvReader(response.payload) tlvReader.enterStructure(AnonymousTag) - val TAG_P_I_N_CODE: Int = 0 + val TAG_PIN_CODE: Int = 0 var PINCode_decoded: String? = null while (!tlvReader.isEndOfContainer()) { val tag = tlvReader.peekElement().tag - if (tag == ContextSpecificTag(TAG_P_I_N_CODE)) { + if (tag == ContextSpecificTag(TAG_PIN_CODE)) { PINCode_decoded = tlvReader.getString(tag) } else { tlvReader.skipElement() @@ -221,8 +221,8 @@ class ContentControlCluster( val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_P_I_N_CODE_REQ: Int = 0 - PINCode?.let { tlvWriter.put(ContextSpecificTag(TAG_P_I_N_CODE_REQ), PINCode) } + val TAG_PIN_CODE_REQ: Int = 0 + PINCode?.let { tlvWriter.put(ContextSpecificTag(TAG_PIN_CODE_REQ), PINCode) } val TAG_BONUS_TIME_REQ: Int = 1 bonusTime?.let { tlvWriter.put(ContextSpecificTag(TAG_BONUS_TIME_REQ), bonusTime) } diff --git a/src/controller/java/generated/java/matter/controller/cluster/clusters/ContentLauncherCluster.kt b/src/controller/java/generated/java/matter/controller/cluster/clusters/ContentLauncherCluster.kt index 67bc46c79b..ae0b6d4935 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/clusters/ContentLauncherCluster.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/clusters/ContentLauncherCluster.kt @@ -190,8 +190,8 @@ class ContentLauncherCluster( val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_CONTENT_U_R_L_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_CONTENT_U_R_L_REQ), contentURL) + val TAG_CONTENT_URL_REQ: Int = 0 + tlvWriter.put(ContextSpecificTag(TAG_CONTENT_URL_REQ), contentURL) val TAG_DISPLAY_STRING_REQ: Int = 1 displayString?.let { tlvWriter.put(ContextSpecificTag(TAG_DISPLAY_STRING_REQ), displayString) } diff --git a/src/controller/java/generated/java/matter/controller/cluster/clusters/DemandResponseLoadControlCluster.kt b/src/controller/java/generated/java/matter/controller/cluster/clusters/DemandResponseLoadControlCluster.kt index f9d0eaf448..ea72cd4cd7 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/clusters/DemandResponseLoadControlCluster.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/clusters/DemandResponseLoadControlCluster.kt @@ -157,8 +157,8 @@ class DemandResponseLoadControlCluster( val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_LOAD_CONTROL_PROGRAM_I_D_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_LOAD_CONTROL_PROGRAM_I_D_REQ), loadControlProgramID) + val TAG_LOAD_CONTROL_PROGRAM_ID_REQ: Int = 0 + tlvWriter.put(ContextSpecificTag(TAG_LOAD_CONTROL_PROGRAM_ID_REQ), loadControlProgramID) tlvWriter.endStructure() val request: InvokeRequest = @@ -206,8 +206,8 @@ class DemandResponseLoadControlCluster( val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_EVENT_I_D_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_EVENT_I_D_REQ), eventID) + val TAG_EVENT_ID_REQ: Int = 0 + tlvWriter.put(ContextSpecificTag(TAG_EVENT_ID_REQ), eventID) val TAG_CANCEL_CONTROL_REQ: Int = 1 tlvWriter.put(ContextSpecificTag(TAG_CANCEL_CONTROL_REQ), cancelControl) diff --git a/src/controller/java/generated/java/matter/controller/cluster/clusters/DeviceEnergyManagementCluster.kt b/src/controller/java/generated/java/matter/controller/cluster/clusters/DeviceEnergyManagementCluster.kt index b0c1a5f320..455b52d4d0 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/clusters/DeviceEnergyManagementCluster.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/clusters/DeviceEnergyManagementCluster.kt @@ -242,8 +242,8 @@ class DeviceEnergyManagementCluster( val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_FORECAST_I_D_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_FORECAST_I_D_REQ), forecastID) + val TAG_FORECAST_ID_REQ: Int = 0 + tlvWriter.put(ContextSpecificTag(TAG_FORECAST_ID_REQ), forecastID) val TAG_SLOT_ADJUSTMENTS_REQ: Int = 1 tlvWriter.startArray(ContextSpecificTag(TAG_SLOT_ADJUSTMENTS_REQ)) diff --git a/src/controller/java/generated/java/matter/controller/cluster/clusters/DiagnosticLogsCluster.kt b/src/controller/java/generated/java/matter/controller/cluster/clusters/DiagnosticLogsCluster.kt index bc49bc27cd..fb4d455810 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/clusters/DiagnosticLogsCluster.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/clusters/DiagnosticLogsCluster.kt @@ -131,7 +131,7 @@ class DiagnosticLogsCluster( val TAG_LOG_CONTENT: Int = 1 var logContent_decoded: ByteArray? = null - val TAG_U_T_C_TIME_STAMP: Int = 2 + val TAG_UTC_TIME_STAMP: Int = 2 var UTCTimeStamp_decoded: ULong? = null val TAG_TIME_SINCE_BOOT: Int = 3 @@ -148,7 +148,7 @@ class DiagnosticLogsCluster( logContent_decoded = tlvReader.getByteArray(tag) } - if (tag == ContextSpecificTag(TAG_U_T_C_TIME_STAMP)) { + if (tag == ContextSpecificTag(TAG_UTC_TIME_STAMP)) { UTCTimeStamp_decoded = if (tlvReader.isNull()) { tlvReader.getNull(tag) diff --git a/src/controller/java/generated/java/matter/controller/cluster/clusters/DoorLockCluster.kt b/src/controller/java/generated/java/matter/controller/cluster/clusters/DoorLockCluster.kt index 79acaad63e..ff0525a58d 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/clusters/DoorLockCluster.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/clusters/DoorLockCluster.kt @@ -227,8 +227,8 @@ class DoorLockCluster(private val controller: MatterController, private val endp val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_P_I_N_CODE_REQ: Int = 0 - PINCode?.let { tlvWriter.put(ContextSpecificTag(TAG_P_I_N_CODE_REQ), PINCode) } + val TAG_PIN_CODE_REQ: Int = 0 + PINCode?.let { tlvWriter.put(ContextSpecificTag(TAG_PIN_CODE_REQ), PINCode) } tlvWriter.endStructure() val request: InvokeRequest = @@ -248,8 +248,8 @@ class DoorLockCluster(private val controller: MatterController, private val endp val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_P_I_N_CODE_REQ: Int = 0 - PINCode?.let { tlvWriter.put(ContextSpecificTag(TAG_P_I_N_CODE_REQ), PINCode) } + val TAG_PIN_CODE_REQ: Int = 0 + PINCode?.let { tlvWriter.put(ContextSpecificTag(TAG_PIN_CODE_REQ), PINCode) } tlvWriter.endStructure() val request: InvokeRequest = @@ -276,8 +276,8 @@ class DoorLockCluster(private val controller: MatterController, private val endp val TAG_TIMEOUT_REQ: Int = 0 tlvWriter.put(ContextSpecificTag(TAG_TIMEOUT_REQ), timeout) - val TAG_P_I_N_CODE_REQ: Int = 1 - PINCode?.let { tlvWriter.put(ContextSpecificTag(TAG_P_I_N_CODE_REQ), PINCode) } + val TAG_PIN_CODE_REQ: Int = 1 + PINCode?.let { tlvWriter.put(ContextSpecificTag(TAG_PIN_CODE_REQ), PINCode) } tlvWriter.endStructure() val request: InvokeRequest = @@ -907,8 +907,8 @@ class DoorLockCluster(private val controller: MatterController, private val endp val TAG_USER_NAME_REQ: Int = 2 userName?.let { tlvWriter.put(ContextSpecificTag(TAG_USER_NAME_REQ), userName) } - val TAG_USER_UNIQUE_I_D_REQ: Int = 3 - userUniqueID?.let { tlvWriter.put(ContextSpecificTag(TAG_USER_UNIQUE_I_D_REQ), userUniqueID) } + val TAG_USER_UNIQUE_ID_REQ: Int = 3 + userUniqueID?.let { tlvWriter.put(ContextSpecificTag(TAG_USER_UNIQUE_ID_REQ), userUniqueID) } val TAG_USER_STATUS_REQ: Int = 4 userStatus?.let { tlvWriter.put(ContextSpecificTag(TAG_USER_STATUS_REQ), userStatus) } @@ -961,7 +961,7 @@ class DoorLockCluster(private val controller: MatterController, private val endp val TAG_USER_NAME: Int = 1 var userName_decoded: String? = null - val TAG_USER_UNIQUE_I_D: Int = 2 + val TAG_USER_UNIQUE_ID: Int = 2 var userUniqueID_decoded: UInt? = null val TAG_USER_STATUS: Int = 3 @@ -1007,7 +1007,7 @@ class DoorLockCluster(private val controller: MatterController, private val endp } } - if (tag == ContextSpecificTag(TAG_USER_UNIQUE_I_D)) { + if (tag == ContextSpecificTag(TAG_USER_UNIQUE_ID)) { userUniqueID_decoded = if (tlvReader.isNull()) { tlvReader.getNull(tag) @@ -1435,8 +1435,8 @@ class DoorLockCluster(private val controller: MatterController, private val endp val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_P_I_N_CODE_REQ: Int = 0 - PINCode?.let { tlvWriter.put(ContextSpecificTag(TAG_P_I_N_CODE_REQ), PINCode) } + val TAG_PIN_CODE_REQ: Int = 0 + PINCode?.let { tlvWriter.put(ContextSpecificTag(TAG_PIN_CODE_REQ), PINCode) } tlvWriter.endStructure() val request: InvokeRequest = diff --git a/src/controller/java/generated/java/matter/controller/cluster/clusters/GeneralCommissioningCluster.kt b/src/controller/java/generated/java/matter/controller/cluster/clusters/GeneralCommissioningCluster.kt index 559a466d01..92e76e250f 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/clusters/GeneralCommissioningCluster.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/clusters/GeneralCommissioningCluster.kt @@ -302,11 +302,11 @@ class GeneralCommissioningCluster( val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_T_C_VERSION_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_T_C_VERSION_REQ), TCVersion) + val TAG_TC_VERSION_REQ: Int = 0 + tlvWriter.put(ContextSpecificTag(TAG_TC_VERSION_REQ), TCVersion) - val TAG_T_C_USER_RESPONSE_REQ: Int = 1 - tlvWriter.put(ContextSpecificTag(TAG_T_C_USER_RESPONSE_REQ), TCUserResponse) + val TAG_TC_USER_RESPONSE_REQ: Int = 1 + tlvWriter.put(ContextSpecificTag(TAG_TC_USER_RESPONSE_REQ), TCUserResponse) tlvWriter.endStructure() val request: InvokeRequest = diff --git a/src/controller/java/generated/java/matter/controller/cluster/clusters/GroupKeyManagementCluster.kt b/src/controller/java/generated/java/matter/controller/cluster/clusters/GroupKeyManagementCluster.kt index 4ca4541acd..a693149fed 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/clusters/GroupKeyManagementCluster.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/clusters/GroupKeyManagementCluster.kt @@ -145,8 +145,8 @@ class GroupKeyManagementCluster( val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_GROUP_KEY_SET_I_D_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_GROUP_KEY_SET_I_D_REQ), groupKeySetID) + val TAG_GROUP_KEY_SET_ID_REQ: Int = 0 + tlvWriter.put(ContextSpecificTag(TAG_GROUP_KEY_SET_ID_REQ), groupKeySetID) tlvWriter.endStructure() val request: InvokeRequest = @@ -189,8 +189,8 @@ class GroupKeyManagementCluster( val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_GROUP_KEY_SET_I_D_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_GROUP_KEY_SET_I_D_REQ), groupKeySetID) + val TAG_GROUP_KEY_SET_ID_REQ: Int = 0 + tlvWriter.put(ContextSpecificTag(TAG_GROUP_KEY_SET_ID_REQ), groupKeySetID) tlvWriter.endStructure() val request: InvokeRequest = diff --git a/src/controller/java/generated/java/matter/controller/cluster/clusters/GroupsCluster.kt b/src/controller/java/generated/java/matter/controller/cluster/clusters/GroupsCluster.kt index 7fe81f7293..6af48037da 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/clusters/GroupsCluster.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/clusters/GroupsCluster.kt @@ -99,8 +99,8 @@ class GroupsCluster(private val controller: MatterController, private val endpoi val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_GROUP_I_D_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_GROUP_I_D_REQ), groupID) + val TAG_GROUP_ID_REQ: Int = 0 + tlvWriter.put(ContextSpecificTag(TAG_GROUP_ID_REQ), groupID) val TAG_GROUP_NAME_REQ: Int = 1 tlvWriter.put(ContextSpecificTag(TAG_GROUP_NAME_REQ), groupName) @@ -121,7 +121,7 @@ class GroupsCluster(private val controller: MatterController, private val endpoi val TAG_STATUS: Int = 0 var status_decoded: UByte? = null - val TAG_GROUP_I_D: Int = 1 + val TAG_GROUP_ID: Int = 1 var groupID_decoded: UShort? = null while (!tlvReader.isEndOfContainer()) { @@ -131,7 +131,7 @@ class GroupsCluster(private val controller: MatterController, private val endpoi status_decoded = tlvReader.getUByte(tag) } - if (tag == ContextSpecificTag(TAG_GROUP_I_D)) { + if (tag == ContextSpecificTag(TAG_GROUP_ID)) { groupID_decoded = tlvReader.getUShort(tag) } else { tlvReader.skipElement() @@ -157,8 +157,8 @@ class GroupsCluster(private val controller: MatterController, private val endpoi val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_GROUP_I_D_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_GROUP_I_D_REQ), groupID) + val TAG_GROUP_ID_REQ: Int = 0 + tlvWriter.put(ContextSpecificTag(TAG_GROUP_ID_REQ), groupID) tlvWriter.endStructure() val request: InvokeRequest = @@ -176,7 +176,7 @@ class GroupsCluster(private val controller: MatterController, private val endpoi val TAG_STATUS: Int = 0 var status_decoded: UByte? = null - val TAG_GROUP_I_D: Int = 1 + val TAG_GROUP_ID: Int = 1 var groupID_decoded: UShort? = null val TAG_GROUP_NAME: Int = 2 @@ -189,7 +189,7 @@ class GroupsCluster(private val controller: MatterController, private val endpoi status_decoded = tlvReader.getUByte(tag) } - if (tag == ContextSpecificTag(TAG_GROUP_I_D)) { + if (tag == ContextSpecificTag(TAG_GROUP_ID)) { groupID_decoded = tlvReader.getUShort(tag) } @@ -302,8 +302,8 @@ class GroupsCluster(private val controller: MatterController, private val endpoi val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_GROUP_I_D_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_GROUP_I_D_REQ), groupID) + val TAG_GROUP_ID_REQ: Int = 0 + tlvWriter.put(ContextSpecificTag(TAG_GROUP_ID_REQ), groupID) tlvWriter.endStructure() val request: InvokeRequest = @@ -321,7 +321,7 @@ class GroupsCluster(private val controller: MatterController, private val endpoi val TAG_STATUS: Int = 0 var status_decoded: UByte? = null - val TAG_GROUP_I_D: Int = 1 + val TAG_GROUP_ID: Int = 1 var groupID_decoded: UShort? = null while (!tlvReader.isEndOfContainer()) { @@ -331,7 +331,7 @@ class GroupsCluster(private val controller: MatterController, private val endpoi status_decoded = tlvReader.getUByte(tag) } - if (tag == ContextSpecificTag(TAG_GROUP_I_D)) { + if (tag == ContextSpecificTag(TAG_GROUP_ID)) { groupID_decoded = tlvReader.getUShort(tag) } else { tlvReader.skipElement() @@ -379,8 +379,8 @@ class GroupsCluster(private val controller: MatterController, private val endpoi val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_GROUP_I_D_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_GROUP_I_D_REQ), groupID) + val TAG_GROUP_ID_REQ: Int = 0 + tlvWriter.put(ContextSpecificTag(TAG_GROUP_ID_REQ), groupID) val TAG_GROUP_NAME_REQ: Int = 1 tlvWriter.put(ContextSpecificTag(TAG_GROUP_NAME_REQ), groupName) diff --git a/src/controller/java/generated/java/matter/controller/cluster/clusters/IcdManagementCluster.kt b/src/controller/java/generated/java/matter/controller/cluster/clusters/IcdManagementCluster.kt index 68f206d72e..414e38d360 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/clusters/IcdManagementCluster.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/clusters/IcdManagementCluster.kt @@ -115,8 +115,8 @@ class IcdManagementCluster( val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_CHECK_IN_NODE_I_D_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_CHECK_IN_NODE_I_D_REQ), checkInNodeID) + val TAG_CHECK_IN_NODE_ID_REQ: Int = 0 + tlvWriter.put(ContextSpecificTag(TAG_CHECK_IN_NODE_ID_REQ), checkInNodeID) val TAG_MONITORED_SUBJECT_REQ: Int = 1 tlvWriter.put(ContextSpecificTag(TAG_MONITORED_SUBJECT_REQ), monitoredSubject) @@ -145,13 +145,13 @@ class IcdManagementCluster( val tlvReader = TlvReader(response.payload) tlvReader.enterStructure(AnonymousTag) - val TAG_I_C_D_COUNTER: Int = 0 + val TAG_ICD_COUNTER: Int = 0 var ICDCounter_decoded: UInt? = null while (!tlvReader.isEndOfContainer()) { val tag = tlvReader.peekElement().tag - if (tag == ContextSpecificTag(TAG_I_C_D_COUNTER)) { + if (tag == ContextSpecificTag(TAG_ICD_COUNTER)) { ICDCounter_decoded = tlvReader.getUInt(tag) } else { tlvReader.skipElement() @@ -177,8 +177,8 @@ class IcdManagementCluster( val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_CHECK_IN_NODE_I_D_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_CHECK_IN_NODE_I_D_REQ), checkInNodeID) + val TAG_CHECK_IN_NODE_ID_REQ: Int = 0 + tlvWriter.put(ContextSpecificTag(TAG_CHECK_IN_NODE_ID_REQ), checkInNodeID) val TAG_VERIFICATION_KEY_REQ: Int = 1 verificationKey?.let { diff --git a/src/controller/java/generated/java/matter/controller/cluster/clusters/MediaPlaybackCluster.kt b/src/controller/java/generated/java/matter/controller/cluster/clusters/MediaPlaybackCluster.kt index 305eb38b66..53a4847c13 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/clusters/MediaPlaybackCluster.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/clusters/MediaPlaybackCluster.kt @@ -867,8 +867,8 @@ class MediaPlaybackCluster( val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_TRACK_I_D_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_TRACK_I_D_REQ), trackID) + val TAG_TRACK_ID_REQ: Int = 0 + tlvWriter.put(ContextSpecificTag(TAG_TRACK_ID_REQ), trackID) val TAG_AUDIO_OUTPUT_INDEX_REQ: Int = 1 tlvWriter.put(ContextSpecificTag(TAG_AUDIO_OUTPUT_INDEX_REQ), audioOutputIndex) @@ -891,8 +891,8 @@ class MediaPlaybackCluster( val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_TRACK_I_D_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_TRACK_I_D_REQ), trackID) + val TAG_TRACK_ID_REQ: Int = 0 + tlvWriter.put(ContextSpecificTag(TAG_TRACK_ID_REQ), trackID) tlvWriter.endStructure() val request: InvokeRequest = diff --git a/src/controller/java/generated/java/matter/controller/cluster/clusters/MessagesCluster.kt b/src/controller/java/generated/java/matter/controller/cluster/clusters/MessagesCluster.kt index 12d6830ad3..e832c5cefe 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/clusters/MessagesCluster.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/clusters/MessagesCluster.kt @@ -116,8 +116,8 @@ class MessagesCluster(private val controller: MatterController, private val endp val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_MESSAGE_I_D_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_MESSAGE_I_D_REQ), messageID) + val TAG_MESSAGE_ID_REQ: Int = 0 + tlvWriter.put(ContextSpecificTag(TAG_MESSAGE_ID_REQ), messageID) val TAG_PRIORITY_REQ: Int = 1 tlvWriter.put(ContextSpecificTag(TAG_PRIORITY_REQ), priority) diff --git a/src/controller/java/generated/java/matter/controller/cluster/clusters/NetworkCommissioningCluster.kt b/src/controller/java/generated/java/matter/controller/cluster/clusters/NetworkCommissioningCluster.kt index 29ff013692..2a144baed4 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/clusters/NetworkCommissioningCluster.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/clusters/NetworkCommissioningCluster.kt @@ -576,8 +576,8 @@ class NetworkCommissioningCluster( val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_NETWORK_I_D_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_NETWORK_I_D_REQ), networkID) + val TAG_NETWORK_ID_REQ: Int = 0 + tlvWriter.put(ContextSpecificTag(TAG_NETWORK_ID_REQ), networkID) val TAG_BREADCRUMB_REQ: Int = 1 breadcrumb?.let { tlvWriter.put(ContextSpecificTag(TAG_BREADCRUMB_REQ), breadcrumb) } @@ -701,8 +701,8 @@ class NetworkCommissioningCluster( val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_NETWORK_I_D_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_NETWORK_I_D_REQ), networkID) + val TAG_NETWORK_ID_REQ: Int = 0 + tlvWriter.put(ContextSpecificTag(TAG_NETWORK_ID_REQ), networkID) val TAG_BREADCRUMB_REQ: Int = 1 breadcrumb?.let { tlvWriter.put(ContextSpecificTag(TAG_BREADCRUMB_REQ), breadcrumb) } @@ -788,8 +788,8 @@ class NetworkCommissioningCluster( val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_NETWORK_I_D_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_NETWORK_I_D_REQ), networkID) + val TAG_NETWORK_ID_REQ: Int = 0 + tlvWriter.put(ContextSpecificTag(TAG_NETWORK_ID_REQ), networkID) val TAG_NETWORK_INDEX_REQ: Int = 1 tlvWriter.put(ContextSpecificTag(TAG_NETWORK_INDEX_REQ), networkIndex) diff --git a/src/controller/java/generated/java/matter/controller/cluster/clusters/OperationalCredentialsCluster.kt b/src/controller/java/generated/java/matter/controller/cluster/clusters/OperationalCredentialsCluster.kt index bf066e2c0b..d96efd654f 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/clusters/OperationalCredentialsCluster.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/clusters/OperationalCredentialsCluster.kt @@ -244,12 +244,12 @@ class OperationalCredentialsCluster( val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_C_S_R_NONCE_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_C_S_R_NONCE_REQ), CSRNonce) + val TAG_CSR_NONCE_REQ: Int = 0 + tlvWriter.put(ContextSpecificTag(TAG_CSR_NONCE_REQ), CSRNonce) - val TAG_IS_FOR_UPDATE_N_O_C_REQ: Int = 1 + val TAG_IS_FOR_UPDATE_NOC_REQ: Int = 1 isForUpdateNOC?.let { - tlvWriter.put(ContextSpecificTag(TAG_IS_FOR_UPDATE_N_O_C_REQ), isForUpdateNOC) + tlvWriter.put(ContextSpecificTag(TAG_IS_FOR_UPDATE_NOC_REQ), isForUpdateNOC) } tlvWriter.endStructure() @@ -265,7 +265,7 @@ class OperationalCredentialsCluster( val tlvReader = TlvReader(response.payload) tlvReader.enterStructure(AnonymousTag) - val TAG_N_O_C_S_R_ELEMENTS: Int = 0 + val TAG_NOCSR_ELEMENTS: Int = 0 var NOCSRElements_decoded: ByteArray? = null val TAG_ATTESTATION_SIGNATURE: Int = 1 @@ -274,7 +274,7 @@ class OperationalCredentialsCluster( while (!tlvReader.isEndOfContainer()) { val tag = tlvReader.peekElement().tag - if (tag == ContextSpecificTag(TAG_N_O_C_S_R_ELEMENTS)) { + if (tag == ContextSpecificTag(TAG_NOCSR_ELEMENTS)) { NOCSRElements_decoded = tlvReader.getByteArray(tag) } @@ -311,14 +311,14 @@ class OperationalCredentialsCluster( val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_N_O_C_VALUE_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_N_O_C_VALUE_REQ), NOCValue) + val TAG_NOC_VALUE_REQ: Int = 0 + tlvWriter.put(ContextSpecificTag(TAG_NOC_VALUE_REQ), NOCValue) - val TAG_I_C_A_C_VALUE_REQ: Int = 1 - ICACValue?.let { tlvWriter.put(ContextSpecificTag(TAG_I_C_A_C_VALUE_REQ), ICACValue) } + val TAG_ICAC_VALUE_REQ: Int = 1 + ICACValue?.let { tlvWriter.put(ContextSpecificTag(TAG_ICAC_VALUE_REQ), ICACValue) } - val TAG_I_P_K_VALUE_REQ: Int = 2 - tlvWriter.put(ContextSpecificTag(TAG_I_P_K_VALUE_REQ), IPKValue) + val TAG_IPK_VALUE_REQ: Int = 2 + tlvWriter.put(ContextSpecificTag(TAG_IPK_VALUE_REQ), IPKValue) val TAG_CASE_ADMIN_SUBJECT_REQ: Int = 3 tlvWriter.put(ContextSpecificTag(TAG_CASE_ADMIN_SUBJECT_REQ), caseAdminSubject) @@ -405,11 +405,11 @@ class OperationalCredentialsCluster( val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_N_O_C_VALUE_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_N_O_C_VALUE_REQ), NOCValue) + val TAG_NOC_VALUE_REQ: Int = 0 + tlvWriter.put(ContextSpecificTag(TAG_NOC_VALUE_REQ), NOCValue) - val TAG_I_C_A_C_VALUE_REQ: Int = 1 - ICACValue?.let { tlvWriter.put(ContextSpecificTag(TAG_I_C_A_C_VALUE_REQ), ICACValue) } + val TAG_ICAC_VALUE_REQ: Int = 1 + ICACValue?.let { tlvWriter.put(ContextSpecificTag(TAG_ICAC_VALUE_REQ), ICACValue) } tlvWriter.endStructure() val request: InvokeRequest = @@ -645,8 +645,8 @@ class OperationalCredentialsCluster( val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_ROOT_C_A_CERTIFICATE_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_ROOT_C_A_CERTIFICATE_REQ), rootCACertificate) + val TAG_ROOT_CA_CERTIFICATE_REQ: Int = 0 + tlvWriter.put(ContextSpecificTag(TAG_ROOT_CA_CERTIFICATE_REQ), rootCACertificate) tlvWriter.endStructure() val request: InvokeRequest = diff --git a/src/controller/java/generated/java/matter/controller/cluster/clusters/OtaSoftwareUpdateProviderCluster.kt b/src/controller/java/generated/java/matter/controller/cluster/clusters/OtaSoftwareUpdateProviderCluster.kt index cfcedb7a1c..cf8525ed7f 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/clusters/OtaSoftwareUpdateProviderCluster.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/clusters/OtaSoftwareUpdateProviderCluster.kt @@ -112,11 +112,11 @@ class OtaSoftwareUpdateProviderCluster( val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_VENDOR_I_D_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_VENDOR_I_D_REQ), vendorID) + val TAG_VENDOR_ID_REQ: Int = 0 + tlvWriter.put(ContextSpecificTag(TAG_VENDOR_ID_REQ), vendorID) - val TAG_PRODUCT_I_D_REQ: Int = 1 - tlvWriter.put(ContextSpecificTag(TAG_PRODUCT_I_D_REQ), productID) + val TAG_PRODUCT_ID_REQ: Int = 1 + tlvWriter.put(ContextSpecificTag(TAG_PRODUCT_ID_REQ), productID) val TAG_SOFTWARE_VERSION_REQ: Int = 2 tlvWriter.put(ContextSpecificTag(TAG_SOFTWARE_VERSION_REQ), softwareVersion) @@ -165,7 +165,7 @@ class OtaSoftwareUpdateProviderCluster( val TAG_DELAYED_ACTION_TIME: Int = 1 var delayedActionTime_decoded: UInt? = null - val TAG_IMAGE_U_R_I: Int = 2 + val TAG_IMAGE_URI: Int = 2 var imageURI_decoded: String? = null val TAG_SOFTWARE_VERSION: Int = 3 @@ -204,7 +204,7 @@ class OtaSoftwareUpdateProviderCluster( } } - if (tag == ContextSpecificTag(TAG_IMAGE_U_R_I)) { + if (tag == ContextSpecificTag(TAG_IMAGE_URI)) { imageURI_decoded = if (tlvReader.isNull()) { tlvReader.getNull(tag) diff --git a/src/controller/java/generated/java/matter/controller/cluster/clusters/OtaSoftwareUpdateRequestorCluster.kt b/src/controller/java/generated/java/matter/controller/cluster/clusters/OtaSoftwareUpdateRequestorCluster.kt index 56a8444d79..21ca7bd092 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/clusters/OtaSoftwareUpdateRequestorCluster.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/clusters/OtaSoftwareUpdateRequestorCluster.kt @@ -124,11 +124,11 @@ class OtaSoftwareUpdateRequestorCluster( val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_PROVIDER_NODE_I_D_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_PROVIDER_NODE_I_D_REQ), providerNodeID) + val TAG_PROVIDER_NODE_ID_REQ: Int = 0 + tlvWriter.put(ContextSpecificTag(TAG_PROVIDER_NODE_ID_REQ), providerNodeID) - val TAG_VENDOR_I_D_REQ: Int = 1 - tlvWriter.put(ContextSpecificTag(TAG_VENDOR_I_D_REQ), vendorID) + val TAG_VENDOR_ID_REQ: Int = 1 + tlvWriter.put(ContextSpecificTag(TAG_VENDOR_ID_REQ), vendorID) val TAG_ANNOUNCEMENT_REASON_REQ: Int = 2 tlvWriter.put(ContextSpecificTag(TAG_ANNOUNCEMENT_REASON_REQ), announcementReason) diff --git a/src/controller/java/generated/java/matter/controller/cluster/clusters/ScenesManagementCluster.kt b/src/controller/java/generated/java/matter/controller/cluster/clusters/ScenesManagementCluster.kt index f3f1927f55..e363f8c88f 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/clusters/ScenesManagementCluster.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/clusters/ScenesManagementCluster.kt @@ -147,11 +147,11 @@ class ScenesManagementCluster( val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_GROUP_I_D_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_GROUP_I_D_REQ), groupID) + val TAG_GROUP_ID_REQ: Int = 0 + tlvWriter.put(ContextSpecificTag(TAG_GROUP_ID_REQ), groupID) - val TAG_SCENE_I_D_REQ: Int = 1 - tlvWriter.put(ContextSpecificTag(TAG_SCENE_I_D_REQ), sceneID) + val TAG_SCENE_ID_REQ: Int = 1 + tlvWriter.put(ContextSpecificTag(TAG_SCENE_ID_REQ), sceneID) val TAG_TRANSITION_TIME_REQ: Int = 2 tlvWriter.put(ContextSpecificTag(TAG_TRANSITION_TIME_REQ), transitionTime) @@ -182,10 +182,10 @@ class ScenesManagementCluster( val TAG_STATUS: Int = 0 var status_decoded: UByte? = null - val TAG_GROUP_I_D: Int = 1 + val TAG_GROUP_ID: Int = 1 var groupID_decoded: UShort? = null - val TAG_SCENE_I_D: Int = 2 + val TAG_SCENE_ID: Int = 2 var sceneID_decoded: UByte? = null while (!tlvReader.isEndOfContainer()) { @@ -195,11 +195,11 @@ class ScenesManagementCluster( status_decoded = tlvReader.getUByte(tag) } - if (tag == ContextSpecificTag(TAG_GROUP_I_D)) { + if (tag == ContextSpecificTag(TAG_GROUP_ID)) { groupID_decoded = tlvReader.getUShort(tag) } - if (tag == ContextSpecificTag(TAG_SCENE_I_D)) { + if (tag == ContextSpecificTag(TAG_SCENE_ID)) { sceneID_decoded = tlvReader.getUByte(tag) } else { tlvReader.skipElement() @@ -233,11 +233,11 @@ class ScenesManagementCluster( val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_GROUP_I_D_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_GROUP_I_D_REQ), groupID) + val TAG_GROUP_ID_REQ: Int = 0 + tlvWriter.put(ContextSpecificTag(TAG_GROUP_ID_REQ), groupID) - val TAG_SCENE_I_D_REQ: Int = 1 - tlvWriter.put(ContextSpecificTag(TAG_SCENE_I_D_REQ), sceneID) + val TAG_SCENE_ID_REQ: Int = 1 + tlvWriter.put(ContextSpecificTag(TAG_SCENE_ID_REQ), sceneID) tlvWriter.endStructure() val request: InvokeRequest = @@ -255,10 +255,10 @@ class ScenesManagementCluster( val TAG_STATUS: Int = 0 var status_decoded: UByte? = null - val TAG_GROUP_I_D: Int = 1 + val TAG_GROUP_ID: Int = 1 var groupID_decoded: UShort? = null - val TAG_SCENE_I_D: Int = 2 + val TAG_SCENE_ID: Int = 2 var sceneID_decoded: UByte? = null val TAG_TRANSITION_TIME: Int = 3 @@ -277,11 +277,11 @@ class ScenesManagementCluster( status_decoded = tlvReader.getUByte(tag) } - if (tag == ContextSpecificTag(TAG_GROUP_I_D)) { + if (tag == ContextSpecificTag(TAG_GROUP_ID)) { groupID_decoded = tlvReader.getUShort(tag) } - if (tag == ContextSpecificTag(TAG_SCENE_I_D)) { + if (tag == ContextSpecificTag(TAG_SCENE_ID)) { sceneID_decoded = tlvReader.getUByte(tag) } @@ -370,11 +370,11 @@ class ScenesManagementCluster( val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_GROUP_I_D_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_GROUP_I_D_REQ), groupID) + val TAG_GROUP_ID_REQ: Int = 0 + tlvWriter.put(ContextSpecificTag(TAG_GROUP_ID_REQ), groupID) - val TAG_SCENE_I_D_REQ: Int = 1 - tlvWriter.put(ContextSpecificTag(TAG_SCENE_I_D_REQ), sceneID) + val TAG_SCENE_ID_REQ: Int = 1 + tlvWriter.put(ContextSpecificTag(TAG_SCENE_ID_REQ), sceneID) tlvWriter.endStructure() val request: InvokeRequest = @@ -392,10 +392,10 @@ class ScenesManagementCluster( val TAG_STATUS: Int = 0 var status_decoded: UByte? = null - val TAG_GROUP_I_D: Int = 1 + val TAG_GROUP_ID: Int = 1 var groupID_decoded: UShort? = null - val TAG_SCENE_I_D: Int = 2 + val TAG_SCENE_ID: Int = 2 var sceneID_decoded: UByte? = null while (!tlvReader.isEndOfContainer()) { @@ -405,11 +405,11 @@ class ScenesManagementCluster( status_decoded = tlvReader.getUByte(tag) } - if (tag == ContextSpecificTag(TAG_GROUP_I_D)) { + if (tag == ContextSpecificTag(TAG_GROUP_ID)) { groupID_decoded = tlvReader.getUShort(tag) } - if (tag == ContextSpecificTag(TAG_SCENE_I_D)) { + if (tag == ContextSpecificTag(TAG_SCENE_ID)) { sceneID_decoded = tlvReader.getUByte(tag) } else { tlvReader.skipElement() @@ -442,8 +442,8 @@ class ScenesManagementCluster( val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_GROUP_I_D_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_GROUP_I_D_REQ), groupID) + val TAG_GROUP_ID_REQ: Int = 0 + tlvWriter.put(ContextSpecificTag(TAG_GROUP_ID_REQ), groupID) tlvWriter.endStructure() val request: InvokeRequest = @@ -461,7 +461,7 @@ class ScenesManagementCluster( val TAG_STATUS: Int = 0 var status_decoded: UByte? = null - val TAG_GROUP_I_D: Int = 1 + val TAG_GROUP_ID: Int = 1 var groupID_decoded: UShort? = null while (!tlvReader.isEndOfContainer()) { @@ -471,7 +471,7 @@ class ScenesManagementCluster( status_decoded = tlvReader.getUByte(tag) } - if (tag == ContextSpecificTag(TAG_GROUP_I_D)) { + if (tag == ContextSpecificTag(TAG_GROUP_ID)) { groupID_decoded = tlvReader.getUShort(tag) } else { tlvReader.skipElement() @@ -501,11 +501,11 @@ class ScenesManagementCluster( val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_GROUP_I_D_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_GROUP_I_D_REQ), groupID) + val TAG_GROUP_ID_REQ: Int = 0 + tlvWriter.put(ContextSpecificTag(TAG_GROUP_ID_REQ), groupID) - val TAG_SCENE_I_D_REQ: Int = 1 - tlvWriter.put(ContextSpecificTag(TAG_SCENE_I_D_REQ), sceneID) + val TAG_SCENE_ID_REQ: Int = 1 + tlvWriter.put(ContextSpecificTag(TAG_SCENE_ID_REQ), sceneID) tlvWriter.endStructure() val request: InvokeRequest = @@ -523,10 +523,10 @@ class ScenesManagementCluster( val TAG_STATUS: Int = 0 var status_decoded: UByte? = null - val TAG_GROUP_I_D: Int = 1 + val TAG_GROUP_ID: Int = 1 var groupID_decoded: UShort? = null - val TAG_SCENE_I_D: Int = 2 + val TAG_SCENE_ID: Int = 2 var sceneID_decoded: UByte? = null while (!tlvReader.isEndOfContainer()) { @@ -536,11 +536,11 @@ class ScenesManagementCluster( status_decoded = tlvReader.getUByte(tag) } - if (tag == ContextSpecificTag(TAG_GROUP_I_D)) { + if (tag == ContextSpecificTag(TAG_GROUP_ID)) { groupID_decoded = tlvReader.getUShort(tag) } - if (tag == ContextSpecificTag(TAG_SCENE_I_D)) { + if (tag == ContextSpecificTag(TAG_SCENE_ID)) { sceneID_decoded = tlvReader.getUByte(tag) } else { tlvReader.skipElement() @@ -575,11 +575,11 @@ class ScenesManagementCluster( val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_GROUP_I_D_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_GROUP_I_D_REQ), groupID) + val TAG_GROUP_ID_REQ: Int = 0 + tlvWriter.put(ContextSpecificTag(TAG_GROUP_ID_REQ), groupID) - val TAG_SCENE_I_D_REQ: Int = 1 - tlvWriter.put(ContextSpecificTag(TAG_SCENE_I_D_REQ), sceneID) + val TAG_SCENE_ID_REQ: Int = 1 + tlvWriter.put(ContextSpecificTag(TAG_SCENE_ID_REQ), sceneID) val TAG_TRANSITION_TIME_REQ: Int = 2 transitionTime?.let { @@ -607,8 +607,8 @@ class ScenesManagementCluster( val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_GROUP_I_D_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_GROUP_I_D_REQ), groupID) + val TAG_GROUP_ID_REQ: Int = 0 + tlvWriter.put(ContextSpecificTag(TAG_GROUP_ID_REQ), groupID) tlvWriter.endStructure() val request: InvokeRequest = @@ -629,7 +629,7 @@ class ScenesManagementCluster( val TAG_CAPACITY: Int = 1 var capacity_decoded: UByte? = null - val TAG_GROUP_I_D: Int = 2 + val TAG_GROUP_ID: Int = 2 var groupID_decoded: UShort? = null val TAG_SCENE_LIST: Int = 3 @@ -657,7 +657,7 @@ class ScenesManagementCluster( } } - if (tag == ContextSpecificTag(TAG_GROUP_I_D)) { + if (tag == ContextSpecificTag(TAG_GROUP_ID)) { groupID_decoded = tlvReader.getUShort(tag) } diff --git a/src/controller/java/generated/java/matter/controller/cluster/clusters/ThreadNetworkDirectoryCluster.kt b/src/controller/java/generated/java/matter/controller/cluster/clusters/ThreadNetworkDirectoryCluster.kt index b5af2b1db2..ee5b2e9aea 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/clusters/ThreadNetworkDirectoryCluster.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/clusters/ThreadNetworkDirectoryCluster.kt @@ -137,8 +137,8 @@ class ThreadNetworkDirectoryCluster( val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_EXTENDED_PAN_I_D_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_EXTENDED_PAN_I_D_REQ), extendedPanID) + val TAG_EXTENDED_PAN_ID_REQ: Int = 0 + tlvWriter.put(ContextSpecificTag(TAG_EXTENDED_PAN_ID_REQ), extendedPanID) tlvWriter.endStructure() val request: InvokeRequest = @@ -161,8 +161,8 @@ class ThreadNetworkDirectoryCluster( val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_EXTENDED_PAN_I_D_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_EXTENDED_PAN_I_D_REQ), extendedPanID) + val TAG_EXTENDED_PAN_ID_REQ: Int = 0 + tlvWriter.put(ContextSpecificTag(TAG_EXTENDED_PAN_ID_REQ), extendedPanID) tlvWriter.endStructure() val request: InvokeRequest = diff --git a/src/controller/java/generated/java/matter/controller/cluster/clusters/TimeSynchronizationCluster.kt b/src/controller/java/generated/java/matter/controller/cluster/clusters/TimeSynchronizationCluster.kt index 74305abccc..c968311230 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/clusters/TimeSynchronizationCluster.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/clusters/TimeSynchronizationCluster.kt @@ -161,8 +161,8 @@ class TimeSynchronizationCluster( val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_U_T_C_TIME_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_U_T_C_TIME_REQ), UTCTime) + val TAG_UTC_TIME_REQ: Int = 0 + tlvWriter.put(ContextSpecificTag(TAG_UTC_TIME_REQ), UTCTime) val TAG_GRANULARITY_REQ: Int = 1 tlvWriter.put(ContextSpecificTag(TAG_GRANULARITY_REQ), granularity) @@ -237,13 +237,13 @@ class TimeSynchronizationCluster( val tlvReader = TlvReader(response.payload) tlvReader.enterStructure(AnonymousTag) - val TAG_D_S_T_OFFSET_REQUIRED: Int = 0 + val TAG_DST_OFFSET_REQUIRED: Int = 0 var DSTOffsetRequired_decoded: Boolean? = null while (!tlvReader.isEndOfContainer()) { val tag = tlvReader.peekElement().tag - if (tag == ContextSpecificTag(TAG_D_S_T_OFFSET_REQUIRED)) { + if (tag == ContextSpecificTag(TAG_DST_OFFSET_REQUIRED)) { DSTOffsetRequired_decoded = tlvReader.getBoolean(tag) } else { tlvReader.skipElement() @@ -268,8 +268,8 @@ class TimeSynchronizationCluster( val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_D_S_T_OFFSET_REQ: Int = 0 - tlvWriter.startArray(ContextSpecificTag(TAG_D_S_T_OFFSET_REQ)) + val TAG_DST_OFFSET_REQ: Int = 0 + tlvWriter.startArray(ContextSpecificTag(TAG_DST_OFFSET_REQ)) for (item in DSTOffset.iterator()) { item.toTlv(AnonymousTag, tlvWriter) } @@ -293,8 +293,8 @@ class TimeSynchronizationCluster( val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) - val TAG_DEFAULT_N_T_P_REQ: Int = 0 - defaultNTP?.let { tlvWriter.put(ContextSpecificTag(TAG_DEFAULT_N_T_P_REQ), defaultNTP) } + val TAG_DEFAULT_NTP_REQ: Int = 0 + defaultNTP?.let { tlvWriter.put(ContextSpecificTag(TAG_DEFAULT_NTP_REQ), defaultNTP) } tlvWriter.endStructure() val request: InvokeRequest = diff --git a/src/controller/java/generated/java/matter/controller/cluster/eventstructs/AccessControlClusterAccessControlEntryChangedEvent.kt b/src/controller/java/generated/java/matter/controller/cluster/eventstructs/AccessControlClusterAccessControlEntryChangedEvent.kt index c4fb86f66e..2ac4b28ebe 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/eventstructs/AccessControlClusterAccessControlEntryChangedEvent.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/eventstructs/AccessControlClusterAccessControlEntryChangedEvent.kt @@ -43,14 +43,14 @@ class AccessControlClusterAccessControlEntryChangedEvent( tlvWriter.apply { startStructure(tlvTag) if (adminNodeID != null) { - put(ContextSpecificTag(TAG_ADMIN_NODE_I_D), adminNodeID) + put(ContextSpecificTag(TAG_ADMIN_NODE_ID), adminNodeID) } else { - putNull(ContextSpecificTag(TAG_ADMIN_NODE_I_D)) + putNull(ContextSpecificTag(TAG_ADMIN_NODE_ID)) } if (adminPasscodeID != null) { - put(ContextSpecificTag(TAG_ADMIN_PASSCODE_I_D), adminPasscodeID) + put(ContextSpecificTag(TAG_ADMIN_PASSCODE_ID), adminPasscodeID) } else { - putNull(ContextSpecificTag(TAG_ADMIN_PASSCODE_I_D)) + putNull(ContextSpecificTag(TAG_ADMIN_PASSCODE_ID)) } put(ContextSpecificTag(TAG_CHANGE_TYPE), changeType) if (latestValue != null) { @@ -64,8 +64,8 @@ class AccessControlClusterAccessControlEntryChangedEvent( } companion object { - private const val TAG_ADMIN_NODE_I_D = 1 - private const val TAG_ADMIN_PASSCODE_I_D = 2 + private const val TAG_ADMIN_NODE_ID = 1 + private const val TAG_ADMIN_PASSCODE_ID = 2 private const val TAG_CHANGE_TYPE = 3 private const val TAG_LATEST_VALUE = 4 private const val TAG_FABRIC_INDEX = 254 @@ -77,16 +77,16 @@ class AccessControlClusterAccessControlEntryChangedEvent( tlvReader.enterStructure(tlvTag) val adminNodeID = if (!tlvReader.isNull()) { - tlvReader.getULong(ContextSpecificTag(TAG_ADMIN_NODE_I_D)) + tlvReader.getULong(ContextSpecificTag(TAG_ADMIN_NODE_ID)) } else { - tlvReader.getNull(ContextSpecificTag(TAG_ADMIN_NODE_I_D)) + tlvReader.getNull(ContextSpecificTag(TAG_ADMIN_NODE_ID)) null } val adminPasscodeID = if (!tlvReader.isNull()) { - tlvReader.getUShort(ContextSpecificTag(TAG_ADMIN_PASSCODE_I_D)) + tlvReader.getUShort(ContextSpecificTag(TAG_ADMIN_PASSCODE_ID)) } else { - tlvReader.getNull(ContextSpecificTag(TAG_ADMIN_PASSCODE_I_D)) + tlvReader.getNull(ContextSpecificTag(TAG_ADMIN_PASSCODE_ID)) null } val changeType = tlvReader.getUByte(ContextSpecificTag(TAG_CHANGE_TYPE)) diff --git a/src/controller/java/generated/java/matter/controller/cluster/eventstructs/AccessControlClusterAccessControlExtensionChangedEvent.kt b/src/controller/java/generated/java/matter/controller/cluster/eventstructs/AccessControlClusterAccessControlExtensionChangedEvent.kt index eefb09a6b6..668ee86be2 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/eventstructs/AccessControlClusterAccessControlExtensionChangedEvent.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/eventstructs/AccessControlClusterAccessControlExtensionChangedEvent.kt @@ -44,14 +44,14 @@ class AccessControlClusterAccessControlExtensionChangedEvent( tlvWriter.apply { startStructure(tlvTag) if (adminNodeID != null) { - put(ContextSpecificTag(TAG_ADMIN_NODE_I_D), adminNodeID) + put(ContextSpecificTag(TAG_ADMIN_NODE_ID), adminNodeID) } else { - putNull(ContextSpecificTag(TAG_ADMIN_NODE_I_D)) + putNull(ContextSpecificTag(TAG_ADMIN_NODE_ID)) } if (adminPasscodeID != null) { - put(ContextSpecificTag(TAG_ADMIN_PASSCODE_I_D), adminPasscodeID) + put(ContextSpecificTag(TAG_ADMIN_PASSCODE_ID), adminPasscodeID) } else { - putNull(ContextSpecificTag(TAG_ADMIN_PASSCODE_I_D)) + putNull(ContextSpecificTag(TAG_ADMIN_PASSCODE_ID)) } put(ContextSpecificTag(TAG_CHANGE_TYPE), changeType) if (latestValue != null) { @@ -65,8 +65,8 @@ class AccessControlClusterAccessControlExtensionChangedEvent( } companion object { - private const val TAG_ADMIN_NODE_I_D = 1 - private const val TAG_ADMIN_PASSCODE_I_D = 2 + private const val TAG_ADMIN_NODE_ID = 1 + private const val TAG_ADMIN_PASSCODE_ID = 2 private const val TAG_CHANGE_TYPE = 3 private const val TAG_LATEST_VALUE = 4 private const val TAG_FABRIC_INDEX = 254 @@ -78,16 +78,16 @@ class AccessControlClusterAccessControlExtensionChangedEvent( tlvReader.enterStructure(tlvTag) val adminNodeID = if (!tlvReader.isNull()) { - tlvReader.getULong(ContextSpecificTag(TAG_ADMIN_NODE_I_D)) + tlvReader.getULong(ContextSpecificTag(TAG_ADMIN_NODE_ID)) } else { - tlvReader.getNull(ContextSpecificTag(TAG_ADMIN_NODE_I_D)) + tlvReader.getNull(ContextSpecificTag(TAG_ADMIN_NODE_ID)) null } val adminPasscodeID = if (!tlvReader.isNull()) { - tlvReader.getUShort(ContextSpecificTag(TAG_ADMIN_PASSCODE_I_D)) + tlvReader.getUShort(ContextSpecificTag(TAG_ADMIN_PASSCODE_ID)) } else { - tlvReader.getNull(ContextSpecificTag(TAG_ADMIN_PASSCODE_I_D)) + tlvReader.getNull(ContextSpecificTag(TAG_ADMIN_PASSCODE_ID)) null } val changeType = tlvReader.getUByte(ContextSpecificTag(TAG_CHANGE_TYPE)) diff --git a/src/controller/java/generated/java/matter/controller/cluster/eventstructs/AccessControlClusterFabricRestrictionReviewUpdateEvent.kt b/src/controller/java/generated/java/matter/controller/cluster/eventstructs/AccessControlClusterFabricRestrictionReviewUpdateEvent.kt index 2dca6ad48f..6bf03e6afc 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/eventstructs/AccessControlClusterFabricRestrictionReviewUpdateEvent.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/eventstructs/AccessControlClusterFabricRestrictionReviewUpdateEvent.kt @@ -47,9 +47,9 @@ class AccessControlClusterFabricRestrictionReviewUpdateEvent( putNull(ContextSpecificTag(TAG_INSTRUCTION)) } if (redirectURL != null) { - put(ContextSpecificTag(TAG_REDIRECT_U_R_L), redirectURL) + put(ContextSpecificTag(TAG_REDIRECT_URL), redirectURL) } else { - putNull(ContextSpecificTag(TAG_REDIRECT_U_R_L)) + putNull(ContextSpecificTag(TAG_REDIRECT_URL)) } put(ContextSpecificTag(TAG_FABRIC_INDEX), fabricIndex) endStructure() @@ -59,7 +59,7 @@ class AccessControlClusterFabricRestrictionReviewUpdateEvent( companion object { private const val TAG_TOKEN = 0 private const val TAG_INSTRUCTION = 1 - private const val TAG_REDIRECT_U_R_L = 2 + private const val TAG_REDIRECT_URL = 2 private const val TAG_FABRIC_INDEX = 254 fun fromTlv( @@ -77,9 +77,9 @@ class AccessControlClusterFabricRestrictionReviewUpdateEvent( } val redirectURL = if (!tlvReader.isNull()) { - tlvReader.getString(ContextSpecificTag(TAG_REDIRECT_U_R_L)) + tlvReader.getString(ContextSpecificTag(TAG_REDIRECT_URL)) } else { - tlvReader.getNull(ContextSpecificTag(TAG_REDIRECT_U_R_L)) + tlvReader.getNull(ContextSpecificTag(TAG_REDIRECT_URL)) null } val fabricIndex = tlvReader.getUByte(ContextSpecificTag(TAG_FABRIC_INDEX)) diff --git a/src/controller/java/generated/java/matter/controller/cluster/eventstructs/ActionsClusterActionFailedEvent.kt b/src/controller/java/generated/java/matter/controller/cluster/eventstructs/ActionsClusterActionFailedEvent.kt index d41926f859..a1fe90125f 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/eventstructs/ActionsClusterActionFailedEvent.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/eventstructs/ActionsClusterActionFailedEvent.kt @@ -40,8 +40,8 @@ class ActionsClusterActionFailedEvent( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_ACTION_I_D), actionID) - put(ContextSpecificTag(TAG_INVOKE_I_D), invokeID) + put(ContextSpecificTag(TAG_ACTION_ID), actionID) + put(ContextSpecificTag(TAG_INVOKE_ID), invokeID) put(ContextSpecificTag(TAG_NEW_STATE), newState) put(ContextSpecificTag(TAG_ERROR), error) endStructure() @@ -49,15 +49,15 @@ class ActionsClusterActionFailedEvent( } companion object { - private const val TAG_ACTION_I_D = 0 - private const val TAG_INVOKE_I_D = 1 + private const val TAG_ACTION_ID = 0 + private const val TAG_INVOKE_ID = 1 private const val TAG_NEW_STATE = 2 private const val TAG_ERROR = 3 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): ActionsClusterActionFailedEvent { tlvReader.enterStructure(tlvTag) - val actionID = tlvReader.getUShort(ContextSpecificTag(TAG_ACTION_I_D)) - val invokeID = tlvReader.getUInt(ContextSpecificTag(TAG_INVOKE_I_D)) + val actionID = tlvReader.getUShort(ContextSpecificTag(TAG_ACTION_ID)) + val invokeID = tlvReader.getUInt(ContextSpecificTag(TAG_INVOKE_ID)) val newState = tlvReader.getUByte(ContextSpecificTag(TAG_NEW_STATE)) val error = tlvReader.getUByte(ContextSpecificTag(TAG_ERROR)) diff --git a/src/controller/java/generated/java/matter/controller/cluster/eventstructs/ActionsClusterStateChangedEvent.kt b/src/controller/java/generated/java/matter/controller/cluster/eventstructs/ActionsClusterStateChangedEvent.kt index f4c4d26bba..8fdefb84b1 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/eventstructs/ActionsClusterStateChangedEvent.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/eventstructs/ActionsClusterStateChangedEvent.kt @@ -38,22 +38,22 @@ class ActionsClusterStateChangedEvent( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_ACTION_I_D), actionID) - put(ContextSpecificTag(TAG_INVOKE_I_D), invokeID) + put(ContextSpecificTag(TAG_ACTION_ID), actionID) + put(ContextSpecificTag(TAG_INVOKE_ID), invokeID) put(ContextSpecificTag(TAG_NEW_STATE), newState) endStructure() } } companion object { - private const val TAG_ACTION_I_D = 0 - private const val TAG_INVOKE_I_D = 1 + private const val TAG_ACTION_ID = 0 + private const val TAG_INVOKE_ID = 1 private const val TAG_NEW_STATE = 2 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): ActionsClusterStateChangedEvent { tlvReader.enterStructure(tlvTag) - val actionID = tlvReader.getUShort(ContextSpecificTag(TAG_ACTION_I_D)) - val invokeID = tlvReader.getUInt(ContextSpecificTag(TAG_INVOKE_I_D)) + val actionID = tlvReader.getUShort(ContextSpecificTag(TAG_ACTION_ID)) + val invokeID = tlvReader.getUInt(ContextSpecificTag(TAG_INVOKE_ID)) val newState = tlvReader.getUByte(ContextSpecificTag(TAG_NEW_STATE)) tlvReader.exitContainer() diff --git a/src/controller/java/generated/java/matter/controller/cluster/eventstructs/DemandResponseLoadControlClusterLoadControlEventStatusChangeEvent.kt b/src/controller/java/generated/java/matter/controller/cluster/eventstructs/DemandResponseLoadControlClusterLoadControlEventStatusChangeEvent.kt index a5e1a7f60e..d5e263249b 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/eventstructs/DemandResponseLoadControlClusterLoadControlEventStatusChangeEvent.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/eventstructs/DemandResponseLoadControlClusterLoadControlEventStatusChangeEvent.kt @@ -68,7 +68,7 @@ class DemandResponseLoadControlClusterLoadControlEventStatusChangeEvent( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_EVENT_I_D), eventID) + put(ContextSpecificTag(TAG_EVENT_ID), eventID) if (transitionIndex != null) { put(ContextSpecificTag(TAG_TRANSITION_INDEX), transitionIndex) } else { @@ -122,7 +122,7 @@ class DemandResponseLoadControlClusterLoadControlEventStatusChangeEvent( } companion object { - private const val TAG_EVENT_I_D = 0 + private const val TAG_EVENT_ID = 0 private const val TAG_TRANSITION_INDEX = 1 private const val TAG_STATUS = 2 private const val TAG_CRITICALITY = 3 @@ -138,7 +138,7 @@ class DemandResponseLoadControlClusterLoadControlEventStatusChangeEvent( tlvReader: TlvReader, ): DemandResponseLoadControlClusterLoadControlEventStatusChangeEvent { tlvReader.enterStructure(tlvTag) - val eventID = tlvReader.getByteArray(ContextSpecificTag(TAG_EVENT_I_D)) + val eventID = tlvReader.getByteArray(ContextSpecificTag(TAG_EVENT_ID)) val transitionIndex = if (!tlvReader.isNull()) { tlvReader.getUByte(ContextSpecificTag(TAG_TRANSITION_INDEX)) diff --git a/src/controller/java/generated/java/matter/controller/cluster/eventstructs/EnergyEvseClusterEVConnectedEvent.kt b/src/controller/java/generated/java/matter/controller/cluster/eventstructs/EnergyEvseClusterEVConnectedEvent.kt index a0770e7e82..672690fcda 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/eventstructs/EnergyEvseClusterEVConnectedEvent.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/eventstructs/EnergyEvseClusterEVConnectedEvent.kt @@ -32,17 +32,17 @@ class EnergyEvseClusterEVConnectedEvent(val sessionID: UInt) { fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_SESSION_I_D), sessionID) + put(ContextSpecificTag(TAG_SESSION_ID), sessionID) endStructure() } } companion object { - private const val TAG_SESSION_I_D = 0 + private const val TAG_SESSION_ID = 0 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): EnergyEvseClusterEVConnectedEvent { tlvReader.enterStructure(tlvTag) - val sessionID = tlvReader.getUInt(ContextSpecificTag(TAG_SESSION_I_D)) + val sessionID = tlvReader.getUInt(ContextSpecificTag(TAG_SESSION_ID)) tlvReader.exitContainer() diff --git a/src/controller/java/generated/java/matter/controller/cluster/eventstructs/EnergyEvseClusterEVNotDetectedEvent.kt b/src/controller/java/generated/java/matter/controller/cluster/eventstructs/EnergyEvseClusterEVNotDetectedEvent.kt index 7af6ae3d08..7f033f40a6 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/eventstructs/EnergyEvseClusterEVNotDetectedEvent.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/eventstructs/EnergyEvseClusterEVNotDetectedEvent.kt @@ -43,7 +43,7 @@ class EnergyEvseClusterEVNotDetectedEvent( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_SESSION_I_D), sessionID) + put(ContextSpecificTag(TAG_SESSION_ID), sessionID) put(ContextSpecificTag(TAG_STATE), state) put(ContextSpecificTag(TAG_SESSION_DURATION), sessionDuration) put(ContextSpecificTag(TAG_SESSION_ENERGY_CHARGED), sessionEnergyCharged) @@ -56,7 +56,7 @@ class EnergyEvseClusterEVNotDetectedEvent( } companion object { - private const val TAG_SESSION_I_D = 0 + private const val TAG_SESSION_ID = 0 private const val TAG_STATE = 1 private const val TAG_SESSION_DURATION = 2 private const val TAG_SESSION_ENERGY_CHARGED = 3 @@ -64,7 +64,7 @@ class EnergyEvseClusterEVNotDetectedEvent( fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): EnergyEvseClusterEVNotDetectedEvent { tlvReader.enterStructure(tlvTag) - val sessionID = tlvReader.getUInt(ContextSpecificTag(TAG_SESSION_I_D)) + val sessionID = tlvReader.getUInt(ContextSpecificTag(TAG_SESSION_ID)) val state = tlvReader.getUByte(ContextSpecificTag(TAG_STATE)) val sessionDuration = tlvReader.getUInt(ContextSpecificTag(TAG_SESSION_DURATION)) val sessionEnergyCharged = tlvReader.getLong(ContextSpecificTag(TAG_SESSION_ENERGY_CHARGED)) diff --git a/src/controller/java/generated/java/matter/controller/cluster/eventstructs/EnergyEvseClusterEnergyTransferStartedEvent.kt b/src/controller/java/generated/java/matter/controller/cluster/eventstructs/EnergyEvseClusterEnergyTransferStartedEvent.kt index 17459394a0..d6ca275c22 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/eventstructs/EnergyEvseClusterEnergyTransferStartedEvent.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/eventstructs/EnergyEvseClusterEnergyTransferStartedEvent.kt @@ -41,7 +41,7 @@ class EnergyEvseClusterEnergyTransferStartedEvent( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_SESSION_I_D), sessionID) + put(ContextSpecificTag(TAG_SESSION_ID), sessionID) put(ContextSpecificTag(TAG_STATE), state) put(ContextSpecificTag(TAG_MAXIMUM_CURRENT), maximumCurrent) if (maximumDischargeCurrent.isPresent) { @@ -53,14 +53,14 @@ class EnergyEvseClusterEnergyTransferStartedEvent( } companion object { - private const val TAG_SESSION_I_D = 0 + private const val TAG_SESSION_ID = 0 private const val TAG_STATE = 1 private const val TAG_MAXIMUM_CURRENT = 2 private const val TAG_MAXIMUM_DISCHARGE_CURRENT = 3 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): EnergyEvseClusterEnergyTransferStartedEvent { tlvReader.enterStructure(tlvTag) - val sessionID = tlvReader.getUInt(ContextSpecificTag(TAG_SESSION_I_D)) + val sessionID = tlvReader.getUInt(ContextSpecificTag(TAG_SESSION_ID)) val state = tlvReader.getUByte(ContextSpecificTag(TAG_STATE)) val maximumCurrent = tlvReader.getLong(ContextSpecificTag(TAG_MAXIMUM_CURRENT)) val maximumDischargeCurrent = diff --git a/src/controller/java/generated/java/matter/controller/cluster/eventstructs/EnergyEvseClusterEnergyTransferStoppedEvent.kt b/src/controller/java/generated/java/matter/controller/cluster/eventstructs/EnergyEvseClusterEnergyTransferStoppedEvent.kt index 56c91b5c1b..1dea5f56e6 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/eventstructs/EnergyEvseClusterEnergyTransferStoppedEvent.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/eventstructs/EnergyEvseClusterEnergyTransferStoppedEvent.kt @@ -43,7 +43,7 @@ class EnergyEvseClusterEnergyTransferStoppedEvent( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_SESSION_I_D), sessionID) + put(ContextSpecificTag(TAG_SESSION_ID), sessionID) put(ContextSpecificTag(TAG_STATE), state) put(ContextSpecificTag(TAG_REASON), reason) put(ContextSpecificTag(TAG_ENERGY_TRANSFERRED), energyTransferred) @@ -56,7 +56,7 @@ class EnergyEvseClusterEnergyTransferStoppedEvent( } companion object { - private const val TAG_SESSION_I_D = 0 + private const val TAG_SESSION_ID = 0 private const val TAG_STATE = 1 private const val TAG_REASON = 2 private const val TAG_ENERGY_TRANSFERRED = 4 @@ -64,7 +64,7 @@ class EnergyEvseClusterEnergyTransferStoppedEvent( fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): EnergyEvseClusterEnergyTransferStoppedEvent { tlvReader.enterStructure(tlvTag) - val sessionID = tlvReader.getUInt(ContextSpecificTag(TAG_SESSION_I_D)) + val sessionID = tlvReader.getUInt(ContextSpecificTag(TAG_SESSION_ID)) val state = tlvReader.getUByte(ContextSpecificTag(TAG_STATE)) val reason = tlvReader.getUByte(ContextSpecificTag(TAG_REASON)) val energyTransferred = tlvReader.getLong(ContextSpecificTag(TAG_ENERGY_TRANSFERRED)) diff --git a/src/controller/java/generated/java/matter/controller/cluster/eventstructs/EnergyEvseClusterFaultEvent.kt b/src/controller/java/generated/java/matter/controller/cluster/eventstructs/EnergyEvseClusterFaultEvent.kt index 534afc36af..02800fa6ed 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/eventstructs/EnergyEvseClusterFaultEvent.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/eventstructs/EnergyEvseClusterFaultEvent.kt @@ -41,9 +41,9 @@ class EnergyEvseClusterFaultEvent( tlvWriter.apply { startStructure(tlvTag) if (sessionID != null) { - put(ContextSpecificTag(TAG_SESSION_I_D), sessionID) + put(ContextSpecificTag(TAG_SESSION_ID), sessionID) } else { - putNull(ContextSpecificTag(TAG_SESSION_I_D)) + putNull(ContextSpecificTag(TAG_SESSION_ID)) } put(ContextSpecificTag(TAG_STATE), state) put(ContextSpecificTag(TAG_FAULT_STATE_PREVIOUS_STATE), faultStatePreviousState) @@ -53,7 +53,7 @@ class EnergyEvseClusterFaultEvent( } companion object { - private const val TAG_SESSION_I_D = 0 + private const val TAG_SESSION_ID = 0 private const val TAG_STATE = 1 private const val TAG_FAULT_STATE_PREVIOUS_STATE = 2 private const val TAG_FAULT_STATE_CURRENT_STATE = 4 @@ -62,9 +62,9 @@ class EnergyEvseClusterFaultEvent( tlvReader.enterStructure(tlvTag) val sessionID = if (!tlvReader.isNull()) { - tlvReader.getUInt(ContextSpecificTag(TAG_SESSION_I_D)) + tlvReader.getUInt(ContextSpecificTag(TAG_SESSION_ID)) } else { - tlvReader.getNull(ContextSpecificTag(TAG_SESSION_I_D)) + tlvReader.getNull(ContextSpecificTag(TAG_SESSION_ID)) null } val state = tlvReader.getUByte(ContextSpecificTag(TAG_STATE)) diff --git a/src/controller/java/generated/java/matter/controller/cluster/eventstructs/MessagesClusterMessageCompleteEvent.kt b/src/controller/java/generated/java/matter/controller/cluster/eventstructs/MessagesClusterMessageCompleteEvent.kt index b47a0919d5..9255c6a84b 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/eventstructs/MessagesClusterMessageCompleteEvent.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/eventstructs/MessagesClusterMessageCompleteEvent.kt @@ -41,14 +41,14 @@ class MessagesClusterMessageCompleteEvent( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_MESSAGE_I_D), messageID) + put(ContextSpecificTag(TAG_MESSAGE_ID), messageID) if (responseID != null) { if (responseID.isPresent) { val optresponseID = responseID.get() - put(ContextSpecificTag(TAG_RESPONSE_I_D), optresponseID) + put(ContextSpecificTag(TAG_RESPONSE_ID), optresponseID) } } else { - putNull(ContextSpecificTag(TAG_RESPONSE_I_D)) + putNull(ContextSpecificTag(TAG_RESPONSE_ID)) } if (reply != null) { if (reply.isPresent) { @@ -68,23 +68,23 @@ class MessagesClusterMessageCompleteEvent( } companion object { - private const val TAG_MESSAGE_I_D = 0 - private const val TAG_RESPONSE_I_D = 1 + private const val TAG_MESSAGE_ID = 0 + private const val TAG_RESPONSE_ID = 1 private const val TAG_REPLY = 2 private const val TAG_FUTURE_MESSAGES_PREFERENCE = 3 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): MessagesClusterMessageCompleteEvent { tlvReader.enterStructure(tlvTag) - val messageID = tlvReader.getByteArray(ContextSpecificTag(TAG_MESSAGE_I_D)) + val messageID = tlvReader.getByteArray(ContextSpecificTag(TAG_MESSAGE_ID)) val responseID = if (!tlvReader.isNull()) { - if (tlvReader.isNextTag(ContextSpecificTag(TAG_RESPONSE_I_D))) { - Optional.of(tlvReader.getUInt(ContextSpecificTag(TAG_RESPONSE_I_D))) + if (tlvReader.isNextTag(ContextSpecificTag(TAG_RESPONSE_ID))) { + Optional.of(tlvReader.getUInt(ContextSpecificTag(TAG_RESPONSE_ID))) } else { Optional.empty() } } else { - tlvReader.getNull(ContextSpecificTag(TAG_RESPONSE_I_D)) + tlvReader.getNull(ContextSpecificTag(TAG_RESPONSE_ID)) null } val reply = diff --git a/src/controller/java/generated/java/matter/controller/cluster/eventstructs/MessagesClusterMessagePresentedEvent.kt b/src/controller/java/generated/java/matter/controller/cluster/eventstructs/MessagesClusterMessagePresentedEvent.kt index 7ca3f028ab..eb92978ebc 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/eventstructs/MessagesClusterMessagePresentedEvent.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/eventstructs/MessagesClusterMessagePresentedEvent.kt @@ -32,17 +32,17 @@ class MessagesClusterMessagePresentedEvent(val messageID: ByteArray) { fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_MESSAGE_I_D), messageID) + put(ContextSpecificTag(TAG_MESSAGE_ID), messageID) endStructure() } } companion object { - private const val TAG_MESSAGE_I_D = 0 + private const val TAG_MESSAGE_ID = 0 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): MessagesClusterMessagePresentedEvent { tlvReader.enterStructure(tlvTag) - val messageID = tlvReader.getByteArray(ContextSpecificTag(TAG_MESSAGE_I_D)) + val messageID = tlvReader.getByteArray(ContextSpecificTag(TAG_MESSAGE_ID)) tlvReader.exitContainer() diff --git a/src/controller/java/generated/java/matter/controller/cluster/eventstructs/MessagesClusterMessageQueuedEvent.kt b/src/controller/java/generated/java/matter/controller/cluster/eventstructs/MessagesClusterMessageQueuedEvent.kt index 6292136f54..5f0e2b0b3c 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/eventstructs/MessagesClusterMessageQueuedEvent.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/eventstructs/MessagesClusterMessageQueuedEvent.kt @@ -32,17 +32,17 @@ class MessagesClusterMessageQueuedEvent(val messageID: ByteArray) { fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_MESSAGE_I_D), messageID) + put(ContextSpecificTag(TAG_MESSAGE_ID), messageID) endStructure() } } companion object { - private const val TAG_MESSAGE_I_D = 0 + private const val TAG_MESSAGE_ID = 0 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): MessagesClusterMessageQueuedEvent { tlvReader.enterStructure(tlvTag) - val messageID = tlvReader.getByteArray(ContextSpecificTag(TAG_MESSAGE_I_D)) + val messageID = tlvReader.getByteArray(ContextSpecificTag(TAG_MESSAGE_ID)) tlvReader.exitContainer() diff --git a/src/controller/java/generated/java/matter/controller/cluster/eventstructs/OtaSoftwareUpdateRequestorClusterVersionAppliedEvent.kt b/src/controller/java/generated/java/matter/controller/cluster/eventstructs/OtaSoftwareUpdateRequestorClusterVersionAppliedEvent.kt index 42e62ce0b2..bc361f53a5 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/eventstructs/OtaSoftwareUpdateRequestorClusterVersionAppliedEvent.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/eventstructs/OtaSoftwareUpdateRequestorClusterVersionAppliedEvent.kt @@ -37,14 +37,14 @@ class OtaSoftwareUpdateRequestorClusterVersionAppliedEvent( tlvWriter.apply { startStructure(tlvTag) put(ContextSpecificTag(TAG_SOFTWARE_VERSION), softwareVersion) - put(ContextSpecificTag(TAG_PRODUCT_I_D), productID) + put(ContextSpecificTag(TAG_PRODUCT_ID), productID) endStructure() } } companion object { private const val TAG_SOFTWARE_VERSION = 0 - private const val TAG_PRODUCT_I_D = 1 + private const val TAG_PRODUCT_ID = 1 fun fromTlv( tlvTag: Tag, @@ -52,7 +52,7 @@ class OtaSoftwareUpdateRequestorClusterVersionAppliedEvent( ): OtaSoftwareUpdateRequestorClusterVersionAppliedEvent { tlvReader.enterStructure(tlvTag) val softwareVersion = tlvReader.getUInt(ContextSpecificTag(TAG_SOFTWARE_VERSION)) - val productID = tlvReader.getUShort(ContextSpecificTag(TAG_PRODUCT_I_D)) + val productID = tlvReader.getUShort(ContextSpecificTag(TAG_PRODUCT_ID)) tlvReader.exitContainer() diff --git a/src/controller/java/generated/java/matter/controller/cluster/eventstructs/TimeSynchronizationClusterDSTStatusEvent.kt b/src/controller/java/generated/java/matter/controller/cluster/eventstructs/TimeSynchronizationClusterDSTStatusEvent.kt index 1f92e4003e..53a976552c 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/eventstructs/TimeSynchronizationClusterDSTStatusEvent.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/eventstructs/TimeSynchronizationClusterDSTStatusEvent.kt @@ -32,17 +32,17 @@ class TimeSynchronizationClusterDSTStatusEvent(val DSTOffsetActive: Boolean) { fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_D_S_T_OFFSET_ACTIVE), DSTOffsetActive) + put(ContextSpecificTag(TAG_DST_OFFSET_ACTIVE), DSTOffsetActive) endStructure() } } companion object { - private const val TAG_D_S_T_OFFSET_ACTIVE = 0 + private const val TAG_DST_OFFSET_ACTIVE = 0 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): TimeSynchronizationClusterDSTStatusEvent { tlvReader.enterStructure(tlvTag) - val DSTOffsetActive = tlvReader.getBoolean(ContextSpecificTag(TAG_D_S_T_OFFSET_ACTIVE)) + val DSTOffsetActive = tlvReader.getBoolean(ContextSpecificTag(TAG_DST_OFFSET_ACTIVE)) tlvReader.exitContainer() diff --git a/src/controller/java/generated/java/matter/controller/cluster/structs/ActionsClusterActionStruct.kt b/src/controller/java/generated/java/matter/controller/cluster/structs/ActionsClusterActionStruct.kt index bf3650489d..080da76540 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/structs/ActionsClusterActionStruct.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/structs/ActionsClusterActionStruct.kt @@ -44,10 +44,10 @@ class ActionsClusterActionStruct( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_ACTION_I_D), actionID) + put(ContextSpecificTag(TAG_ACTION_ID), actionID) put(ContextSpecificTag(TAG_NAME), name) put(ContextSpecificTag(TAG_TYPE), type) - put(ContextSpecificTag(TAG_ENDPOINT_LIST_I_D), endpointListID) + put(ContextSpecificTag(TAG_ENDPOINT_LIST_ID), endpointListID) put(ContextSpecificTag(TAG_SUPPORTED_COMMANDS), supportedCommands) put(ContextSpecificTag(TAG_STATE), state) endStructure() @@ -55,19 +55,19 @@ class ActionsClusterActionStruct( } companion object { - private const val TAG_ACTION_I_D = 0 + private const val TAG_ACTION_ID = 0 private const val TAG_NAME = 1 private const val TAG_TYPE = 2 - private const val TAG_ENDPOINT_LIST_I_D = 3 + private const val TAG_ENDPOINT_LIST_ID = 3 private const val TAG_SUPPORTED_COMMANDS = 4 private const val TAG_STATE = 5 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): ActionsClusterActionStruct { tlvReader.enterStructure(tlvTag) - val actionID = tlvReader.getUShort(ContextSpecificTag(TAG_ACTION_I_D)) + val actionID = tlvReader.getUShort(ContextSpecificTag(TAG_ACTION_ID)) val name = tlvReader.getString(ContextSpecificTag(TAG_NAME)) val type = tlvReader.getUByte(ContextSpecificTag(TAG_TYPE)) - val endpointListID = tlvReader.getUShort(ContextSpecificTag(TAG_ENDPOINT_LIST_I_D)) + val endpointListID = tlvReader.getUShort(ContextSpecificTag(TAG_ENDPOINT_LIST_ID)) val supportedCommands = tlvReader.getUShort(ContextSpecificTag(TAG_SUPPORTED_COMMANDS)) val state = tlvReader.getUByte(ContextSpecificTag(TAG_STATE)) diff --git a/src/controller/java/generated/java/matter/controller/cluster/structs/ActionsClusterEndpointListStruct.kt b/src/controller/java/generated/java/matter/controller/cluster/structs/ActionsClusterEndpointListStruct.kt index ce70c5b1ea..3c4603e164 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/structs/ActionsClusterEndpointListStruct.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/structs/ActionsClusterEndpointListStruct.kt @@ -41,7 +41,7 @@ class ActionsClusterEndpointListStruct( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_ENDPOINT_LIST_I_D), endpointListID) + put(ContextSpecificTag(TAG_ENDPOINT_LIST_ID), endpointListID) put(ContextSpecificTag(TAG_NAME), name) put(ContextSpecificTag(TAG_TYPE), type) startArray(ContextSpecificTag(TAG_ENDPOINTS)) @@ -54,14 +54,14 @@ class ActionsClusterEndpointListStruct( } companion object { - private const val TAG_ENDPOINT_LIST_I_D = 0 + private const val TAG_ENDPOINT_LIST_ID = 0 private const val TAG_NAME = 1 private const val TAG_TYPE = 2 private const val TAG_ENDPOINTS = 3 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): ActionsClusterEndpointListStruct { tlvReader.enterStructure(tlvTag) - val endpointListID = tlvReader.getUShort(ContextSpecificTag(TAG_ENDPOINT_LIST_I_D)) + val endpointListID = tlvReader.getUShort(ContextSpecificTag(TAG_ENDPOINT_LIST_ID)) val name = tlvReader.getString(ContextSpecificTag(TAG_NAME)) val type = tlvReader.getUByte(ContextSpecificTag(TAG_TYPE)) val endpoints = diff --git a/src/controller/java/generated/java/matter/controller/cluster/structs/ApplicationBasicClusterApplicationStruct.kt b/src/controller/java/generated/java/matter/controller/cluster/structs/ApplicationBasicClusterApplicationStruct.kt index 603c99e96d..be4a1e7984 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/structs/ApplicationBasicClusterApplicationStruct.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/structs/ApplicationBasicClusterApplicationStruct.kt @@ -36,20 +36,20 @@ class ApplicationBasicClusterApplicationStruct( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_CATALOG_VENDOR_I_D), catalogVendorID) - put(ContextSpecificTag(TAG_APPLICATION_I_D), applicationID) + put(ContextSpecificTag(TAG_CATALOG_VENDOR_ID), catalogVendorID) + put(ContextSpecificTag(TAG_APPLICATION_ID), applicationID) endStructure() } } companion object { - private const val TAG_CATALOG_VENDOR_I_D = 0 - private const val TAG_APPLICATION_I_D = 1 + private const val TAG_CATALOG_VENDOR_ID = 0 + private const val TAG_APPLICATION_ID = 1 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): ApplicationBasicClusterApplicationStruct { tlvReader.enterStructure(tlvTag) - val catalogVendorID = tlvReader.getUShort(ContextSpecificTag(TAG_CATALOG_VENDOR_I_D)) - val applicationID = tlvReader.getString(ContextSpecificTag(TAG_APPLICATION_I_D)) + val catalogVendorID = tlvReader.getUShort(ContextSpecificTag(TAG_CATALOG_VENDOR_ID)) + val applicationID = tlvReader.getString(ContextSpecificTag(TAG_APPLICATION_ID)) tlvReader.exitContainer() diff --git a/src/controller/java/generated/java/matter/controller/cluster/structs/ApplicationLauncherClusterApplicationStruct.kt b/src/controller/java/generated/java/matter/controller/cluster/structs/ApplicationLauncherClusterApplicationStruct.kt index 8827b46c04..ea921ee690 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/structs/ApplicationLauncherClusterApplicationStruct.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/structs/ApplicationLauncherClusterApplicationStruct.kt @@ -36,20 +36,20 @@ class ApplicationLauncherClusterApplicationStruct( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_CATALOG_VENDOR_I_D), catalogVendorID) - put(ContextSpecificTag(TAG_APPLICATION_I_D), applicationID) + put(ContextSpecificTag(TAG_CATALOG_VENDOR_ID), catalogVendorID) + put(ContextSpecificTag(TAG_APPLICATION_ID), applicationID) endStructure() } } companion object { - private const val TAG_CATALOG_VENDOR_I_D = 0 - private const val TAG_APPLICATION_I_D = 1 + private const val TAG_CATALOG_VENDOR_ID = 0 + private const val TAG_APPLICATION_ID = 1 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): ApplicationLauncherClusterApplicationStruct { tlvReader.enterStructure(tlvTag) - val catalogVendorID = tlvReader.getUShort(ContextSpecificTag(TAG_CATALOG_VENDOR_I_D)) - val applicationID = tlvReader.getString(ContextSpecificTag(TAG_APPLICATION_I_D)) + val catalogVendorID = tlvReader.getUShort(ContextSpecificTag(TAG_CATALOG_VENDOR_ID)) + val applicationID = tlvReader.getString(ContextSpecificTag(TAG_APPLICATION_ID)) tlvReader.exitContainer() diff --git a/src/controller/java/generated/java/matter/controller/cluster/structs/ChannelClusterProgramStruct.kt b/src/controller/java/generated/java/matter/controller/cluster/structs/ChannelClusterProgramStruct.kt index 243e78b0a5..c8dfd42de6 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/structs/ChannelClusterProgramStruct.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/structs/ChannelClusterProgramStruct.kt @@ -151,7 +151,7 @@ class ChannelClusterProgramStruct( } if (externalIDList.isPresent) { val optexternalIDList = externalIDList.get() - startArray(ContextSpecificTag(TAG_EXTERNAL_I_D_LIST)) + startArray(ContextSpecificTag(TAG_EXTERNAL_ID_LIST)) for (item in optexternalIDList.iterator()) { item.toTlv(AnonymousTag, this) } @@ -180,7 +180,7 @@ class ChannelClusterProgramStruct( private const val TAG_SERIES_INFO = 15 private const val TAG_CATEGORY_LIST = 16 private const val TAG_CAST_LIST = 17 - private const val TAG_EXTERNAL_I_D_LIST = 18 + private const val TAG_EXTERNAL_ID_LIST = 18 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): ChannelClusterProgramStruct { tlvReader.enterStructure(tlvTag) @@ -308,10 +308,10 @@ class ChannelClusterProgramStruct( Optional.empty() } val externalIDList = - if (tlvReader.isNextTag(ContextSpecificTag(TAG_EXTERNAL_I_D_LIST))) { + if (tlvReader.isNextTag(ContextSpecificTag(TAG_EXTERNAL_ID_LIST))) { Optional.of( buildList { - tlvReader.enterArray(ContextSpecificTag(TAG_EXTERNAL_I_D_LIST)) + tlvReader.enterArray(ContextSpecificTag(TAG_EXTERNAL_ID_LIST)) while (!tlvReader.isEndOfContainer()) { add(ChannelClusterProgramCastStruct.fromTlv(AnonymousTag, tlvReader)) } diff --git a/src/controller/java/generated/java/matter/controller/cluster/structs/ContentLauncherClusterParameterStruct.kt b/src/controller/java/generated/java/matter/controller/cluster/structs/ContentLauncherClusterParameterStruct.kt index 6d94bd6492..1785ef89c5 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/structs/ContentLauncherClusterParameterStruct.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/structs/ContentLauncherClusterParameterStruct.kt @@ -44,7 +44,7 @@ class ContentLauncherClusterParameterStruct( put(ContextSpecificTag(TAG_VALUE), value) if (externalIDList.isPresent) { val optexternalIDList = externalIDList.get() - startArray(ContextSpecificTag(TAG_EXTERNAL_I_D_LIST)) + startArray(ContextSpecificTag(TAG_EXTERNAL_ID_LIST)) for (item in optexternalIDList.iterator()) { item.toTlv(AnonymousTag, this) } @@ -57,17 +57,17 @@ class ContentLauncherClusterParameterStruct( companion object { private const val TAG_TYPE = 0 private const val TAG_VALUE = 1 - private const val TAG_EXTERNAL_I_D_LIST = 2 + private const val TAG_EXTERNAL_ID_LIST = 2 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): ContentLauncherClusterParameterStruct { tlvReader.enterStructure(tlvTag) val type = tlvReader.getUByte(ContextSpecificTag(TAG_TYPE)) val value = tlvReader.getString(ContextSpecificTag(TAG_VALUE)) val externalIDList = - if (tlvReader.isNextTag(ContextSpecificTag(TAG_EXTERNAL_I_D_LIST))) { + if (tlvReader.isNextTag(ContextSpecificTag(TAG_EXTERNAL_ID_LIST))) { Optional.of( buildList { - tlvReader.enterArray(ContextSpecificTag(TAG_EXTERNAL_I_D_LIST)) + tlvReader.enterArray(ContextSpecificTag(TAG_EXTERNAL_ID_LIST)) while (!tlvReader.isEndOfContainer()) { add(ContentLauncherClusterAdditionalInfoStruct.fromTlv(AnonymousTag, tlvReader)) } diff --git a/src/controller/java/generated/java/matter/controller/cluster/structs/ContentLauncherClusterStyleInformationStruct.kt b/src/controller/java/generated/java/matter/controller/cluster/structs/ContentLauncherClusterStyleInformationStruct.kt index be5d5dd35f..b1a5ea8bfe 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/structs/ContentLauncherClusterStyleInformationStruct.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/structs/ContentLauncherClusterStyleInformationStruct.kt @@ -41,7 +41,7 @@ class ContentLauncherClusterStyleInformationStruct( startStructure(tlvTag) if (imageURL.isPresent) { val optimageURL = imageURL.get() - put(ContextSpecificTag(TAG_IMAGE_U_R_L), optimageURL) + put(ContextSpecificTag(TAG_IMAGE_URL), optimageURL) } if (color.isPresent) { val optcolor = color.get() @@ -56,15 +56,15 @@ class ContentLauncherClusterStyleInformationStruct( } companion object { - private const val TAG_IMAGE_U_R_L = 0 + private const val TAG_IMAGE_URL = 0 private const val TAG_COLOR = 1 private const val TAG_SIZE = 2 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): ContentLauncherClusterStyleInformationStruct { tlvReader.enterStructure(tlvTag) val imageURL = - if (tlvReader.isNextTag(ContextSpecificTag(TAG_IMAGE_U_R_L))) { - Optional.of(tlvReader.getString(ContextSpecificTag(TAG_IMAGE_U_R_L))) + if (tlvReader.isNextTag(ContextSpecificTag(TAG_IMAGE_URL))) { + Optional.of(tlvReader.getString(ContextSpecificTag(TAG_IMAGE_URL))) } else { Optional.empty() } diff --git a/src/controller/java/generated/java/matter/controller/cluster/structs/DemandResponseLoadControlClusterLoadControlEventStruct.kt b/src/controller/java/generated/java/matter/controller/cluster/structs/DemandResponseLoadControlClusterLoadControlEventStruct.kt index 83fb56f785..e17da92ffd 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/structs/DemandResponseLoadControlClusterLoadControlEventStruct.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/structs/DemandResponseLoadControlClusterLoadControlEventStruct.kt @@ -50,11 +50,11 @@ class DemandResponseLoadControlClusterLoadControlEventStruct( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_EVENT_I_D), eventID) + put(ContextSpecificTag(TAG_EVENT_ID), eventID) if (programID != null) { - put(ContextSpecificTag(TAG_PROGRAM_I_D), programID) + put(ContextSpecificTag(TAG_PROGRAM_ID), programID) } else { - putNull(ContextSpecificTag(TAG_PROGRAM_I_D)) + putNull(ContextSpecificTag(TAG_PROGRAM_ID)) } put(ContextSpecificTag(TAG_CONTROL), control) put(ContextSpecificTag(TAG_DEVICE_CLASS), deviceClass) @@ -78,8 +78,8 @@ class DemandResponseLoadControlClusterLoadControlEventStruct( } companion object { - private const val TAG_EVENT_I_D = 0 - private const val TAG_PROGRAM_I_D = 1 + private const val TAG_EVENT_ID = 0 + private const val TAG_PROGRAM_ID = 1 private const val TAG_CONTROL = 2 private const val TAG_DEVICE_CLASS = 3 private const val TAG_ENROLLMENT_GROUP = 4 @@ -92,12 +92,12 @@ class DemandResponseLoadControlClusterLoadControlEventStruct( tlvReader: TlvReader, ): DemandResponseLoadControlClusterLoadControlEventStruct { tlvReader.enterStructure(tlvTag) - val eventID = tlvReader.getByteArray(ContextSpecificTag(TAG_EVENT_I_D)) + val eventID = tlvReader.getByteArray(ContextSpecificTag(TAG_EVENT_ID)) val programID = if (!tlvReader.isNull()) { - tlvReader.getByteArray(ContextSpecificTag(TAG_PROGRAM_I_D)) + tlvReader.getByteArray(ContextSpecificTag(TAG_PROGRAM_ID)) } else { - tlvReader.getNull(ContextSpecificTag(TAG_PROGRAM_I_D)) + tlvReader.getNull(ContextSpecificTag(TAG_PROGRAM_ID)) null } val control = tlvReader.getUShort(ContextSpecificTag(TAG_CONTROL)) diff --git a/src/controller/java/generated/java/matter/controller/cluster/structs/DemandResponseLoadControlClusterLoadControlProgramStruct.kt b/src/controller/java/generated/java/matter/controller/cluster/structs/DemandResponseLoadControlClusterLoadControlProgramStruct.kt index 7e73951b40..e22ed84158 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/structs/DemandResponseLoadControlClusterLoadControlProgramStruct.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/structs/DemandResponseLoadControlClusterLoadControlProgramStruct.kt @@ -42,7 +42,7 @@ class DemandResponseLoadControlClusterLoadControlProgramStruct( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_PROGRAM_I_D), programID) + put(ContextSpecificTag(TAG_PROGRAM_ID), programID) put(ContextSpecificTag(TAG_NAME), name) if (enrollmentGroup != null) { put(ContextSpecificTag(TAG_ENROLLMENT_GROUP), enrollmentGroup) @@ -64,7 +64,7 @@ class DemandResponseLoadControlClusterLoadControlProgramStruct( } companion object { - private const val TAG_PROGRAM_I_D = 0 + private const val TAG_PROGRAM_ID = 0 private const val TAG_NAME = 1 private const val TAG_ENROLLMENT_GROUP = 2 private const val TAG_RANDOM_START_MINUTES = 3 @@ -75,7 +75,7 @@ class DemandResponseLoadControlClusterLoadControlProgramStruct( tlvReader: TlvReader, ): DemandResponseLoadControlClusterLoadControlProgramStruct { tlvReader.enterStructure(tlvTag) - val programID = tlvReader.getByteArray(ContextSpecificTag(TAG_PROGRAM_I_D)) + val programID = tlvReader.getByteArray(ContextSpecificTag(TAG_PROGRAM_ID)) val name = tlvReader.getString(ContextSpecificTag(TAG_NAME)) val enrollmentGroup = if (!tlvReader.isNull()) { diff --git a/src/controller/java/generated/java/matter/controller/cluster/structs/DescriptorClusterSemanticTagStruct.kt b/src/controller/java/generated/java/matter/controller/cluster/structs/DescriptorClusterSemanticTagStruct.kt index 358cf48bbb..f0206f14fa 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/structs/DescriptorClusterSemanticTagStruct.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/structs/DescriptorClusterSemanticTagStruct.kt @@ -46,7 +46,7 @@ class DescriptorClusterSemanticTagStruct( } else { putNull(ContextSpecificTag(TAG_MFG_CODE)) } - put(ContextSpecificTag(TAG_NAMESPACE_I_D), namespaceID) + put(ContextSpecificTag(TAG_NAMESPACE_ID), namespaceID) put(ContextSpecificTag(TAG_TAG), tag) if (label != null) { if (label.isPresent) { @@ -62,7 +62,7 @@ class DescriptorClusterSemanticTagStruct( companion object { private const val TAG_MFG_CODE = 0 - private const val TAG_NAMESPACE_I_D = 1 + private const val TAG_NAMESPACE_ID = 1 private const val TAG_TAG = 2 private const val TAG_LABEL = 3 @@ -75,7 +75,7 @@ class DescriptorClusterSemanticTagStruct( tlvReader.getNull(ContextSpecificTag(TAG_MFG_CODE)) null } - val namespaceID = tlvReader.getUByte(ContextSpecificTag(TAG_NAMESPACE_I_D)) + val namespaceID = tlvReader.getUByte(ContextSpecificTag(TAG_NAMESPACE_ID)) val tag = tlvReader.getUByte(ContextSpecificTag(TAG_TAG)) val label = if (!tlvReader.isNull()) { diff --git a/src/controller/java/generated/java/matter/controller/cluster/structs/DeviceEnergyManagementClusterForecastStruct.kt b/src/controller/java/generated/java/matter/controller/cluster/structs/DeviceEnergyManagementClusterForecastStruct.kt index f58179f523..d10b032374 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/structs/DeviceEnergyManagementClusterForecastStruct.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/structs/DeviceEnergyManagementClusterForecastStruct.kt @@ -52,7 +52,7 @@ class DeviceEnergyManagementClusterForecastStruct( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_FORECAST_I_D), forecastID) + put(ContextSpecificTag(TAG_FORECAST_ID), forecastID) if (activeSlotNumber != null) { put(ContextSpecificTag(TAG_ACTIVE_SLOT_NUMBER), activeSlotNumber) } else { @@ -84,7 +84,7 @@ class DeviceEnergyManagementClusterForecastStruct( } companion object { - private const val TAG_FORECAST_I_D = 0 + private const val TAG_FORECAST_ID = 0 private const val TAG_ACTIVE_SLOT_NUMBER = 1 private const val TAG_START_TIME = 2 private const val TAG_END_TIME = 3 @@ -96,7 +96,7 @@ class DeviceEnergyManagementClusterForecastStruct( fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): DeviceEnergyManagementClusterForecastStruct { tlvReader.enterStructure(tlvTag) - val forecastID = tlvReader.getUInt(ContextSpecificTag(TAG_FORECAST_I_D)) + val forecastID = tlvReader.getUInt(ContextSpecificTag(TAG_FORECAST_ID)) val activeSlotNumber = if (!tlvReader.isNull()) { tlvReader.getUShort(ContextSpecificTag(TAG_ACTIVE_SLOT_NUMBER)) diff --git a/src/controller/java/generated/java/matter/controller/cluster/structs/DeviceEnergyManagementClusterSlotStruct.kt b/src/controller/java/generated/java/matter/controller/cluster/structs/DeviceEnergyManagementClusterSlotStruct.kt index 794aef83e5..d1babaf255 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/structs/DeviceEnergyManagementClusterSlotStruct.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/structs/DeviceEnergyManagementClusterSlotStruct.kt @@ -89,7 +89,7 @@ class DeviceEnergyManagementClusterSlotStruct( } if (manufacturerESAState.isPresent) { val optmanufacturerESAState = manufacturerESAState.get() - put(ContextSpecificTag(TAG_MANUFACTURER_E_S_A_STATE), optmanufacturerESAState) + put(ContextSpecificTag(TAG_MANUFACTURER_ESA_STATE), optmanufacturerESAState) } if (nominalPower.isPresent) { val optnominalPower = nominalPower.get() @@ -144,7 +144,7 @@ class DeviceEnergyManagementClusterSlotStruct( private const val TAG_SLOT_IS_PAUSABLE = 5 private const val TAG_MIN_PAUSE_DURATION = 6 private const val TAG_MAX_PAUSE_DURATION = 7 - private const val TAG_MANUFACTURER_E_S_A_STATE = 8 + private const val TAG_MANUFACTURER_ESA_STATE = 8 private const val TAG_NOMINAL_POWER = 9 private const val TAG_MIN_POWER = 10 private const val TAG_MAX_POWER = 11 @@ -181,8 +181,8 @@ class DeviceEnergyManagementClusterSlotStruct( Optional.empty() } val manufacturerESAState = - if (tlvReader.isNextTag(ContextSpecificTag(TAG_MANUFACTURER_E_S_A_STATE))) { - Optional.of(tlvReader.getUShort(ContextSpecificTag(TAG_MANUFACTURER_E_S_A_STATE))) + if (tlvReader.isNextTag(ContextSpecificTag(TAG_MANUFACTURER_ESA_STATE))) { + Optional.of(tlvReader.getUShort(ContextSpecificTag(TAG_MANUFACTURER_ESA_STATE))) } else { Optional.empty() } diff --git a/src/controller/java/generated/java/matter/controller/cluster/structs/EcosystemInformationClusterEcosystemLocationStruct.kt b/src/controller/java/generated/java/matter/controller/cluster/structs/EcosystemInformationClusterEcosystemLocationStruct.kt index 5d44434897..f59492e619 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/structs/EcosystemInformationClusterEcosystemLocationStruct.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/structs/EcosystemInformationClusterEcosystemLocationStruct.kt @@ -40,7 +40,7 @@ class EcosystemInformationClusterEcosystemLocationStruct( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_UNIQUE_LOCATION_I_D), uniqueLocationID) + put(ContextSpecificTag(TAG_UNIQUE_LOCATION_ID), uniqueLocationID) locationDescriptor.toTlv(ContextSpecificTag(TAG_LOCATION_DESCRIPTOR), this) put(ContextSpecificTag(TAG_LOCATION_DESCRIPTOR_LAST_EDIT), locationDescriptorLastEdit) put(ContextSpecificTag(TAG_FABRIC_INDEX), fabricIndex) @@ -49,7 +49,7 @@ class EcosystemInformationClusterEcosystemLocationStruct( } companion object { - private const val TAG_UNIQUE_LOCATION_I_D = 0 + private const val TAG_UNIQUE_LOCATION_ID = 0 private const val TAG_LOCATION_DESCRIPTOR = 1 private const val TAG_LOCATION_DESCRIPTOR_LAST_EDIT = 2 private const val TAG_FABRIC_INDEX = 254 @@ -59,7 +59,7 @@ class EcosystemInformationClusterEcosystemLocationStruct( tlvReader: TlvReader, ): EcosystemInformationClusterEcosystemLocationStruct { tlvReader.enterStructure(tlvTag) - val uniqueLocationID = tlvReader.getString(ContextSpecificTag(TAG_UNIQUE_LOCATION_I_D)) + val uniqueLocationID = tlvReader.getString(ContextSpecificTag(TAG_UNIQUE_LOCATION_ID)) val locationDescriptor = EcosystemInformationClusterLocationDescriptorStruct.fromTlv( ContextSpecificTag(TAG_LOCATION_DESCRIPTOR), diff --git a/src/controller/java/generated/java/matter/controller/cluster/structs/GroupKeyManagementClusterGroupKeyMapStruct.kt b/src/controller/java/generated/java/matter/controller/cluster/structs/GroupKeyManagementClusterGroupKeyMapStruct.kt index fae021994f..ad1823e569 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/structs/GroupKeyManagementClusterGroupKeyMapStruct.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/structs/GroupKeyManagementClusterGroupKeyMapStruct.kt @@ -39,7 +39,7 @@ class GroupKeyManagementClusterGroupKeyMapStruct( tlvWriter.apply { startStructure(tlvTag) put(ContextSpecificTag(TAG_GROUP_ID), groupId) - put(ContextSpecificTag(TAG_GROUP_KEY_SET_I_D), groupKeySetID) + put(ContextSpecificTag(TAG_GROUP_KEY_SET_ID), groupKeySetID) put(ContextSpecificTag(TAG_FABRIC_INDEX), fabricIndex) endStructure() } @@ -47,13 +47,13 @@ class GroupKeyManagementClusterGroupKeyMapStruct( companion object { private const val TAG_GROUP_ID = 1 - private const val TAG_GROUP_KEY_SET_I_D = 2 + private const val TAG_GROUP_KEY_SET_ID = 2 private const val TAG_FABRIC_INDEX = 254 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): GroupKeyManagementClusterGroupKeyMapStruct { tlvReader.enterStructure(tlvTag) val groupId = tlvReader.getUShort(ContextSpecificTag(TAG_GROUP_ID)) - val groupKeySetID = tlvReader.getUShort(ContextSpecificTag(TAG_GROUP_KEY_SET_I_D)) + val groupKeySetID = tlvReader.getUShort(ContextSpecificTag(TAG_GROUP_KEY_SET_ID)) val fabricIndex = tlvReader.getUByte(ContextSpecificTag(TAG_FABRIC_INDEX)) tlvReader.exitContainer() diff --git a/src/controller/java/generated/java/matter/controller/cluster/structs/GroupKeyManagementClusterGroupKeySetStruct.kt b/src/controller/java/generated/java/matter/controller/cluster/structs/GroupKeyManagementClusterGroupKeySetStruct.kt index 9443c0f6f8..1419d29377 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/structs/GroupKeyManagementClusterGroupKeySetStruct.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/structs/GroupKeyManagementClusterGroupKeySetStruct.kt @@ -48,7 +48,7 @@ class GroupKeyManagementClusterGroupKeySetStruct( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_GROUP_KEY_SET_I_D), groupKeySetID) + put(ContextSpecificTag(TAG_GROUP_KEY_SET_ID), groupKeySetID) put(ContextSpecificTag(TAG_GROUP_KEY_SECURITY_POLICY), groupKeySecurityPolicy) if (epochKey0 != null) { put(ContextSpecificTag(TAG_EPOCH_KEY0), epochKey0) @@ -85,7 +85,7 @@ class GroupKeyManagementClusterGroupKeySetStruct( } companion object { - private const val TAG_GROUP_KEY_SET_I_D = 0 + private const val TAG_GROUP_KEY_SET_ID = 0 private const val TAG_GROUP_KEY_SECURITY_POLICY = 1 private const val TAG_EPOCH_KEY0 = 2 private const val TAG_EPOCH_START_TIME0 = 3 @@ -96,7 +96,7 @@ class GroupKeyManagementClusterGroupKeySetStruct( fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): GroupKeyManagementClusterGroupKeySetStruct { tlvReader.enterStructure(tlvTag) - val groupKeySetID = tlvReader.getUShort(ContextSpecificTag(TAG_GROUP_KEY_SET_I_D)) + val groupKeySetID = tlvReader.getUShort(ContextSpecificTag(TAG_GROUP_KEY_SET_ID)) val groupKeySecurityPolicy = tlvReader.getUByte(ContextSpecificTag(TAG_GROUP_KEY_SECURITY_POLICY)) val epochKey0 = diff --git a/src/controller/java/generated/java/matter/controller/cluster/structs/IcdManagementClusterMonitoringRegistrationStruct.kt b/src/controller/java/generated/java/matter/controller/cluster/structs/IcdManagementClusterMonitoringRegistrationStruct.kt index fbf95fd9f4..478ce9f25c 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/structs/IcdManagementClusterMonitoringRegistrationStruct.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/structs/IcdManagementClusterMonitoringRegistrationStruct.kt @@ -40,7 +40,7 @@ class IcdManagementClusterMonitoringRegistrationStruct( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_CHECK_IN_NODE_I_D), checkInNodeID) + put(ContextSpecificTag(TAG_CHECK_IN_NODE_ID), checkInNodeID) put(ContextSpecificTag(TAG_MONITORED_SUBJECT), monitoredSubject) put(ContextSpecificTag(TAG_CLIENT_TYPE), clientType) put(ContextSpecificTag(TAG_FABRIC_INDEX), fabricIndex) @@ -49,7 +49,7 @@ class IcdManagementClusterMonitoringRegistrationStruct( } companion object { - private const val TAG_CHECK_IN_NODE_I_D = 1 + private const val TAG_CHECK_IN_NODE_ID = 1 private const val TAG_MONITORED_SUBJECT = 2 private const val TAG_CLIENT_TYPE = 4 private const val TAG_FABRIC_INDEX = 254 @@ -59,7 +59,7 @@ class IcdManagementClusterMonitoringRegistrationStruct( tlvReader: TlvReader, ): IcdManagementClusterMonitoringRegistrationStruct { tlvReader.enterStructure(tlvTag) - val checkInNodeID = tlvReader.getULong(ContextSpecificTag(TAG_CHECK_IN_NODE_I_D)) + val checkInNodeID = tlvReader.getULong(ContextSpecificTag(TAG_CHECK_IN_NODE_ID)) val monitoredSubject = tlvReader.getULong(ContextSpecificTag(TAG_MONITORED_SUBJECT)) val clientType = tlvReader.getUByte(ContextSpecificTag(TAG_CLIENT_TYPE)) val fabricIndex = tlvReader.getUByte(ContextSpecificTag(TAG_FABRIC_INDEX)) diff --git a/src/controller/java/generated/java/matter/controller/cluster/structs/MessagesClusterMessageResponseOptionStruct.kt b/src/controller/java/generated/java/matter/controller/cluster/structs/MessagesClusterMessageResponseOptionStruct.kt index ed263ece2d..7240826c29 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/structs/MessagesClusterMessageResponseOptionStruct.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/structs/MessagesClusterMessageResponseOptionStruct.kt @@ -39,7 +39,7 @@ class MessagesClusterMessageResponseOptionStruct( startStructure(tlvTag) if (messageResponseID.isPresent) { val optmessageResponseID = messageResponseID.get() - put(ContextSpecificTag(TAG_MESSAGE_RESPONSE_I_D), optmessageResponseID) + put(ContextSpecificTag(TAG_MESSAGE_RESPONSE_ID), optmessageResponseID) } if (label.isPresent) { val optlabel = label.get() @@ -50,14 +50,14 @@ class MessagesClusterMessageResponseOptionStruct( } companion object { - private const val TAG_MESSAGE_RESPONSE_I_D = 0 + private const val TAG_MESSAGE_RESPONSE_ID = 0 private const val TAG_LABEL = 1 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): MessagesClusterMessageResponseOptionStruct { tlvReader.enterStructure(tlvTag) val messageResponseID = - if (tlvReader.isNextTag(ContextSpecificTag(TAG_MESSAGE_RESPONSE_I_D))) { - Optional.of(tlvReader.getUInt(ContextSpecificTag(TAG_MESSAGE_RESPONSE_I_D))) + if (tlvReader.isNextTag(ContextSpecificTag(TAG_MESSAGE_RESPONSE_ID))) { + Optional.of(tlvReader.getUInt(ContextSpecificTag(TAG_MESSAGE_RESPONSE_ID))) } else { Optional.empty() } diff --git a/src/controller/java/generated/java/matter/controller/cluster/structs/MessagesClusterMessageStruct.kt b/src/controller/java/generated/java/matter/controller/cluster/structs/MessagesClusterMessageStruct.kt index 90990310f0..ff033fa133 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/structs/MessagesClusterMessageStruct.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/structs/MessagesClusterMessageStruct.kt @@ -48,7 +48,7 @@ class MessagesClusterMessageStruct( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_MESSAGE_I_D), messageID) + put(ContextSpecificTag(TAG_MESSAGE_ID), messageID) put(ContextSpecificTag(TAG_PRIORITY), priority) put(ContextSpecificTag(TAG_MESSAGE_CONTROL), messageControl) if (startTime != null) { @@ -75,7 +75,7 @@ class MessagesClusterMessageStruct( } companion object { - private const val TAG_MESSAGE_I_D = 0 + private const val TAG_MESSAGE_ID = 0 private const val TAG_PRIORITY = 1 private const val TAG_MESSAGE_CONTROL = 2 private const val TAG_START_TIME = 3 @@ -85,7 +85,7 @@ class MessagesClusterMessageStruct( fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): MessagesClusterMessageStruct { tlvReader.enterStructure(tlvTag) - val messageID = tlvReader.getByteArray(ContextSpecificTag(TAG_MESSAGE_I_D)) + val messageID = tlvReader.getByteArray(ContextSpecificTag(TAG_MESSAGE_ID)) val priority = tlvReader.getUByte(ContextSpecificTag(TAG_PRIORITY)) val messageControl = tlvReader.getUByte(ContextSpecificTag(TAG_MESSAGE_CONTROL)) val startTime = diff --git a/src/controller/java/generated/java/matter/controller/cluster/structs/NetworkCommissioningClusterNetworkInfoStruct.kt b/src/controller/java/generated/java/matter/controller/cluster/structs/NetworkCommissioningClusterNetworkInfoStruct.kt index 7a8718ff52..e7503f3751 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/structs/NetworkCommissioningClusterNetworkInfoStruct.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/structs/NetworkCommissioningClusterNetworkInfoStruct.kt @@ -41,7 +41,7 @@ class NetworkCommissioningClusterNetworkInfoStruct( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_NETWORK_I_D), networkID) + put(ContextSpecificTag(TAG_NETWORK_ID), networkID) put(ContextSpecificTag(TAG_CONNECTED), connected) if (networkIdentifier != null) { if (networkIdentifier.isPresent) { @@ -64,14 +64,14 @@ class NetworkCommissioningClusterNetworkInfoStruct( } companion object { - private const val TAG_NETWORK_I_D = 0 + private const val TAG_NETWORK_ID = 0 private const val TAG_CONNECTED = 1 private const val TAG_NETWORK_IDENTIFIER = 2 private const val TAG_CLIENT_IDENTIFIER = 3 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): NetworkCommissioningClusterNetworkInfoStruct { tlvReader.enterStructure(tlvTag) - val networkID = tlvReader.getByteArray(ContextSpecificTag(TAG_NETWORK_I_D)) + val networkID = tlvReader.getByteArray(ContextSpecificTag(TAG_NETWORK_ID)) val connected = tlvReader.getBoolean(ContextSpecificTag(TAG_CONNECTED)) val networkIdentifier = if (!tlvReader.isNull()) { diff --git a/src/controller/java/generated/java/matter/controller/cluster/structs/OperationalCredentialsClusterFabricDescriptorStruct.kt b/src/controller/java/generated/java/matter/controller/cluster/structs/OperationalCredentialsClusterFabricDescriptorStruct.kt index 66c28dc3e1..6fad97097c 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/structs/OperationalCredentialsClusterFabricDescriptorStruct.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/structs/OperationalCredentialsClusterFabricDescriptorStruct.kt @@ -45,9 +45,9 @@ class OperationalCredentialsClusterFabricDescriptorStruct( tlvWriter.apply { startStructure(tlvTag) put(ContextSpecificTag(TAG_ROOT_PUBLIC_KEY), rootPublicKey) - put(ContextSpecificTag(TAG_VENDOR_I_D), vendorID) - put(ContextSpecificTag(TAG_FABRIC_I_D), fabricID) - put(ContextSpecificTag(TAG_NODE_I_D), nodeID) + put(ContextSpecificTag(TAG_VENDOR_ID), vendorID) + put(ContextSpecificTag(TAG_FABRIC_ID), fabricID) + put(ContextSpecificTag(TAG_NODE_ID), nodeID) put(ContextSpecificTag(TAG_LABEL), label) put(ContextSpecificTag(TAG_FABRIC_INDEX), fabricIndex) endStructure() @@ -56,9 +56,9 @@ class OperationalCredentialsClusterFabricDescriptorStruct( companion object { private const val TAG_ROOT_PUBLIC_KEY = 1 - private const val TAG_VENDOR_I_D = 2 - private const val TAG_FABRIC_I_D = 3 - private const val TAG_NODE_I_D = 4 + private const val TAG_VENDOR_ID = 2 + private const val TAG_FABRIC_ID = 3 + private const val TAG_NODE_ID = 4 private const val TAG_LABEL = 5 private const val TAG_FABRIC_INDEX = 254 @@ -68,9 +68,9 @@ class OperationalCredentialsClusterFabricDescriptorStruct( ): OperationalCredentialsClusterFabricDescriptorStruct { tlvReader.enterStructure(tlvTag) val rootPublicKey = tlvReader.getByteArray(ContextSpecificTag(TAG_ROOT_PUBLIC_KEY)) - val vendorID = tlvReader.getUShort(ContextSpecificTag(TAG_VENDOR_I_D)) - val fabricID = tlvReader.getULong(ContextSpecificTag(TAG_FABRIC_I_D)) - val nodeID = tlvReader.getULong(ContextSpecificTag(TAG_NODE_I_D)) + val vendorID = tlvReader.getUShort(ContextSpecificTag(TAG_VENDOR_ID)) + val fabricID = tlvReader.getULong(ContextSpecificTag(TAG_FABRIC_ID)) + val nodeID = tlvReader.getULong(ContextSpecificTag(TAG_NODE_ID)) val label = tlvReader.getString(ContextSpecificTag(TAG_LABEL)) val fabricIndex = tlvReader.getUByte(ContextSpecificTag(TAG_FABRIC_INDEX)) diff --git a/src/controller/java/generated/java/matter/controller/cluster/structs/OperationalStateClusterErrorStateStruct.kt b/src/controller/java/generated/java/matter/controller/cluster/structs/OperationalStateClusterErrorStateStruct.kt index 94eb1ac461..bea86d884f 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/structs/OperationalStateClusterErrorStateStruct.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/structs/OperationalStateClusterErrorStateStruct.kt @@ -39,7 +39,7 @@ class OperationalStateClusterErrorStateStruct( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_ERROR_STATE_I_D), errorStateID) + put(ContextSpecificTag(TAG_ERROR_STATE_ID), errorStateID) if (errorStateLabel.isPresent) { val opterrorStateLabel = errorStateLabel.get() put(ContextSpecificTag(TAG_ERROR_STATE_LABEL), opterrorStateLabel) @@ -53,13 +53,13 @@ class OperationalStateClusterErrorStateStruct( } companion object { - private const val TAG_ERROR_STATE_I_D = 0 + private const val TAG_ERROR_STATE_ID = 0 private const val TAG_ERROR_STATE_LABEL = 1 private const val TAG_ERROR_STATE_DETAILS = 2 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): OperationalStateClusterErrorStateStruct { tlvReader.enterStructure(tlvTag) - val errorStateID = tlvReader.getUByte(ContextSpecificTag(TAG_ERROR_STATE_I_D)) + val errorStateID = tlvReader.getUByte(ContextSpecificTag(TAG_ERROR_STATE_ID)) val errorStateLabel = if (tlvReader.isNextTag(ContextSpecificTag(TAG_ERROR_STATE_LABEL))) { Optional.of(tlvReader.getString(ContextSpecificTag(TAG_ERROR_STATE_LABEL))) diff --git a/src/controller/java/generated/java/matter/controller/cluster/structs/OperationalStateClusterOperationalStateStruct.kt b/src/controller/java/generated/java/matter/controller/cluster/structs/OperationalStateClusterOperationalStateStruct.kt index 22ba9ba6e8..7626d4a769 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/structs/OperationalStateClusterOperationalStateStruct.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/structs/OperationalStateClusterOperationalStateStruct.kt @@ -37,7 +37,7 @@ class OperationalStateClusterOperationalStateStruct( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_OPERATIONAL_STATE_I_D), operationalStateID) + put(ContextSpecificTag(TAG_OPERATIONAL_STATE_ID), operationalStateID) if (operationalStateLabel.isPresent) { val optoperationalStateLabel = operationalStateLabel.get() put(ContextSpecificTag(TAG_OPERATIONAL_STATE_LABEL), optoperationalStateLabel) @@ -47,12 +47,12 @@ class OperationalStateClusterOperationalStateStruct( } companion object { - private const val TAG_OPERATIONAL_STATE_I_D = 0 + private const val TAG_OPERATIONAL_STATE_ID = 0 private const val TAG_OPERATIONAL_STATE_LABEL = 1 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): OperationalStateClusterOperationalStateStruct { tlvReader.enterStructure(tlvTag) - val operationalStateID = tlvReader.getUByte(ContextSpecificTag(TAG_OPERATIONAL_STATE_I_D)) + val operationalStateID = tlvReader.getUByte(ContextSpecificTag(TAG_OPERATIONAL_STATE_ID)) val operationalStateLabel = if (tlvReader.isNextTag(ContextSpecificTag(TAG_OPERATIONAL_STATE_LABEL))) { Optional.of(tlvReader.getString(ContextSpecificTag(TAG_OPERATIONAL_STATE_LABEL))) diff --git a/src/controller/java/generated/java/matter/controller/cluster/structs/OtaSoftwareUpdateRequestorClusterProviderLocation.kt b/src/controller/java/generated/java/matter/controller/cluster/structs/OtaSoftwareUpdateRequestorClusterProviderLocation.kt index 5708a4006e..209c1580f3 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/structs/OtaSoftwareUpdateRequestorClusterProviderLocation.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/structs/OtaSoftwareUpdateRequestorClusterProviderLocation.kt @@ -38,7 +38,7 @@ class OtaSoftwareUpdateRequestorClusterProviderLocation( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_PROVIDER_NODE_I_D), providerNodeID) + put(ContextSpecificTag(TAG_PROVIDER_NODE_ID), providerNodeID) put(ContextSpecificTag(TAG_ENDPOINT), endpoint) put(ContextSpecificTag(TAG_FABRIC_INDEX), fabricIndex) endStructure() @@ -46,7 +46,7 @@ class OtaSoftwareUpdateRequestorClusterProviderLocation( } companion object { - private const val TAG_PROVIDER_NODE_I_D = 1 + private const val TAG_PROVIDER_NODE_ID = 1 private const val TAG_ENDPOINT = 2 private const val TAG_FABRIC_INDEX = 254 @@ -55,7 +55,7 @@ class OtaSoftwareUpdateRequestorClusterProviderLocation( tlvReader: TlvReader, ): OtaSoftwareUpdateRequestorClusterProviderLocation { tlvReader.enterStructure(tlvTag) - val providerNodeID = tlvReader.getULong(ContextSpecificTag(TAG_PROVIDER_NODE_I_D)) + val providerNodeID = tlvReader.getULong(ContextSpecificTag(TAG_PROVIDER_NODE_ID)) val endpoint = tlvReader.getUShort(ContextSpecificTag(TAG_ENDPOINT)) val fabricIndex = tlvReader.getUByte(ContextSpecificTag(TAG_FABRIC_INDEX)) diff --git a/src/controller/java/generated/java/matter/controller/cluster/structs/OvenCavityOperationalStateClusterErrorStateStruct.kt b/src/controller/java/generated/java/matter/controller/cluster/structs/OvenCavityOperationalStateClusterErrorStateStruct.kt index cbb84396c2..442c55ea08 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/structs/OvenCavityOperationalStateClusterErrorStateStruct.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/structs/OvenCavityOperationalStateClusterErrorStateStruct.kt @@ -39,7 +39,7 @@ class OvenCavityOperationalStateClusterErrorStateStruct( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_ERROR_STATE_I_D), errorStateID) + put(ContextSpecificTag(TAG_ERROR_STATE_ID), errorStateID) if (errorStateLabel.isPresent) { val opterrorStateLabel = errorStateLabel.get() put(ContextSpecificTag(TAG_ERROR_STATE_LABEL), opterrorStateLabel) @@ -53,7 +53,7 @@ class OvenCavityOperationalStateClusterErrorStateStruct( } companion object { - private const val TAG_ERROR_STATE_I_D = 0 + private const val TAG_ERROR_STATE_ID = 0 private const val TAG_ERROR_STATE_LABEL = 1 private const val TAG_ERROR_STATE_DETAILS = 2 @@ -62,7 +62,7 @@ class OvenCavityOperationalStateClusterErrorStateStruct( tlvReader: TlvReader, ): OvenCavityOperationalStateClusterErrorStateStruct { tlvReader.enterStructure(tlvTag) - val errorStateID = tlvReader.getUByte(ContextSpecificTag(TAG_ERROR_STATE_I_D)) + val errorStateID = tlvReader.getUByte(ContextSpecificTag(TAG_ERROR_STATE_ID)) val errorStateLabel = if (tlvReader.isNextTag(ContextSpecificTag(TAG_ERROR_STATE_LABEL))) { Optional.of(tlvReader.getString(ContextSpecificTag(TAG_ERROR_STATE_LABEL))) diff --git a/src/controller/java/generated/java/matter/controller/cluster/structs/OvenCavityOperationalStateClusterOperationalStateStruct.kt b/src/controller/java/generated/java/matter/controller/cluster/structs/OvenCavityOperationalStateClusterOperationalStateStruct.kt index b7d604467b..ef6a876dce 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/structs/OvenCavityOperationalStateClusterOperationalStateStruct.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/structs/OvenCavityOperationalStateClusterOperationalStateStruct.kt @@ -37,7 +37,7 @@ class OvenCavityOperationalStateClusterOperationalStateStruct( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_OPERATIONAL_STATE_I_D), operationalStateID) + put(ContextSpecificTag(TAG_OPERATIONAL_STATE_ID), operationalStateID) if (operationalStateLabel.isPresent) { val optoperationalStateLabel = operationalStateLabel.get() put(ContextSpecificTag(TAG_OPERATIONAL_STATE_LABEL), optoperationalStateLabel) @@ -47,7 +47,7 @@ class OvenCavityOperationalStateClusterOperationalStateStruct( } companion object { - private const val TAG_OPERATIONAL_STATE_I_D = 0 + private const val TAG_OPERATIONAL_STATE_ID = 0 private const val TAG_OPERATIONAL_STATE_LABEL = 1 fun fromTlv( @@ -55,7 +55,7 @@ class OvenCavityOperationalStateClusterOperationalStateStruct( tlvReader: TlvReader, ): OvenCavityOperationalStateClusterOperationalStateStruct { tlvReader.enterStructure(tlvTag) - val operationalStateID = tlvReader.getUByte(ContextSpecificTag(TAG_OPERATIONAL_STATE_I_D)) + val operationalStateID = tlvReader.getUByte(ContextSpecificTag(TAG_OPERATIONAL_STATE_ID)) val operationalStateLabel = if (tlvReader.isNextTag(ContextSpecificTag(TAG_OPERATIONAL_STATE_LABEL))) { Optional.of(tlvReader.getString(ContextSpecificTag(TAG_OPERATIONAL_STATE_LABEL))) diff --git a/src/controller/java/generated/java/matter/controller/cluster/structs/RvcOperationalStateClusterErrorStateStruct.kt b/src/controller/java/generated/java/matter/controller/cluster/structs/RvcOperationalStateClusterErrorStateStruct.kt index 1ccfa0c395..e60738d973 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/structs/RvcOperationalStateClusterErrorStateStruct.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/structs/RvcOperationalStateClusterErrorStateStruct.kt @@ -39,7 +39,7 @@ class RvcOperationalStateClusterErrorStateStruct( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_ERROR_STATE_I_D), errorStateID) + put(ContextSpecificTag(TAG_ERROR_STATE_ID), errorStateID) if (errorStateLabel.isPresent) { val opterrorStateLabel = errorStateLabel.get() put(ContextSpecificTag(TAG_ERROR_STATE_LABEL), opterrorStateLabel) @@ -53,13 +53,13 @@ class RvcOperationalStateClusterErrorStateStruct( } companion object { - private const val TAG_ERROR_STATE_I_D = 0 + private const val TAG_ERROR_STATE_ID = 0 private const val TAG_ERROR_STATE_LABEL = 1 private const val TAG_ERROR_STATE_DETAILS = 2 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): RvcOperationalStateClusterErrorStateStruct { tlvReader.enterStructure(tlvTag) - val errorStateID = tlvReader.getUByte(ContextSpecificTag(TAG_ERROR_STATE_I_D)) + val errorStateID = tlvReader.getUByte(ContextSpecificTag(TAG_ERROR_STATE_ID)) val errorStateLabel = if (tlvReader.isNextTag(ContextSpecificTag(TAG_ERROR_STATE_LABEL))) { Optional.of(tlvReader.getString(ContextSpecificTag(TAG_ERROR_STATE_LABEL))) diff --git a/src/controller/java/generated/java/matter/controller/cluster/structs/RvcOperationalStateClusterOperationalStateStruct.kt b/src/controller/java/generated/java/matter/controller/cluster/structs/RvcOperationalStateClusterOperationalStateStruct.kt index 3ab7c3ab3b..00680b85bb 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/structs/RvcOperationalStateClusterOperationalStateStruct.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/structs/RvcOperationalStateClusterOperationalStateStruct.kt @@ -37,7 +37,7 @@ class RvcOperationalStateClusterOperationalStateStruct( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_OPERATIONAL_STATE_I_D), operationalStateID) + put(ContextSpecificTag(TAG_OPERATIONAL_STATE_ID), operationalStateID) if (operationalStateLabel.isPresent) { val optoperationalStateLabel = operationalStateLabel.get() put(ContextSpecificTag(TAG_OPERATIONAL_STATE_LABEL), optoperationalStateLabel) @@ -47,7 +47,7 @@ class RvcOperationalStateClusterOperationalStateStruct( } companion object { - private const val TAG_OPERATIONAL_STATE_I_D = 0 + private const val TAG_OPERATIONAL_STATE_ID = 0 private const val TAG_OPERATIONAL_STATE_LABEL = 1 fun fromTlv( @@ -55,7 +55,7 @@ class RvcOperationalStateClusterOperationalStateStruct( tlvReader: TlvReader, ): RvcOperationalStateClusterOperationalStateStruct { tlvReader.enterStructure(tlvTag) - val operationalStateID = tlvReader.getUByte(ContextSpecificTag(TAG_OPERATIONAL_STATE_I_D)) + val operationalStateID = tlvReader.getUByte(ContextSpecificTag(TAG_OPERATIONAL_STATE_ID)) val operationalStateLabel = if (tlvReader.isNextTag(ContextSpecificTag(TAG_OPERATIONAL_STATE_LABEL))) { Optional.of(tlvReader.getString(ContextSpecificTag(TAG_OPERATIONAL_STATE_LABEL))) diff --git a/src/controller/java/generated/java/matter/controller/cluster/structs/ScenesManagementClusterAttributeValuePairStruct.kt b/src/controller/java/generated/java/matter/controller/cluster/structs/ScenesManagementClusterAttributeValuePairStruct.kt index 9f142d41b3..232bfea8c1 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/structs/ScenesManagementClusterAttributeValuePairStruct.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/structs/ScenesManagementClusterAttributeValuePairStruct.kt @@ -51,7 +51,7 @@ class ScenesManagementClusterAttributeValuePairStruct( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_ATTRIBUTE_I_D), attributeID) + put(ContextSpecificTag(TAG_ATTRIBUTE_ID), attributeID) if (valueUnsigned8.isPresent) { val optvalueUnsigned8 = valueUnsigned8.get() put(ContextSpecificTag(TAG_VALUE_UNSIGNED8), optvalueUnsigned8) @@ -89,7 +89,7 @@ class ScenesManagementClusterAttributeValuePairStruct( } companion object { - private const val TAG_ATTRIBUTE_I_D = 0 + private const val TAG_ATTRIBUTE_ID = 0 private const val TAG_VALUE_UNSIGNED8 = 1 private const val TAG_VALUE_SIGNED8 = 2 private const val TAG_VALUE_UNSIGNED16 = 3 @@ -104,7 +104,7 @@ class ScenesManagementClusterAttributeValuePairStruct( tlvReader: TlvReader, ): ScenesManagementClusterAttributeValuePairStruct { tlvReader.enterStructure(tlvTag) - val attributeID = tlvReader.getUInt(ContextSpecificTag(TAG_ATTRIBUTE_I_D)) + val attributeID = tlvReader.getUInt(ContextSpecificTag(TAG_ATTRIBUTE_ID)) val valueUnsigned8 = if (tlvReader.isNextTag(ContextSpecificTag(TAG_VALUE_UNSIGNED8))) { Optional.of(tlvReader.getUByte(ContextSpecificTag(TAG_VALUE_UNSIGNED8))) diff --git a/src/controller/java/generated/java/matter/controller/cluster/structs/ScenesManagementClusterExtensionFieldSet.kt b/src/controller/java/generated/java/matter/controller/cluster/structs/ScenesManagementClusterExtensionFieldSet.kt index bd219e98d1..4fcc98ecaf 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/structs/ScenesManagementClusterExtensionFieldSet.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/structs/ScenesManagementClusterExtensionFieldSet.kt @@ -37,7 +37,7 @@ class ScenesManagementClusterExtensionFieldSet( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_CLUSTER_I_D), clusterID) + put(ContextSpecificTag(TAG_CLUSTER_ID), clusterID) startArray(ContextSpecificTag(TAG_ATTRIBUTE_VALUE_LIST)) for (item in attributeValueList.iterator()) { item.toTlv(AnonymousTag, this) @@ -48,12 +48,12 @@ class ScenesManagementClusterExtensionFieldSet( } companion object { - private const val TAG_CLUSTER_I_D = 0 + private const val TAG_CLUSTER_ID = 0 private const val TAG_ATTRIBUTE_VALUE_LIST = 1 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): ScenesManagementClusterExtensionFieldSet { tlvReader.enterStructure(tlvTag) - val clusterID = tlvReader.getUInt(ContextSpecificTag(TAG_CLUSTER_I_D)) + val clusterID = tlvReader.getUInt(ContextSpecificTag(TAG_CLUSTER_ID)) val attributeValueList = buildList { tlvReader.enterArray(ContextSpecificTag(TAG_ATTRIBUTE_VALUE_LIST)) diff --git a/src/controller/java/generated/java/matter/controller/cluster/structs/ServiceAreaClusterAreaStruct.kt b/src/controller/java/generated/java/matter/controller/cluster/structs/ServiceAreaClusterAreaStruct.kt index adfe228d33..d310fe5c31 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/structs/ServiceAreaClusterAreaStruct.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/structs/ServiceAreaClusterAreaStruct.kt @@ -38,11 +38,11 @@ class ServiceAreaClusterAreaStruct( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_AREA_I_D), areaID) + put(ContextSpecificTag(TAG_AREA_ID), areaID) if (mapID != null) { - put(ContextSpecificTag(TAG_MAP_I_D), mapID) + put(ContextSpecificTag(TAG_MAP_ID), mapID) } else { - putNull(ContextSpecificTag(TAG_MAP_I_D)) + putNull(ContextSpecificTag(TAG_MAP_ID)) } areaDesc.toTlv(ContextSpecificTag(TAG_AREA_DESC), this) endStructure() @@ -50,18 +50,18 @@ class ServiceAreaClusterAreaStruct( } companion object { - private const val TAG_AREA_I_D = 0 - private const val TAG_MAP_I_D = 1 + private const val TAG_AREA_ID = 0 + private const val TAG_MAP_ID = 1 private const val TAG_AREA_DESC = 2 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): ServiceAreaClusterAreaStruct { tlvReader.enterStructure(tlvTag) - val areaID = tlvReader.getUInt(ContextSpecificTag(TAG_AREA_I_D)) + val areaID = tlvReader.getUInt(ContextSpecificTag(TAG_AREA_ID)) val mapID = if (!tlvReader.isNull()) { - tlvReader.getUInt(ContextSpecificTag(TAG_MAP_I_D)) + tlvReader.getUInt(ContextSpecificTag(TAG_MAP_ID)) } else { - tlvReader.getNull(ContextSpecificTag(TAG_MAP_I_D)) + tlvReader.getNull(ContextSpecificTag(TAG_MAP_ID)) null } val areaDesc = diff --git a/src/controller/java/generated/java/matter/controller/cluster/structs/ServiceAreaClusterMapStruct.kt b/src/controller/java/generated/java/matter/controller/cluster/structs/ServiceAreaClusterMapStruct.kt index 528888247d..19df0938c5 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/structs/ServiceAreaClusterMapStruct.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/structs/ServiceAreaClusterMapStruct.kt @@ -33,19 +33,19 @@ class ServiceAreaClusterMapStruct(val mapID: UInt, val name: String) { fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_MAP_I_D), mapID) + put(ContextSpecificTag(TAG_MAP_ID), mapID) put(ContextSpecificTag(TAG_NAME), name) endStructure() } } companion object { - private const val TAG_MAP_I_D = 0 + private const val TAG_MAP_ID = 0 private const val TAG_NAME = 1 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): ServiceAreaClusterMapStruct { tlvReader.enterStructure(tlvTag) - val mapID = tlvReader.getUInt(ContextSpecificTag(TAG_MAP_I_D)) + val mapID = tlvReader.getUInt(ContextSpecificTag(TAG_MAP_ID)) val name = tlvReader.getString(ContextSpecificTag(TAG_NAME)) tlvReader.exitContainer() diff --git a/src/controller/java/generated/java/matter/controller/cluster/structs/ServiceAreaClusterProgressStruct.kt b/src/controller/java/generated/java/matter/controller/cluster/structs/ServiceAreaClusterProgressStruct.kt index 4421bb606a..02b16f17cd 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/structs/ServiceAreaClusterProgressStruct.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/structs/ServiceAreaClusterProgressStruct.kt @@ -41,7 +41,7 @@ class ServiceAreaClusterProgressStruct( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_AREA_I_D), areaID) + put(ContextSpecificTag(TAG_AREA_ID), areaID) put(ContextSpecificTag(TAG_STATUS), status) if (totalOperationalTime != null) { if (totalOperationalTime.isPresent) { @@ -64,14 +64,14 @@ class ServiceAreaClusterProgressStruct( } companion object { - private const val TAG_AREA_I_D = 0 + private const val TAG_AREA_ID = 0 private const val TAG_STATUS = 1 private const val TAG_TOTAL_OPERATIONAL_TIME = 2 private const val TAG_ESTIMATED_TIME = 3 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): ServiceAreaClusterProgressStruct { tlvReader.enterStructure(tlvTag) - val areaID = tlvReader.getUInt(ContextSpecificTag(TAG_AREA_I_D)) + val areaID = tlvReader.getUInt(ContextSpecificTag(TAG_AREA_ID)) val status = tlvReader.getUByte(ContextSpecificTag(TAG_STATUS)) val totalOperationalTime = if (!tlvReader.isNull()) { diff --git a/src/controller/java/generated/java/matter/controller/cluster/structs/ThermostatClusterAtomicAttributeStatusStruct.kt b/src/controller/java/generated/java/matter/controller/cluster/structs/ThermostatClusterAtomicAttributeStatusStruct.kt index 2a67c0cccb..42fc80b898 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/structs/ThermostatClusterAtomicAttributeStatusStruct.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/structs/ThermostatClusterAtomicAttributeStatusStruct.kt @@ -33,19 +33,19 @@ class ThermostatClusterAtomicAttributeStatusStruct(val attributeID: UInt, val st fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_ATTRIBUTE_I_D), attributeID) + put(ContextSpecificTag(TAG_ATTRIBUTE_ID), attributeID) put(ContextSpecificTag(TAG_STATUS_CODE), statusCode) endStructure() } } companion object { - private const val TAG_ATTRIBUTE_I_D = 0 + private const val TAG_ATTRIBUTE_ID = 0 private const val TAG_STATUS_CODE = 1 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): ThermostatClusterAtomicAttributeStatusStruct { tlvReader.enterStructure(tlvTag) - val attributeID = tlvReader.getUInt(ContextSpecificTag(TAG_ATTRIBUTE_I_D)) + val attributeID = tlvReader.getUInt(ContextSpecificTag(TAG_ATTRIBUTE_ID)) val statusCode = tlvReader.getUByte(ContextSpecificTag(TAG_STATUS_CODE)) tlvReader.exitContainer() diff --git a/src/controller/java/generated/java/matter/controller/cluster/structs/ThreadNetworkDiagnosticsClusterRouteTableStruct.kt b/src/controller/java/generated/java/matter/controller/cluster/structs/ThreadNetworkDiagnosticsClusterRouteTableStruct.kt index 797bd6aa66..86860ea680 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/structs/ThreadNetworkDiagnosticsClusterRouteTableStruct.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/structs/ThreadNetworkDiagnosticsClusterRouteTableStruct.kt @@ -57,8 +57,8 @@ class ThreadNetworkDiagnosticsClusterRouteTableStruct( put(ContextSpecificTag(TAG_ROUTER_ID), routerId) put(ContextSpecificTag(TAG_NEXT_HOP), nextHop) put(ContextSpecificTag(TAG_PATH_COST), pathCost) - put(ContextSpecificTag(TAG_L_Q_I_IN), LQIIn) - put(ContextSpecificTag(TAG_L_Q_I_OUT), LQIOut) + put(ContextSpecificTag(TAG_LQI_IN), LQIIn) + put(ContextSpecificTag(TAG_LQI_OUT), LQIOut) put(ContextSpecificTag(TAG_AGE), age) put(ContextSpecificTag(TAG_ALLOCATED), allocated) put(ContextSpecificTag(TAG_LINK_ESTABLISHED), linkEstablished) @@ -72,8 +72,8 @@ class ThreadNetworkDiagnosticsClusterRouteTableStruct( private const val TAG_ROUTER_ID = 2 private const val TAG_NEXT_HOP = 3 private const val TAG_PATH_COST = 4 - private const val TAG_L_Q_I_IN = 5 - private const val TAG_L_Q_I_OUT = 6 + private const val TAG_LQI_IN = 5 + private const val TAG_LQI_OUT = 6 private const val TAG_AGE = 7 private const val TAG_ALLOCATED = 8 private const val TAG_LINK_ESTABLISHED = 9 @@ -88,8 +88,8 @@ class ThreadNetworkDiagnosticsClusterRouteTableStruct( val routerId = tlvReader.getUByte(ContextSpecificTag(TAG_ROUTER_ID)) val nextHop = tlvReader.getUByte(ContextSpecificTag(TAG_NEXT_HOP)) val pathCost = tlvReader.getUByte(ContextSpecificTag(TAG_PATH_COST)) - val LQIIn = tlvReader.getUByte(ContextSpecificTag(TAG_L_Q_I_IN)) - val LQIOut = tlvReader.getUByte(ContextSpecificTag(TAG_L_Q_I_OUT)) + val LQIIn = tlvReader.getUByte(ContextSpecificTag(TAG_LQI_IN)) + val LQIOut = tlvReader.getUByte(ContextSpecificTag(TAG_LQI_OUT)) val age = tlvReader.getUByte(ContextSpecificTag(TAG_AGE)) val allocated = tlvReader.getBoolean(ContextSpecificTag(TAG_ALLOCATED)) val linkEstablished = tlvReader.getBoolean(ContextSpecificTag(TAG_LINK_ESTABLISHED)) diff --git a/src/controller/java/generated/java/matter/controller/cluster/structs/ThreadNetworkDirectoryClusterThreadNetworkStruct.kt b/src/controller/java/generated/java/matter/controller/cluster/structs/ThreadNetworkDirectoryClusterThreadNetworkStruct.kt index bacfb45753..04f8c6abcd 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/structs/ThreadNetworkDirectoryClusterThreadNetworkStruct.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/structs/ThreadNetworkDirectoryClusterThreadNetworkStruct.kt @@ -40,7 +40,7 @@ class ThreadNetworkDirectoryClusterThreadNetworkStruct( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_EXTENDED_PAN_I_D), extendedPanID) + put(ContextSpecificTag(TAG_EXTENDED_PAN_ID), extendedPanID) put(ContextSpecificTag(TAG_NETWORK_NAME), networkName) put(ContextSpecificTag(TAG_CHANNEL), channel) put(ContextSpecificTag(TAG_ACTIVE_TIMESTAMP), activeTimestamp) @@ -49,7 +49,7 @@ class ThreadNetworkDirectoryClusterThreadNetworkStruct( } companion object { - private const val TAG_EXTENDED_PAN_I_D = 0 + private const val TAG_EXTENDED_PAN_ID = 0 private const val TAG_NETWORK_NAME = 1 private const val TAG_CHANNEL = 2 private const val TAG_ACTIVE_TIMESTAMP = 3 @@ -59,7 +59,7 @@ class ThreadNetworkDirectoryClusterThreadNetworkStruct( tlvReader: TlvReader, ): ThreadNetworkDirectoryClusterThreadNetworkStruct { tlvReader.enterStructure(tlvTag) - val extendedPanID = tlvReader.getByteArray(ContextSpecificTag(TAG_EXTENDED_PAN_I_D)) + val extendedPanID = tlvReader.getByteArray(ContextSpecificTag(TAG_EXTENDED_PAN_ID)) val networkName = tlvReader.getString(ContextSpecificTag(TAG_NETWORK_NAME)) val channel = tlvReader.getUShort(ContextSpecificTag(TAG_CHANNEL)) val activeTimestamp = tlvReader.getULong(ContextSpecificTag(TAG_ACTIVE_TIMESTAMP)) diff --git a/src/controller/java/generated/java/matter/controller/cluster/structs/TimeSynchronizationClusterFabricScopedTrustedTimeSourceStruct.kt b/src/controller/java/generated/java/matter/controller/cluster/structs/TimeSynchronizationClusterFabricScopedTrustedTimeSourceStruct.kt index b90c3a6520..f294cfbe42 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/structs/TimeSynchronizationClusterFabricScopedTrustedTimeSourceStruct.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/structs/TimeSynchronizationClusterFabricScopedTrustedTimeSourceStruct.kt @@ -36,14 +36,14 @@ class TimeSynchronizationClusterFabricScopedTrustedTimeSourceStruct( fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) - put(ContextSpecificTag(TAG_NODE_I_D), nodeID) + put(ContextSpecificTag(TAG_NODE_ID), nodeID) put(ContextSpecificTag(TAG_ENDPOINT), endpoint) endStructure() } } companion object { - private const val TAG_NODE_I_D = 0 + private const val TAG_NODE_ID = 0 private const val TAG_ENDPOINT = 1 fun fromTlv( @@ -51,7 +51,7 @@ class TimeSynchronizationClusterFabricScopedTrustedTimeSourceStruct( tlvReader: TlvReader, ): TimeSynchronizationClusterFabricScopedTrustedTimeSourceStruct { tlvReader.enterStructure(tlvTag) - val nodeID = tlvReader.getULong(ContextSpecificTag(TAG_NODE_I_D)) + val nodeID = tlvReader.getULong(ContextSpecificTag(TAG_NODE_ID)) val endpoint = tlvReader.getUShort(ContextSpecificTag(TAG_ENDPOINT)) tlvReader.exitContainer() diff --git a/src/controller/java/generated/java/matter/controller/cluster/structs/TimeSynchronizationClusterTrustedTimeSourceStruct.kt b/src/controller/java/generated/java/matter/controller/cluster/structs/TimeSynchronizationClusterTrustedTimeSourceStruct.kt index 4e1df456a9..215bb8c35d 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/structs/TimeSynchronizationClusterTrustedTimeSourceStruct.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/structs/TimeSynchronizationClusterTrustedTimeSourceStruct.kt @@ -39,7 +39,7 @@ class TimeSynchronizationClusterTrustedTimeSourceStruct( tlvWriter.apply { startStructure(tlvTag) put(ContextSpecificTag(TAG_FABRIC_INDEX), fabricIndex) - put(ContextSpecificTag(TAG_NODE_I_D), nodeID) + put(ContextSpecificTag(TAG_NODE_ID), nodeID) put(ContextSpecificTag(TAG_ENDPOINT), endpoint) endStructure() } @@ -47,7 +47,7 @@ class TimeSynchronizationClusterTrustedTimeSourceStruct( companion object { private const val TAG_FABRIC_INDEX = 0 - private const val TAG_NODE_I_D = 1 + private const val TAG_NODE_ID = 1 private const val TAG_ENDPOINT = 2 fun fromTlv( @@ -56,7 +56,7 @@ class TimeSynchronizationClusterTrustedTimeSourceStruct( ): TimeSynchronizationClusterTrustedTimeSourceStruct { tlvReader.enterStructure(tlvTag) val fabricIndex = tlvReader.getUByte(ContextSpecificTag(TAG_FABRIC_INDEX)) - val nodeID = tlvReader.getULong(ContextSpecificTag(TAG_NODE_I_D)) + val nodeID = tlvReader.getULong(ContextSpecificTag(TAG_NODE_ID)) val endpoint = tlvReader.getUShort(ContextSpecificTag(TAG_ENDPOINT)) tlvReader.exitContainer() diff --git a/src/controller/python/chip/yaml/runner.py b/src/controller/python/chip/yaml/runner.py index 84f0e06ff7..00e0de2154 100644 --- a/src/controller/python/chip/yaml/runner.py +++ b/src/controller/python/chip/yaml/runner.py @@ -24,7 +24,6 @@ import chip.interaction_model import chip.yaml.format_converter as Converter -import stringcase # type: ignore from chip.ChipDeviceCtrl import ChipDeviceController, discovery from chip.clusters import ClusterObjects from chip.clusters.Attribute import (AttributeStatus, EventReadResult, SubscriptionTransaction, TypedAttributePath, @@ -32,6 +31,7 @@ from chip.exceptions import ChipStackError from chip.yaml.data_model_lookup import DataModelLookup from chip.yaml.errors import ActionCreationError, UnexpectedActionCreationError +from matter_idl.generators.filters import to_pascal_case, to_snake_case from matter_yamltests.pseudo_clusters.pseudo_clusters import get_default_pseudo_clusters from .data_model_lookup import PreDefinedDataModelLookup @@ -150,7 +150,7 @@ def __init__(self, test_step, cluster: str, context: _ExecutionContext): ''' super().__init__(test_step) self._busy_wait_ms = test_step.busy_wait_ms - self._command_name = stringcase.pascalcase(test_step.command) + self._command_name = to_pascal_case(test_step.command) self._cluster = cluster self._interation_timeout_ms = test_step.timed_interaction_timeout_ms self._request_object = None @@ -217,7 +217,7 @@ def __init__(self, test_step, cluster: str, context: _ExecutionContext): UnexpectedActionCreationError: Raised if there is an unexpected parsing error. ''' super().__init__(test_step) - self._attribute_name = stringcase.pascalcase(test_step.attribute) + self._attribute_name = to_pascal_case(test_step.attribute) self._cluster = cluster self._endpoint = test_step.endpoint self._node_id = test_step.node_id @@ -294,7 +294,7 @@ def __init__(self, test_step, cluster: str, context: _ExecutionContext): UnexpectedActionCreationError: Raised if there is an unexpected parsing error. ''' super().__init__(test_step) - self._event_name = stringcase.pascalcase(test_step.event) + self._event_name = to_pascal_case(test_step.event) self._cluster = cluster self._endpoint = test_step.endpoint self._node_id = test_step.node_id @@ -531,7 +531,7 @@ def __init__(self, test_step, cluster: str, context: _ExecutionContext): UnexpectedActionCreationError: Raised if there is an unexpected parsing error. ''' super().__init__(test_step) - self._attribute_name = stringcase.pascalcase(test_step.attribute) + self._attribute_name = to_pascal_case(test_step.attribute) self._busy_wait_ms = test_step.busy_wait_ms self._cluster = cluster self._endpoint = test_step.endpoint @@ -609,9 +609,9 @@ def __init__(self, test_step, context: _ExecutionContext): ''' super().__init__(test_step) if test_step.attribute is not None: - queue_name = stringcase.pascalcase(test_step.attribute) + queue_name = to_pascal_case(test_step.attribute) elif test_step.event is not None: - queue_name = stringcase.pascalcase(test_step.event) + queue_name = to_pascal_case(test_step.event) else: raise UnexpectedActionCreationError( 'WaitForReport needs to wait on either attribute or event, neither were provided') @@ -886,12 +886,12 @@ def decode(self, result: _ActionResult): return response if isinstance(response, chip.interaction_model.InteractionModelError): - decoded_response['error'] = stringcase.snakecase(response.status.name).upper() + decoded_response['error'] = to_snake_case(response.status.name).upper() decoded_response['clusterError'] = response.clusterStatus return decoded_response if isinstance(response, chip.interaction_model.Status): - decoded_response['error'] = stringcase.snakecase(response.name).upper() + decoded_response['error'] = to_snake_case(response.name).upper() return decoded_response if isinstance(response, _GetCommissionerNodeIdResult): @@ -936,7 +936,7 @@ def decode(self, result: _ActionResult): decoded_response = [] for event in response.event_result_list: if event.Status != chip.interaction_model.Status.Success: - error_message = stringcase.snakecase(event.Status.name).upper() + error_message = to_snake_case(event.Status.name).upper() decoded_response.append({'error': error_message}) continue cluster_id = event.Header.ClusterId From 859ee35fc6a8a3efa5cdf940578f799065414e77 Mon Sep 17 00:00:00 2001 From: Jakub Latusek Date: Wed, 14 Aug 2024 16:12:13 +0200 Subject: [PATCH 040/165] [Tizen] Update Tizen SDK to 8.0 (#34171) * Update tizen to 8.0 * Install platform certificate * Reverse restyle diff * Review fix - version update * Add information about used 7.0 tizen package --------- Co-authored-by: Arkadiusz Bokowy --- .../docker/images/base/chip-build/version | 2 +- .../stage-2/chip-build-tizen/Dockerfile | 4 ++-- .../tizen-sdk-installer/install.sh | 20 ++++++++++--------- 3 files changed, 14 insertions(+), 12 deletions(-) diff --git a/integrations/docker/images/base/chip-build/version b/integrations/docker/images/base/chip-build/version index 5b9870bc97..18dcb8d04c 100644 --- a/integrations/docker/images/base/chip-build/version +++ b/integrations/docker/images/base/chip-build/version @@ -1 +1 @@ -71 : [NXP] Update k32w1 SDK as it will use common NXP SDK +72 : Update Tizen version to 8.0 diff --git a/integrations/docker/images/stage-2/chip-build-tizen/Dockerfile b/integrations/docker/images/stage-2/chip-build-tizen/Dockerfile index 4d907b1d6e..c127296bac 100644 --- a/integrations/docker/images/stage-2/chip-build-tizen/Dockerfile +++ b/integrations/docker/images/stage-2/chip-build-tizen/Dockerfile @@ -20,7 +20,7 @@ RUN set -x \ # ------------------------------------------------------------------------------ # Install tizen -ENV TIZEN_VERSION 7.0 +ENV TIZEN_VERSION 8.0 ENV TIZEN_SDK_ROOT /opt/tizen-sdk COPY tizen-sdk-installer $TIZEN_SDK_ROOT/files/installer @@ -35,7 +35,7 @@ RUN set -x \ # ------------------------------------------------------------------------------ # Set environment ENV TIZEN_SDK_TOOLCHAIN $TIZEN_SDK_ROOT/tools/arm-linux-gnueabi-gcc-9.2 -ENV TIZEN_SDK_SYSROOT $TIZEN_SDK_ROOT/platforms/tizen-$TIZEN_VERSION/mobile/rootstraps/mobile-$TIZEN_VERSION-device.core +ENV TIZEN_SDK_SYSROOT $TIZEN_SDK_ROOT/platforms/tizen-$TIZEN_VERSION/tizen/rootstraps/tizen-$TIZEN_VERSION-device.core ENV PATH="$TIZEN_SDK_TOOLCHAIN/bin:$TIZEN_SDK_ROOT/tools/ide/bin:$TIZEN_SDK_ROOT/tools:$PATH" # ------------------------------------------------------------------------------ diff --git a/integrations/docker/images/stage-2/chip-build-tizen/tizen-sdk-installer/install.sh b/integrations/docker/images/stage-2/chip-build-tizen/tizen-sdk-installer/install.sh index e206e71c19..59843f99ba 100755 --- a/integrations/docker/images/stage-2/chip-build-tizen/tizen-sdk-installer/install.sh +++ b/integrations/docker/images/stage-2/chip-build-tizen/tizen-sdk-installer/install.sh @@ -21,7 +21,7 @@ set -e # Default settings options TIZEN_SDK_ROOT=/opt/tizen-sdk TIZEN_SDK_DATA_PATH=$HOME/tizen-sdk-data -TIZEN_VERSION=7.0 +TIZEN_VERSION=8.0 SECRET_TOOL=false SCRIPT_NAME=$(basename -- "$(readlink -f "${BASH_SOURCE:?}")") @@ -133,7 +133,7 @@ function install_tizen_sdk() { info "Tizen SDK installation directory: $TIZEN_SDK_ROOT" - TIZEN_SDK_SYSROOT="$TIZEN_SDK_ROOT/platforms/tizen-$TIZEN_VERSION/mobile/rootstraps/mobile-$TIZEN_VERSION-device.core" + TIZEN_SDK_SYSROOT="$TIZEN_SDK_ROOT/platforms/tizen-$TIZEN_VERSION/tizen/rootstraps/tizen-$TIZEN_VERSION-device.core" cd "$TMP_DIR" || return @@ -144,7 +144,7 @@ function install_tizen_sdk() { URL="http://download.tizen.org/sdk/tizenstudio/official/binary/" PKG_ARR=( 'certificate-encryptor_1.0.10_ubuntu-64.zip' - 'certificate-generator_0.1.3_ubuntu-64.zip' + 'certificate-generator_0.1.4_ubuntu-64.zip' 'new-common-cli_2.5.64_ubuntu-64.zip' 'new-native-cli_2.5.64_ubuntu-64.zip' 'sdb_4.2.23_ubuntu-64.zip') @@ -167,8 +167,8 @@ function install_tizen_sdk() { # Different versions of Tizen have different rootstrap versions URL="http://download.tizen.org/sdk/tizenstudio/official/binary/" PKG_ARR=( - "mobile-$TIZEN_VERSION-core-add-ons_*_ubuntu-64.zip" - "mobile-$TIZEN_VERSION-rs-device.core_*_ubuntu-64.zip") + "tizen-$TIZEN_VERSION-core-add-ons_*_ubuntu-64.zip" + "tizen-$TIZEN_VERSION-rs-device.core_*_ubuntu-64.zip") download "$URL" "${PKG_ARR[@]}" # Base packages @@ -232,13 +232,15 @@ function install_tizen_sdk() { 'capi-system-peripheral-io-*.armv7l.rpm' 'capi-system-peripheral-io-devel-*.armv7l.rpm' 'capi-system-resource-1*.armv7l.rpm' - 'libnsd-dns-sd-*.armv7l.rpm') + 'libnsd-dns-sd-*.armv7l.rpm' + 'sensord-*.armv7l.rpm') download "$URL" "${PKG_ARR[@]}" # Tizen Developer Platform Certificate URL="http://download.tizen.org/sdk/extensions/Tizen_IoT_Headless/binary/" + # Tizen site do not has this package available in version 8.0. Certificates are the same for 7.0 and 8.0. PKG_ARR=( - "$TIZEN_VERSION-iot-things-add-ons_*_ubuntu-64.zip") + "7.0-iot-things-add-ons_*_ubuntu-64.zip") download "$URL" "${PKG_ARR[@]}" # Install all @@ -271,7 +273,7 @@ function install_tizen_sdk() { ln -sf "$(basename "$(readlink "$LNK")")" "$LNK" done ln -sf ../../lib/libcap.so.2 "$TIZEN_SDK_SYSROOT/usr/lib/libcap.so" - ln -sf openssl1.1.pc "$TIZEN_SDK_SYSROOT/usr/lib/pkgconfig/openssl.pc" + ln -sf openssl3.pc "$TIZEN_SDK_SYSROOT/usr/lib/pkgconfig/openssl.pc" info "Done." echo @@ -282,7 +284,7 @@ function install_tizen_sdk() { echo "export TIZEN_VERSION=\"$TIZEN_VERSION\"" echo "export TIZEN_SDK_ROOT=\"$(realpath "$TIZEN_SDK_ROOT")\"" echo "export TIZEN_SDK_TOOLCHAIN=\"\$TIZEN_SDK_ROOT/tools/arm-linux-gnueabi-gcc-9.2\"" - echo "export TIZEN_SDK_SYSROOT=\"\$TIZEN_SDK_ROOT/platforms/tizen-$TIZEN_VERSION/mobile/rootstraps/mobile-$TIZEN_VERSION-device.core\"" + echo "export TIZEN_SDK_SYSROOT=\"\$TIZEN_SDK_ROOT/platforms/tizen-$TIZEN_VERSION/tizen/rootstraps/tizen-$TIZEN_VERSION-device.core\"" echo "export PATH=\"\$TIZEN_SDK_TOOLCHAIN/bin:\$TIZEN_SDK_ROOT/tools/ide/bin:\$TIZEN_SDK_ROOT/tools:\$PATH\"" echo -n "$COLOR_NONE" } From 350b13f76c0ad630081c4e50d608f6d62477ac1a Mon Sep 17 00:00:00 2001 From: fesseha-eve <88329315+fessehaeve@users.noreply.github.com> Date: Wed, 14 Aug 2024 16:24:47 +0200 Subject: [PATCH 041/165] updated list of AcceptedCommands list for Thermostat cluster with Preset feature enabled (#34981) --- src/app/tests/suites/certification/Test_TC_TSTAT_1_1.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/app/tests/suites/certification/Test_TC_TSTAT_1_1.yaml b/src/app/tests/suites/certification/Test_TC_TSTAT_1_1.yaml index 194babe282..35da0e04be 100644 --- a/src/app/tests/suites/certification/Test_TC_TSTAT_1_1.yaml +++ b/src/app/tests/suites/certification/Test_TC_TSTAT_1_1.yaml @@ -624,7 +624,7 @@ tests: response: constraints: type: list - contains: [254] + contains: [6, 254] - label: "Step 7a: TH reads from the DUT the GeneratedCommandList attribute." From 5ffe9ec641deeb64edd03ddf60788bc06e4652e5 Mon Sep 17 00:00:00 2001 From: Andrei Litvin Date: Wed, 14 Aug 2024 11:05:20 -0400 Subject: [PATCH 042/165] Update CCTRL 2.2 to not potentially use uninitialized variables in the class on teardown (#34955) * Do not use uninitialized bits in teardown * Extra guard for file remove * Fix a few more instances of app_process --------- Co-authored-by: Andrei Litvin --- src/python_testing/TC_BRBINFO_4_1.py | 15 +++++++++++---- src/python_testing/TC_CCTRL_2_2.py | 14 ++++++++++---- src/python_testing/TC_MCORE_FS_1_1.py | 15 ++++++++++----- 3 files changed, 31 insertions(+), 13 deletions(-) diff --git a/src/python_testing/TC_BRBINFO_4_1.py b/src/python_testing/TC_BRBINFO_4_1.py index 6c65f634bb..18e478c872 100644 --- a/src/python_testing/TC_BRBINFO_4_1.py +++ b/src/python_testing/TC_BRBINFO_4_1.py @@ -107,6 +107,7 @@ async def setup_class(self): self.set_of_dut_endpoints_before_adding_device = set(root_part_list) super().setup_class() + self.app_process = None app = self.user_params.get("th_server_app_path", None) if not app: asserts.fail('This test requires a TH_SERVER app. Specify app path with --string-arg th_server_app_path:') @@ -135,10 +136,16 @@ async def setup_class(self): params.commissioningParameters.setupManualCode, params.commissioningParameters.setupQRCode) def teardown_class(self): - logging.warning("Stopping app with SIGTERM") - self.app_process.send_signal(signal.SIGTERM.value) - self.app_process.wait() - os.remove(self.kvs) + # In case the th_server_app_path does not exist, then we failed the test + # and there is nothing to remove + if self.app_process is not None: + logging.warning("Stopping app with SIGTERM") + self.app_process.send_signal(signal.SIGTERM.value) + self.app_process.wait() + + if os.path.exists(self.kvs): + os.remove(self.kvs) + super().teardown_class() # diff --git a/src/python_testing/TC_CCTRL_2_2.py b/src/python_testing/TC_CCTRL_2_2.py index a2d209f054..6fd6b9764a 100644 --- a/src/python_testing/TC_CCTRL_2_2.py +++ b/src/python_testing/TC_CCTRL_2_2.py @@ -45,6 +45,7 @@ class TC_CCTRL_2_2(MatterBaseTest): async def setup_class(self): super().setup_class() # TODO: confirm whether we can open processes like this on the TH + self.app_process = None app = self.user_params.get("th_server_app_path", None) if not app: asserts.fail('This test requires a TH_SERVER app. Specify app path with --string-arg th_server_app_path:') @@ -73,11 +74,16 @@ async def setup_class(self): logging.info("Commissioning TH_SERVER complete") def teardown_class(self): - logging.warning("Stopping app with SIGTERM") - self.app_process.send_signal(signal.SIGTERM.value) - self.app_process.wait() + # In case the th_server_app_path does not exist, then we failed the test + # and there is nothing to remove + if self.app_process is not None: + logging.warning("Stopping app with SIGTERM") + self.app_process.send_signal(signal.SIGTERM.value) + self.app_process.wait() + + if os.path.exists(self.kvs): + os.remove(self.kvs) - os.remove(self.kvs) super().teardown_class() def steps_TC_CCTRL_2_2(self) -> list[TestStep]: diff --git a/src/python_testing/TC_MCORE_FS_1_1.py b/src/python_testing/TC_MCORE_FS_1_1.py index 50f4dc55c7..0680210bab 100755 --- a/src/python_testing/TC_MCORE_FS_1_1.py +++ b/src/python_testing/TC_MCORE_FS_1_1.py @@ -37,6 +37,7 @@ class TC_MCORE_FS_1_1(MatterBaseTest): async def setup_class(self): super().setup_class() # TODO: confirm whether we can open processes like this on the TH + self.app_process = None app = self.user_params.get("th_server_app_path", None) if not app: asserts.fail('This test requires a TH_SERVER app. Specify app path with --string-arg th_server_app_path:') @@ -64,11 +65,15 @@ async def setup_class(self): logging.info("Commissioning TH_SERVER complete") def teardown_class(self): - logging.warning("Stopping app with SIGTERM") - self.app_process.send_signal(signal.SIGTERM.value) - self.app_process.wait() - - os.remove(self.kvs) + # In case the th_server_app_path does not exist, then we failed the test + # and there is nothing to remove + if self.app_process is not None: + logging.warning("Stopping app with SIGTERM") + self.app_process.send_signal(signal.SIGTERM.value) + self.app_process.wait() + + if os.path.exists(self.kvs): + os.remove(self.kvs) super().teardown_class() def steps_TC_MCORE_FS_1_1(self) -> list[TestStep]: From e1f29bdeddc89e73753406a9400c370ed81b1b02 Mon Sep 17 00:00:00 2001 From: Arkadiusz Bokowy Date: Wed, 14 Aug 2024 17:36:31 +0200 Subject: [PATCH 043/165] [Python] Auto-import all clusters into the chip.clusters namespace (#34928) * Auto-import all clusters into the chip.clusters namespace * Fix __all__ lists * ZAP-generate __all__ with all clusters --- .../py_matter_idl/matter_idl/lint/__init__.py | 2 +- scripts/tools/memory/memdf/__init__.py | 5 +- .../python/chip/clusters/Objects.py | 132 ++++++++++++++++++ .../python/chip/clusters/__init__.py | 58 +------- src/controller/python/chip/yaml/__init__.py | 2 +- .../templates/python-cluster-Objects-py.zapt | 9 ++ 6 files changed, 149 insertions(+), 59 deletions(-) diff --git a/scripts/py_matter_idl/matter_idl/lint/__init__.py b/scripts/py_matter_idl/matter_idl/lint/__init__.py index 3ab2b9f7ba..6c7b1373f7 100644 --- a/scripts/py_matter_idl/matter_idl/lint/__init__.py +++ b/scripts/py_matter_idl/matter_idl/lint/__init__.py @@ -14,4 +14,4 @@ from .lint_rules_parser import CreateParser -__all__ = [CreateParser] +__all__ = ['CreateParser'] diff --git a/scripts/tools/memory/memdf/__init__.py b/scripts/tools/memory/memdf/__init__.py index fa0e107011..0a523fbb29 100644 --- a/scripts/tools/memory/memdf/__init__.py +++ b/scripts/tools/memory/memdf/__init__.py @@ -18,4 +18,7 @@ from memdf.df import DF, DFs, ExtentDF, SectionDF, SegmentDF, SymbolDF from memdf.util.config import Config, ConfigDescription -__all__ = [DF, SymbolDF, SectionDF, SegmentDF, ExtentDF, DFs, Config, ConfigDescription] +__all__ = [ + 'DF', 'SymbolDF', 'SectionDF', 'SegmentDF', 'ExtentDF', + 'DFs', 'Config', 'ConfigDescription', +] diff --git a/src/controller/python/chip/clusters/Objects.py b/src/controller/python/chip/clusters/Objects.py index cff7adf4ae..eff056a243 100644 --- a/src/controller/python/chip/clusters/Objects.py +++ b/src/controller/python/chip/clusters/Objects.py @@ -36,6 +36,138 @@ ClusterObjectDescriptor, ClusterObjectFieldDescriptor) from .Types import Nullable, NullValue + +__all__ = [ + "Globals", + "Identify", + "Groups", + "OnOff", + "OnOffSwitchConfiguration", + "LevelControl", + "BinaryInputBasic", + "PulseWidthModulation", + "Descriptor", + "Binding", + "AccessControl", + "Actions", + "BasicInformation", + "OtaSoftwareUpdateProvider", + "OtaSoftwareUpdateRequestor", + "LocalizationConfiguration", + "TimeFormatLocalization", + "UnitLocalization", + "PowerSourceConfiguration", + "PowerSource", + "GeneralCommissioning", + "NetworkCommissioning", + "DiagnosticLogs", + "GeneralDiagnostics", + "SoftwareDiagnostics", + "ThreadNetworkDiagnostics", + "WiFiNetworkDiagnostics", + "EthernetNetworkDiagnostics", + "TimeSynchronization", + "BridgedDeviceBasicInformation", + "Switch", + "AdministratorCommissioning", + "OperationalCredentials", + "GroupKeyManagement", + "FixedLabel", + "UserLabel", + "ProxyConfiguration", + "ProxyDiscovery", + "ProxyValid", + "BooleanState", + "IcdManagement", + "Timer", + "OvenCavityOperationalState", + "OvenMode", + "LaundryDryerControls", + "ModeSelect", + "LaundryWasherMode", + "RefrigeratorAndTemperatureControlledCabinetMode", + "LaundryWasherControls", + "RvcRunMode", + "RvcCleanMode", + "TemperatureControl", + "RefrigeratorAlarm", + "DishwasherMode", + "AirQuality", + "SmokeCoAlarm", + "DishwasherAlarm", + "MicrowaveOvenMode", + "MicrowaveOvenControl", + "OperationalState", + "RvcOperationalState", + "ScenesManagement", + "HepaFilterMonitoring", + "ActivatedCarbonFilterMonitoring", + "BooleanStateConfiguration", + "ValveConfigurationAndControl", + "ElectricalPowerMeasurement", + "ElectricalEnergyMeasurement", + "WaterHeaterManagement", + "DemandResponseLoadControl", + "Messages", + "DeviceEnergyManagement", + "EnergyEvse", + "EnergyPreference", + "PowerTopology", + "EnergyEvseMode", + "WaterHeaterMode", + "DeviceEnergyManagementMode", + "DoorLock", + "WindowCovering", + "BarrierControl", + "ServiceArea", + "PumpConfigurationAndControl", + "Thermostat", + "FanControl", + "ThermostatUserInterfaceConfiguration", + "ColorControl", + "BallastConfiguration", + "IlluminanceMeasurement", + "TemperatureMeasurement", + "PressureMeasurement", + "FlowMeasurement", + "RelativeHumidityMeasurement", + "OccupancySensing", + "CarbonMonoxideConcentrationMeasurement", + "CarbonDioxideConcentrationMeasurement", + "NitrogenDioxideConcentrationMeasurement", + "OzoneConcentrationMeasurement", + "Pm25ConcentrationMeasurement", + "FormaldehydeConcentrationMeasurement", + "Pm1ConcentrationMeasurement", + "Pm10ConcentrationMeasurement", + "TotalVolatileOrganicCompoundsConcentrationMeasurement", + "RadonConcentrationMeasurement", + "WiFiNetworkManagement", + "ThreadBorderRouterManagement", + "ThreadNetworkDirectory", + "WakeOnLan", + "Channel", + "TargetNavigator", + "MediaPlayback", + "MediaInput", + "LowPower", + "KeypadInput", + "ContentLauncher", + "AudioOutput", + "ApplicationLauncher", + "ApplicationBasic", + "AccountLogin", + "ContentControl", + "ContentAppObserver", + "EcosystemInformation", + "CommissionerControl", + "ElectricalMeasurement", + "UnitTesting", + "FaultInjection", + "SampleMei", +] + + class Globals: class Enums: class AreaTypeTag(MatterIntEnum): diff --git a/src/controller/python/chip/clusters/__init__.py b/src/controller/python/chip/clusters/__init__.py index b135345e96..14dc6f3e1d 100644 --- a/src/controller/python/chip/clusters/__init__.py +++ b/src/controller/python/chip/clusters/__init__.py @@ -15,59 +15,5 @@ # limitations under the License. # -# -# @file -# Provides Python APIs for CHIP. -# - -"""Provides Python APIs for CHIP.""" - -from . import Attribute, CHIPClusters, Command -from .Objects import (AccessControl, AccountLogin, Actions, ActivatedCarbonFilterMonitoring, AdministratorCommissioning, AirQuality, - ApplicationBasic, ApplicationLauncher, AudioOutput, BallastConfiguration, BarrierControl, BasicInformation, - BinaryInputBasic, Binding, BooleanState, BooleanStateConfiguration, BridgedDeviceBasicInformation, - CarbonDioxideConcentrationMeasurement, CarbonMonoxideConcentrationMeasurement, Channel, ColorControl, - CommissionerControl, ContentControl, ContentLauncher, DemandResponseLoadControl, Descriptor, - DeviceEnergyManagement, DeviceEnergyManagementMode, DiagnosticLogs, DishwasherAlarm, DishwasherMode, DoorLock, - EcosystemInformation, ElectricalEnergyMeasurement, ElectricalMeasurement, ElectricalPowerMeasurement, - EnergyEvse, EnergyEvseMode, EnergyPreference, EthernetNetworkDiagnostics, FanControl, FaultInjection, - FixedLabel, FlowMeasurement, FormaldehydeConcentrationMeasurement, GeneralCommissioning, GeneralDiagnostics, - Globals, GroupKeyManagement, Groups, HepaFilterMonitoring, IcdManagement, Identify, IlluminanceMeasurement, - KeypadInput, LaundryDryerControls, LaundryWasherControls, LaundryWasherMode, LevelControl, - LocalizationConfiguration, LowPower, MediaInput, MediaPlayback, MicrowaveOvenControl, MicrowaveOvenMode, - ModeSelect, NetworkCommissioning, NitrogenDioxideConcentrationMeasurement, OccupancySensing, OnOff, - OnOffSwitchConfiguration, OperationalCredentials, OperationalState, OtaSoftwareUpdateProvider, - OtaSoftwareUpdateRequestor, OvenCavityOperationalState, OvenMode, OzoneConcentrationMeasurement, - Pm1ConcentrationMeasurement, Pm10ConcentrationMeasurement, Pm25ConcentrationMeasurement, PowerSource, - PowerSourceConfiguration, PowerTopology, PressureMeasurement, ProxyConfiguration, ProxyDiscovery, ProxyValid, - PulseWidthModulation, PumpConfigurationAndControl, RadonConcentrationMeasurement, RefrigeratorAlarm, - RefrigeratorAndTemperatureControlledCabinetMode, RelativeHumidityMeasurement, RvcCleanMode, - RvcOperationalState, RvcRunMode, ScenesManagement, ServiceArea, SmokeCoAlarm, SoftwareDiagnostics, Switch, - TargetNavigator, TemperatureControl, TemperatureMeasurement, Thermostat, ThermostatUserInterfaceConfiguration, - ThreadBorderRouterManagement, ThreadNetworkDiagnostics, ThreadNetworkDirectory, TimeFormatLocalization, - TimeSynchronization, TotalVolatileOrganicCompoundsConcentrationMeasurement, UnitLocalization, UnitTesting, - UserLabel, ValveConfigurationAndControl, WakeOnLan, WaterHeaterManagement, WaterHeaterMode, - WiFiNetworkDiagnostics, WindowCovering) - -__all__ = [Attribute, CHIPClusters, Command, AccessControl, AccountLogin, Actions, ActivatedCarbonFilterMonitoring, AdministratorCommissioning, AirQuality, - ApplicationBasic, ApplicationLauncher, AudioOutput, BallastConfiguration, BarrierControl, BasicInformation, - BinaryInputBasic, Binding, BooleanState, BooleanStateConfiguration, BridgedDeviceBasicInformation, CarbonDioxideConcentrationMeasurement, - CarbonMonoxideConcentrationMeasurement, Channel, ColorControl, CommissionerControl, - ContentControl, ContentLauncher, DemandResponseLoadControl, Descriptor, DeviceEnergyManagementMode, DeviceEnergyManagement, DeviceEnergyManagementMode, DiagnosticLogs, DishwasherAlarm, DishwasherMode, - DoorLock, EcosystemInformation, ElectricalEnergyMeasurement, ElectricalMeasurement, ElectricalPowerMeasurement, EnergyEvse, EnergyEvseMode, EnergyPreference, - EthernetNetworkDiagnostics, FanControl, FaultInjection, FixedLabel, FlowMeasurement, - FormaldehydeConcentrationMeasurement, GeneralCommissioning, GeneralDiagnostics, Globals, GroupKeyManagement, Groups, - HepaFilterMonitoring, IcdManagement, Identify, IlluminanceMeasurement, KeypadInput, LaundryDryerControls, - LaundryWasherControls, LaundryWasherMode, LevelControl, LocalizationConfiguration, LowPower, MediaInput, MediaPlayback, MicrowaveOvenControl, - MicrowaveOvenMode, ModeSelect, NetworkCommissioning, NitrogenDioxideConcentrationMeasurement, - OccupancySensing, OnOff, OnOffSwitchConfiguration, OperationalCredentials, OperationalState, - OtaSoftwareUpdateProvider, OtaSoftwareUpdateRequestor, OvenCavityOperationalState, OvenMode, - OzoneConcentrationMeasurement, Pm1ConcentrationMeasurement, Pm10ConcentrationMeasurement, - Pm25ConcentrationMeasurement, PowerSource, PowerSourceConfiguration, PowerTopology, PressureMeasurement, ProxyConfiguration, - ProxyDiscovery, ProxyValid, PulseWidthModulation, PumpConfigurationAndControl, RadonConcentrationMeasurement, - RefrigeratorAlarm, RefrigeratorAndTemperatureControlledCabinetMode, RelativeHumidityMeasurement, RvcCleanMode, - RvcOperationalState, RvcRunMode, ScenesManagement, ServiceArea, SmokeCoAlarm, SoftwareDiagnostics, - Switch, TargetNavigator, TemperatureControl, TemperatureMeasurement, Thermostat, ThermostatUserInterfaceConfiguration, - ThreadBorderRouterManagement, ThreadNetworkDiagnostics, ThreadNetworkDirectory, TimeFormatLocalization, TimeSynchronization, - TotalVolatileOrganicCompoundsConcentrationMeasurement, UnitLocalization, - UnitTesting, UserLabel, ValveConfigurationAndControl, WakeOnLan, WaterHeaterManagement, WaterHeaterMode, WiFiNetworkDiagnostics, WindowCovering] +from . import Attribute, CHIPClusters, Command, Objects # noqa: F401 +from .Objects import * # noqa: F401, F403 diff --git a/src/controller/python/chip/yaml/__init__.py b/src/controller/python/chip/yaml/__init__.py index 7f312912b6..db829e9764 100644 --- a/src/controller/python/chip/yaml/__init__.py +++ b/src/controller/python/chip/yaml/__init__.py @@ -23,4 +23,4 @@ from . import runner -__all__ = [runner] +__all__ = ['runner'] diff --git a/src/controller/python/templates/python-cluster-Objects-py.zapt b/src/controller/python/templates/python-cluster-Objects-py.zapt index 0aa05721e6..3cb973d86d 100644 --- a/src/controller/python/templates/python-cluster-Objects-py.zapt +++ b/src/controller/python/templates/python-cluster-Objects-py.zapt @@ -19,6 +19,15 @@ from .ClusterObjects import (Cluster, ClusterAttributeDescriptor, ClusterCommand ClusterObjectDescriptor, ClusterObjectFieldDescriptor) from .Types import Nullable, NullValue + +__all__ = [ + "Globals", +{{#zcl_clusters}} + "{{asUpperCamelCase name}}", +{{/zcl_clusters}} +] + + class Globals: class Enums: {{#zcl_enums}} From 51dbf0ace51ba44f1c7512158aec3be864c6b097 Mon Sep 17 00:00:00 2001 From: Kiel Oleson Date: Wed, 14 Aug 2024 10:37:18 -0700 Subject: [PATCH 044/165] fix unused variable issue on non-macOS testing (#34970) --- .../Framework/CHIPTests/TestHelpers/MTRTestServerAppRunner.m | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/darwin/Framework/CHIPTests/TestHelpers/MTRTestServerAppRunner.m b/src/darwin/Framework/CHIPTests/TestHelpers/MTRTestServerAppRunner.m index 18424ed332..077cd49404 100644 --- a/src/darwin/Framework/CHIPTests/TestHelpers/MTRTestServerAppRunner.m +++ b/src/darwin/Framework/CHIPTests/TestHelpers/MTRTestServerAppRunner.m @@ -21,11 +21,13 @@ static unsigned sAppRunnerIndex = 1; +#if HAVE_NSTASK // kBasePort gets the discriminator added to it to figure out the port the app // should be using. This ensures that apps with distinct discriminators use // distinct ports. static const uint16_t kMinDiscriminator = 1111; static const uint16_t kBasePort = 5542 - kMinDiscriminator; +#endif // HAVE_NSTASK @implementation MTRTestServerAppRunner { unsigned _uniqueIndex; From f84ad54cae4602088410324bc46d8f618b0c9438 Mon Sep 17 00:00:00 2001 From: Andrei Litvin Date: Wed, 14 Aug 2024 14:49:14 -0400 Subject: [PATCH 045/165] Add constraint enforcement on responseTimeoutSeconds in commissioner control cluster (#34982) * Add constraint enforcement on responseTimeoutSeconds This adds constraints in the implementation and also fixes up error codes in CCTRL_2_2 test. * Fix comment --- .../commissioner-control-server.cpp | 8 ++++++++ src/python_testing/TC_CCTRL_2_2.py | 4 ++-- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/src/app/clusters/commissioner-control-server/commissioner-control-server.cpp b/src/app/clusters/commissioner-control-server/commissioner-control-server.cpp index 25f6153959..d8a655f6af 100644 --- a/src/app/clusters/commissioner-control-server/commissioner-control-server.cpp +++ b/src/app/clusters/commissioner-control-server/commissioner-control-server.cpp @@ -216,6 +216,14 @@ bool emberAfCommissionerControlClusterCommissionNodeCallback( auto sourceNodeId = GetNodeId(commandObj); + // Constraint on responseTimeoutSeconds is [30; 120] seconds + if ((commandData.responseTimeoutSeconds < 30) || (commandData.responseTimeoutSeconds > 120)) + { + ChipLogError(Zcl, "Invalid responseTimeoutSeconds for CommissionNode."); + commandObj->AddStatus(commandPath, Status::ConstraintError); + return true; + } + // Check if the command is executed via a CASE session if (sourceNodeId == kUndefinedNodeId) { diff --git a/src/python_testing/TC_CCTRL_2_2.py b/src/python_testing/TC_CCTRL_2_2.py index 6fd6b9764a..5204352b8b 100644 --- a/src/python_testing/TC_CCTRL_2_2.py +++ b/src/python_testing/TC_CCTRL_2_2.py @@ -217,7 +217,7 @@ async def test_TC_CCTRL_2_2(self): await self.send_single_cmd(cmd=cmd) asserts.fail("Unexpected success on CommissionNode") except InteractionModelError as e: - asserts.assert_equal(e.status, Status.Failure, "Incorrect error returned") + asserts.assert_equal(e.status, Status.ConstraintError, "Incorrect error returned") self.step(16) cmd = Clusters.CommissionerControl.Commands.CommissionNode(requestId=good_request_id, responseTimeoutSeconds=121) @@ -225,7 +225,7 @@ async def test_TC_CCTRL_2_2(self): await self.send_single_cmd(cmd=cmd) asserts.fail("Unexpected success on CommissionNode") except InteractionModelError as e: - asserts.assert_equal(e.status, Status.Failure, "Incorrect error returned") + asserts.assert_equal(e.status, Status.ConstraintError, "Incorrect error returned") self.step(17) cmd = Clusters.CommissionerControl.Commands.CommissionNode(requestId=good_request_id, responseTimeoutSeconds=30) From 4205cc36e473ee2dac850f9018d1a9c7d8ea9fef Mon Sep 17 00:00:00 2001 From: Andrei Litvin Date: Wed, 14 Aug 2024 14:59:10 -0400 Subject: [PATCH 046/165] Fix conversion error (#34989) --- .../CodegenDataModelProvider_Write.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/app/codegen-data-model-provider/CodegenDataModelProvider_Write.cpp b/src/app/codegen-data-model-provider/CodegenDataModelProvider_Write.cpp index 333c9e27e4..7420427f84 100644 --- a/src/app/codegen-data-model-provider/CodegenDataModelProvider_Write.cpp +++ b/src/app/codegen-data-model-provider/CodegenDataModelProvider_Write.cpp @@ -51,7 +51,7 @@ using Protocols::InteractionModel::Status; /// /// If it returns std::nullopt, then there is no AAI to handle the given path /// and processing should figure out the value otherwise (generally from other ember data) -std::optional TryWriteViaAccessInterface(const ConcreteAttributePath & path, AttributeAccessInterface * aai, +std::optional TryWriteViaAccessInterface(const ConcreteDataAttributePath & path, AttributeAccessInterface * aai, AttributeValueDecoder & decoder) { // Processing can happen only if an attribute access interface actually exists.. From 12c1a57647451cf222c677ed4812ae203d80ce7b Mon Sep 17 00:00:00 2001 From: Arkadiusz Bokowy Date: Thu, 15 Aug 2024 00:30:59 +0200 Subject: [PATCH 047/165] Update ZAP to newest nightly to get fix for global types (#34996) * Update zap.version * Update zap.json * Bump min ZAP version * Regen ZAP files after update * Restore extra newline --- scripts/setup/zap.json | 4 ++-- scripts/setup/zap.version | 2 +- scripts/tools/zap/zap_execution.py | 2 +- src/controller/python/chip/clusters/Objects.py | 8 ++++---- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/scripts/setup/zap.json b/scripts/setup/zap.json index d137149db0..38dec06969 100644 --- a/scripts/setup/zap.json +++ b/scripts/setup/zap.json @@ -8,13 +8,13 @@ "mac-amd64", "windows-amd64" ], - "tags": ["version:2@v2024.08.06-nightly.1"] + "tags": ["version:2@v2024.08.14-nightly.1"] }, { "_comment": "Always get the amd64 version on mac until usable arm64 zap build is available", "path": "fuchsia/third_party/zap/mac-amd64", "platforms": ["mac-arm64"], - "tags": ["version:2@v2024.08.06-nightly.1"] + "tags": ["version:2@v2024.08.14-nightly.1"] } ] } diff --git a/scripts/setup/zap.version b/scripts/setup/zap.version index db8c344a7d..5e2fd1daf0 100644 --- a/scripts/setup/zap.version +++ b/scripts/setup/zap.version @@ -1 +1 @@ -v2024.08.06-nightly +v2024.08.14-nightly diff --git a/scripts/tools/zap/zap_execution.py b/scripts/tools/zap/zap_execution.py index d2d4bc557a..40bc2e2a4b 100644 --- a/scripts/tools/zap/zap_execution.py +++ b/scripts/tools/zap/zap_execution.py @@ -23,7 +23,7 @@ # Use scripts/tools/zap/version_update.py to manage ZAP versioning as many # files may need updating for versions # -MIN_ZAP_VERSION = '2024.8.5' +MIN_ZAP_VERSION = '2024.8.14' class ZapTool: diff --git a/src/controller/python/chip/clusters/Objects.py b/src/controller/python/chip/clusters/Objects.py index eff056a243..ed3c9154cc 100644 --- a/src/controller/python/chip/clusters/Objects.py +++ b/src/controller/python/chip/clusters/Objects.py @@ -47252,7 +47252,7 @@ def descriptor(cls) -> ClusterObjectDescriptor: ]) uniqueLocationID: 'str' = "" - locationDescriptor: 'Globals.Structs.LocationDescriptorStruct' = field(default_factory=lambda: EcosystemInformation.Structs.LocationDescriptorStruct()) + locationDescriptor: 'Globals.Structs.LocationDescriptorStruct' = field(default_factory=lambda: Globals.Structs.LocationDescriptorStruct()) locationDescriptorLastEdit: 'uint' = 0 fabricIndex: 'uint' = 0 @@ -51090,7 +51090,7 @@ def descriptor(cls) -> ClusterObjectDescriptor: ClusterObjectFieldDescriptor(Label="field2", Tag=1, Type=Globals.Enums.TestGlobalEnum), ]) - field1: 'Globals.Structs.TestGlobalStruct' = field(default_factory=lambda: UnitTesting.Structs.TestGlobalStruct()) + field1: 'Globals.Structs.TestGlobalStruct' = field(default_factory=lambda: Globals.Structs.TestGlobalStruct()) field2: 'Globals.Enums.TestGlobalEnum' = 0 @dataclass @@ -51303,7 +51303,7 @@ def descriptor(cls) -> ClusterObjectDescriptor: ClusterObjectFieldDescriptor(Label="field2", Tag=1, Type=Globals.Enums.TestGlobalEnum), ]) - field1: 'Globals.Structs.TestGlobalStruct' = field(default_factory=lambda: UnitTesting.Structs.TestGlobalStruct()) + field1: 'Globals.Structs.TestGlobalStruct' = field(default_factory=lambda: Globals.Structs.TestGlobalStruct()) field2: 'Globals.Enums.TestGlobalEnum' = 0 @dataclass @@ -52127,7 +52127,7 @@ def attribute_id(cls) -> int: def attribute_type(cls) -> ClusterObjectFieldDescriptor: return ClusterObjectFieldDescriptor(Type=Globals.Structs.TestGlobalStruct) - value: 'Globals.Structs.TestGlobalStruct' = field(default_factory=lambda: UnitTesting.Structs.TestGlobalStruct()) + value: 'Globals.Structs.TestGlobalStruct' = field(default_factory=lambda: Globals.Structs.TestGlobalStruct()) @dataclass class Unsupported(ClusterAttributeDescriptor): From c11c0ee9de0381a97393d08b802e3f345f53f434 Mon Sep 17 00:00:00 2001 From: Terence Hampson Date: Wed, 14 Aug 2024 18:33:57 -0400 Subject: [PATCH 048/165] Create new ICD Manager in fabric-admin to service KeepActive Command (#34894) --------- Co-authored-by: Restyled.io Co-authored-by: yunhanw --- examples/fabric-admin/BUILD.gn | 4 + .../commands/common/CHIPCommand.cpp | 6 +- .../commands/common/CHIPCommand.h | 1 - .../commands/common/IcdManager.cpp | 47 ++++++++ .../fabric-admin/commands/common/IcdManager.h | 51 +++++++++ .../commands/common/StayActiveSender.cpp | 99 ++++++++++++++++ .../commands/common/StayActiveSender.h | 107 ++++++++++++++++++ .../commands/pairing/PairingCommand.cpp | 2 +- examples/fabric-admin/rpc/RpcServer.cpp | 73 ++++++++++-- 9 files changed, 377 insertions(+), 13 deletions(-) create mode 100644 examples/fabric-admin/commands/common/IcdManager.cpp create mode 100644 examples/fabric-admin/commands/common/IcdManager.h create mode 100644 examples/fabric-admin/commands/common/StayActiveSender.cpp create mode 100644 examples/fabric-admin/commands/common/StayActiveSender.h diff --git a/examples/fabric-admin/BUILD.gn b/examples/fabric-admin/BUILD.gn index 7fbd13e071..77e851a53c 100644 --- a/examples/fabric-admin/BUILD.gn +++ b/examples/fabric-admin/BUILD.gn @@ -69,8 +69,12 @@ static_library("fabric-admin-utils") { "commands/common/Commands.h", "commands/common/CredentialIssuerCommands.h", "commands/common/HexConversion.h", + "commands/common/IcdManager.cpp", + "commands/common/IcdManager.h", "commands/common/RemoteDataModelLogger.cpp", "commands/common/RemoteDataModelLogger.h", + "commands/common/StayActiveSender.cpp", + "commands/common/StayActiveSender.h", "commands/fabric-sync/FabricSyncCommand.cpp", "commands/pairing/DeviceSynchronization.cpp", "commands/pairing/DeviceSynchronization.h", diff --git a/examples/fabric-admin/commands/common/CHIPCommand.cpp b/examples/fabric-admin/commands/common/CHIPCommand.cpp index 982c857d20..0c5455439b 100644 --- a/examples/fabric-admin/commands/common/CHIPCommand.cpp +++ b/examples/fabric-admin/commands/common/CHIPCommand.cpp @@ -18,6 +18,7 @@ #include "CHIPCommand.h" +#include "IcdManager.h" #include #include #include @@ -52,7 +53,6 @@ chip::Credentials::GroupDataProviderImpl CHIPCommand::sGroupDataProvider{ kMaxGr // All fabrics share the same ICD client storage. chip::app::DefaultICDClientStorage CHIPCommand::sICDClientStorage; chip::Crypto::RawKeySessionKeystore CHIPCommand::sSessionKeystore; -chip::app::DefaultCheckInDelegate CHIPCommand::sCheckInDelegate; chip::app::CheckInHandler CHIPCommand::sCheckInHandler; namespace { @@ -148,9 +148,9 @@ CHIP_ERROR CHIPCommand::MaybeSetUpStack() auto engine = chip::app::InteractionModelEngine::GetInstance(); VerifyOrReturnError(engine != nullptr, CHIP_ERROR_INCORRECT_STATE); - ReturnLogErrorOnFailure(sCheckInDelegate.Init(&sICDClientStorage, engine)); + ReturnLogErrorOnFailure(IcdManager::Instance().Init(&sICDClientStorage, engine)); ReturnLogErrorOnFailure(sCheckInHandler.Init(DeviceControllerFactory::GetInstance().GetSystemState()->ExchangeMgr(), - &sICDClientStorage, &sCheckInDelegate, engine)); + &sICDClientStorage, &IcdManager::Instance(), engine)); CommissionerIdentity nullIdentity{ kIdentityNull, chip::kUndefinedNodeId }; ReturnLogErrorOnFailure(InitializeCommissioner(nullIdentity, kIdentityNullFabricId)); diff --git a/examples/fabric-admin/commands/common/CHIPCommand.h b/examples/fabric-admin/commands/common/CHIPCommand.h index 6711b3e4f9..abd68f6344 100644 --- a/examples/fabric-admin/commands/common/CHIPCommand.h +++ b/examples/fabric-admin/commands/common/CHIPCommand.h @@ -168,7 +168,6 @@ class CHIPCommand : public Command static chip::Credentials::GroupDataProviderImpl sGroupDataProvider; static chip::app::DefaultICDClientStorage sICDClientStorage; - static chip::app::DefaultCheckInDelegate sCheckInDelegate; static chip::app::CheckInHandler sCheckInHandler; CredentialIssuerCommands * mCredIssuerCmds; diff --git a/examples/fabric-admin/commands/common/IcdManager.cpp b/examples/fabric-admin/commands/common/IcdManager.cpp new file mode 100644 index 0000000000..201d732554 --- /dev/null +++ b/examples/fabric-admin/commands/common/IcdManager.cpp @@ -0,0 +1,47 @@ +/* + * 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 "IcdManager.h" + +IcdManager IcdManager::sInstance; + +IcdManager & IcdManager::Instance() +{ + return sInstance; +} + +void IcdManager::OnCheckInComplete(const chip::app::ICDClientInfo & clientInfo) +{ + DefaultCheckInDelegate::OnCheckInComplete(clientInfo); + if (mDelegate) + { + mDelegate->OnCheckInCompleted(clientInfo); + } +} + +void IcdManager::SetDelegate(Delegate * delegate) +{ + // To keep IcdManager simple, there is an assumption that there is only ever + // one delegate set and it's lifetime is identical to IcdManager. In the + // future this assumption can change should there be a need, but that will + // require code changes to IcdManager. For now we will crash if someone tries + // to call SetDelegate for a second time or if delegate is non-null. + VerifyOrDie(delegate); + VerifyOrDie(!mDelegate); + mDelegate = delegate; +} diff --git a/examples/fabric-admin/commands/common/IcdManager.h b/examples/fabric-admin/commands/common/IcdManager.h new file mode 100644 index 0000000000..8993f24e53 --- /dev/null +++ b/examples/fabric-admin/commands/common/IcdManager.h @@ -0,0 +1,51 @@ +/* + * 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 + +/** + * @brief Manages check-ins from ICD devices. + * + * Intended to be used as a thin CheckInDelegate. This allows a delegate register + * themselves so they can be aware when ICD device checks-in allowing the + * delegate to interact with the ICD device during the short window that it is + * awake. + */ +class IcdManager : public chip::app::DefaultCheckInDelegate +{ +public: + class Delegate + { + public: + virtual ~Delegate() = default; + virtual void OnCheckInCompleted(const chip::app::ICDClientInfo & clientInfo) = 0; + }; + + static IcdManager & Instance(); + void OnCheckInComplete(const chip::app::ICDClientInfo & clientInfo) override; + + // There is an assumption delegate assigned only happens once and that it lives + // for the entirety of the lifetime of fabric admin. + void SetDelegate(Delegate * delegate); + +private: + static IcdManager sInstance; + Delegate * mDelegate = nullptr; +}; diff --git a/examples/fabric-admin/commands/common/StayActiveSender.cpp b/examples/fabric-admin/commands/common/StayActiveSender.cpp new file mode 100644 index 0000000000..16f1d5cd13 --- /dev/null +++ b/examples/fabric-admin/commands/common/StayActiveSender.cpp @@ -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. + */ + +#include "StayActiveSender.h" + +#include +#include +#include +#include + +CHIP_ERROR StayActiveSender::SendStayActiveCommand(uint32_t stayActiveDurationMs, const chip::ScopedNodeId & peerNode, + chip::app::InteractionModelEngine * engine, OnDoneCallbackType onDone) +{ + ConstructorOnlyInternallyCallable internal; + auto stayActiveSender = chip::Platform::New(internal, stayActiveDurationMs, peerNode, + chip::app::InteractionModelEngine::GetInstance(), onDone); + VerifyOrReturnError(stayActiveSender != nullptr, CHIP_ERROR_NO_MEMORY); + CHIP_ERROR err = stayActiveSender->EstablishSessionToPeer(); + if (CHIP_NO_ERROR != err) + { + chip::Platform::Delete(stayActiveSender); + } + return err; +} + +StayActiveSender::StayActiveSender(const ConstructorOnlyInternallyCallable & _, uint32_t stayActiveDurationMs, + const chip::ScopedNodeId & peerNode, chip::app::InteractionModelEngine * engine, + OnDoneCallbackType onDone) : + mStayActiveDurationMs(stayActiveDurationMs), + mPeerNode(peerNode), mpImEngine(engine), mOnDone(onDone), mOnConnectedCallback(HandleDeviceConnected, this), + mOnConnectionFailureCallback(HandleDeviceConnectionFailure, this) +{} + +CHIP_ERROR StayActiveSender::SendStayActiveCommand(chip::Messaging::ExchangeManager & exchangeMgr, + const chip::SessionHandle & sessionHandle) +{ + auto onSuccess = [&](const chip::app::ConcreteCommandPath & commandPath, const chip::app::StatusIB & status, + const auto & dataResponse) { + uint32_t promisedActiveDurationMs = dataResponse.promisedActiveDuration; + ChipLogProgress(ICD, "StayActive command succeeded with promised duration %u", promisedActiveDurationMs); + mOnDone(promisedActiveDurationMs); + chip::Platform::Delete(this); + }; + + auto onFailure = [&](CHIP_ERROR error) { + ChipLogError(ICD, "StayActive command failed: %" CHIP_ERROR_FORMAT, error.Format()); + chip::Platform::Delete(this); + }; + + chip::EndpointId endpointId = 0; + chip::app::Clusters::IcdManagement::Commands::StayActiveRequest::Type request; + request.stayActiveDuration = mStayActiveDurationMs; + return chip::Controller::InvokeCommandRequest(&exchangeMgr, sessionHandle, endpointId, request, onSuccess, onFailure); +} + +CHIP_ERROR StayActiveSender::EstablishSessionToPeer() +{ + ChipLogProgress(ICD, "Trying to establish a CASE session to extend the active period for lit icd device"); + auto * caseSessionManager = mpImEngine->GetCASESessionManager(); + VerifyOrReturnError(caseSessionManager != nullptr, CHIP_ERROR_INVALID_CASE_PARAMETER); + caseSessionManager->FindOrEstablishSession(mPeerNode, &mOnConnectedCallback, &mOnConnectionFailureCallback); + return CHIP_NO_ERROR; +} + +void StayActiveSender::HandleDeviceConnected(void * context, chip::Messaging::ExchangeManager & exchangeMgr, + const chip::SessionHandle & sessionHandle) +{ + StayActiveSender * const _this = static_cast(context); + VerifyOrDie(_this != nullptr); + + CHIP_ERROR err = _this->SendStayActiveCommand(exchangeMgr, sessionHandle); + if (CHIP_NO_ERROR != err) + { + ChipLogError(ICD, "Failed to send stay active command"); + chip::Platform::Delete(_this); + } +} + +void StayActiveSender::HandleDeviceConnectionFailure(void * context, const chip::ScopedNodeId & peerId, CHIP_ERROR err) +{ + StayActiveSender * const _this = static_cast(context); + VerifyOrDie(_this != nullptr); + ChipLogError(ICD, "Failed to establish CASE for stay active command with error '%" CHIP_ERROR_FORMAT "'", err.Format()); + chip::Platform::Delete(_this); +} diff --git a/examples/fabric-admin/commands/common/StayActiveSender.h b/examples/fabric-admin/commands/common/StayActiveSender.h new file mode 100644 index 0000000000..c0caa380e6 --- /dev/null +++ b/examples/fabric-admin/commands/common/StayActiveSender.h @@ -0,0 +1,107 @@ +/* + * + * 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 + +/** + * @brief StayActiveSender contains all the data and methods needed for active period extension of an ICD client. + * + * Lifetime of instance of StayActiveSender is entirely self managed. + */ +class StayActiveSender +{ +private: + // Ideally StayActiveSender would be a private constructor, unfortunately that is not possible as Platform::New + // does not have access to private constructors. As a workaround we have defined this private struct that can + // be forwarded by Platform::New that allows us to enforce that the only way StayActiveSender is constructed is + // if SendStayActiveCommand is called. + struct ConstructorOnlyInternallyCallable + { + }; + +public: + using OnDoneCallbackType = std::function; + + /** + * @brief Attempts to send a StayActiveRequest command + * + * @param[in] stayActiveDurationMs StayActiveRequest command parameter. + * @param[in] peerNode Peer node we sending StayActiveRequest command to + * @param[in] engine Interaction Model Engine instance for sending command. + * @param[in] onDone Upon this function returning success, it is expected that onDone will be called after we + * have successfully recieved a response + * + * @return CHIP_ERROR CHIP_NO_ERROR on success, or corresponding error code. + */ + static CHIP_ERROR SendStayActiveCommand(uint32_t stayActiveDurationMs, const chip::ScopedNodeId & peerNode, + chip::app::InteractionModelEngine * engine, OnDoneCallbackType onDone); + + // Ideally this would be a private constructor, unfortunately that is not possible as Platform::New does not + // have access to private constructors. As a workaround we have defined a private struct that can be forwarded + // by Platform::New that allows us to enforce that the only way this is constructed is if SendStayActiveCommand + // is called. + StayActiveSender(const ConstructorOnlyInternallyCallable & _, uint32_t stayActiveDurationMs, + const chip::ScopedNodeId & peerNode, chip::app::InteractionModelEngine * engine, OnDoneCallbackType onDone); + +private: + /** + * @brief Sets up a CASE session with the peer to extend the client's active period with that peer. + * Returns error if we did not even manage to kick off a CASE attempt. + */ + CHIP_ERROR EstablishSessionToPeer(); + + // CASE session callbacks + /** + *@brief Callback received on successfully establishing a CASE session in order to keep the 'lit icd device' active + * + * @param[in] context - context of the client establishing the CASE session + * @param[in] exchangeMgr - exchange manager to use for the re-registration + * @param[in] sessionHandle - session handle to use for the re-registration + */ + static void HandleDeviceConnected(void * context, chip::Messaging::ExchangeManager & exchangeMgr, + const chip::SessionHandle & sessionHandle); + /** + * @brief Callback received on failure to establish a CASE session + * + * @param[in] context - context of the client establishing the CASE session + * @param[in] peerId - Scoped Node ID of the peer node + * @param[in] err - failure reason + */ + static void HandleDeviceConnectionFailure(void * context, const chip::ScopedNodeId & peerId, CHIP_ERROR err); + + /** + * @brief Used to send a stayActive command to the peer + * + * @param[in] exchangeMgr - exchange manager to use for the re-registration + * @param[in] sessionHandle - session handle to use for the re-registration + */ + CHIP_ERROR SendStayActiveCommand(chip::Messaging::ExchangeManager & exchangeMgr, const chip::SessionHandle & sessionHandle); + + uint32_t mStayActiveDurationMs = 0; + chip::ScopedNodeId mPeerNode; + chip::app::InteractionModelEngine * mpImEngine = nullptr; + OnDoneCallbackType mOnDone; + + chip::Callback::Callback mOnConnectedCallback; + chip::Callback::Callback mOnConnectionFailureCallback; +}; diff --git a/examples/fabric-admin/commands/pairing/PairingCommand.cpp b/examples/fabric-admin/commands/pairing/PairingCommand.cpp index 21b023f423..aecd259d37 100644 --- a/examples/fabric-admin/commands/pairing/PairingCommand.cpp +++ b/examples/fabric-admin/commands/pairing/PairingCommand.cpp @@ -464,7 +464,7 @@ void PairingCommand::OnICDRegistrationComplete(ScopedNodeId nodeId, uint32_t icd sizeof(icdSymmetricKeyHex), chip::Encoding::HexFlags::kNullTerminate); app::ICDClientInfo clientInfo; - clientInfo.peer_node = chip::ScopedNodeId(mICDCheckInNodeId.Value(), nodeId.GetFabricIndex()); + clientInfo.peer_node = nodeId; clientInfo.monitored_subject = mICDMonitoredSubject.Value(); clientInfo.start_icd_counter = icdCounter; diff --git a/examples/fabric-admin/rpc/RpcServer.cpp b/examples/fabric-admin/rpc/RpcServer.cpp index 16ff695e15..86d90ad294 100644 --- a/examples/fabric-admin/rpc/RpcServer.cpp +++ b/examples/fabric-admin/rpc/RpcServer.cpp @@ -20,11 +20,16 @@ #include "pw_rpc_system_server/rpc_server.h" #include "pw_rpc_system_server/socket.h" +#include +#include + +#include "RpcClient.h" +#include +#include #include #include #include #include -#include #if defined(PW_RPC_FABRIC_ADMIN_SERVICE) && PW_RPC_FABRIC_ADMIN_SERVICE #include "pigweed/rpc_services/FabricAdmin.h" @@ -35,9 +40,33 @@ using namespace ::chip; namespace { #if defined(PW_RPC_FABRIC_ADMIN_SERVICE) && PW_RPC_FABRIC_ADMIN_SERVICE -class FabricAdmin final : public rpc::FabricAdmin + +class FabricAdmin final : public rpc::FabricAdmin, public IcdManager::Delegate { public: + void OnCheckInCompleted(const chip::app::ICDClientInfo & clientInfo) override + { + chip::NodeId nodeId = clientInfo.peer_node.GetNodeId(); + auto it = mPendingKeepActiveTimesMs.find(nodeId); + VerifyOrReturn(it != mPendingKeepActiveTimesMs.end()); + // TODO(#33221): We also need a mechanism here to drop KeepActive + // request if they were recieved over 60 mins ago. + uint32_t stayActiveDurationMs = it->second; + + // TODO(#33221): If there is a failure in sending the message this request just gets dropped. + // Work to see if there should be update to spec on whether some sort of failure later on + // Should be indicated in some manner, or identify a better recovery mechanism here. + mPendingKeepActiveTimesMs.erase(nodeId); + + auto onDone = [=](uint32_t promisedActiveDuration) { ActiveChanged(nodeId, promisedActiveDuration); }; + CHIP_ERROR err = StayActiveSender::SendStayActiveCommand(stayActiveDurationMs, clientInfo.peer_node, + chip::app::InteractionModelEngine::GetInstance(), onDone); + if (err != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to send StayActive command %s", err.AsString()); + } + } + pw::Status OpenCommissioningWindow(const chip_rpc_DeviceCommissioningWindowInfo & request, chip_rpc_OperationStatus & response) override { @@ -65,14 +94,41 @@ class FabricAdmin final : public rpc::FabricAdmin pw::Status KeepActive(const chip_rpc_KeepActiveParameters & request, pw_protobuf_Empty & response) override { ChipLogProgress(NotSpecified, "Received KeepActive request: 0x%lx, %u", request.node_id, request.stay_active_duration_ms); - // TODO(#33221): When we get this command hopefully we are already registered with an ICD device to be - // notified when it wakes up. We will need to add in hooks there to make sure we send the StayActiveRequest - // Important thing to note: - // * If we get this call multiple times before we get a wakeup from ICD, we only send out one StayActiveRequest command - // * After 60 mins from last exipry we no longer will send out a StayActiveRequest. - + // TODO(#33221): We should really be using ScopedNode, but that requires larger fix in communication between + // fabric-admin and fabric-bridge. For now we make the assumption that there is only one fabric used by + // fabric-admin. + KeepActiveWorkData * data = chip::Platform::New(this, request.node_id, request.stay_active_duration_ms); + VerifyOrReturnValue(data, pw::Status::Internal()); + chip::DeviceLayer::PlatformMgr().ScheduleWork(KeepActiveWork, reinterpret_cast(data)); return pw::OkStatus(); } + + void ScheduleSendingKeepActiveOnCheckIn(chip::NodeId nodeId, uint32_t stayActiveDurationMs) + { + mPendingKeepActiveTimesMs[nodeId] = stayActiveDurationMs; + } + +private: + struct KeepActiveWorkData + { + KeepActiveWorkData(FabricAdmin * fabricAdmin, chip::NodeId nodeId, uint32_t stayActiveDurationMs) : + mFabricAdmin(fabricAdmin), mNodeId(nodeId), mStayActiveDurationMs(stayActiveDurationMs) + {} + + FabricAdmin * mFabricAdmin; + chip::NodeId mNodeId; + uint32_t mStayActiveDurationMs; + }; + + static void KeepActiveWork(intptr_t arg) + { + KeepActiveWorkData * data = reinterpret_cast(arg); + data->mFabricAdmin->ScheduleSendingKeepActiveOnCheckIn(data->mNodeId, data->mStayActiveDurationMs); + chip::Platform::Delete(data); + } + + // Modifications to mPendingKeepActiveTimesMs should be done on the MatterEventLoop thread + std::map mPendingKeepActiveTimesMs; }; FabricAdmin fabric_admin_service; @@ -82,6 +138,7 @@ void RegisterServices(pw::rpc::Server & server) { #if defined(PW_RPC_FABRIC_ADMIN_SERVICE) && PW_RPC_FABRIC_ADMIN_SERVICE server.RegisterService(fabric_admin_service); + IcdManager::Instance().SetDelegate(&fabric_admin_service); #endif } From 4b8ac58eae4c5117810cada35a87f8815aa08774 Mon Sep 17 00:00:00 2001 From: Junior Martinez <67972863+jmartinez-silabs@users.noreply.github.com> Date: Wed, 14 Aug 2024 20:46:08 -0400 Subject: [PATCH 049/165] [Silabs]Provision storage sourceset (#34929) * Create a separte source_set for the provision storage implementation * Fix efr32 build using provision flash storage * fix argument duplication which is not needed. * apply suggested renames --- examples/platform/silabs/SiWx917/BUILD.gn | 10 +--- examples/platform/silabs/efr32/BUILD.gn | 7 +-- examples/platform/silabs/provision/BUILD.gn | 52 +++++++++++++++++++ .../silabs/efr32/efr32-chip-mbedtls-config.h | 6 +++ third_party/silabs/efr32_sdk.gni | 9 ++++ 5 files changed, 69 insertions(+), 15 deletions(-) create mode 100644 examples/platform/silabs/provision/BUILD.gn diff --git a/examples/platform/silabs/SiWx917/BUILD.gn b/examples/platform/silabs/SiWx917/BUILD.gn index 1a4bc78863..80d247b56c 100644 --- a/examples/platform/silabs/SiWx917/BUILD.gn +++ b/examples/platform/silabs/SiWx917/BUILD.gn @@ -115,12 +115,6 @@ source_set("siwx917-matter-shell") { config("siwx917-common-config") { defines = [ "OTA_PERIODIC_TIMEOUT=${ota_periodic_query_timeout_sec}" ] - if (sl_si91x_crypto_flavor == "psa") { - libs = - [ "${sdk_support_root}/matter/provision/lib/libProvisionPSA_si917.a" ] - } else { - libs = [ "${sdk_support_root}/matter/provision/lib/libProvision_si917.a" ] - } if (!disable_lcd) { include_dirs = [ "${silabs_common_plat_dir}/display" ] @@ -177,7 +171,7 @@ config("silabs-wifi-config") { } source_set("siwx917-common") { - deps = [ "${chip_root}/src/platform/silabs/provision:provision-headers" ] + deps = [ "${silabs_common_plat_dir}/provision:storage" ] defines = [] public_deps = [] public_configs = [ @@ -197,8 +191,6 @@ source_set("siwx917-common") { "${silabs_common_plat_dir}/LEDWidget.cpp", "${silabs_common_plat_dir}/MatterConfig.cpp", "${silabs_common_plat_dir}/SoftwareFaultReports.cpp", - "${silabs_common_plat_dir}/provision/ProvisionStorageCustom.cpp", - "${silabs_common_plat_dir}/provision/ProvisionStorageFlash.cpp", "${silabs_common_plat_dir}/silabs_utils.cpp", "${silabs_common_plat_dir}/syscalls_stubs.cpp", "${silabs_plat_si91x_wifi_dir}/dhcp_client.cpp", diff --git a/examples/platform/silabs/efr32/BUILD.gn b/examples/platform/silabs/efr32/BUILD.gn index bff7d1e37b..22b7458588 100644 --- a/examples/platform/silabs/efr32/BUILD.gn +++ b/examples/platform/silabs/efr32/BUILD.gn @@ -148,9 +148,6 @@ source_set("efr-matter-shell") { config("efr32-common-config") { defines = [ "OTA_PERIODIC_TIMEOUT=${ota_periodic_query_timeout_sec}" ] - libs = [ - "${sdk_support_root}/matter/provision/lib/libProvision_${silabs_family}.a", - ] if (!disable_lcd) { include_dirs = [ "${silabs_common_plat_dir}/display" ] @@ -212,7 +209,7 @@ config("silabs-wifi-config") { } source_set("efr32-common") { - deps = [ "${chip_root}/src/platform/silabs/provision:provision-headers" ] + deps = [ "${silabs_common_plat_dir}/provision:storage" ] defines = [] public_deps = [] public_configs = [ @@ -241,8 +238,6 @@ source_set("efr32-common") { "${silabs_common_plat_dir}/LEDWidget.cpp", "${silabs_common_plat_dir}/MatterConfig.cpp", "${silabs_common_plat_dir}/SoftwareFaultReports.cpp", - "${silabs_common_plat_dir}/provision/ProvisionStorageCustom.cpp", - "${silabs_common_plat_dir}/provision/ProvisionStorageDefault.cpp", "${silabs_common_plat_dir}/silabs_utils.cpp", "${silabs_common_plat_dir}/syscalls_stubs.cpp", ] diff --git a/examples/platform/silabs/provision/BUILD.gn b/examples/platform/silabs/provision/BUILD.gn new file mode 100644 index 0000000000..ccd5b919bc --- /dev/null +++ b/examples/platform/silabs/provision/BUILD.gn @@ -0,0 +1,52 @@ +# 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("${efr32_sdk_build_root}/silabs_board.gni") + +if (wifi_soc) { + import("${efr32_sdk_build_root}/SiWx917_sdk.gni") +} else { + import("${efr32_sdk_build_root}/efr32_sdk.gni") +} + +source_set("storage") { + sources = [ "ProvisionStorageCustom.cpp" ] + + if (use_provision_flash_storage) { + sources += [ "ProvisionStorageFlash.cpp" ] + } else { + sources += [ "ProvisionStorageDefault.cpp" ] + } + + if (wifi_soc) { + if (sl_si91x_crypto_flavor == "psa") { + libs = + [ "${sdk_support_root}/matter/provision/lib/libProvisionPSA_si917.a" ] + } else { + libs = [ "${sdk_support_root}/matter/provision/lib/libProvision_si917.a" ] + } + } else { + if (use_provision_flash_storage) { + libs = [ "${sdk_support_root}/matter/provision/lib/libProvisionFlash_${silabs_family}.a" ] + } else { + libs = [ "${sdk_support_root}/matter/provision/lib/libProvision_${silabs_family}.a" ] + } + } + + deps = [ "${chip_root}/src/lib" ] + public_deps = + [ "${chip_root}/src/platform/silabs/provision:provision-headers" ] +} diff --git a/src/platform/silabs/efr32/efr32-chip-mbedtls-config.h b/src/platform/silabs/efr32/efr32-chip-mbedtls-config.h index 6ecfae7d3e..c707fe9e9f 100644 --- a/src/platform/silabs/efr32/efr32-chip-mbedtls-config.h +++ b/src/platform/silabs/efr32/efr32-chip-mbedtls-config.h @@ -87,6 +87,12 @@ #define PSA_WANT_ALG_SOME_PAKE #endif // SL_USE_COAP_CONFIG +#if SL_MATTER_PROVISION_FLASH +#define MBEDTLS_SHA256_C +#define MBEDTLS_HMAC_DRBG_C +#define MBEDTLS_ECDSA_DETERMINISTIC +#endif // SL_MATTER_PROVISION_FLASH + #define MBEDTLS_PLATFORM_SNPRINTF_MACRO snprintf #define MBEDTLS_AES_ROM_TABLES diff --git a/third_party/silabs/efr32_sdk.gni b/third_party/silabs/efr32_sdk.gni index ccbae7f1ec..c9126d02e4 100644 --- a/third_party/silabs/efr32_sdk.gni +++ b/third_party/silabs/efr32_sdk.gni @@ -82,6 +82,9 @@ declare_args() { chip_enable_multi_ota_requestor = false chip_enable_multi_ota_encryption = false chip_enable_ota_custom_tlv_testing = false + + # Factory Provision storage + use_provision_flash_storage = wifi_soc } examples_plat_dir = "${chip_root}/examples/platform/silabs/efr32" @@ -469,6 +472,12 @@ template("efr32_sdk") { defines += [ "SL_USE_COAP_CONFIG=0" ] } + if (use_provision_flash_storage) { + defines += [ "SL_MATTER_PROVISION_FLASH=1" ] + } else { + defines += [ "SL_MATTER_PROVISION_FLASH=0" ] + } + if (chip_enable_ble_rs911x) { defines += [ "RSI_BLE_ENABLE=1", From 9d8587d7119142fae862540cef0e0449ab07397f Mon Sep 17 00:00:00 2001 From: Alex Tsitsiura Date: Thu, 15 Aug 2024 16:39:30 +0300 Subject: [PATCH 050/165] [Telink] Update Docker image (Zephyr update) (#34980) * [Telink] Update Docker image (Zephyr update) * [Telink] Update Docker image (Zephyr update) --------- Co-authored-by: Andrei Litvin --- 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 18dcb8d04c..dfc4231a8e 100644 --- a/integrations/docker/images/base/chip-build/version +++ b/integrations/docker/images/base/chip-build/version @@ -1 +1 @@ -72 : Update Tizen version to 8.0 +73 : [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 bea580245e..e9c3da6812 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=ef7bfc2214602ecf237332b71e6a2bdd69205fbd +ARG ZEPHYR_REVISION=446337fb7b31cd9751720a57d0add62da89c962a WORKDIR /opt/telink/zephyrproject RUN set -x \ && python3 -m pip install --break-system-packages -U --no-cache-dir west \ From 0d71711875e486c9961761808965d4f91c88bbea Mon Sep 17 00:00:00 2001 From: jrhees-cae <61466710+jrhees-cae@users.noreply.github.com> Date: Thu, 15 Aug 2024 08:22:41 -0600 Subject: [PATCH 051/165] [DRLK] Bugfix: return INVALID_COMMAND when attempting to add/modify (#34120) * [DRLK] Bugfix: return INVALID_COMMAND when attempting to add/modify credential from a different fabric than the User/Credential's creator fabric Add YAML test steps to verify correct behavior Fixes #34119 * Restyled by prettier-yaml * Update src/app/tests/suites/DL_UsersAndCredentials.yaml Co-authored-by: Andrei Litvin --------- Co-authored-by: Restyled.io Co-authored-by: Andrei Litvin --- .../door-lock-server/door-lock-server.cpp | 35 ++ .../tests/suites/DL_UsersAndCredentials.yaml | 333 +++++++++++++++++- 2 files changed, 365 insertions(+), 3 deletions(-) diff --git a/src/app/clusters/door-lock-server/door-lock-server.cpp b/src/app/clusters/door-lock-server/door-lock-server.cpp index 29a7685322..3842130aa3 100644 --- a/src/app/clusters/door-lock-server/door-lock-server.cpp +++ b/src/app/clusters/door-lock-server/door-lock-server.cpp @@ -803,6 +803,19 @@ void DoorLockServer::setCredentialCommandHandler( return; } + // return INVALID_COMMAND if the accessing fabric index doesn’t match the + // CreatorFabricIndex of the credential being modified + if (existingCredential.createdBy != fabricIdx) + { + ChipLogProgress(Zcl, + "[createCredential] Unable to modify credential. Fabric index differs from creator fabric " + "[endpointId=%d,credentialIndex=%d,creatorIdx=%d,modifierIdx=%d]", + commandPath.mEndpointId, credentialIndex, existingCredential.createdBy, fabricIdx); + + sendSetCredentialResponse(commandObj, commandPath, DlStatus::kInvalidField, 0, nextAvailableCredentialSlot); + return; + } + // if userIndex is NULL then we're changing the programming user PIN if (userIndex.IsNull()) { @@ -2218,6 +2231,17 @@ DlStatus DoorLockServer::createNewCredentialAndAddItToUser(chip::EndpointId endp return DlStatus::kInvalidField; } + // return INVALID_COMMAND if the accessing fabric index doesn’t match the + // CreatorFabricIndex in the user record pointed to by UserIndex + if (user.createdBy != modifierFabricIdx) + { + ChipLogProgress(Zcl, + "[createCredential] Unable to create credential for user created by different fabric " + "[endpointId=%d,userIndex=%d,creatorIdx=%d,fabricIdx=%d]", + endpointId, userIndex, user.createdBy, modifierFabricIdx); + return DlStatus::kInvalidField; + } + // Add new credential to the user auto status = addCredentialToUser(endpointId, modifierFabricIdx, userIndex, credential); if (DlStatus::kSuccess != status) @@ -2338,6 +2362,17 @@ DlStatus DoorLockServer::modifyCredentialForUser(chip::EndpointId endpointId, ch return DlStatus::kFailure; } + // return INVALID_COMMAND if the accessing fabric index doesn’t match the + // CreatorFabricIndex in the user record pointed to by UserIndex + if (user.createdBy != modifierFabricIdx) + { + ChipLogProgress(Zcl, + "[createCredential] Unable to modify credential for user created by different fabric " + "[endpointId=%d,userIndex=%d,creatorIdx=%d,fabricIdx=%d]", + endpointId, userIndex, user.createdBy, modifierFabricIdx); + return DlStatus::kInvalidField; + } + for (size_t i = 0; i < user.credentials.size(); ++i) { // appclusters, 5.2.4.40: user should already be associated with given credential diff --git a/src/app/tests/suites/DL_UsersAndCredentials.yaml b/src/app/tests/suites/DL_UsersAndCredentials.yaml index 5030145412..6edbef1d64 100644 --- a/src/app/tests/suites/DL_UsersAndCredentials.yaml +++ b/src/app/tests/suites/DL_UsersAndCredentials.yaml @@ -18,6 +18,18 @@ config: nodeId: 0x12344321 cluster: "Door Lock" endpoint: 1 + payload: + type: char_string + defaultValue: "MT:-24J0AFN00KA0648G00" + discriminator: + type: int16u + defaultValue: 3840 + waitAfterCommissioning: + type: int16u + defaultValue: 1000 + PakeVerifier: + type: octet_string + defaultValue: "hex:b96170aae803346884724fe9a3b287c30330c2a660375d17bb205a8cf1aecb350457f8ab79ee253ab6a8e46bb09e543ae422736de501e3db37d441fe344920d09548e4c18240630c4ff4913c53513839b7c07fcc0627a1b8573a149fcd1fa466cf" tests: - label: "Wait for the commissioned device to be retrieved" @@ -64,6 +76,57 @@ tests: saveAs: NumberOfTotalUsersSupportedValue value: 10 + # + # Commission to second fabric to facilitate testing SetCredential/SetUser fabric restrictions + # + - label: "Open Commissioning Window from alpha" + endpoint: 0 + cluster: "Administrator Commissioning" + command: "OpenCommissioningWindow" + timedInteractionTimeoutMs: 10000 + arguments: + values: + - name: "CommissioningTimeout" + value: 180 + - name: "PAKEPasscodeVerifier" + value: PakeVerifier + - name: "Discriminator" + value: discriminator + - name: "Iterations" + value: 1000 + - name: "Salt" + value: "SPAKE2P Key Salt" + + - label: "Waiting after opening commissioning window" + cluster: "DelayCommands" + command: "WaitForMs" + arguments: + values: + - name: "ms" + value: waitAfterCommissioning + + - label: "Commission from TH2" + identity: "beta" + endpoint: 0 + cluster: "CommissionerCommands" + command: "PairWithCode" + arguments: + values: + - name: "nodeId" + value: nodeId + - name: "payload" + value: payload + + - label: "Wait for the commissioned device to be retrieved for TH2" + endpoint: 0 + identity: beta + cluster: "DelayCommands" + command: "WaitForCommissionee" + arguments: + values: + - name: "nodeId" + value: nodeId + - label: "Read fails for user with index 0" command: "GetUser" arguments: @@ -448,6 +511,136 @@ tests: - name: "NextUserIndex" value: null + - label: + "Modify UserStatus, UserType, CredentialRule for existing user from + different fabric" + command: "SetUser" + identity: "beta" + timedInteractionTimeoutMs: 10000 + arguments: + values: + - name: "OperationType" + value: 2 + - name: "UserIndex" + value: 1 + - name: "UserName" + value: null + - name: "UserUniqueID" + value: null + - name: "UserStatus" + value: 3 + - name: "UserType" + value: 6 + - name: "CredentialRule" + value: 2 + + - label: "Read the modified user back and verify its fields" + command: "GetUser" + arguments: + values: + - name: "UserIndex" + value: 1 + response: + values: + - name: "UserIndex" + value: 1 + - name: "UserName" + value: "test_user" + - name: "UserUniqueID" + value: 0x1BCDA0A0 + - name: "UserStatus" + value: 3 + - name: "UserType" + value: 6 + - name: "CredentialRule" + value: 2 + - name: "Credentials" + value: [] + - name: "CreatorFabricIndex" + value: 1 + - name: "LastModifiedFabricIndex" + value: 2 + - name: "NextUserIndex" + value: null + + - label: + "Attempt to modify UserName for existing user from different fabric" + command: "SetUser" + identity: "beta" + timedInteractionTimeoutMs: 10000 + arguments: + values: + - name: "OperationType" + value: 2 + - name: "UserIndex" + value: 1 + - name: "UserName" + value: "test_fab2" + - name: "UserUniqueID" + value: null + - name: "UserStatus" + value: null + - name: "UserType" + value: null + - name: "CredentialRule" + value: null + response: + error: INVALID_COMMAND + + - label: + "Attempt to modify userUniqueId for existing user from different + fabric" + command: "SetUser" + identity: "beta" + timedInteractionTimeoutMs: 10000 + arguments: + values: + - name: "OperationType" + value: 2 + - name: "UserIndex" + value: 1 + - name: "UserName" + value: null + - name: "UserUniqueID" + value: 0x1234ABCD + - name: "UserStatus" + value: null + - name: "UserType" + value: null + - name: "CredentialRule" + value: null + response: + error: INVALID_COMMAND + + - label: "Read the modified user back and verify its fields" + command: "GetUser" + arguments: + values: + - name: "UserIndex" + value: 1 + response: + values: + - name: "UserIndex" + value: 1 + - name: "UserName" + value: "test_user" + - name: "UserUniqueID" + value: 0x1BCDA0A0 + - name: "UserStatus" + value: 3 + - name: "UserType" + value: 6 + - name: "CredentialRule" + value: 2 + - name: "Credentials" + value: [] + - name: "CreatorFabricIndex" + value: 1 + - name: "LastModifiedFabricIndex" + value: 2 + - name: "NextUserIndex" + value: null + - label: "Add another user with non-default fields" command: "SetUser" timedInteractionTimeoutMs: 10000 @@ -1327,6 +1520,83 @@ tests: - name: "NextCredentialIndex" value: 2 + - label: + "Attempt to create new RFID credential from different fabric and add + it to existing user" + command: "SetCredential" + identity: "beta" + timedInteractionTimeoutMs: 10000 + arguments: + values: + - name: "OperationType" + value: 0 + - name: "Credential" + value: { CredentialType: 2, CredentialIndex: 1 } + - name: "CredentialData" + value: "rfid_data_123456" + - name: "UserIndex" + value: 1 + - name: "UserStatus" + value: null + - name: "UserType" + value: null + response: + values: + - name: "Status" + value: 0x85 + - name: "UserIndex" + value: null + - name: "NextCredentialIndex" + value: 2 + + - label: "Verify user has not been modified" + command: "GetUser" + arguments: + values: + - name: "UserIndex" + value: 1 + response: + values: + - name: "UserIndex" + value: 1 + - name: "UserName" + value: "" + - name: "UserUniqueID" + value: null + - name: "UserStatus" + value: 1 + - name: "UserType" + value: 0 + - name: "CredentialRule" + value: 0 + - name: "Credentials" + value: [{ CredentialType: 1, CredentialIndex: 1 }] + - name: "CreatorFabricIndex" + value: 1 + - name: "LastModifiedFabricIndex" + value: 1 + - name: "NextUserIndex" + value: null + + - label: "Verify no credential has been created" + command: "GetCredentialStatus" + arguments: + values: + - name: "Credential" + value: { CredentialType: 2, CredentialIndex: 1 } + response: + values: + - name: "CredentialExists" + value: false + - name: "UserIndex" + value: null + - name: "CreatorFabricIndex" + value: null + - name: "LastModifiedFabricIndex" + value: null + - name: "NextCredentialIndex" + value: null + - label: "Create new RFID credential and add it to existing user" command: "SetCredential" timedInteractionTimeoutMs: 10000 @@ -1405,6 +1675,63 @@ tests: - name: "NextCredentialIndex" value: null + - label: + "Attempt to modify credentialData of existing RFID credential from + different fabric" + command: "SetCredential" + identity: "beta" + timedInteractionTimeoutMs: 10000 + arguments: + values: + - name: "OperationType" + value: 2 + - name: "Credential" + value: { CredentialType: 2, CredentialIndex: 1 } + - name: "CredentialData" + value: "rfid_data_654321" + - name: "UserIndex" + value: 1 + - name: "UserStatus" + value: null + - name: "UserType" + value: null + response: + values: + - name: "Status" + value: 0x85 + - name: "UserIndex" + value: null + - name: "NextCredentialIndex" + value: 2 + + - label: + "Verify that credential was not changed by attempting to create new + credential with unmodified data" + command: "SetCredential" + timedInteractionTimeoutMs: 10000 + arguments: + values: + - name: "OperationType" + value: 0 + - name: "Credential" + value: { CredentialType: 2, CredentialIndex: 2 } + - name: "CredentialData" + value: "rfid_data_123456" + - name: "UserIndex" + value: null + - name: "UserStatus" + value: null + - name: "UserType" + value: null + response: + values: + - name: "Status" + value: 0x02 + - name: "UserIndex" + value: null + - name: "NextCredentialIndex" + value: 3 + - label: "Create new RFID credential and user with index 0 fails" command: "SetCredential" timedInteractionTimeoutMs: 10000 @@ -2054,10 +2381,10 @@ tests: - label: "Make sure a LockUserChange event was generated" command: "readEvent" event: "LockUserChange" - # I wish there were a way to not hardcode this 25, but it's experimentally - # determined: doing a read without an eventNumber filter here shows 24 + # I wish there were a way to not hardcode this 27, but it's experimentally + # determined: doing a read without an eventNumber filter here shows 26 # LockUserChange events before this removal. - eventNumber: 25 + eventNumber: 27 response: value: { From 5e37f1efdded50a0d926947d1381d70ccf26389d Mon Sep 17 00:00:00 2001 From: Marius Tache <102153746+marius-alex-tache@users.noreply.github.com> Date: Thu, 15 Aug 2024 17:25:33 +0300 Subject: [PATCH 052/165] [NXP][k32w1] Rework reference apps (#34926) * [NXP][platform][common] Update pw RPC flag in streamer_nxp Signed-off-by: marius-alex-tache (cherry picked from commit 4ae033a1bddd5d914e862791c111eebca41a62e8) * [NXP][examples][common] Fix binding issue due to generated Zap flag renaming Signed-off-by: Martin Girardot (cherry picked from commit b50b382478138ad02103e55194b0145b1e61e841) * [NXP][examples][common] make-pretty update (cherry picked from commit efc51cc65471f4f5f667947ef18a4656e1d29578) * [NXP][examples][common] Fix contact-sensor-app always returning empty diagnostic logs The LogProvider class method GetSizeForIntent() was always returning zero as log size due to an incorrect evaluation of the result of the SyncGetValue() call. GetSizeForIntent() is evaluating the size of the diagnostic log by trying to read the key using a zero length buffer. This action will return the size of the key in storage, but it will also yield a CHIP_ERROR_BUFFER_TOO_SMALL error code. GetSizeForIntent() however was not expecting this error code and it was returning zero in all situations when the status returned by SyncGetValue() was anything else but CHIP_NO_ERROR. The function was updated to take into account that, under these circumstances, the SyncGetValue() function always returns CHIP_ERROR_BUFFER_TOO_SMALL. Signed-off-by: Marian Chereji Reviewed-by: Doru-Cristian Gucea (cherry picked from commit dd3b3b784318f73cf6f0390f79d1fdf0160169d3) * [NXP][examples][common] Call init using the base class reference Signed-off-by: marius-alex-tache (cherry picked from commit b7a0a0a4d88bd5d03b70f36b34c2475b614bd296) * [NXP][examples][common] Update app task common code New task base API: - PostEventsProcessedAction - this will be called in the main loop, after all events have been processed. An example of concrete action is to animate some LEDs. - PrintOnboardingInfo - the default implementation remains the same. It can be overwritten by the concrete application task class. - AppMatter_DisallowDeviceToSleep/AppMatter_AllowDeviceToSleep - An application that uses low power mode should overwrite the API to implement the allow/disallow entering low power mechanism. Before taking the OT mutex, the device is disallowed to enter low power. The device is allowed to enter low power after the OT mutex is released. Other changes: - The app event queue handle should be static such that the concrete application task can initialize it during Start() call. - The ticksToWait passed to xQueueReceived is used to specify the maximum amount of time the task should block waiting for an event. This can be modified according to the application needs, e.g. is needed by an application that has LED animation. - PostEvent should take into account ISR context when populating the event queue. - PostEvent becomes a static method. - Thread device type is specified by the following flag: CONFIG_THREAD_DEVICE_TYPE This is set by default to kThreadDeviceType_Router. Signed-off-by: marius-alex-tache (cherry picked from commit d88e78ea6c973eb736915110bb227ad3515eec98) * [NXP][examples][common] Add additional common components - Add led widget component - Add diagnostic logs component - chip::NXP::App::DiagnosticLogsDemo::DisplayUsage should be implemeneted to showcase how the diagnostic logs provider should be used. - Add low power component - chip::NXP::App::LowPower::Init should be implemented according to the application needs. A default example is implemented, which registers an empty enter/exit low power callback. - Add operational keystore component - the API contains two functions: - GetInstance - should return the address of a concrete operational keystore class - Init - can be used to register a persistent storage delegate in case the concrete class is using persistent storage (which will be our case) - Add user interface feedback component - this component defines an abstract interface that can be implemented by applications in order to provide some kind of feedback to the user in certain conditions: logging, LED animations, etc. Add example of lighting manager, which uses LED animation for user feedback. - Add clusters component - add an API for identify related callbacks. Add implementation for common MatterPostAttributeChangeCallback, which delegates the work to the device manager component. - Add RPC component - this is a simple Init API that can be used to initialize PW RPC related components, such as UART. Signed-off-by: marius-alex-tache (cherry picked from commit 46a1d3d673b9cae14d33c749e3741727449e6ff9) * [NXP][examples][common] Add missing header in Identify Signed-off-by: marius-alex-tache (cherry picked from commit 3abfee2c6eea327ae931a150733ac83639d157d5) * [NXP][examples][common] Add multi-image OTA requestor initiator Signed-off-by: marius-alex-tache (cherry picked from commit 5848e4d4e2d384c4bfe41714bd41e25c4b1ba1e8) * [NXP][examples][common] Update pw RPC implementation Update AppRpc API by adding two new methods used by the common RPC implementation: - ButtonHandler - Reboot Signed-off-by: marius-alex-tache (cherry picked from commit 5e40934145825c61444e43e479ed7ac5c26605a4) * [NXP][examples][common] Small updates to common app code - Add call to feedback manager init. - Remove PostEventsProcessedAction. Call FeedbackMgr().DisplayInLoop() directly in the main loop. - Move PostEvent in AppTaskBase interface and make it virtual. - Add demo of diagnostic logs usage. - Update PrintOnboardingInfo to take into account user action requried commissioning flow. - Remove usage of deprecated sFunction from Lighting manager. - Add LowPower::Init call. - If FSL_OSA_TASK_ENABLE is used, then call AppTaskMain inside Start, instead of creating the app task. - Add PrintCurrentVersion API to print the software version string and software version. - Enclose DeviceInfoProviderImpl usage based on CONFIG_DEVICE_INFO_PROVIDER_IMPL - Add diagnostic logs cluster init under the corresponding flag. Signed-off-by: marius-alex-tache (cherry picked from commit 1619c92380275dc0466f9cf9dc9e818671406b06) * [NXP][examples][common] Make Animate pure virtual Signed-off-by: marius-alex-tache (cherry picked from commit eaf3789fc2d1e562fe030acc758e5f322b5f02d3) * [NXP][examples][common] Add pw RPC init RPC_TASK_STACK_SIZE and RPC_TASK_PRIORITY can now be defined in the build system to override the default values. Signed-off-by: marius-alex-tache (cherry picked from commit 7962d612b14502dc3f514c5c3d39891b086cfd63) * [NXP][examples][common] Allow platforms to redefine the path to the FactoryDataProvider.h that needs to be included Signed-off-by: Dina Benamar (cherry picked from commit 097cd999c4767572f8cc55fac18f93ac3cb5d50c) * [NXP][examples][common] Add TestEventTriggerDelegate * TestEventTriggerDelegate is now used at Server Initialization to add the ICDManager instance as Handler Signed-off-by: Andrei Menzopol (cherry picked from commit edce1dc967130589e74cdd9c8289719171141178) * [NXP][examples][common] Minor updates for some components The KVS wear stats are stored in the user diagnostic log key hence only initialize this key if the KVS wear stats are not enabled. Signed-off-by: Marian Chereji [nxp noup][examples][common] Remove UpdateState API The interface can be simplified by calling RestoreState instead of UpdateState when needed. This implies that the caller must update the cluster attribute by itself. Signed-off-by: marius-alex-tache [nxp noup][examples][common] Rename LightingManager to LedManager Signed-off-by: marius-alex-tache * [NXP][examples][common] Add initial version of lighting app - Copy lighting app sources to common folder - Add device callbacks - Use common OTA support - Use common app factory data - Use led widgets for lighting app - Use common app task and button management - Decouple lighting manager from app task - Update LED status function - Update lighting manager related flags Flags: - LIGHTING_MANAGER_ENABLE_DIMMABLE_LED to enable dimmable LED feature - LIGHTING_MANAGER_ENABLE_STATUS_LED to enable status LED usage These flags can be overwritten in AppConfig.h. - Make lighting manager more configurable - Create button manager The ButtonManager class should define the buttons callbacks and all callback delegates. Moved AppMatterButton_registerButtons implementation inside the button manager source file. - Update lighting manager interface - Replace lighting manager calls with feedback manager LightingManager now implements the UserFeedbackInterface abstract class and the dimmable feature was moved to a new class: LightingManagerDimmable. - Move identify code in a separate file - Remove deprecated #include statements from all files. - Add commissioning complete state A boolean static member is added to AppTask. It is set when the kCommissioningComplete event is received. It should be used by other components if they need a way to check the state of the device. - Add button action to switch to ICD active mode - Add support for BooleanState in device callbacks - Add diagnostic logs usage demo - Enclose feedback manager calls in CONFIG_ENABLE_FEEDBACK flag This flag should be defined whenever the application must provide some kind of user interface feedback, such as LED animation. In case of low power, this flag will not be defined. - Remove unused features (e.g. diagnostic logs) - Overwrite event queue and ticks to wait - Call PlatformMgrImpl API for PreInitMatterStack actions - Replace PW_RPC_ENABLED with CONFIG_ENABLE_PW_RPC Signed-off-by: marius-alex-tache (cherry picked from commit bed6655227d44900279cbd0ef547771da9143895) * [NXP][examples][common] Add initial version of contact sensor Signed-off-by: marius-alex-tache (cherry picked from commit 637580aa6c63048ae1a956807c284165c2af17ed) * [NXP][openthread][k32w1] Update mbedtls target Signed-off-by: marius-alex-tache (cherry picked from commit 3c84b1fd3987958bc0dcf49a283c281e48b400f8) * [NXP][platform][k32w] OTA/FactoryData changes * Add FactoryDataDriver interface which handles factory data update functionality and factory data ram backup operations; must be implemented for each platform * Make FactoryDataProvider global instances * Move Restore mechanism and plain-text SignWithDacKey in common FactoryDataProvider * Adapt Validate and SearchForId to use factory data config which stores size, start, payload * Move OTAFactoryDataProcessor in common folder * Adapt to be generic and use FactoryDataDriver functions instead Signed-off-by: Andrei Menzopol (cherry picked from commit 3a81c2367013c2a2ed08ecbbeac89ce15943998e) * [NXP][platform][k32w1] SDK 2.15 platform updates * remove RNG_SetPseudoRandomNoSeed call to accomodate new RNG API changes. * add SDK root, SDK release, and SDK 2.15 gn arguments. They will be used to differentiate between SDK versions (2.12 vs 2.15) and release status (repo vs packages). Signed-off-by: Andrei Menzopol [nxp noup][platform][k32w] Small fixes for k32w platform code * correct typos * remove executable access permissions * remove unused files * change openthread_root to ot-nxp/openthread-k32w1 * use nxp_mbedtls gn target Signed-off-by: Andrei Menzopol (cherry picked from commit 1905c1cea645506f8a88e514c2eacecea81ac385) * [NXP][platform][k32w1] Add "chip_key_storage" solution selector and littlefs support Updated the K32W1 platform build files by adding the "chip_key_storage" selector which will help developers select an implementation option for the key storage between "littlefs" and "fwk_nvm". Signed-off-by: Marian Chereji [nxp noup][k32w1] Temporarily disable OpenThread settings save-on-idle when using LittleFS key storage When using LittleFS key storage, the OpenThread settings save-on-idle feature requires additional support in the application idle task, which is not yet available. In order for the OT settings saving to work at this stage and in this configuration, the save-on-idle feature must be disabled until the required idle task support will be implemented. Signed-off-by: Marian Chereji [nxp noup][platform][k32w1] Fix minimum data chunk size required when programming the flash memory According to the specifications, the internal flash memory of the K32W1 platform supports programming chunks of memory which are 128 bytes long (instead of 256). Signed-off-by: Marian Chereji [nxp noup][platform][k32w1] Increase LittleFS cache size to 1K to suppress frequent data synchronizations A small cache size forces LittleFS to perform frequent data synchronizations with the storage (flash memory) and this consumes a number of data blocks which are not available in the K32W1 Matter applications. To reduce the fast consumption of flash memory data blocks, the LittleFS cache size was increased to 1KB. Signed-off-by: Marian Chereji (cherry picked from commit 753f7d7390661bd5dbd29cc9cfa7d3a4e4728ba2) * [NXP][platform][k32w1] Add Zephyr NVS based key storage build option Added a new build option (chip_key_storage="nvs") which allows the developers to use the Zephyr NVS file system as a key storage solution. Signed-off-by: Marian Chereji (cherry picked from commit 1d42e48d8f50f6e9999b49025ea3d71545e89a3d) * [NXP][examples][k32w1] App updates * the sdk root was moved to platform args. * update readme files * Add CONNECTIVITY_MANAGER_THREAD_DEVICE_TYPE define. * Set define accordingly based on FTD/MTD configuration. * Solve issue when lighting-app is MTD but device type is set to Router because it was hardcoded. * Remove deprecated files * Move some headers in examples/platform for common usage Signed-off-by: Andrei Menzopol (cherry picked from commit c2b626df132e058ce674df0ee20965b3029c462d) * [NXP][examples][k32w1] Update ZclCallbacks after transition to common code Signed-off-by: marius-alex-tache * [NXP][k32w1] Remove k32w parent folder Signed-off-by: marius-alex-tache * [NXP][platform][k32w1] Add FactoryDataDriver implementation Signed-off-by: marius-alex-tache * [NXP][platform][k32w] Remove k32w/common This folder was moved to nxp/common/legacy area. Signed-off-by: marius-alex-tache (cherry picked from commit 755081c71bde287e2d065e5fd9b1a0922c3b341a) * [NXP][scripts] Minor updates for NXP related scripts Add HWParams APP FactoryData support * Add proper format for HWParameters app factory data section * Put changes under new argument Signed-off-by: Andrei Menzopol [nxp noup][scripts][common] Fix Crc16 attribute when using latest version Signed-off-by: marius-alex-tache [nxp noup][scripts] Update structure k32w1 path All k32w1 folders were moved under nxp, removing the k32w parent. Signed-off-by: marius-alex-tache [nxp noup][scripts][ota] Update paths after k32w transition Signed-off-by: marius-alex-tache (cherry picked from commit 4963ce98725b74e94f498f959d46edf4933fa56c) * [NXP][platform][common] Add nxp_factory_data, nxp_ota gn targets The application can use these targets to integrate the default, platform-specific NXP factory data provider and OTA implementation. Each platform should define an "nxp_factory_data" and "nxp_ota" source sets. Usage: deps += [ "${chip_root}/src/platform/nxp:nxp_factory_data" ] deps += [ "${chip_root}/src/platform/nxp:nxp_ota" ] Signed-off-by: marius-alex-tache (cherry picked from commit 4869c4a97134692fe87a59b9b69d33f836d9b2e9) * [NXP][platform][common] Create NXPConfigNVS.cpp file, remove NXPConfig BLE dependencies Signed-off-by: Martin Girardot (cherry picked from commit 50e14e4a1b9f8561126310e19ebbaf72ca7bbdbe) * [NXP] revert mcxw71 headers Signed-off-by: marius-alex-tache * [NXP][k32w1] Add default logging target Signed-off-by: marius-alex-tache * [NXP][k32w1] Update paths to reference nxp_matter_support Signed-off-by: marius-alex-tache * [NXP] Bump nxp_matter_support Signed-off-by: marius-alex-tache * Restyled by whitespace * Restyled by clang-format * Restyled by gn * Restyled by prettier-markdown * Restyled by autopep8 * Restyled by isort * [NXP][k32w1] Fix gn import order Signed-off-by: marius-alex-tache * [NXP][k32w1] Fix wrong README reference Signed-off-by: marius-alex-tache * [NXP][k32w1] Update workflow docker image Signed-off-by: marius-alex-tache * [NXP][rw61x] Adding nxp_ota and nxp_factory_data as they are now mandatory Signed-off-by: Gatien Chapon * [NXP][platform][common] Fix build warning (cherry picked from commit 72b1cbaaf36fe6cf2af57a8c7ad3cc457b45c713) * Restyled by gn * [NXP][platform] Remove deprecated files Signed-off-by: marius-alex-tache * [NXP][workflow] Create separate jobs for k32w0/k32w1 k32w0 builds use chip-build-k32w Docker image, but k32w1 builds use chip-build-nxp Docker image. Signed-off-by: marius-alex-tache * [NXP][k32w0] Adding nxp_ota and nxp_factory_data as they are now mandatory Signed-off-by: marius-alex-tache * [NXP][scripts] Fix script issue when there is no --args Signed-off-by: Martin Girardot * [NXP][k32w1] Disable SMU2 Signed-off-by: marius-alex-tache --------- Signed-off-by: marius-alex-tache Signed-off-by: Gatien Chapon Signed-off-by: Martin Girardot Co-authored-by: Martin Girardot Co-authored-by: Dina Benamar Co-authored-by: Marian Chereji Co-authored-by: Andrei Menzopol Co-authored-by: Restyled.io Co-authored-by: Gatien Chapon Co-authored-by: Yassine El Aissaoui --- .github/workflows/examples-nxp.yaml | 64 +- .../contact-sensor-app/nxp/common/AppTask.cpp | 53 + .../nxp/common/DeviceCallbacks.cpp | 69 + .../nxp/common/ZclCallbacks.cpp | 38 + .../nxp/common/include/AppEvent.h | 18 +- .../nxp/common/include/AppTask.h | 50 + .../nxp/common/include/DeviceCallbacks.h | 51 + .../contact-sensor-app/nxp/common/main.cpp | 39 + .../nxp/k32w/k32w1/BUILD.gn | 186 --- .../nxp/k32w/k32w1/build_overrides | 1 - .../nxp/k32w/k32w1/main/AppTask.cpp | 908 ----------- .../k32w/k32w1/main/ContactSensorManager.cpp | 84 - .../nxp/k32w/k32w1/main/ZclCallbacks.cpp | 113 -- .../nxp/k32w/k32w1/main/include/AppEvent.h | 63 - .../nxp/k32w/k32w1/main/include/AppTask.h | 144 -- .../k32w1/main/include/ContactSensorManager.h | 66 - .../nxp/k32w/k32w1/main/include/app_config.h | 52 - .../nxp/k32w/k32w1/main/main.cpp | 143 -- .../k32w/k32w1/third_party/connectedhomeip | 1 - .../nxp/{k32w => }/k32w1/.gn | 2 +- .../contact-sensor-app/nxp/k32w1/BUILD.gn | 261 +++ .../nxp/{k32w => }/k32w1/README.md | 132 +- .../nxp/{k32w => }/k32w1/args.gni | 7 +- .../nxp/k32w1/build_overrides | 1 + .../nxp/k32w1/include/config/AppConfig.h | 29 + .../include/config}/CHIPProjectConfig.h | 7 + .../nxp/k32w1/third_party/connectedhomeip | 1 + examples/lighting-app/nxp/common/AppTask.cpp | 37 + .../DeviceCallbacks.cpp} | 55 +- .../nxp/common/include/AppEvent.h | 19 +- .../lighting-app/nxp/common/include/AppTask.h | 46 + .../nxp/common/include/DeviceCallbacks.h | 51 + examples/lighting-app/nxp/common/main.cpp | 39 + examples/lighting-app/nxp/k32w/k32w1/BUILD.gn | 196 --- .../nxp/k32w/k32w1/build_overrides | 1 - .../nxp/k32w/k32w1/include/FreeRTOSConfig.h | 181 --- .../nxp/k32w/k32w1/main/AppTask.cpp | 932 ----------- .../nxp/k32w/k32w1/main/LightingManager.cpp | 121 -- .../nxp/k32w/k32w1/main/include/AppEvent.h | 57 - .../nxp/k32w/k32w1/main/include/AppTask.h | 126 -- .../k32w/k32w1/main/include/LightingManager.h | 74 - .../nxp/k32w/k32w1/main/include/app_config.h | 49 - .../lighting-app/nxp/k32w/k32w1/main/main.cpp | 156 -- .../k32w/k32w1/third_party/connectedhomeip | 1 - .../lighting-app/nxp/{k32w => }/k32w1/.gn | 2 +- examples/lighting-app/nxp/k32w1/BUILD.gn | 268 +++ .../nxp/{k32w => }/k32w1/README.md | 159 +- .../nxp/{k32w => }/k32w1/args.gni | 11 +- .../lighting-app/nxp/k32w1/build_overrides | 1 + .../nxp/k32w1/include/config/AppConfig.h | 29 + .../include/config}/CHIPProjectConfig.h | 0 .../nxp/k32w1/third_party/connectedhomeip | 1 + .../nxp/{k32w => }/k32w1/with_pw_rpc.gni | 18 +- examples/platform/nxp/Rpc.cpp | 12 +- .../nxp/common/app_task/include/AppTaskBase.h | 49 +- .../common/app_task/include/AppTaskFreeRTOS.h | 24 +- .../common/app_task/include/AppTaskZephyr.h | 12 +- .../common/app_task/source/AppTaskBase.cpp | 127 +- .../app_task/source/AppTaskFreeRTOS.cpp | 75 +- .../nxp/common/clusters/include/Identify.h | 31 + .../common/clusters/source/ZclCallbacks.cpp | 52 + .../source/CommonDeviceCallbacks.cpp | 1 - .../include/DiagnosticLogsDemo.h | 31 + .../DiagnosticLogsProviderDelegateImpl.h | 0 .../source/DiagnosticLogsDemo.cpp | 47 + .../DiagnosticLogsProviderDelegateImpl.cpp | 2 +- .../source/AppFactoryDataDefaultImpl.cpp | 7 +- .../nxp/common/led_widget/include/LedDimmer.h | 37 + .../nxp/common/led_widget/include/LedOnOff.h | 47 + .../led_widget/include/LedWidgetInterface.h} | 43 +- .../nxp/common/low_power/include/LowPower.h | 32 + .../nxp/common/low_power/source/LowPower.cpp | 48 + .../include/OperationalKeystore.h | 41 + .../source/OperationalKeystoreEmpty.cpp | 31 + .../OTARequestorInitiatorMultiImage.cpp | 43 + .../platform/nxp/common/rpc/include/AppRpc.h | 56 + .../common/ui_feedback/include/LedManager.h | 91 ++ .../include/UserInterfaceFeedback.h | 72 + .../common/ui_feedback/source/LedManager.cpp | 150 ++ examples/platform/nxp/k32w/k32w1/BUILD.gn | 35 - examples/platform/nxp/k32w/k32w1/app/BUILD.gn | 27 - examples/platform/nxp/k32w/k32w1/app/args.gni | 28 - examples/platform/nxp/k32w/k32w1/args.gni | 38 - .../k32w1/app/ldscripts/k32w1_app.ld | 0 .../freeRTOS}/FreeRTOSConfig.h | 5 - .../openthread}/OpenThreadConfig.h | 0 .../nxp/{k32w => }/k32w1/app/support/BUILD.gn | 16 +- .../k32w1/app/support/FreeRtosHooks.c | 8 +- .../k32w1/app/support/FreeRtosHooks.h | 0 .../k32w1/app/support/Memconfig.cpp | 0 .../platform/nxp/k32w1/board/peripherals.c | 66 + .../platform/nxp/k32w1/board/peripherals.h | 101 ++ .../nxp/k32w1/button/ButtonManager.cpp | 215 +++ .../platform/nxp/k32w1/button/ButtonManager.h | 108 ++ .../platform/nxp/k32w1/clusters/Identify.cpp | 123 ++ .../k32w1/doc/images/debug_k32w1.jpg | Bin .../k32w1/doc/images/import_demo.jpg | Bin .../k32w1/doc/images/installed_sdks.jpg | Bin .../{k32w => }/k32w1/doc/images/k32w1-evk.jpg | Bin .../k32w1/doc/images/mcux-sdk-download.jpg | Bin .../k32w1/doc/images/new_project.jpg | Bin .../k32w1/doc/images/ota_topology.JPG | Bin .../source/AppFactoryDataExample.cpp | 76 + .../OperationalKeystore.cpp | 34 + .../LED_Dimmer.h => k32w1/ota/OtaUtils.cpp} | 11 +- examples/platform/nxp/k32w1/rpc/AppRpc.cpp | 75 + .../util/LedDimmer.cpp} | 18 +- .../LEDWidget.cpp => k32w1/util/LedOnOff.cpp} | 70 +- .../k32w1/util/LightingManagerDimmable.cpp | 79 + .../nxp/k32w1/util/LightingManagerDimmable.h | 85 + examples/platform/nxp/pw_rpc_server.gni | 1 + scripts/build/builders/nxp.py | 5 +- .../nxp/factory_data_generator/generate.py | 12 + scripts/tools/nxp/ota/README.md | 2 +- src/lib/shell/streamer_nxp.cpp | 4 +- src/platform/nxp/BUILD.gn | 17 +- src/platform/nxp/common/NXPConfig.cpp | 3 +- src/platform/nxp/common/NXPConfig.h | 3 +- src/platform/nxp/common/NXPConfigKS.cpp | 3 +- src/platform/nxp/common/NXPConfigNVS.cpp | 347 ++++ .../nxp/k32w/common/BLEManagerCommon.cpp | 1435 ----------------- .../nxp/k32w/common/BLEManagerCommon.h | 249 --- .../CHIPDevicePlatformRamStorageConfig.h | 173 -- .../nxp/k32w/common/FactoryDataProvider.cpp | 368 ----- .../nxp/k32w/common/FactoryDataProvider.h | 151 -- .../nxp/k32w/common/K32W_OTA_README.md | 149 -- .../nxp/k32w/common/OTAImageProcessorImpl.cpp | 424 ----- .../nxp/k32w/common/OTAImageProcessorImpl.h | 114 -- .../nxp/k32w/common/OTATlvProcessor.cpp | 178 -- .../nxp/k32w/common/OTATlvProcessor.h | 180 --- src/platform/nxp/k32w/k32w1/BUILD.gn | 153 -- .../k32w/k32w1/SoftwareUpdateManagerImpl.cpp | 46 - .../k32w/k32w1/SoftwareUpdateManagerImpl.h | 89 - src/platform/nxp/k32w0/BUILD.gn | 5 + .../nxp/{k32w => }/k32w1/BLEManagerImpl.cpp | 3 +- .../nxp/{k32w => }/k32w1/BLEManagerImpl.h | 2 +- src/platform/nxp/k32w1/BUILD.gn | 211 +++ .../nxp/{k32w => }/k32w1/BlePlatformConfig.h | 0 .../{k32w => }/k32w1/CHIPCryptoPalK32W1.cpp | 0 .../k32w1/CHIPDevicePlatformConfig.h | 10 + .../k32w1/CHIPDevicePlatformEvent.h | 0 .../nxp/{k32w => }/k32w1/CHIPPlatformConfig.h | 0 .../k32w1/ConfigurationManagerImpl.cpp | 51 +- .../k32w1/ConfigurationManagerImpl.h | 8 +- .../k32w1/ConnectivityManagerImpl.cpp | 0 .../k32w1/ConnectivityManagerImpl.h | 0 .../k32w1/DiagnosticDataProviderImpl.cpp | 2 +- .../k32w1/DiagnosticDataProviderImpl.h | 0 .../nxp/k32w1/FactoryDataDriverImpl.cpp | 147 ++ .../nxp/k32w1/FactoryDataDriverImpl.h | 59 + .../k32w1/FactoryDataProviderImpl.cpp | 206 ++- .../k32w1/FactoryDataProviderImpl.h | 29 +- .../nxp/{k32w => }/k32w1/InetPlatformConfig.h | 0 .../nxp/{k32w => }/k32w1/K32W1Config.cpp | 46 +- .../nxp/{k32w => }/k32w1/K32W1Config.h | 2 +- .../K32W1PersistentStorageOpKeystore.cpp | 0 .../k32w1/K32W1PersistentStorageOpKeystore.h | 0 .../k32w1/KeyValueStoreManagerImpl.cpp | 26 +- .../k32w1/KeyValueStoreManagerImpl.h | 0 src/platform/nxp/{k32w => }/k32w1/Logging.cpp | 6 +- .../nxp/{k32w => }/k32w1/LowPowerHooks.cpp | 0 .../{k32w => }/k32w1/OTAFirmwareProcessor.cpp | 4 +- .../{k32w => }/k32w1/OTAFirmwareProcessor.h | 2 +- .../nxp/{k32w => }/k32w1/OTAHooks.cpp | 19 +- .../{k32w => }/k32w1/PlatformManagerImpl.cpp | 39 +- .../{k32w => }/k32w1/PlatformManagerImpl.h | 4 +- .../nxp/{k32w => }/k32w1/SMU2Manager.cpp | 1 + .../nxp/{k32w => }/k32w1/SMU2Manager.h | 0 .../{k32w => }/k32w1/SystemPlatformConfig.h | 0 .../{k32w => }/k32w1/SystemTimeSupport.cpp | 0 .../k32w1/ThreadStackManagerImpl.cpp | 14 +- .../{k32w => }/k32w1/ThreadStackManagerImpl.h | 0 src/platform/nxp/{k32w => }/k32w1/args.gni | 27 +- .../nxp/{k32w => }/k32w1/ble_function_mux.c | 0 .../nxp/{k32w => }/k32w1/ble_function_mux.h | 0 src/platform/nxp/{k32w => }/k32w1/gatt_db.h | 0 .../nxp/{k32w => }/k32w1/gatt_uuid128.h | 0 .../k32w1/k32w1-chip-mbedtls-config.h | 0 .../nxp/{k32w => }/k32w1/ram_storage.c | 0 .../nxp/{k32w => }/k32w1/ram_storage.h | 0 src/platform/nxp/rt/rw61x/BUILD.gn | 5 + third_party/nxp/nxp_matter_support | 2 +- .../platforms/nxp/{k32w => }/k32w1/BUILD.gn | 39 +- 183 files changed, 4708 insertions(+), 7959 deletions(-) create mode 100644 examples/contact-sensor-app/nxp/common/AppTask.cpp create mode 100644 examples/contact-sensor-app/nxp/common/DeviceCallbacks.cpp create mode 100644 examples/contact-sensor-app/nxp/common/ZclCallbacks.cpp rename src/platform/nxp/k32w/k32w1/DefaultTestEventTriggerDelegate.cpp => examples/contact-sensor-app/nxp/common/include/AppEvent.h (62%) create mode 100644 examples/contact-sensor-app/nxp/common/include/AppTask.h create mode 100644 examples/contact-sensor-app/nxp/common/include/DeviceCallbacks.h create mode 100644 examples/contact-sensor-app/nxp/common/main.cpp delete mode 100644 examples/contact-sensor-app/nxp/k32w/k32w1/BUILD.gn delete mode 120000 examples/contact-sensor-app/nxp/k32w/k32w1/build_overrides delete mode 100644 examples/contact-sensor-app/nxp/k32w/k32w1/main/AppTask.cpp delete mode 100644 examples/contact-sensor-app/nxp/k32w/k32w1/main/ContactSensorManager.cpp delete mode 100644 examples/contact-sensor-app/nxp/k32w/k32w1/main/ZclCallbacks.cpp delete mode 100644 examples/contact-sensor-app/nxp/k32w/k32w1/main/include/AppEvent.h delete mode 100644 examples/contact-sensor-app/nxp/k32w/k32w1/main/include/AppTask.h delete mode 100644 examples/contact-sensor-app/nxp/k32w/k32w1/main/include/ContactSensorManager.h delete mode 100644 examples/contact-sensor-app/nxp/k32w/k32w1/main/include/app_config.h delete mode 100644 examples/contact-sensor-app/nxp/k32w/k32w1/main/main.cpp delete mode 120000 examples/contact-sensor-app/nxp/k32w/k32w1/third_party/connectedhomeip rename examples/contact-sensor-app/nxp/{k32w => }/k32w1/.gn (93%) create mode 100644 examples/contact-sensor-app/nxp/k32w1/BUILD.gn rename examples/contact-sensor-app/nxp/{k32w => }/k32w1/README.md (83%) rename examples/contact-sensor-app/nxp/{k32w => }/k32w1/args.gni (84%) create mode 120000 examples/contact-sensor-app/nxp/k32w1/build_overrides create mode 100644 examples/contact-sensor-app/nxp/k32w1/include/config/AppConfig.h rename examples/contact-sensor-app/nxp/{k32w/k32w1/include => k32w1/include/config}/CHIPProjectConfig.h (98%) create mode 120000 examples/contact-sensor-app/nxp/k32w1/third_party/connectedhomeip create mode 100644 examples/lighting-app/nxp/common/AppTask.cpp rename examples/lighting-app/nxp/{k32w/k32w1/main/ZclCallbacks.cpp => common/DeviceCallbacks.cpp} (51%) rename src/platform/nxp/k32w/k32w1/DefaultTestEventTriggerDelegate.h => examples/lighting-app/nxp/common/include/AppEvent.h (60%) create mode 100644 examples/lighting-app/nxp/common/include/AppTask.h create mode 100644 examples/lighting-app/nxp/common/include/DeviceCallbacks.h create mode 100644 examples/lighting-app/nxp/common/main.cpp delete mode 100644 examples/lighting-app/nxp/k32w/k32w1/BUILD.gn delete mode 120000 examples/lighting-app/nxp/k32w/k32w1/build_overrides delete mode 100644 examples/lighting-app/nxp/k32w/k32w1/include/FreeRTOSConfig.h delete mode 100644 examples/lighting-app/nxp/k32w/k32w1/main/AppTask.cpp delete mode 100644 examples/lighting-app/nxp/k32w/k32w1/main/LightingManager.cpp delete mode 100644 examples/lighting-app/nxp/k32w/k32w1/main/include/AppEvent.h delete mode 100644 examples/lighting-app/nxp/k32w/k32w1/main/include/AppTask.h delete mode 100644 examples/lighting-app/nxp/k32w/k32w1/main/include/LightingManager.h delete mode 100644 examples/lighting-app/nxp/k32w/k32w1/main/include/app_config.h delete mode 100644 examples/lighting-app/nxp/k32w/k32w1/main/main.cpp delete mode 120000 examples/lighting-app/nxp/k32w/k32w1/third_party/connectedhomeip rename examples/lighting-app/nxp/{k32w => }/k32w1/.gn (93%) create mode 100644 examples/lighting-app/nxp/k32w1/BUILD.gn rename examples/lighting-app/nxp/{k32w => }/k32w1/README.md (80%) rename examples/lighting-app/nxp/{k32w => }/k32w1/args.gni (74%) create mode 120000 examples/lighting-app/nxp/k32w1/build_overrides create mode 100644 examples/lighting-app/nxp/k32w1/include/config/AppConfig.h rename examples/lighting-app/nxp/{k32w/k32w1/include => k32w1/include/config}/CHIPProjectConfig.h (100%) create mode 120000 examples/lighting-app/nxp/k32w1/third_party/connectedhomeip rename examples/lighting-app/nxp/{k32w => }/k32w1/with_pw_rpc.gni (84%) create mode 100644 examples/platform/nxp/common/clusters/include/Identify.h create mode 100644 examples/platform/nxp/common/clusters/source/ZclCallbacks.cpp create mode 100644 examples/platform/nxp/common/diagnostic_logs/include/DiagnosticLogsDemo.h rename examples/platform/nxp/common/diagnostic_logs/{ => include}/DiagnosticLogsProviderDelegateImpl.h (100%) create mode 100644 examples/platform/nxp/common/diagnostic_logs/source/DiagnosticLogsDemo.cpp rename examples/platform/nxp/common/diagnostic_logs/{ => source}/DiagnosticLogsProviderDelegateImpl.cpp (98%) create mode 100644 examples/platform/nxp/common/led_widget/include/LedDimmer.h create mode 100644 examples/platform/nxp/common/led_widget/include/LedOnOff.h rename examples/platform/nxp/{k32w/k32w1/util/include/LEDWidget.h => common/led_widget/include/LedWidgetInterface.h} (55%) create mode 100644 examples/platform/nxp/common/low_power/include/LowPower.h create mode 100644 examples/platform/nxp/common/low_power/source/LowPower.cpp create mode 100644 examples/platform/nxp/common/operational_keystore/include/OperationalKeystore.h create mode 100644 examples/platform/nxp/common/operational_keystore/source/OperationalKeystoreEmpty.cpp create mode 100644 examples/platform/nxp/common/ota_requestor/source/OTARequestorInitiatorMultiImage.cpp create mode 100644 examples/platform/nxp/common/rpc/include/AppRpc.h create mode 100644 examples/platform/nxp/common/ui_feedback/include/LedManager.h create mode 100644 examples/platform/nxp/common/ui_feedback/include/UserInterfaceFeedback.h create mode 100644 examples/platform/nxp/common/ui_feedback/source/LedManager.cpp delete mode 100644 examples/platform/nxp/k32w/k32w1/BUILD.gn delete mode 100644 examples/platform/nxp/k32w/k32w1/app/BUILD.gn delete mode 100644 examples/platform/nxp/k32w/k32w1/app/args.gni delete mode 100644 examples/platform/nxp/k32w/k32w1/args.gni rename examples/platform/nxp/{k32w => }/k32w1/app/ldscripts/k32w1_app.ld (100%) rename examples/{contact-sensor-app/nxp/k32w/k32w1/include => platform/nxp/k32w1/app/project_include/freeRTOS}/FreeRTOSConfig.h (97%) rename examples/platform/nxp/{k32w/k32w1/app/project_include => k32w1/app/project_include/openthread}/OpenThreadConfig.h (100%) rename examples/platform/nxp/{k32w => }/k32w1/app/support/BUILD.gn (78%) rename examples/platform/nxp/{k32w => }/k32w1/app/support/FreeRtosHooks.c (96%) rename examples/platform/nxp/{k32w => }/k32w1/app/support/FreeRtosHooks.h (100%) rename examples/platform/nxp/{k32w => }/k32w1/app/support/Memconfig.cpp (100%) create mode 100644 examples/platform/nxp/k32w1/board/peripherals.c create mode 100644 examples/platform/nxp/k32w1/board/peripherals.h create mode 100644 examples/platform/nxp/k32w1/button/ButtonManager.cpp create mode 100644 examples/platform/nxp/k32w1/button/ButtonManager.h create mode 100644 examples/platform/nxp/k32w1/clusters/Identify.cpp rename examples/platform/nxp/{k32w => }/k32w1/doc/images/debug_k32w1.jpg (100%) rename examples/platform/nxp/{k32w => }/k32w1/doc/images/import_demo.jpg (100%) rename examples/platform/nxp/{k32w => }/k32w1/doc/images/installed_sdks.jpg (100%) rename examples/platform/nxp/{k32w => }/k32w1/doc/images/k32w1-evk.jpg (100%) rename examples/platform/nxp/{k32w => }/k32w1/doc/images/mcux-sdk-download.jpg (100%) rename examples/platform/nxp/{k32w => }/k32w1/doc/images/new_project.jpg (100%) rename examples/platform/nxp/{k32w => }/k32w1/doc/images/ota_topology.JPG (100%) create mode 100644 examples/platform/nxp/k32w1/factory_data/source/AppFactoryDataExample.cpp create mode 100644 examples/platform/nxp/k32w1/operational_keystore/OperationalKeystore.cpp rename examples/platform/nxp/{k32w/k32w1/util/include/LED_Dimmer.h => k32w1/ota/OtaUtils.cpp} (81%) create mode 100644 examples/platform/nxp/k32w1/rpc/AppRpc.cpp rename examples/platform/nxp/{k32w/k32w1/util/LED_Dimmer.cpp => k32w1/util/LedDimmer.cpp} (97%) rename examples/platform/nxp/{k32w/k32w1/util/LEDWidget.cpp => k32w1/util/LedOnOff.cpp} (53%) create mode 100644 examples/platform/nxp/k32w1/util/LightingManagerDimmable.cpp create mode 100644 examples/platform/nxp/k32w1/util/LightingManagerDimmable.h create mode 100644 src/platform/nxp/common/NXPConfigNVS.cpp delete mode 100644 src/platform/nxp/k32w/common/BLEManagerCommon.cpp delete mode 100644 src/platform/nxp/k32w/common/BLEManagerCommon.h delete mode 100644 src/platform/nxp/k32w/common/CHIPDevicePlatformRamStorageConfig.h delete mode 100644 src/platform/nxp/k32w/common/FactoryDataProvider.cpp delete mode 100644 src/platform/nxp/k32w/common/FactoryDataProvider.h delete mode 100644 src/platform/nxp/k32w/common/K32W_OTA_README.md delete mode 100644 src/platform/nxp/k32w/common/OTAImageProcessorImpl.cpp delete mode 100644 src/platform/nxp/k32w/common/OTAImageProcessorImpl.h delete mode 100644 src/platform/nxp/k32w/common/OTATlvProcessor.cpp delete mode 100644 src/platform/nxp/k32w/common/OTATlvProcessor.h delete mode 100644 src/platform/nxp/k32w/k32w1/BUILD.gn delete mode 100644 src/platform/nxp/k32w/k32w1/SoftwareUpdateManagerImpl.cpp delete mode 100644 src/platform/nxp/k32w/k32w1/SoftwareUpdateManagerImpl.h rename src/platform/nxp/{k32w => }/k32w1/BLEManagerImpl.cpp (97%) rename src/platform/nxp/{k32w => }/k32w1/BLEManagerImpl.h (97%) create mode 100644 src/platform/nxp/k32w1/BUILD.gn rename src/platform/nxp/{k32w => }/k32w1/BlePlatformConfig.h (100%) rename src/platform/nxp/{k32w => }/k32w1/CHIPCryptoPalK32W1.cpp (100%) rename src/platform/nxp/{k32w => }/k32w1/CHIPDevicePlatformConfig.h (94%) rename src/platform/nxp/{k32w => }/k32w1/CHIPDevicePlatformEvent.h (100%) rename src/platform/nxp/{k32w => }/k32w1/CHIPPlatformConfig.h (100%) rename src/platform/nxp/{k32w => }/k32w1/ConfigurationManagerImpl.cpp (80%) rename src/platform/nxp/{k32w => }/k32w1/ConfigurationManagerImpl.h (95%) rename src/platform/nxp/{k32w => }/k32w1/ConnectivityManagerImpl.cpp (100%) rename src/platform/nxp/{k32w => }/k32w1/ConnectivityManagerImpl.h (100%) rename src/platform/nxp/{k32w => }/k32w1/DiagnosticDataProviderImpl.cpp (99%) rename src/platform/nxp/{k32w => }/k32w1/DiagnosticDataProviderImpl.h (100%) create mode 100644 src/platform/nxp/k32w1/FactoryDataDriverImpl.cpp create mode 100644 src/platform/nxp/k32w1/FactoryDataDriverImpl.h rename src/platform/nxp/{k32w => }/k32w1/FactoryDataProviderImpl.cpp (70%) rename src/platform/nxp/{k32w => }/k32w1/FactoryDataProviderImpl.h (81%) rename src/platform/nxp/{k32w => }/k32w1/InetPlatformConfig.h (100%) rename src/platform/nxp/{k32w => }/k32w1/K32W1Config.cpp (87%) rename src/platform/nxp/{k32w => }/k32w1/K32W1Config.h (99%) rename src/platform/nxp/{k32w => }/k32w1/K32W1PersistentStorageOpKeystore.cpp (100%) rename src/platform/nxp/{k32w => }/k32w1/K32W1PersistentStorageOpKeystore.h (100%) rename src/platform/nxp/{k32w => }/k32w1/KeyValueStoreManagerImpl.cpp (85%) rename src/platform/nxp/{k32w => }/k32w1/KeyValueStoreManagerImpl.h (100%) rename src/platform/nxp/{k32w => }/k32w1/Logging.cpp (98%) rename src/platform/nxp/{k32w => }/k32w1/LowPowerHooks.cpp (100%) rename src/platform/nxp/{k32w => }/k32w1/OTAFirmwareProcessor.cpp (96%) rename src/platform/nxp/{k32w => }/k32w1/OTAFirmwareProcessor.h (96%) rename src/platform/nxp/{k32w => }/k32w1/OTAHooks.cpp (82%) rename src/platform/nxp/{k32w => }/k32w1/PlatformManagerImpl.cpp (80%) rename src/platform/nxp/{k32w => }/k32w1/PlatformManagerImpl.h (96%) rename src/platform/nxp/{k32w => }/k32w1/SMU2Manager.cpp (99%) rename src/platform/nxp/{k32w => }/k32w1/SMU2Manager.h (100%) rename src/platform/nxp/{k32w => }/k32w1/SystemPlatformConfig.h (100%) rename src/platform/nxp/{k32w => }/k32w1/SystemTimeSupport.cpp (100%) rename src/platform/nxp/{k32w => }/k32w1/ThreadStackManagerImpl.cpp (90%) rename src/platform/nxp/{k32w => }/k32w1/ThreadStackManagerImpl.h (100%) rename src/platform/nxp/{k32w => }/k32w1/args.gni (72%) rename src/platform/nxp/{k32w => }/k32w1/ble_function_mux.c (100%) rename src/platform/nxp/{k32w => }/k32w1/ble_function_mux.h (100%) rename src/platform/nxp/{k32w => }/k32w1/gatt_db.h (100%) rename src/platform/nxp/{k32w => }/k32w1/gatt_uuid128.h (100%) rename src/platform/nxp/{k32w => }/k32w1/k32w1-chip-mbedtls-config.h (100%) rename src/platform/nxp/{k32w => }/k32w1/ram_storage.c (100%) rename src/platform/nxp/{k32w => }/k32w1/ram_storage.h (100%) rename third_party/openthread/platforms/nxp/{k32w => }/k32w1/BUILD.gn (73%) diff --git a/.github/workflows/examples-nxp.yaml b/.github/workflows/examples-nxp.yaml index 747813d6aa..975d9292a1 100644 --- a/.github/workflows/examples-nxp.yaml +++ b/.github/workflows/examples-nxp.yaml @@ -29,8 +29,8 @@ env: CHIP_NO_LOG_TIMESTAMPS: true jobs: - k32w: - name: K32W + k32w0: + name: K32W0 env: BUILD_TYPE: gn_k32w @@ -39,7 +39,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-k32w:66 + image: ghcr.io/project-chip/chip-build-k32w:71 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" steps: @@ -66,8 +66,6 @@ jobs: --target nxp-k32w0-freertos-contact-sensor \ --target nxp-k32w0-freertos-contact-sensor-low-power \ --target nxp-k32w0-freertos-contact-sensor-low-power-factory \ - --target nxp-k32w1-freertos-lighting \ - --target nxp-k32w1-freertos-contact-sensor-low-power \ build \ --copy-artifacts-to out/artifacts \ " @@ -77,16 +75,62 @@ jobs: nxp k32w0+release light \ out/artifacts/nxp-k32w0-freertos-lighting/chip-k32w0x-light-example.elf \ /tmp/bloat_reports/ - .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py \ - nxp k32w1+release light \ - out/artifacts/nxp-k32w1-freertos-lighting/chip-k32w1-light-example.elf \ - /tmp/bloat_reports/ - name: Get contact sensor size stats run: | .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py \ nxp k32w0+release contact \ out/artifacts/nxp-k32w0-freertos-contact-sensor-low-power/chip-k32w0x-contact-example.elf \ /tmp/bloat_reports/ + - name: Uploading Size Reports + uses: ./.github/actions/upload-size-reports + if: ${{ !env.ACT }} + with: + platform-name: K32W0 + k32w1: + name: K32W1 + + env: + BUILD_TYPE: gn_k32w + + runs-on: ubuntu-latest + if: github.actor != 'restyled-io[bot]' + + container: + image: ghcr.io/project-chip/chip-build-nxp:71 + volumes: + - "/tmp/bloat_reports:/tmp/bloat_reports" + steps: + - name: Checkout + uses: actions/checkout@v4 + - name: Checkout submodules & Bootstrap + uses: ./.github/actions/checkout-submodules-and-bootstrap + with: + platform: nxp + extra-submodule-parameters: --recursive + + - name: Set up environment for size reports + uses: ./.github/actions/setup-size-reports + if: ${{ !env.ACT }} + with: + gh-context: ${{ toJson(github) }} + + - name: Build examples + run: | + scripts/run_in_build_env.sh "\ + ./scripts/build/build_examples.py \ + --target nxp-k32w1-freertos-lighting \ + --target nxp-k32w1-freertos-contact-sensor-low-power \ + build \ + --copy-artifacts-to out/artifacts \ + " + - name: Get lighting app size stats + run: | + .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py \ + nxp k32w1+release light \ + out/artifacts/nxp-k32w1-freertos-lighting/chip-k32w1-light-example.elf \ + /tmp/bloat_reports/ + - name: Get contact sensor size stats + run: | .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py \ nxp k32w1+release contact \ out/artifacts/nxp-k32w1-freertos-contact-sensor-low-power/chip-k32w1-contact-example.elf \ @@ -95,7 +139,7 @@ jobs: uses: ./.github/actions/upload-size-reports if: ${{ !env.ACT }} with: - platform-name: K32W + platform-name: K32W1 rw61x: name: RW61X diff --git a/examples/contact-sensor-app/nxp/common/AppTask.cpp b/examples/contact-sensor-app/nxp/common/AppTask.cpp new file mode 100644 index 0000000000..f49c603cbb --- /dev/null +++ b/examples/contact-sensor-app/nxp/common/AppTask.cpp @@ -0,0 +1,53 @@ +/* + * + * 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 "AppTask.h" + +#if CONFIG_LOW_POWER +#include "PWR_Interface.h" +#endif + +#include + +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; + return sAppTask; +} + +chip::NXP::App::AppTaskBase & chip::NXP::App::GetAppTask() +{ + return ContactSensorApp::AppTask::GetDefaultInstance(); +} diff --git a/examples/contact-sensor-app/nxp/common/DeviceCallbacks.cpp b/examples/contact-sensor-app/nxp/common/DeviceCallbacks.cpp new file mode 100644 index 0000000000..8cd301d81f --- /dev/null +++ b/examples/contact-sensor-app/nxp/common/DeviceCallbacks.cpp @@ -0,0 +1,69 @@ +/* + * + * 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 "DeviceCallbacks.h" +#if CONFIG_ENABLE_FEEDBACK +#include "UserInterfaceFeedback.h" +#endif + +#include +#include +#include + +using namespace ::chip; +using namespace ::chip::app::Clusters; + +void logBooleanStateEvent(bool state) +{ + chip::EventNumber eventNumber; + chip::app::Clusters::BooleanState::Events::StateChange::Type event{ state }; + if (CHIP_NO_ERROR != chip::app::LogEvent(event, 1, eventNumber)) + { + ChipLogProgress(Zcl, "booleanstate: failed to reacord state-change event"); + } +} + +void ContactSensorApp::DeviceCallbacks::PostAttributeChangeCallback(chip::EndpointId endpoint, chip::ClusterId clusterId, + chip::AttributeId attributeId, uint8_t type, uint16_t size, + uint8_t * value) +{ + if (clusterId == BooleanState::Id) + { + if (attributeId != BooleanState::Attributes::StateValue::Id) + { + ChipLogProgress(Zcl, "Unknown attribute ID: " ChipLogFormatMEI, ChipLogValueMEI(attributeId)); + return; + } +#if CONFIG_ENABLE_FEEDBACK + FeedbackMgr().RestoreState(); +#endif + logBooleanStateEvent(static_cast(*value)); + } + else + { + ChipLogProgress(Zcl, "Unknown attribute ID: " ChipLogFormatMEI, ChipLogValueMEI(attributeId)); + } +} + +chip::DeviceManager::CHIPDeviceManagerCallbacks & chip::NXP::App::GetDeviceCallbacks() +{ + static ContactSensorApp::DeviceCallbacks sDeviceCallbacks; + return sDeviceCallbacks; +} diff --git a/examples/contact-sensor-app/nxp/common/ZclCallbacks.cpp b/examples/contact-sensor-app/nxp/common/ZclCallbacks.cpp new file mode 100644 index 0000000000..cbadc5510d --- /dev/null +++ b/examples/contact-sensor-app/nxp/common/ZclCallbacks.cpp @@ -0,0 +1,38 @@ +/* + * + * 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 + +#if CONFIG_ENABLE_FEEDBACK +#include "UserInterfaceFeedback.h" +#endif + +/** @brief BooleanState Cluster Init + * + * This function is called when a specific cluster is initialized. It gives the + * application an opportunity to take care of cluster initialization procedures. + * It is called exactly once for each endpoint where cluster is present. + */ +void emberAfBooleanStateClusterInitCallback(chip::EndpointId endpoint) +{ + ChipLogProgress(Zcl, "emberAfBooleanStateClusterInitCallback\n"); +#if CONFIG_ENABLE_FEEDBACK + FeedbackMgr().RestoreState(); +#endif +} diff --git a/src/platform/nxp/k32w/k32w1/DefaultTestEventTriggerDelegate.cpp b/examples/contact-sensor-app/nxp/common/include/AppEvent.h similarity index 62% rename from src/platform/nxp/k32w/k32w1/DefaultTestEventTriggerDelegate.cpp rename to examples/contact-sensor-app/nxp/common/include/AppEvent.h index 69935bb024..b292afaddf 100644 --- a/src/platform/nxp/k32w/k32w1/DefaultTestEventTriggerDelegate.cpp +++ b/examples/contact-sensor-app/nxp/common/include/AppEvent.h @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2022 Project CHIP Authors + * Copyright (c) 2024 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -16,16 +16,12 @@ * limitations under the License. */ -#include "DefaultTestEventTriggerDelegate.h" +#pragma once -#include -#include +struct AppEvent; +typedef void (*EventHandler)(const AppEvent &); -namespace chip { - -bool DefaultTestEventTriggerDelegate::DoesEnableKeyMatch(const ByteSpan & enableKey) const +struct AppEvent { - return !mEnableKey.empty() && mEnableKey.data_equal(enableKey); -} - -} // namespace chip + EventHandler Handler; +}; diff --git a/examples/contact-sensor-app/nxp/common/include/AppTask.h b/examples/contact-sensor-app/nxp/common/include/AppTask.h new file mode 100644 index 0000000000..69b3ffc820 --- /dev/null +++ b/examples/contact-sensor-app/nxp/common/include/AppTask.h @@ -0,0 +1,50 @@ +/* + * + * 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 "AppConfig.h" +#include "AppTaskFreeRTOS.h" + +#include + +namespace ContactSensorApp { + +class AppTask : public chip::NXP::App::AppTaskFreeRTOS +{ +public: + // 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(); +}; + +} // namespace ContactSensorApp + +/** + * Returns the application-specific implementation of the AppTaskBase object. + * + * Applications can use this to gain access to features of the AppTaskBase + * that are specific to the selected application. + */ +chip::NXP::App::AppTaskBase & GetAppTask(); diff --git a/examples/contact-sensor-app/nxp/common/include/DeviceCallbacks.h b/examples/contact-sensor-app/nxp/common/include/DeviceCallbacks.h new file mode 100644 index 0000000000..7234c2b8c7 --- /dev/null +++ b/examples/contact-sensor-app/nxp/common/include/DeviceCallbacks.h @@ -0,0 +1,51 @@ +/* + * + * 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. + */ + +/** + * @file DeviceCallbacks.h + * + * Lighting app implementation for the DeviceManager callbacks for all applications + * + **/ + +#pragma once + +#include "CHIPDeviceManager.h" +#include "CommonDeviceCallbacks.h" + +namespace ContactSensorApp { + +class DeviceCallbacks : public chip::NXP::App::CommonDeviceCallbacks +{ +public: + void PostAttributeChangeCallback(chip::EndpointId endpoint, chip::ClusterId clusterId, chip::AttributeId attributeId, + uint8_t type, uint16_t size, uint8_t * value) override; +}; + +} // namespace ContactSensorApp + +namespace chip::NXP::App { +/** + * Returns the application-specific implementation of the CommonDeviceCallbacks object. + * + * Applications can use this to gain access to features of the CommonDeviceCallbacks + * that are specific to the selected application. + */ +chip::DeviceManager::CHIPDeviceManagerCallbacks & GetDeviceCallbacks(); + +} // namespace chip::NXP::App diff --git a/examples/contact-sensor-app/nxp/common/main.cpp b/examples/contact-sensor-app/nxp/common/main.cpp new file mode 100644 index 0000000000..d9672b5402 --- /dev/null +++ b/examples/contact-sensor-app/nxp/common/main.cpp @@ -0,0 +1,39 @@ +/* + * + * 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 "AppTask.h" +#include "FreeRTOS.h" + +#if configAPPLICATION_ALLOCATED_HEAP +uint8_t __attribute__((section(".heap"))) ucHeap[configTOTAL_HEAP_SIZE]; +#endif + +#if FSL_OSA_MAIN_FUNC_ENABLE +extern "C" void main_task(void const * argument) +{ + chip::DeviceLayer::PlatformMgrImpl().HardwareInit(); + chip::NXP::App::GetAppTask().Start(); +} +#else +extern "C" int main(int argc, char * argv[]) +{ + chip::DeviceLayer::PlatformMgrImpl().HardwareInit(); + chip::NXP::App::GetAppTask().Start(); + vTaskStartScheduler(); +} +#endif diff --git a/examples/contact-sensor-app/nxp/k32w/k32w1/BUILD.gn b/examples/contact-sensor-app/nxp/k32w/k32w1/BUILD.gn deleted file mode 100644 index f4ccc1ec4d..0000000000 --- a/examples/contact-sensor-app/nxp/k32w/k32w1/BUILD.gn +++ /dev/null @@ -1,186 +0,0 @@ -# Copyright (c) 2021-2023 Project CHIP Authors -# Copyright (c) 2023 NXP -# -# 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/nxp_sdk.gni") -import("//build_overrides/openthread.gni") - -import("${nxp_sdk_build_root}/nxp_sdk.gni") - -import("${nxp_sdk_build_root}/${nxp_sdk_name}/nxp_executable.gni") - -import("${nxp_sdk_build_root}/${nxp_sdk_name}/${nxp_sdk_name}.gni") - -import("${chip_root}/src/app/icd/icd.gni") -import("${chip_root}/src/crypto/crypto.gni") -import("${chip_root}/src/lib/core/core.gni") -import("${chip_root}/src/platform/device.gni") -import("${chip_root}/src/platform/nxp/${nxp_platform}/args.gni") - -declare_args() { - chip_software_version = 0 - - # Setup discriminator as argument - setup_discriminator = 3840 - chip_with_diag_logs_demo = true -} - -assert(current_os == "freertos") - -common_example_dir = "${chip_root}/examples/platform/nxp/common" -k32w1_platform_dir = "${chip_root}/examples/platform/nxp/k32w/k32w1" -k32w1_sdk_root = getenv("NXP_K32W1_SDK_ROOT") - -k32w1_sdk("sdk") { - sources = [ - "${k32w1_platform_dir}/app/project_include/OpenThreadConfig.h", - "include/CHIPProjectConfig.h", - "include/FreeRTOSConfig.h", - "main/include/app_config.h", - ] - - public_deps = - [ "${chip_root}/third_party/openthread/platforms:libopenthread-platform" ] - - include_dirs = [ - "main/include", - "main", - "include", - "${k32w1_platform_dir}/app/project_include", - "${k32w1_platform_dir}/app/support", - "${k32w1_platform_dir}/util/include", - ] - - defines = [] - if (is_debug) { - defines += [ "BUILD_RELEASE=0" ] - } else { - defines += [ "BUILD_RELEASE=1" ] - } - - if (chip_software_version != 0) { - defines += [ - "CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION=${chip_software_version}", - ] - } - - defines += [ - "CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR=${setup_discriminator}", - ] - - if (chip_with_diag_logs_demo) { - defines += [ "CONFIG_DIAG_LOGS_DEMO=1" ] - } -} - -k32w1_executable("contact_sensor_app") { - output_name = "chip-k32w1-contact-example" - - defines = [] - - sources = [ - "${k32w1_platform_dir}/util/LEDWidget.cpp", - "${k32w1_platform_dir}/util/include/LEDWidget.h", - "main/AppTask.cpp", - "main/ContactSensorManager.cpp", - "main/ZclCallbacks.cpp", - "main/include/AppEvent.h", - "main/include/AppTask.h", - "main/include/ContactSensorManager.h", - "main/main.cpp", - ] - - include_dirs = [ "${common_example_dir}/diagnostic_logs" ] - - deps = [ - ":sdk", - "${chip_root}/examples/common/QRCode", - "${chip_root}/examples/providers:device_info_provider", - "${chip_root}/src/lib", - "${chip_root}/src/platform:syscalls_stub", - "${chip_root}/src/platform/logging:default", - "${chip_root}/third_party/mbedtls:mbedtls", - "${k32w1_platform_dir}/app/support:freertos_mbedtls_utils", - ] - - #lit and sit are using different zap files - if (chip_enable_icd_lit) { - deps += [ "${chip_root}/examples/contact-sensor-app/nxp/zap-lit/" ] - - defines += [ "CHIP_ENABLE_LIT=1" ] - } else { - deps += [ "${chip_root}/examples/contact-sensor-app/nxp/zap-sit/" ] - } - - if (chip_openthread_ftd) { - deps += [ - "${openthread_root}:libopenthread-cli-ftd", - "${openthread_root}:libopenthread-ftd", - ] - } else { - deps += [ - "${openthread_root}:libopenthread-cli-mtd", - "${openthread_root}:libopenthread-mtd", - ] - } - - #lit and sit are using different zap files - if (chip_enable_icd_lit) { - deps += [ "${chip_root}/examples/contact-sensor-app/nxp/zap-lit/" ] - - defines += [ "CHIP_ENABLE_LIT=1" ] - } else { - deps += [ "${chip_root}/examples/contact-sensor-app/nxp/zap-sit/" ] - } - - cflags = [ "-Wconversion" ] - - output_dir = root_out_dir - - ldscript = "${k32w1_sdk_root}/middleware/wireless/framework/Common/devices/kw45_k32w1/gcc/connectivity.ld" - - inputs = [ ldscript ] - - ldflags = [ - "-Wl,--defsym=__heap_size__=0", - "-Wl,--defsym=__stack_size__=0x480", - "-Wl,--defsym=lp_ram_lower_limit=0x04000000", - "-Wl,--defsym=lp_ram_upper_limit=0x2001C000", - "-Wl,-print-memory-usage", - "-Wl,--no-warn-rwx-segments", - "-T" + rebase_path(ldscript, root_build_dir), - ] - - if (chip_with_factory_data == 1) { - ldflags += [ "-Wl,--defsym=gUseFactoryData_d=1" ] - } - - if (chip_with_diag_logs_demo) { - sources += [ - "${common_example_dir}/diagnostic_logs/DiagnosticLogsProviderDelegateImpl.cpp", - "${common_example_dir}/diagnostic_logs/DiagnosticLogsProviderDelegateImpl.h", - ] - } - - output_dir = root_out_dir -} - -group("k32w1") { - deps = [ ":contact_sensor_app" ] -} - -group("default") { - deps = [ ":k32w1" ] -} diff --git a/examples/contact-sensor-app/nxp/k32w/k32w1/build_overrides b/examples/contact-sensor-app/nxp/k32w/k32w1/build_overrides deleted file mode 120000 index ad07557834..0000000000 --- a/examples/contact-sensor-app/nxp/k32w/k32w1/build_overrides +++ /dev/null @@ -1 +0,0 @@ -../../../../build_overrides/ \ No newline at end of file diff --git a/examples/contact-sensor-app/nxp/k32w/k32w1/main/AppTask.cpp b/examples/contact-sensor-app/nxp/k32w/k32w1/main/AppTask.cpp deleted file mode 100644 index 6f0459178c..0000000000 --- a/examples/contact-sensor-app/nxp/k32w/k32w1/main/AppTask.cpp +++ /dev/null @@ -1,908 +0,0 @@ -/* - * - * Copyright (c) 2022-2023 Project CHIP Authors - * Copyright (c) 2022 Google LLC. - * Copyright (c) 2023 NXP - * 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 "AppTask.h" -#include "AppEvent.h" -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#if CONFIG_DIAG_LOGS_DEMO -#include "DiagnosticLogsProviderDelegateImpl.h" -#endif - -#include -#include -#include -#include - -/* OTA related includes */ -#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR -#include "OtaSupport.h" -#include -#include -#include -#include -#include -#endif - -#include - -#include "K32W1PersistentStorageOpKeystore.h" - -#include "LEDWidget.h" -#include "app.h" -#include "app_config.h" -#include "fsl_component_button.h" -#include "fwk_platform.h" - -#define FACTORY_RESET_TRIGGER_TIMEOUT 6000 -#define FACTORY_RESET_CANCEL_WINDOW_TIMEOUT 3000 -#define APP_TASK_PRIORITY 2 -#define APP_EVENT_QUEUE_SIZE 10 - -TimerHandle_t sFunctionTimer; // FreeRTOS app sw timer. - -static QueueHandle_t sAppEventQueue; - -#if !defined(chip_with_low_power) || (chip_with_low_power == 0) -/* - * The status LED and the external flash CS pin are wired together. - * The OTA image writing may fail if used together. - */ -#ifndef CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR -static LEDWidget sStatusLED; -#endif -static LEDWidget sContactSensorLED; -#endif - -static bool sIsThreadProvisioned = false; -static bool sHaveBLEConnections = false; -#if CHIP_ENABLE_LIT -static bool sIsDeviceCommissioned = false; -#endif - -static uint32_t eventMask = 0; - -#if CHIP_DEVICE_CONFIG_THREAD_ENABLE_CLI -extern "C" void otPlatUartProcess(void); -#endif - -extern "C" void PWR_DisallowDeviceToSleep(void); -extern "C" void PWR_AllowDeviceToSleep(void); - -using namespace ::chip::Credentials; -using namespace ::chip::DeviceLayer; -using namespace chip; -using namespace chip::app; -#if CONFIG_DIAG_LOGS_DEMO -using namespace chip::app::Clusters::DiagnosticLogs; -#endif - -AppTask AppTask::sAppTask; -#if CONFIG_CHIP_LOAD_REAL_FACTORY_DATA -static AppTask::FactoryDataProvider sFactoryDataProvider; -#endif - -static Identify gIdentify = { chip::EndpointId{ 1 }, AppTask::OnIdentifyStart, AppTask::OnIdentifyStop, - Clusters::Identify::IdentifyTypeEnum::kVisibleIndicator }; - -/* OTA related variables */ -#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR -static DefaultOTARequestor gRequestorCore __attribute__((section(".data"))); -static DefaultOTARequestorStorage gRequestorStorage __attribute__((section(".data"))); -static DeviceLayer::DefaultOTARequestorDriver gRequestorUser __attribute__((section(".data"))); -static BDXDownloader gDownloader __attribute__((section(".data"))); - -constexpr uint16_t requestedOtaBlockSize = 1024; -#endif - -static pm_notify_element_t appNotifyElement = { - .notifyCallback = AppTask::LowPowerCallback, - .data = NULL, -}; - -static void app_gap_callback(gapGenericEvent_t * event) -{ - /* This callback is called in the context of BLE task, so event processing - * should be posted to app task. */ -} - -static void app_gatt_callback(deviceId_t id, gattServerEvent_t * event) -{ - /* This callback is called in the context of BLE task, so event processing - * should be posted to app task. */ -} - -CHIP_ERROR AppTask::StartAppTask() -{ - CHIP_ERROR err = CHIP_NO_ERROR; - - sAppEventQueue = xQueueCreate(APP_EVENT_QUEUE_SIZE, sizeof(AppEvent)); - if (sAppEventQueue == NULL) - { - err = APP_ERROR_EVENT_QUEUE_FAILED; - K32W_LOG("Failed to allocate app event queue"); - assert(err == CHIP_NO_ERROR); - } - - return err; -} - -CHIP_ERROR AppTask::Init() -{ - CHIP_ERROR err = CHIP_NO_ERROR; - - if (ContactSensorMgr().Init() != 0) - { - K32W_LOG("ContactSensorMgr().Init() failed"); - assert(0); - } - - // Register enter/exit low power application callback. - status_t status = PM_RegisterNotify(kPM_NotifyGroup2, &appNotifyElement); - if (status != kStatus_Success) - { - K32W_LOG("Failed to register low power app callback.") - return APP_ERROR_PM_REGISTER_LP_CALLBACK_FAILED; - } - - PlatformMgr().AddEventHandler(MatterEventHandler, 0); - - // Init ZCL Data Model and start server - PlatformMgr().ScheduleWork(InitServer, 0); - -#if CONFIG_CHIP_LOAD_REAL_FACTORY_DATA - ReturnErrorOnFailure(sFactoryDataProvider.Init()); - SetDeviceInstanceInfoProvider(&sFactoryDataProvider); - SetDeviceAttestationCredentialsProvider(&sFactoryDataProvider); - SetCommissionableDataProvider(&sFactoryDataProvider); -#else - SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); -#endif // CONFIG_CHIP_LOAD_REAL_FACTORY_DATA - - // QR code will be used with CHIP Tool - AppTask::PrintOnboardingInfo(); - -#if !defined(chip_with_low_power) || (chip_with_low_power == 0) - /* start with all LEDS turnedd off */ -#ifndef CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR - sStatusLED.Init(SYSTEM_STATE_LED, false); -#endif - - sContactSensorLED.Init(CONTACT_SENSOR_STATE_LED, false); - sContactSensorLED.Set(ContactSensorMgr().IsContactClosed()); -#endif - - UpdateDeviceState(); - - /* intialize the Keyboard and button press callback */ - BUTTON_InstallCallback((button_handle_t) g_buttonHandle[0], KBD_Callback, (void *) BLE_BUTTON); - BUTTON_InstallCallback((button_handle_t) g_buttonHandle[1], KBD_Callback, (void *) CONTACT_SENSOR_BUTTON); - - // Create FreeRTOS sw timer for Function Selection. - sFunctionTimer = xTimerCreate("FnTmr", // Just a text name, not used by the RTOS kernel - 1, // == default timer period (mS) - false, // no timer reload (==one-shot) - (void *) this, // init timer id = app task obj context - TimerEventHandler // timer callback handler - ); - if (sFunctionTimer == NULL) - { - err = APP_ERROR_CREATE_TIMER_FAILED; - K32W_LOG("app_timer_create() failed"); - assert(err == CHIP_NO_ERROR); - } - - ContactSensorMgr().SetCallback(OnStateChanged); - - // Print the current software version - char currentSoftwareVer[ConfigurationManager::kMaxSoftwareVersionStringLength + 1] = { 0 }; - err = ConfigurationMgr().GetSoftwareVersionString(currentSoftwareVer, sizeof(currentSoftwareVer)); - if (err != CHIP_NO_ERROR) - { - K32W_LOG("Get version error"); - assert(err == CHIP_NO_ERROR); - } - - uint32_t currentVersion; - err = ConfigurationMgr().GetSoftwareVersion(currentVersion); - - K32W_LOG("Current Software Version: %s, %d", currentSoftwareVer, currentVersion); - - auto & bleManager = chip::DeviceLayer::Internal::BLEMgrImpl(); - bleManager.RegisterAppCallbacks(app_gap_callback, app_gatt_callback); - - return err; -} - -void LockOpenThreadTask(void) -{ - PWR_DisallowDeviceToSleep(); - chip::DeviceLayer::ThreadStackMgr().LockThreadStack(); -} - -void UnlockOpenThreadTask(void) -{ - chip::DeviceLayer::ThreadStackMgr().UnlockThreadStack(); - PWR_AllowDeviceToSleep(); -} - -void AppTask::InitServer(intptr_t arg) -{ - static chip::CommonCaseDeviceServerInitParams initParams; - (void) initParams.InitializeStaticResourcesBeforeServerInit(); - -#if CHIP_CRYPTO_PLATFORM - static chip::K32W1PersistentStorageOpKeystore sK32W1PersistentStorageOpKeystore; - VerifyOrDie((sK32W1PersistentStorageOpKeystore.Init(initParams.persistentStorageDelegate)) == CHIP_NO_ERROR); - initParams.operationalKeystore = &sK32W1PersistentStorageOpKeystore; -#endif - - // Init ZCL Data Model and start server - chip::Inet::EndPointStateOpenThread::OpenThreadEndpointInitParam nativeParams; - nativeParams.lockCb = LockOpenThreadTask; - nativeParams.unlockCb = UnlockOpenThreadTask; - nativeParams.openThreadInstancePtr = chip::DeviceLayer::ThreadStackMgrImpl().OTInstance(); - initParams.endpointNativeParams = static_cast(&nativeParams); - VerifyOrDie((chip::Server::GetInstance().Init(initParams)) == CHIP_NO_ERROR); - -#if CONFIG_DIAG_LOGS_DEMO - char diagLog[CHIP_DEVICE_CONFIG_MAX_DIAG_LOG_SIZE]; - uint16_t diagLogSize = CHIP_DEVICE_CONFIG_MAX_DIAG_LOG_SIZE; - - StorageKeyName keyUser = LogProvider::GetKeyDiagUserSupport(); - StorageKeyName keyNwk = LogProvider::GetKeyDiagNetwork(); - StorageKeyName keyCrash = LogProvider::GetKeyDiagCrashLog(); - - memset(diagLog, 0, diagLogSize); - Server::GetInstance().GetPersistentStorage().SyncSetKeyValue(keyUser.KeyName(), diagLog, diagLogSize); - - memset(diagLog, 1, diagLogSize); - Server::GetInstance().GetPersistentStorage().SyncSetKeyValue(keyNwk.KeyName(), diagLog, diagLogSize); - - memset(diagLog, 2, diagLogSize); - Server::GetInstance().GetPersistentStorage().SyncSetKeyValue(keyCrash.KeyName(), diagLog, diagLogSize); -#endif -} - -void AppTask::PrintOnboardingInfo() -{ - chip::PayloadContents payload; - CHIP_ERROR err = GetPayloadContents(payload, chip::RendezvousInformationFlags(chip::RendezvousInformationFlag::kBLE)); - if (err != CHIP_NO_ERROR) - { - ChipLogError(AppServer, "GetPayloadContents() failed: %" CHIP_ERROR_FORMAT, err.Format()); - } - payload.commissioningFlow = chip::CommissioningFlow::kUserActionRequired; - PrintOnboardingCodes(payload); -} - -#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR -void AppTask::InitOTA(intptr_t arg) -{ - // Initialize and interconnect the Requestor and Image Processor objects -- START - SetRequestorInstance(&gRequestorCore); - - gRequestorStorage.Init(chip::Server::GetInstance().GetPersistentStorage()); - gRequestorCore.Init(chip::Server::GetInstance(), gRequestorStorage, gRequestorUser, gDownloader); - gRequestorUser.SetMaxDownloadBlockSize(requestedOtaBlockSize); - auto & imageProcessor = OTAImageProcessorImpl::GetDefaultInstance(); - gRequestorUser.Init(&gRequestorCore, &imageProcessor); - CHIP_ERROR err = imageProcessor.Init(&gDownloader); - if (err != CHIP_NO_ERROR) - { - K32W_LOG("Image processor init failed"); - assert(err == CHIP_NO_ERROR); - } - - // Connect the gDownloader and Image Processor objects - gDownloader.SetImageProcessorDelegate(&imageProcessor); - // Initialize and interconnect the Requestor and Image Processor objects -- END -} -#endif - -void AppTask::AppTaskMain(void * pvParameter) -{ - AppEvent event; - - CHIP_ERROR err = sAppTask.Init(); - if (err != CHIP_NO_ERROR) - { - K32W_LOG("AppTask.Init() failed"); - assert(err == CHIP_NO_ERROR); - } - - while (true) - { - TickType_t xTicksToWait = pdMS_TO_TICKS(10); - -#if defined(chip_with_low_power) && (chip_with_low_power == 1) - xTicksToWait = portMAX_DELAY; -#endif - - BaseType_t eventReceived = xQueueReceive(sAppEventQueue, &event, xTicksToWait); - while (eventReceived == pdTRUE) - { - sAppTask.DispatchEvent(&event); - eventReceived = xQueueReceive(sAppEventQueue, &event, 0); - } - - // Collect connectivity and configuration state from the CHIP stack. Because the - // CHIP event loop is being run in a separate task, the stack must be locked - // while these values are queried. However we use a non-blocking lock request - // (TryLockChipStack()) to avoid blocking other UI activities when the CHIP - // task is busy (e.g. with a long crypto operation). - if (PlatformMgr().TryLockChipStack()) - { -#if CHIP_DEVICE_CONFIG_THREAD_ENABLE_CLI - otPlatUartProcess(); -#endif - - sHaveBLEConnections = (ConnectivityMgr().NumBLEConnections() != 0); - PlatformMgr().UnlockChipStack(); - } - - // Update the status LED if factory reset or identify process have not been initiated. - // - // If system has "full connectivity", keep the LED On constantly. - // - // If thread and service provisioned, but not attached to the thread network yet OR no - // connectivity to the service OR subscriptions are not fully established - // THEN blink the LED Off for a short period of time. - // - // If the system has ble connection(s) uptill the stage above, THEN blink the LEDs at an even - // rate of 100ms. - // - // Otherwise, blink the LED ON for a very short time. - -#if !defined(chip_with_low_power) || (chip_with_low_power == 0) -#ifndef CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR - if (sAppTask.mFunction != Function::kFactoryReset && sAppTask.mFunction != Function::kIdentify) - { - if (sIsThreadProvisioned) - { - sStatusLED.Blink(950, 50); - } - else if (sHaveBLEConnections) - { - sStatusLED.Blink(100, 100); - } - else - { - sStatusLED.Blink(50, 950); - } - } - - sStatusLED.Animate(); -#endif - - sContactSensorLED.Animate(); -#endif - } -} - -void AppTask::ButtonEventHandler(uint8_t pin_no, uint8_t button_action) -{ - if ((pin_no != RESET_BUTTON) && (pin_no != CONTACT_SENSOR_BUTTON) && (pin_no != SOFT_RESET_BUTTON) && (pin_no != BLE_BUTTON)) - { - return; - } - - AppEvent button_event; - button_event.Type = AppEvent::kButton; - button_event.ButtonEvent.PinNo = pin_no; - button_event.ButtonEvent.Action = button_action; - - if (pin_no == RESET_BUTTON) - { - button_event.Handler = ResetActionEventHandler; - } - else if (pin_no == CONTACT_SENSOR_BUTTON) - { - button_event.Handler = ContactActionEventHandler; - } - else if (pin_no == SOFT_RESET_BUTTON) - { - // Soft reset ensures that platform manager shutdown procedure is called. - button_event.Handler = SoftResetHandler; - } - else if (pin_no == BLE_BUTTON) - { - button_event.Handler = BleHandler; - - if (button_action == RESET_BUTTON_PUSH) - { - button_event.Handler = ResetActionEventHandler; - } -#if CHIP_ENABLE_LIT - else if (button_action == USER_ACTIVE_MODE_TRIGGER_PUSH) - { - button_event.Handler = UserActiveModeHandler; - } -#endif - } - - sAppTask.PostEvent(&button_event); -} - -button_status_t AppTask::KBD_Callback(void * buttonHandle, button_callback_message_t * message, void * callbackParam) -{ - uint32_t pinNb = (uint32_t) callbackParam; - switch (message->event) - { - case kBUTTON_EventOneClick: - case kBUTTON_EventShortPress: - switch (pinNb) - { - case BLE_BUTTON: - K32W_LOG("pb1 short press"); - if (sAppTask.mResetTimerActive) - { - ButtonEventHandler(BLE_BUTTON, RESET_BUTTON_PUSH); - } -#if CHIP_ENABLE_LIT - else if (sIsDeviceCommissioned) - { - ButtonEventHandler(BLE_BUTTON, USER_ACTIVE_MODE_TRIGGER_PUSH); - } -#endif - else - { - ButtonEventHandler(BLE_BUTTON, BLE_BUTTON_PUSH); - } - break; - - case CONTACT_SENSOR_BUTTON: - K32W_LOG("pb2 short press"); - ButtonEventHandler(CONTACT_SENSOR_BUTTON, CONTACT_SENSOR_BUTTON_PUSH); - break; - } - break; - - case kBUTTON_EventLongPress: - switch (pinNb) - { - case BLE_BUTTON: - K32W_LOG("pb1 long press"); - ButtonEventHandler(BLE_BUTTON, RESET_BUTTON_PUSH); - break; - - case CONTACT_SENSOR_BUTTON: - K32W_LOG("pb2 long press"); - ButtonEventHandler(SOFT_RESET_BUTTON, SOFT_RESET_BUTTON_PUSH); - break; - } - break; - - default: - /* No action required */ - break; - } - return kStatus_BUTTON_Success; -} - -void AppTask::TimerEventHandler(TimerHandle_t xTimer) -{ - AppEvent event; - event.Type = AppEvent::kTimer; - event.TimerEvent.Context = (void *) xTimer; - event.Handler = FunctionTimerEventHandler; - sAppTask.PostEvent(&event); -} - -void AppTask::FunctionTimerEventHandler(void * aGenericEvent) -{ - AppEvent * aEvent = (AppEvent *) aGenericEvent; - - if (aEvent->Type != AppEvent::kTimer) - return; - - K32W_LOG("Device will factory reset..."); - - // Actually trigger Factory Reset - chip::Server::GetInstance().ScheduleFactoryReset(); -} - -void AppTask::ResetActionEventHandler(void * aGenericEvent) -{ - AppEvent * aEvent = (AppEvent *) aGenericEvent; - - if (aEvent->ButtonEvent.PinNo != RESET_BUTTON && aEvent->ButtonEvent.PinNo != BLE_BUTTON) - return; - - if (sAppTask.mResetTimerActive) - { - sAppTask.CancelTimer(); - sAppTask.mFunction = Function::kNoneSelected; - -#if !defined(chip_with_low_power) || (chip_with_low_power == 0) - /* restore initial state for the LED indicating contact state */ - if (!ContactSensorMgr().IsContactClosed()) - { - sContactSensorLED.Set(false); - } - else - { - sContactSensorLED.Set(true); - } -#endif - - K32W_LOG("Factory Reset was cancelled!"); - } - else - { - uint32_t resetTimeout = FACTORY_RESET_TRIGGER_TIMEOUT; - - if (sAppTask.mFunction != Function::kNoneSelected) - { - K32W_LOG("Another function is scheduled. Could not initiate Factory Reset!"); - return; - } - - K32W_LOG("Factory Reset Triggered. Push the RESET button within %lu ms to cancel!", resetTimeout); - 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) -#ifndef CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR - sStatusLED.Set(false); - sStatusLED.Blink(500); -#endif - sContactSensorLED.Set(false); - sContactSensorLED.Blink(500); -#endif - - sAppTask.StartTimer(FACTORY_RESET_TRIGGER_TIMEOUT); - } -} - -void AppTask::ContactActionEventHandler(void * aGenericEvent) -{ - AppEvent * aEvent = (AppEvent *) aGenericEvent; - ContactSensorManager::Action action = ContactSensorManager::Action::kInvalid; - CHIP_ERROR err = CHIP_NO_ERROR; - bool state_changed = false; - - if (sAppTask.mFunction != Function::kNoneSelected) - { - K32W_LOG("Another function is scheduled. Could not change contact state."); - return; - } - - if (aEvent->Type == AppEvent::kContact) - { - action = static_cast(aEvent->ContactEvent.Action); - } - else if (aEvent->Type == AppEvent::kButton) - { - if (ContactSensorMgr().IsContactClosed()) - { - action = ContactSensorManager::Action::kSignalLost; - } - else - { - action = ContactSensorManager::Action::kSignalDetected; - } - - sAppTask.SetSyncClusterToButtonAction(true); - } - else - { - err = APP_ERROR_UNHANDLED_EVENT; - action = ContactSensorManager::Action::kInvalid; - } - - if (err == CHIP_NO_ERROR) - { - ContactSensorMgr().InitiateAction(action); - } -} - -void AppTask::SoftResetHandler(void * aGenericEvent) -{ - AppEvent * aEvent = (AppEvent *) aGenericEvent; - if (aEvent->ButtonEvent.PinNo != SOFT_RESET_BUTTON) - return; - - PlatformMgrImpl().CleanReset(); -} - -void AppTask::BleHandler(void * aGenericEvent) -{ - AppEvent * aEvent = (AppEvent *) aGenericEvent; - - if (aEvent->ButtonEvent.PinNo != BLE_BUTTON) - return; - - if (sAppTask.mFunction != Function::kNoneSelected) - { - K32W_LOG("Another function is scheduled. Could not toggle BLE state!"); - return; - } - PlatformMgr().ScheduleWork(AppTask::BleStartAdvertising, 0); -} - -void AppTask::BleStartAdvertising(intptr_t arg) -{ - if (ConnectivityMgr().IsBLEAdvertisingEnabled()) - { - ConnectivityMgr().SetBLEAdvertisingEnabled(false); - K32W_LOG("Stopped BLE Advertising!"); - } - else - { - ConnectivityMgr().SetBLEAdvertisingEnabled(true); - - if (chip::Server::GetInstance().GetCommissioningWindowManager().OpenBasicCommissioningWindow() == CHIP_NO_ERROR) - { - K32W_LOG("Started BLE Advertising!"); - } - else - { - K32W_LOG("OpenBasicCommissioningWindow() failed"); - } - } -} - -#if CHIP_ENABLE_LIT -void AppTask::UserActiveModeHandler(void * aGenericEvent) -{ - AppEvent * aEvent = (AppEvent *) aGenericEvent; - - if (aEvent->ButtonEvent.PinNo != BLE_BUTTON) - return; - - if (sAppTask.mFunction != Function::kNoneSelected) - { - K32W_LOG("Another function is scheduled. Could not request ICD Active Mode!"); - return; - } - PlatformMgr().ScheduleWork(AppTask::UserActiveModeTrigger, 0); -} - -void AppTask::UserActiveModeTrigger(intptr_t arg) -{ - ICDNotifier::GetInstance().NotifyNetworkActivityNotification(); -} -#endif - -void AppTask::MatterEventHandler(const ChipDeviceEvent * event, intptr_t) -{ - if (event->Type == DeviceEventType::kServiceProvisioningChange && event->ServiceProvisioningChange.IsServiceProvisioned) - { - if (event->ServiceProvisioningChange.IsServiceProvisioned) - { - sIsThreadProvisioned = TRUE; - } - else - { - sIsThreadProvisioned = FALSE; - } - } -#if CHIP_ENABLE_LIT - else if (event->Type == DeviceEventType::kCommissioningComplete) - { - sIsDeviceCommissioned = TRUE; - } -#endif - -#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR - if (event->Type == DeviceEventType::kDnssdInitialized) - { - K32W_LOG("Dnssd platform initialized."); - PlatformMgr().ScheduleWork(InitOTA, 0); - } -#endif -} - -void AppTask::CancelTimer() -{ - if (xTimerStop(sFunctionTimer, 0) == pdFAIL) - { - K32W_LOG("app timer stop() failed"); - } - - mResetTimerActive = false; -} - -void AppTask::StartTimer(uint32_t aTimeoutInMs) -{ - if (xTimerIsTimerActive(sFunctionTimer)) - { - K32W_LOG("app timer already started!"); - CancelTimer(); - } - - // timer is not active, change its period to required value (== restart). - // FreeRTOS- Block for a maximum of 100 ticks if the change period command - // cannot immediately be sent to the timer command queue. - if (xTimerChangePeriod(sFunctionTimer, aTimeoutInMs / portTICK_PERIOD_MS, 100) != pdPASS) - { - K32W_LOG("app timer start() failed"); - } - - mResetTimerActive = true; -} - -void AppTask::OnStateChanged(ContactSensorManager::State aState) -{ - // If the contact state was changed, update LED state and cluster state (only if button was pressed). - // - turn on the contact LED if contact sensor is in closed state. - // - turn off the lock LED if contact sensor is in opened state. - if (ContactSensorManager::State::kContactClosed == aState) - { - K32W_LOG("Contact state changed to closed.") -#if !defined(chip_with_low_power) || (chip_with_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) - sContactSensorLED.Set(false); -#endif - } - - if (sAppTask.IsSyncClusterToButtonAction()) - { - sAppTask.UpdateClusterState(); - } - - sAppTask.mFunction = Function::kNoneSelected; -} - -void AppTask::OnIdentifyStart(Identify * identify) -{ - if (Clusters::Identify::EffectIdentifierEnum::kBlink == identify->mCurrentEffectIdentifier) - { - if (Function::kNoneSelected != sAppTask.mFunction) - { - K32W_LOG("Another function is scheduled. Could not initiate Identify process!"); - return; - } - 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) -#ifndef CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR - sStatusLED.Set(false); - sStatusLED.Blink(500); -#endif -#endif - } -} - -void AppTask::OnIdentifyStop(Identify * identify) -{ - if (Clusters::Identify::EffectIdentifierEnum::kBlink == identify->mCurrentEffectIdentifier) - { - K32W_LOG("Identify process has stopped."); - sAppTask.mFunction = Function::kNoneSelected; - } -} - -status_t AppTask::LowPowerCallback(pm_event_type_t eventType, uint8_t powerState, void * data) -{ - return kStatus_Success; -} - -void AppTask::PostContactActionRequest(ContactSensorManager::Action aAction) -{ - AppEvent event; - event.Type = AppEvent::kContact; - event.ContactEvent.Action = static_cast(aAction); - event.Handler = ContactActionEventHandler; - PostEvent(&event); -} - -void AppTask::PostEvent(const AppEvent * aEvent) -{ - portBASE_TYPE taskToWake = pdFALSE; - if (sAppEventQueue != NULL) - { - if (__get_IPSR()) - { - if (!xQueueSendToFrontFromISR(sAppEventQueue, aEvent, &taskToWake)) - { - K32W_LOG("Failed to post event to app task event queue"); - } - if (taskToWake) - { - portYIELD_FROM_ISR(taskToWake); - } - } - else if (!xQueueSend(sAppEventQueue, aEvent, 0)) - { - K32W_LOG("Failed to post event to app task event queue"); - } - } -} - -void AppTask::DispatchEvent(AppEvent * aEvent) -{ -#if defined(chip_with_low_power) && (chip_with_low_power == 1) - /* specific processing for events sent from App_PostCallbackMessage (see main.cpp) */ - if (aEvent->Type == AppEvent::kEventType_Lp) - { - aEvent->Handler(aEvent->param); - } - else -#endif - - if (aEvent->Handler) - { - aEvent->Handler(aEvent); - } - else - { - K32W_LOG("Event received with no handler. Dropping event."); - } -} - -void AppTask::UpdateClusterState(void) -{ - PlatformMgr().ScheduleWork(UpdateClusterStateInternal, 0); -} -extern void logBooleanStateEvent(bool state); -void AppTask::UpdateClusterStateInternal(intptr_t arg) -{ - uint8_t newValue = ContactSensorMgr().IsContactClosed(); - - // write the new on/off value - Protocols::InteractionModel::Status status = app::Clusters::BooleanState::Attributes::StateValue::Set(1, newValue); - - if (status != Protocols::InteractionModel::Status::Success) - { - ChipLogError(NotSpecified, "ERR: updating boolean status value %x", to_underlying(status)); - } - logBooleanStateEvent(newValue); -} - -void AppTask::UpdateDeviceState(void) -{ - PlatformMgr().ScheduleWork(UpdateDeviceStateInternal, 0); -} - -void AppTask::UpdateDeviceStateInternal(intptr_t arg) -{ - bool stateValueAttrValue = 0; - - /* get onoff attribute value */ - (void) app::Clusters::BooleanState::Attributes::StateValue::Get(1, &stateValueAttrValue); - -#if !defined(chip_with_low_power) || (chip_with_low_power == 0) - /* set the device state */ - sContactSensorLED.Set(stateValueAttrValue); -#endif -} - -extern "C" void OTAIdleActivities(void) -{ -#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR - OTA_TransactionResume(); -#endif -} diff --git a/examples/contact-sensor-app/nxp/k32w/k32w1/main/ContactSensorManager.cpp b/examples/contact-sensor-app/nxp/k32w/k32w1/main/ContactSensorManager.cpp deleted file mode 100644 index 9e0a665cbb..0000000000 --- a/examples/contact-sensor-app/nxp/k32w/k32w1/main/ContactSensorManager.cpp +++ /dev/null @@ -1,84 +0,0 @@ -/* - * - * Copyright (c) 2022-2023 Project CHIP Authors - * Copyright (c) 2022 Google LLC. - * Copyright (c) 2023 NXP - * 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 "ContactSensorManager.h" - -#include "AppTask.h" -#include "FreeRTOS.h" - -#include "app_config.h" - -ContactSensorManager ContactSensorManager::sContactSensor; - -int ContactSensorManager::Init() -{ - int err = 0; - - mState = State::kContactOpened; - mCallbackStateChanged = nullptr; - - return err; -} - -void ContactSensorManager::SetCallback(CallbackStateChanged aCallbackStateChanged) -{ - mCallbackStateChanged = aCallbackStateChanged; -} - -bool ContactSensorManager::IsContactClosed() -{ - return mState == State::kContactClosed; -} - -void ContactSensorManager::InitiateAction(Action aAction) -{ - AppEvent event; - event.Type = AppEvent::kContact; - event.ContactEvent.Action = static_cast(aAction); - event.Handler = HandleAction; - GetAppTask().PostEvent(&event); -} - -void ContactSensorManager::HandleAction(void * aGenericEvent) -{ - AppEvent * event = static_cast(aGenericEvent); - Action action = static_cast(event->ContactEvent.Action); - // Change current state based on action: - // - if state is closed and action is signal lost, change state to opened - // - if state is opened and action is signal detected, change state to closed - // - else, the state/action combination does not change the state. - if (State::kContactClosed == sContactSensor.mState && Action::kSignalLost == action) - { - sContactSensor.mState = State::kContactOpened; - } - else if (State::kContactOpened == sContactSensor.mState && Action::kSignalDetected == action) - { - sContactSensor.mState = State::kContactClosed; - } - - if (sContactSensor.mCallbackStateChanged != nullptr) - { - sContactSensor.mCallbackStateChanged(sContactSensor.mState); - } - else - { - K32W_LOG("Callback for state change was not set. Please set an appropriate callback."); - } -} diff --git a/examples/contact-sensor-app/nxp/k32w/k32w1/main/ZclCallbacks.cpp b/examples/contact-sensor-app/nxp/k32w/k32w1/main/ZclCallbacks.cpp deleted file mode 100644 index e69daab980..0000000000 --- a/examples/contact-sensor-app/nxp/k32w/k32w1/main/ZclCallbacks.cpp +++ /dev/null @@ -1,113 +0,0 @@ -/* - * - * Copyright (c) 2022-2023 Project CHIP Authors - * Copyright (c) 2023 NXP - * 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 "AppTask.h" -#include "ContactSensorManager.h" - -#include -#include -#include -#include -#include -#include - -#if CONFIG_DIAG_LOGS_DEMO -#include "DiagnosticLogsProviderDelegateImpl.h" -#include -#endif - -using namespace ::chip; -using namespace ::chip::app; -using namespace ::chip::app::Clusters; -using namespace ::chip::app::Clusters::BooleanState; -#if CONFIG_DIAG_LOGS_DEMO -using namespace ::chip::app::Clusters::DiagnosticLogs; -#endif - -void MatterPostAttributeChangeCallback(const chip::app::ConcreteAttributePath & path, uint8_t type, uint16_t size, uint8_t * value) -{ - ChipLogProgress(Zcl, "MatterPostAttributeChangeCallback, value:%d\n", *value); - if (path.mClusterId != BooleanState::Id) - { - ChipLogProgress(Zcl, "Unknown cluster ID: " ChipLogFormatMEI, ChipLogValueMEI(path.mClusterId)); - return; - } - - if (path.mAttributeId != BooleanState::Attributes::StateValue::Id) - { - ChipLogProgress(Zcl, "Unknown attribute ID: " ChipLogFormatMEI, ChipLogValueMEI(path.mAttributeId)); - return; - } - - AppTask & task = GetAppTask(); - // If the callback is called after the cluster attribute was changed due to pressing a button, - // set the sync value to false. Both LED and attribute were updated at this point. - // On the other hand, if the cluster attribute was changed due to a cluster command, - // forward the request to AppTask in order to update the LED state. - if (task.IsSyncClusterToButtonAction()) - { - task.SetSyncClusterToButtonAction(false); - } - else - { - task.PostContactActionRequest(*value ? ContactSensorManager::Action::kSignalDetected - : ContactSensorManager::Action::kSignalLost); - } -} - -/** @brief OnOff Cluster Init - * - * This function is called when a specific cluster is initialized. It gives the - * application an opportunity to take care of cluster initialization procedures. - * It is called exactly once for each endpoint where cluster is present. - * - * @param endpoint Ver.: always - * - * TODO Issue #3841 - * emberAfOnOffClusterInitCallback happens before the stack initialize the cluster - * attributes to the default value. - * The logic here expects something similar to the deprecated Plugins callback - * emberAfPluginOnOffClusterServerPostInitCallback. - * - */ -void emberAfBooleanStateClusterInitCallback(EndpointId endpoint) -{ - ChipLogProgress(Zcl, "emberAfBooleanStateClusterInitCallback\n"); - GetAppTask().UpdateClusterState(); -} - -void logBooleanStateEvent(bool state) -{ - EventNumber eventNumber; - Events::StateChange::Type event{ state }; - if (CHIP_NO_ERROR != LogEvent(event, 1, eventNumber)) - { - ChipLogProgress(Zcl, "booleanstate: failed to reacord state-change event"); - } -} - -#if CONFIG_DIAG_LOGS_DEMO -void emberAfDiagnosticLogsClusterInitCallback(chip::EndpointId endpoint) -{ - auto & logProvider = LogProvider::GetInstance(); - DiagnosticLogsServer::Instance().SetDiagnosticLogsProviderDelegate(endpoint, &logProvider); -} -#endif diff --git a/examples/contact-sensor-app/nxp/k32w/k32w1/main/include/AppEvent.h b/examples/contact-sensor-app/nxp/k32w/k32w1/main/include/AppEvent.h deleted file mode 100644 index f3e0d729ab..0000000000 --- a/examples/contact-sensor-app/nxp/k32w/k32w1/main/include/AppEvent.h +++ /dev/null @@ -1,63 +0,0 @@ -/* - * - * Copyright (c) 2022 Nest Labs, Inc. - * Copyright (c) 2023 NXP - * 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 - -struct AppEvent; -typedef void (*EventHandler)(void *); - -struct AppEvent -{ - enum AppEventTypes - { - kButton = 0, - kTimer, - kContact, - kInstall, -#if defined(chip_with_low_power) && (chip_with_low_power == 1) - kEventType_Lp, -#endif - kOTAResume, - }; - - AppEventTypes Type; - - union - { - struct - { - uint8_t PinNo; - uint8_t Action; - } ButtonEvent; - struct - { - void * Context; - } TimerEvent; - struct - { - uint8_t Action; - } ContactEvent; - }; - - EventHandler Handler; - -#if defined(chip_with_low_power) && (chip_with_low_power == 1) - void * param; -#endif -}; diff --git a/examples/contact-sensor-app/nxp/k32w/k32w1/main/include/AppTask.h b/examples/contact-sensor-app/nxp/k32w/k32w1/main/include/AppTask.h deleted file mode 100644 index 64842e3105..0000000000 --- a/examples/contact-sensor-app/nxp/k32w/k32w1/main/include/AppTask.h +++ /dev/null @@ -1,144 +0,0 @@ -/* - * - * Copyright (c) 2022 Google LLC. - * Copyright (c) 2023 NXP - * 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 "AppEvent.h" -#include "ContactSensorManager.h" - -#include "CHIPProjectConfig.h" - -#include -#include - -#if CONFIG_CHIP_LOAD_REAL_FACTORY_DATA -#include -#endif - -#include "FreeRTOS.h" -#include "fsl_component_button.h" -#include "fsl_pm_core.h" -#include "timers.h" - -// Application-defined error codes in the CHIP_ERROR space. -#define APP_ERROR_EVENT_QUEUE_FAILED CHIP_APPLICATION_ERROR(0x01) -#define APP_ERROR_CREATE_TASK_FAILED CHIP_APPLICATION_ERROR(0x02) -#define APP_ERROR_UNHANDLED_EVENT CHIP_APPLICATION_ERROR(0x03) -#define APP_ERROR_CREATE_TIMER_FAILED CHIP_APPLICATION_ERROR(0x04) -#define APP_ERROR_START_TIMER_FAILED CHIP_APPLICATION_ERROR(0x05) -#define APP_ERROR_STOP_TIMER_FAILED CHIP_APPLICATION_ERROR(0x06) -#define APP_ERROR_PM_REGISTER_LP_CALLBACK_FAILED CHIP_APPLICATION_ERROR(0x07) - -class AppTask -{ -public: -#if CONFIG_CHIP_LOAD_REAL_FACTORY_DATA - using FactoryDataProvider = chip::DeviceLayer::FactoryDataProviderImpl; -#endif - CHIP_ERROR StartAppTask(); - static void AppTaskMain(void * pvParameter); - - void PostContactActionRequest(ContactSensorManager::Action aAction); - void PostEvent(const AppEvent * event); - - void UpdateClusterState(void); - void UpdateDeviceState(void); - - bool IsSyncClusterToButtonAction(); - void SetSyncClusterToButtonAction(bool value); - // Identify cluster callbacks. - static void OnIdentifyStart(Identify * identify); - static void OnIdentifyStop(Identify * identify); - - static status_t LowPowerCallback(pm_event_type_t eventType, uint8_t powerState, void * data); - -private: - friend AppTask & GetAppTask(void); - - CHIP_ERROR Init(); - - static void OnStateChanged(ContactSensorManager::State aState); - - void CancelTimer(void); - - void DispatchEvent(AppEvent * event); - - static void FunctionTimerEventHandler(void * aGenericEvent); - static button_status_t KBD_Callback(void * buttonHandle, button_callback_message_t * message, void * callbackParam); - static void HandleKeyboard(void); - static void SoftResetHandler(void * aGenericEvent); - static void BleHandler(void * aGenericEvent); - static void BleStartAdvertising(intptr_t arg); - static void ContactActionEventHandler(void * aGenericEvent); - static void ResetActionEventHandler(void * aGenericEvent); - static void InstallEventHandler(void * aGenericEvent); -#if CHIP_ENABLE_LIT - static void UserActiveModeHandler(void * aGenericEvent); - static void UserActiveModeTrigger(intptr_t arg); -#endif - - static void ButtonEventHandler(uint8_t pin_no, uint8_t button_action); - static void TimerEventHandler(TimerHandle_t xTimer); - - static void MatterEventHandler(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg); - - void StartTimer(uint32_t aTimeoutInMs); - -#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR - static void InitOTA(intptr_t arg); -#endif - - static void UpdateClusterStateInternal(intptr_t arg); - static void UpdateDeviceStateInternal(intptr_t arg); - static void InitServer(intptr_t arg); - static void PrintOnboardingInfo(); - - enum class Function : uint8_t - { - kNoneSelected = 0, - kFactoryReset, - kContact, - kIdentify, - kInvalid - }; - - Function mFunction = Function::kNoneSelected; - bool mResetTimerActive = false; - bool mSyncClusterToButtonAction = false; - - static AppTask sAppTask; -}; - -inline AppTask & GetAppTask(void) -{ - return AppTask::sAppTask; -} - -inline bool AppTask::IsSyncClusterToButtonAction() -{ - return mSyncClusterToButtonAction; -} - -inline void AppTask::SetSyncClusterToButtonAction(bool value) -{ - mSyncClusterToButtonAction = value; -} diff --git a/examples/contact-sensor-app/nxp/k32w/k32w1/main/include/ContactSensorManager.h b/examples/contact-sensor-app/nxp/k32w/k32w1/main/include/ContactSensorManager.h deleted file mode 100644 index 69a71ee14e..0000000000 --- a/examples/contact-sensor-app/nxp/k32w/k32w1/main/include/ContactSensorManager.h +++ /dev/null @@ -1,66 +0,0 @@ -/* - * - * Copyright (c) 2022 Google LLC. - * Copyright (c) 2023 NXP - * 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 "AppEvent.h" - -#include "FreeRTOS.h" -#include "timers.h" // provides FreeRTOS timer support - -class ContactSensorManager -{ -public: - enum class Action : uint8_t - { - kSignalDetected = 0, - kSignalLost, - kInvalid - }; - - enum class State : uint8_t - { - kContactClosed = 0, - kContactOpened, - kInvalid - }; - - int Init(); - bool IsContactClosed(); - void InitiateAction(Action aAction); - - typedef void (*CallbackStateChanged)(State aState); - void SetCallback(CallbackStateChanged aCallbackStateChanged); - - static void HandleAction(void * aGenericEvent); - -private: - friend ContactSensorManager & ContactSensorMgr(void); - State mState; - CallbackStateChanged mCallbackStateChanged; - static ContactSensorManager sContactSensor; -}; - -inline ContactSensorManager & ContactSensorMgr(void) -{ - return ContactSensorManager::sContactSensor; -} diff --git a/examples/contact-sensor-app/nxp/k32w/k32w1/main/include/app_config.h b/examples/contact-sensor-app/nxp/k32w/k32w1/main/include/app_config.h deleted file mode 100644 index 7001f636db..0000000000 --- a/examples/contact-sensor-app/nxp/k32w/k32w1/main/include/app_config.h +++ /dev/null @@ -1,52 +0,0 @@ -/* - * - * Copyright (c) 2022 Google LLC. - * Copyright (c) 2023 NXP - * 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 - -// ---- Contact Example App Config ---- - -#define RESET_BUTTON 1 -#define CONTACT_SENSOR_BUTTON 2 -#define SOFT_RESET_BUTTON 3 -#define BLE_BUTTON 4 - -#define RESET_BUTTON_PUSH 1 -#define CONTACT_SENSOR_BUTTON_PUSH 2 -#define SOFT_RESET_BUTTON_PUSH 3 -#define BLE_BUTTON_PUSH 4 -#define USER_ACTIVE_MODE_TRIGGER_PUSH 5 - -#define APP_BUTTON_PUSH 1 - -#define CONTACT_SENSOR_STATE_LED 1 -#define SYSTEM_STATE_LED 0 - -// ---- Contact Example SWU Config ---- -#define SWU_INTERVAl_WINDOW_MIN_MS (23 * 60 * 60 * 1000) // 23 hours -#define SWU_INTERVAl_WINDOW_MAX_MS (24 * 60 * 60 * 1000) // 24 hours - -// ---- Thread Polling Config ---- -// #define THREAD_ACTIVE_POLLING_INTERVAL_MS 100 -// #define THREAD_INACTIVE_POLLING_INTERVAL_MS 1000 - -#if K32W_LOG_ENABLED -#define K32W_LOG(...) otPlatLog(OT_LOG_LEVEL_NONE, OT_LOG_REGION_API, ##__VA_ARGS__); -#else -#define K32W_LOG(...) -#endif diff --git a/examples/contact-sensor-app/nxp/k32w/k32w1/main/main.cpp b/examples/contact-sensor-app/nxp/k32w/k32w1/main/main.cpp deleted file mode 100644 index 700bbc5ad9..0000000000 --- a/examples/contact-sensor-app/nxp/k32w/k32w1/main/main.cpp +++ /dev/null @@ -1,143 +0,0 @@ -/* - * - * Copyright (c) 2022 Google LLC. - * Copyright (c) 2023 NXP - * 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. - */ - -// ================================================================================ -// Main Code -// ================================================================================ - -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -#include "FreeRtosHooks.h" -#include "app_config.h" -#include "openthread/platform/logging.h" - -using namespace ::chip; -using namespace ::chip::Inet; -using namespace ::chip::DeviceLayer; -using namespace ::chip::Logging; - -#include - -typedef void (*InitFunc)(void); -extern InitFunc __init_array_start; -extern InitFunc __init_array_end; - -extern "C" void main_task(void const * argument) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - - /* Call C++ constructors */ - InitFunc * pFunc = &__init_array_start; - for (; pFunc < &__init_array_end; ++pFunc) - { - (*pFunc)(); - } - - mbedtls_platform_set_calloc_free(CHIPPlatformMemoryCalloc, CHIPPlatformMemoryFree); - - err = PlatformMgrImpl().InitBoardFwk(); - if (err != CHIP_NO_ERROR) - { - return; - } - - /* Used for HW initializations */ - otSysInit(0, NULL); - - if (err != CHIP_NO_ERROR) - { - return; - } - - K32W_LOG("Welcome to NXP Contact Sensor Demo App"); - - /* Mbedtls Threading support is needed because both - * Thread and Matter tasks are using it */ - freertos_mbedtls_mutex_init(); - - // Init Chip memory management before the stack - chip::Platform::MemoryInit(); - - err = PlatformMgr().InitChipStack(); - if (err != CHIP_NO_ERROR) - { - K32W_LOG("Error during PlatformMgr().InitMatterStack()"); - goto exit; - } - - err = ThreadStackMgr().InitThreadStack(); - if (err != CHIP_NO_ERROR) - { - K32W_LOG("Error during ThreadStackMgr().InitThreadStack()"); - goto exit; - } - - err = ConnectivityMgr().SetThreadDeviceType(ConnectivityManager::kThreadDeviceType_SleepyEndDevice); - if (err != CHIP_NO_ERROR) - { - goto exit; - } - - // Start OpenThread task - err = ThreadStackMgrImpl().StartThreadTask(); - if (err != CHIP_NO_ERROR) - { - K32W_LOG("Error during ThreadStackMgrImpl().StartThreadTask()"); - goto exit; - } - - err = GetAppTask().StartAppTask(); - if (err != CHIP_NO_ERROR) - { - K32W_LOG("Error during GetAppTask().StartAppTask()"); - goto exit; - } - - err = PlatformMgr().StartEventLoopTask(); - if (err != CHIP_NO_ERROR) - { - K32W_LOG("Error during PlatformMgr().StartEventLoopTask();"); - goto exit; - } - - GetAppTask().AppTaskMain(NULL); - -exit: - return; -} - -/** - * Glue function called directly by the OpenThread stack - * when system event processing work is pending. - */ -extern "C" void otSysEventSignalPending(void) -{ - BaseType_t yieldRequired = ThreadStackMgrImpl().SignalThreadActivityPendingFromISR(); - portYIELD_FROM_ISR(yieldRequired); -} diff --git a/examples/contact-sensor-app/nxp/k32w/k32w1/third_party/connectedhomeip b/examples/contact-sensor-app/nxp/k32w/k32w1/third_party/connectedhomeip deleted file mode 120000 index 305f2077ff..0000000000 --- a/examples/contact-sensor-app/nxp/k32w/k32w1/third_party/connectedhomeip +++ /dev/null @@ -1 +0,0 @@ -../../../../../.. \ No newline at end of file diff --git a/examples/contact-sensor-app/nxp/k32w/k32w1/.gn b/examples/contact-sensor-app/nxp/k32w1/.gn similarity index 93% rename from examples/contact-sensor-app/nxp/k32w/k32w1/.gn rename to examples/contact-sensor-app/nxp/k32w1/.gn index 1e848295f6..885f306753 100644 --- a/examples/contact-sensor-app/nxp/k32w/k32w1/.gn +++ b/examples/contact-sensor-app/nxp/k32w1/.gn @@ -28,5 +28,5 @@ default_args = { import("//args.gni") # Import default platform configs - import("${chip_root}/src/platform/nxp/k32w/k32w1/args.gni") + import("${chip_root}/src/platform/nxp/k32w1/args.gni") } diff --git a/examples/contact-sensor-app/nxp/k32w1/BUILD.gn b/examples/contact-sensor-app/nxp/k32w1/BUILD.gn new file mode 100644 index 0000000000..119dc5cf72 --- /dev/null +++ b/examples/contact-sensor-app/nxp/k32w1/BUILD.gn @@ -0,0 +1,261 @@ +# Copyright (c) 2021-2023 Project CHIP Authors +# Copyright (c) 2023 NXP +# +# 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/nxp_sdk.gni") +import("//build_overrides/openthread.gni") + +import("${nxp_sdk_build_root}/nxp_sdk.gni") + +import("${nxp_sdk_build_root}/${nxp_sdk_name}/nxp_executable.gni") + +import("${nxp_sdk_build_root}/${nxp_sdk_name}/${nxp_sdk_name}.gni") + +import("${chip_root}/src/app/icd/icd.gni") +import("${chip_root}/src/crypto/crypto.gni") +import("${chip_root}/src/platform/device.gni") +import("${chip_root}/src/platform/nxp/${nxp_platform}/args.gni") + +declare_args() { + # Setup discriminator as argument + setup_discriminator = 3840 + chip_with_diag_logs_demo = true +} + +assert(current_os == "freertos") +assert(target_os == "freertos") + +example_platform_dir = "${chip_root}/examples/platform/nxp/${nxp_platform}" +common_example_dir = "${chip_root}/examples/platform/nxp/common" + +k32w1_sdk("sdk") { + defines = [] + include_dirs = [] + sources = [] + + # Indicate the path to CHIPProjectConfig.h + include_dirs += [ "include/config" ] + + # Indicate the default path to FreeRTOSConfig.h + include_dirs += [ "${example_platform_dir}/app/project_include/freeRTOS" ] + + # Indicate the default path to OpenThreadConfig.h + include_dirs += [ "${example_platform_dir}/app/project_include/openthread" ] + + include_dirs += [ + "${k32w1_sdk_root}/middleware/wireless/framework/boards/kw45_k32w1", + "${k32w1_sdk_root}/middleware/wireless/framework/boards/kw45_k32w1/K32W1480", + ] + + sources += [ + "${k32w1_sdk_root}/middleware/wireless/framework/boards/kw45_k32w1/K32W1480/clock_config.c", + "${k32w1_sdk_root}/middleware/wireless/framework/boards/kw45_k32w1/K32W1480/pin_mux.c", + "${k32w1_sdk_root}/middleware/wireless/framework/boards/kw45_k32w1/app_services_init.c", + "${k32w1_sdk_root}/middleware/wireless/framework/boards/kw45_k32w1/board.c", + "${k32w1_sdk_root}/middleware/wireless/framework/boards/kw45_k32w1/board_comp.c", + "${k32w1_sdk_root}/middleware/wireless/framework/boards/kw45_k32w1/board_dcdc.c", + "${k32w1_sdk_root}/middleware/wireless/framework/boards/kw45_k32w1/board_extflash.c", + "${k32w1_sdk_root}/middleware/wireless/framework/boards/kw45_k32w1/board_lp.c", + "${k32w1_sdk_root}/middleware/wireless/framework/boards/kw45_k32w1/hardware_init.c", + ] + + if (is_debug) { + defines += [ "BUILD_RELEASE=0" ] + } else { + defines += [ "BUILD_RELEASE=1" ] + } + + defines += [ + "CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR=${setup_discriminator}", + ] + + if (chip_key_storage == "littlefs") { + include_dirs += [ "${example_platform_dir}/board" ] + sources += [ + "${example_platform_dir}/board/peripherals.c", + "${example_platform_dir}/board/peripherals.h", + ] + } +} + +k32w1_executable("contact_sensor_app") { + output_name = "chip-k32w1-contact-example" + + defines = [] + deps = [] + include_dirs = [] + sources = [] + + # Defines used by common code + defines += [ + "CONFIG_NET_L2_OPENTHREAD=1", + "CONFIG_NETWORK_LAYER_BLE=1", + "CONFIG_THREAD_DEVICE_TYPE=kThreadDeviceType_SleepyEndDevice", + "CONFIG_OPERATIONAL_KEYSTORE=1", + "EXTERNAL_FACTORY_DATA_PROVIDER_HEADER=\"platform/nxp/common/legacy/FactoryDataProvider.h\"", + ] + + if (chip_with_diag_logs_demo) { + defines += [ "CONFIG_DIAG_LOGS_DEMO=1" ] + } + + if (chip_with_low_power == 1) { + defines += [ "CONFIG_LOW_POWER=1" ] + } else { + defines += [ + "CONFIG_ENABLE_FEEDBACK=1", + "APP_QUEUE_TICKS_TO_WAIT=pdMS_TO_TICKS(10)", + ] + } + + # App common files + include_dirs += [ + "${common_example_dir}/app_task/include", + "${common_example_dir}/matter_button/include", + "${common_example_dir}/clusters/include", + "${common_example_dir}/device_callbacks/include", + "${common_example_dir}/device_manager/include", + "${common_example_dir}/diagnostic_logs/include", + "${common_example_dir}/factory_data/include", + "${common_example_dir}/led_widget/include", + "${common_example_dir}/low_power/include", + "${common_example_dir}/operational_keystore/include", + "${common_example_dir}/ui_feedback/include", + ] + + sources += [ + "${common_example_dir}/app_task/source/AppTaskBase.cpp", + "${common_example_dir}/app_task/source/AppTaskFreeRTOS.cpp", + "${common_example_dir}/clusters/source/ZclCallbacks.cpp", + "${common_example_dir}/device_callbacks/source/CommonDeviceCallbacks.cpp", + "${common_example_dir}/device_manager/source/CHIPDeviceManager.cpp", + "${example_platform_dir}/factory_data/source/AppFactoryDataExample.cpp", + ] + + if (chip_with_low_power == 1) { + sources += [ "${common_example_dir}/low_power/source/LowPower.cpp" ] + } + + if (chip_with_factory_data == 1) { + include_dirs += [ "${chip_root}/src/platform/nxp/common/legacy" ] + deps += [ "${chip_root}/src/platform/nxp:nxp_factory_data" ] + } + + if (chip_enable_ota_requestor) { + defines += [ + "CONFIG_CHIP_OTA_IMAGE_PROCESSOR_HEADER=\"platform/nxp/common/legacy/OTAImageProcessorImpl.h\"", + + # The status LED and the external flash CS pin are wired together. The OTA image writing may fail if used together. + "LED_MANAGER_ENABLE_STATUS_LED=0", + ] + + include_dirs += [ "${common_example_dir}/ota_requestor/include" ] + sources += [ "${common_example_dir}/ota_requestor/source/OTARequestorInitiatorMultiImage.cpp" ] + deps += [ "${chip_root}/src/platform/nxp:nxp_ota" ] + } + + if (chip_with_diag_logs_demo) { + sources += [ + "${common_example_dir}/diagnostic_logs/source/DiagnosticLogsDemo.cpp", + "${common_example_dir}/diagnostic_logs/source/DiagnosticLogsProviderDelegateImpl.cpp", + ] + } + + # Platform specific files + include_dirs += [ + "${example_platform_dir}/util", + "${example_platform_dir}/app/support", + "${example_platform_dir}/button", + ] + + sources += [ + "${example_platform_dir}/button/ButtonManager.cpp", + "${example_platform_dir}/clusters/Identify.cpp", + "${example_platform_dir}/operational_keystore/OperationalKeystore.cpp", + ] + + if (chip_enable_ota_requestor) { + sources += [ "${example_platform_dir}/ota/OtaUtils.cpp" ] + } + + include_dirs += [ + "include/config", + "../common/include", + ] + + sources += [ + "../common/AppTask.cpp", + "../common/DeviceCallbacks.cpp", + "../common/ZclCallbacks.cpp", + "../common/main.cpp", + ] + + if (chip_with_low_power == 0) { + sources += [ + "${common_example_dir}/ui_feedback/source/LedManager.cpp", + "${example_platform_dir}/util/LedOnOff.cpp", + ] + } + + deps += [ + "${chip_root}/examples/providers:device_info_provider", + "${chip_root}/src/platform/logging:default", + ] + + #lit and sit are using different zap files + if (chip_enable_icd_lit) { + deps += [ "${chip_root}/examples/contact-sensor-app/nxp/zap-lit/" ] + } else { + deps += [ "${chip_root}/examples/contact-sensor-app/nxp/zap-sit/" ] + } + + if (chip_openthread_ftd) { + deps += [ + "${openthread_root}:libopenthread-cli-ftd", + "${openthread_root}:libopenthread-ftd", + ] + } else { + deps += [ + "${openthread_root}:libopenthread-cli-mtd", + "${openthread_root}:libopenthread-mtd", + ] + } + + cflags = [ "-Wconversion" ] + + ldscript = "${k32w1_sdk_root}/middleware/wireless/framework/Common/devices/kw45_k32w1/gcc/connectivity.ld" + + inputs = [ ldscript ] + + ldflags = [ + "-Wl,--defsym=__heap_size__=0", + "-Wl,--defsym=__stack_size__=0x480", + "-Wl,--defsym=lp_ram_lower_limit=0x04000000", + "-Wl,--defsym=lp_ram_upper_limit=0x2001C000", + "-Wl,-print-memory-usage", + "-Wl,--no-warn-rwx-segments", + "-T" + rebase_path(ldscript, root_build_dir), + ] + + if (chip_with_factory_data == 1) { + ldflags += [ "-Wl,--defsym=gUseFactoryData_d=1" ] + } + + output_dir = root_out_dir +} + +group("default") { + deps = [ ":contact_sensor_app" ] +} diff --git a/examples/contact-sensor-app/nxp/k32w/k32w1/README.md b/examples/contact-sensor-app/nxp/k32w1/README.md similarity index 83% rename from examples/contact-sensor-app/nxp/k32w/k32w1/README.md rename to examples/contact-sensor-app/nxp/k32w1/README.md index f3896a01b8..7a70f746f6 100644 --- a/examples/contact-sensor-app/nxp/k32w/k32w1/README.md +++ b/examples/contact-sensor-app/nxp/k32w1/README.md @@ -14,29 +14,29 @@ into an existing Matter network and can be controlled by this network.
- [Matter K32W1 Contact Sensor Example Application](#matter-k32w1-contact-sensor-example-application) -- [Introduction](#introduction) - - [Bluetooth LE Advertising](#bluetooth-le-advertising) - - [Bluetooth LE Rendezvous](#bluetooth-le-rendezvous) -- [Device UI](#device-ui) -- [Building](#building) -- [Long Idle Time ICD Support](#long-idle-time-icd-support) -- [Manufacturing data](#manufacturing-data) -- [Flashing](#flashing) - - [Flashing the NBU image](#flashing-the-nbu-image) - - [Flashing the host image](#flashing-the-host-image) -- [Debugging](#debugging) -- [OTA](#ota) - - [Convert srec into sb3 file](#convert-srec-into-sb3-file) - - [Convert sb3 into ota file](#convert-sb3-into-ota-file) - - [Running OTA](#running-ota) - - [Known issues](#known-issues) -- [Low power](#low-power) - - + - [Introduction](#introduction) + - [Bluetooth LE Advertising](#bluetooth-le-advertising) + - [Bluetooth LE Rendezvous](#bluetooth-le-rendezvous) + - [Thread Provisioning](#thread-provisioning) + - [Device UI](#device-ui) + - [Building](#building) + - [Long Idle Time ICD Support](#long-idle-time-icd-support) + - [Manufacturing data](#manufacturing-data) + - [Flashing](#flashing) + - [Flashing the `NBU` image](#flashing-the-nbu-image) + - [Flashing the host image](#flashing-the-host-image) + - [Debugging](#debugging) + - [OTA](#ota) + - [Convert `srec` into `sb3` file](#convert-srec-into-sb3-file) + - [Convert `sb3` into `ota` file](#convert-sb3-into-ota-file) + - [OTA factory data](#ota-factory-data) + - [Running OTA](#running-ota) + - [Low power](#low-power) + - [Known issues](#known-issues) ## Introduction -![K32W1 EVK](../../../../platform/nxp/k32w/k32w1/doc/images/k32w1-evk.jpg) +![K32W1 EVK](../../../platform/nxp/k32w1/doc/images/k32w1-evk.jpg) The K32W1 contact sensor example application provides a working demonstration of a connected contact sensor device, built using the Matter codebase and the NXP @@ -118,23 +118,50 @@ Matter shutdown procedure. ## Building -In order to build the Matter example, we recommend using a Linux distribution -(the demo-application was compiled on Ubuntu 20.04). +In order to build the Project CHIP example, we recommend using a Linux +distribution. Supported Operating Systems and prerequisites are listed in +[BUILDING](../../../../docs/guides/BUILDING.md). -- Download [K32W1 SDK for Matter](https://mcuxpresso.nxp.com/). Creating an - nxp.com account is required before being able to download the SDK. Once the - account is created, login and follow the steps for downloading K32W1 SDK. - The SDK Builder UI selection should be similar with the one from the image - below. - ![MCUXpresso SDK Download](../../../../platform/nxp/k32w/k32w1/doc/images/mcux-sdk-download.jpg) +- Make sure that below prerequisites are correctly installed + +``` +sudo apt-get install git gcc g++ pkg-config libssl-dev libdbus-1-dev \ + libglib2.0-dev libavahi-client-dev ninja-build python3-venv python3-dev \ + python3-pip unzip libgirepository1.0-dev libcairo2-dev libreadline-dev +``` + +- Step 1: checkout NXP specific submodules only ``` -user@ubuntu:~/Desktop/git/connectedhomeip$ export NXP_K32W1_SDK_ROOT=/home/user/Desktop/SDK_K32W1/ -user@ubuntu:~/Desktop/git/connectedhomeip$ source ./scripts/activate.sh user@ubuntu:~/Desktop/git/connectedhomeip$ scripts/checkout_submodules.py --shallow --platform nxp --recursive -user@ubuntu:~/Desktop/git/connectedhomeip$ cd examples/contact-sensor-app/nxp/k32w/k32w1 -user@ubuntu:~/Desktop/git/connectedhomeip/examples/contact-sensor-app/nxp/k32w/k32w1$ gn gen out/debug -user@ubuntu:~/Desktop/git/connectedhomeip/examples/contact-sensor-app/nxp/k32w/k32w1$ ninja -C out/debug +``` + +- Step 2: activate local environment + +``` +user@ubuntu:~/Desktop/git/connectedhomeip$ source scripts/activate.sh +``` + +If the script says the environment is out of date, you can update it by running +the following command: + +``` +user@ubuntu:~/Desktop/git/connectedhomeip$ source scripts/bootstrap.sh +``` + +- Step 3: Init NXP SDK(s) + +``` +user@ubuntu:~/Desktop/git/connectedhomeip$ scripts/setup/nxp/update_nxp_sdk.py --platform common_sdk +``` + +Note: By default setup/nxp/update_nxp_sdk.py will try to initialize all NXP +SDKs. Arg "-- help" could be used to view all available options. + +``` +user@ubuntu:~/Desktop/git/connectedhomeip$ cd examples/contact-sensor-app/nxp/k32w1 +user@ubuntu:~/Desktop/git/connectedhomeip/examples/contact-sensor-app/nxp/k32w1$ gn gen out/debug +user@ubuntu:~/Desktop/git/connectedhomeip/examples/contact-sensor-app/nxp/k32w1$ ninja -C out/debug ``` In case that Openthread CLI is needed, chip_with_ot_cli build argument must be @@ -185,7 +212,7 @@ using Fibonacci backoff for retries pacing. Use `chip_with_factory_data=1` 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/guides/nxp/nxp_manufacturing_flow.md). +[Guide for writing manufacturing data on NXP devices](../../../../docs/guides/nxp/nxp_manufacturing_flow.md). ## Flashing @@ -248,7 +275,7 @@ One option for debugging would be to use MCUXpresso IDE. - Drag-and-drop the zip file containing the NXP SDK in the "Installed SDKs" tab: -![Installed SDKs](../../../../platform/nxp/k32w/k32w1/doc/images/installed_sdks.jpg) +![Installed SDKs](../../../platform/nxp/k32w1/doc/images/installed_sdks.jpg) - Import any demo application from the installed SDK: @@ -256,7 +283,7 @@ One option for debugging would be to use MCUXpresso IDE. Import SDK example(s).. -> choose a demo app (demo_apps -> hello_world) -> Finish ``` -![Import demo](../../../../platform/nxp/k32w/k32w1/doc/images/import_demo.jpg) +![Import demo](../../../platform/nxp/k32w1/doc/images/import_demo.jpg) - Flash the previously imported demo application on the board: @@ -275,7 +302,7 @@ resulted after ot-nxp compilation. File -> Import -> C/C++ -> Existing Code as Makefile Project ``` -![New Project](../../../../platform/nxp/k32w/k32w1/doc/images/new_project.jpg) +![New Project](../../../platform/nxp/k32w1/doc/images/new_project.jpg) - Replace the path of the existing demo application with the path of the K32W1 application: @@ -284,7 +311,7 @@ File -> Import -> C/C++ -> Existing Code as Makefile Project Run -> Debug Configurations... -> C/C++ Application ``` -![Debug K32W1](../../../../platform/nxp/k32w/k32w1/doc/images/debug_k32w1.jpg) +![Debug K32W1](../../../platform/nxp/k32w1/doc/images/debug_k32w1.jpg) ## OTA @@ -312,16 +339,21 @@ In `OTAP` application In order to build an OTA image, use NXP wrapper over the standard tool `src/app/ota_image_tool.py`: -- `scripts/tools/nxp/factory_data_generator/ota_image_tool.py` The tool can be - used to generate an OTA image with the following format: - `| OTA image header | TLV1 | TLV2 | ... | TLVn |` where each TLV is in the - form `|tag|length|value|` +- `scripts/tools/nxp/factory_data_generator/ota_image_tool.py`. + +The tool can be used to generate an OTA image with the following format: + +``` + | OTA image header | TLV1 | TLV2 | ... | TLVn | +``` + +where each TLV is in the form `|tag|length|value|`. Note that "standard" TLV format is used. Matter TLV format is only used for factory data TLV value. Please see more in the -[OTA image tool guide](../../../../../scripts/tools/nxp/ota/README.md). +[OTA image tool guide](../../../../scripts/tools/nxp/ota/README.md). Here is an example that generates an OTA image with application update TLV from a `sb3` file: @@ -338,12 +370,24 @@ having a correct OTA process, the OTA header version should be the same as the binary embedded software version. A user can set a custom software version in the gn build args by setting `chip_software_version` to the wanted version. +### OTA factory data + +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 + update processor (disabled by default). + +The OTA image used must be updated to include the new factory data. + +[OTA image tool guide](../../../../scripts/tools/nxp/ota/README.md). + ### Running OTA The OTA topology used for OTA testing is illustrated in the figure below. Topology is similar with the one used for Matter Test Events. -![OTA_TOPOLOGY](../../../../platform/nxp/k32w/k32w1/doc/images/ota_topology.JPG) +![OTA_TOPOLOGY](../../../platform/nxp/k32w1/doc/images/ota_topology.JPG) The concept for OTA is the next one: diff --git a/examples/contact-sensor-app/nxp/k32w/k32w1/args.gni b/examples/contact-sensor-app/nxp/k32w1/args.gni similarity index 84% rename from examples/contact-sensor-app/nxp/k32w/k32w1/args.gni rename to examples/contact-sensor-app/nxp/k32w1/args.gni index 23e6730b79..cb952c94bd 100644 --- a/examples/contact-sensor-app/nxp/k32w/k32w1/args.gni +++ b/examples/contact-sensor-app/nxp/k32w1/args.gni @@ -17,12 +17,17 @@ import("//build_overrides/chip.gni") import("${chip_root}/config/standalone/args.gni") # SDK target. This is overridden to add our SDK app_config.h & defines. -k32w1_sdk_target = get_label_info(":sdk", "label_no_toolchain") +nxp_sdk_target = get_label_info(":sdk", "label_no_toolchain") +nxp_device = "K32W1480" chip_enable_ota_requestor = true chip_stack_lock_tracking = "fatal" chip_enable_ble = true +chip_system_config_provide_statistics = false +chip_system_config_use_open_thread_inet_endpoints = true +chip_with_lwip = false + chip_enable_icd_server = true chip_enable_icd_lit = false icd_enforce_sit_slow_poll_limit = true diff --git a/examples/contact-sensor-app/nxp/k32w1/build_overrides b/examples/contact-sensor-app/nxp/k32w1/build_overrides new file mode 120000 index 0000000000..ee19c065d6 --- /dev/null +++ b/examples/contact-sensor-app/nxp/k32w1/build_overrides @@ -0,0 +1 @@ +../../../build_overrides/ \ No newline at end of file diff --git a/examples/contact-sensor-app/nxp/k32w1/include/config/AppConfig.h b/examples/contact-sensor-app/nxp/k32w1/include/config/AppConfig.h new file mode 100644 index 0000000000..0c8019d8e7 --- /dev/null +++ b/examples/contact-sensor-app/nxp/k32w1/include/config/AppConfig.h @@ -0,0 +1,29 @@ +/* + * Copyright 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 + +/* ---- App Config ---- */ +#define APP_DEVICE_TYPE_ENDPOINT 1 +#define APP_CLUSTER_ATTRIBUTE chip::app::Clusters::BooleanState::Attributes::StateValue + +/* ---- Button Manager Config ---- */ +#define BUTTON_MANAGER_FACTORY_RESET_TIMEOUT_MS 6000 + +/* ---- LED Manager Config ---- */ +#define LED_MANAGER_STATUS_LED_INDEX 0 +#define LED_MANAGER_LIGHT_LED_INDEX 1 diff --git a/examples/contact-sensor-app/nxp/k32w/k32w1/include/CHIPProjectConfig.h b/examples/contact-sensor-app/nxp/k32w1/include/config/CHIPProjectConfig.h similarity index 98% rename from examples/contact-sensor-app/nxp/k32w/k32w1/include/CHIPProjectConfig.h rename to examples/contact-sensor-app/nxp/k32w1/include/config/CHIPProjectConfig.h index 0d9a4e3b50..a16c1bb8b3 100644 --- a/examples/contact-sensor-app/nxp/k32w/k32w1/include/CHIPProjectConfig.h +++ b/examples/contact-sensor-app/nxp/k32w1/include/config/CHIPProjectConfig.h @@ -192,6 +192,13 @@ #define CHIP_DEVICE_CONFIG_ENABLE_SED 1 +/** + * @def CHIP_DEVICE_CONFIG_KVS_WEAR_STATS + * + * @brief Toggle support for key value store wear stats on or off. + */ +#define CHIP_DEVICE_CONFIG_KVS_WEAR_STATS 1 + /** * @def CHIP_IM_MAX_NUM_COMMAND_HANDLER * diff --git a/examples/contact-sensor-app/nxp/k32w1/third_party/connectedhomeip b/examples/contact-sensor-app/nxp/k32w1/third_party/connectedhomeip new file mode 120000 index 0000000000..59307833b4 --- /dev/null +++ b/examples/contact-sensor-app/nxp/k32w1/third_party/connectedhomeip @@ -0,0 +1 @@ +../../../../.. \ No newline at end of file diff --git a/examples/lighting-app/nxp/common/AppTask.cpp b/examples/lighting-app/nxp/common/AppTask.cpp new file mode 100644 index 0000000000..6bca466976 --- /dev/null +++ b/examples/lighting-app/nxp/common/AppTask.cpp @@ -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. + */ + +#include "AppTask.h" + +#include + +void LightingApp::AppTask::PreInitMatterStack() +{ + ChipLogProgress(DeviceLayer, "Welcome to NXP Lighting Demo App"); +} + +LightingApp::AppTask & LightingApp::AppTask::GetDefaultInstance() +{ + static LightingApp::AppTask sAppTask; + return sAppTask; +} + +chip::NXP::App::AppTaskBase & chip::NXP::App::GetAppTask() +{ + return LightingApp::AppTask::GetDefaultInstance(); +} diff --git a/examples/lighting-app/nxp/k32w/k32w1/main/ZclCallbacks.cpp b/examples/lighting-app/nxp/common/DeviceCallbacks.cpp similarity index 51% rename from examples/lighting-app/nxp/k32w/k32w1/main/ZclCallbacks.cpp rename to examples/lighting-app/nxp/common/DeviceCallbacks.cpp index 97a3fb9aa7..140cdffb9f 100644 --- a/examples/lighting-app/nxp/k32w/k32w1/main/ZclCallbacks.cpp +++ b/examples/lighting-app/nxp/common/DeviceCallbacks.cpp @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2024 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -18,59 +18,72 @@ #include -#include "AppTask.h" -#include "LightingManager.h" +#include "DeviceCallbacks.h" +#if CONFIG_ENABLE_FEEDBACK +#include "UserInterfaceFeedback.h" +#endif #include #include -#include -#include using namespace ::chip; using namespace ::chip::app::Clusters; -void MatterPostAttributeChangeCallback(const chip::app::ConcreteAttributePath & path, uint8_t type, uint16_t size, uint8_t * value) +void LightingApp::DeviceCallbacks::PostAttributeChangeCallback(chip::EndpointId endpoint, chip::ClusterId clusterId, + chip::AttributeId attributeId, uint8_t type, uint16_t size, + uint8_t * value) { - if (path.mClusterId == OnOff::Id) + if (clusterId == OnOff::Id) { - if (path.mAttributeId != OnOff::Attributes::OnOff::Id) + if (attributeId != OnOff::Attributes::OnOff::Id) { - ChipLogProgress(Zcl, "Unknown attribute ID: " ChipLogFormatMEI, ChipLogValueMEI(path.mAttributeId)); + ChipLogProgress(Zcl, "Unknown attribute ID: " ChipLogFormatMEI, ChipLogValueMEI(attributeId)); return; } - - LightingMgr().InitiateAction(0, *value ? LightingManager::TURNON_ACTION : LightingManager::TURNOFF_ACTION, *value); +#if CONFIG_ENABLE_FEEDBACK + FeedbackMgr().RestoreState(); +#endif } - else if (path.mClusterId == LevelControl::Id) + else if (clusterId == LevelControl::Id) { - if (path.mAttributeId != LevelControl::Attributes::CurrentLevel::Id) + if (attributeId != LevelControl::Attributes::CurrentLevel::Id) { - ChipLogProgress(Zcl, "Unknown attribute ID: " ChipLogFormatMEI, ChipLogValueMEI(path.mAttributeId)); + ChipLogProgress(Zcl, "Unknown attribute ID: " ChipLogFormatMEI, ChipLogValueMEI(attributeId)); return; } - +#if LIGHTING_MANAGER_ENABLE_DIMMABLE_LED if (*value > 1 && *value < 254) { ChipLogProgress(Zcl, "Setting value: %d", *value); - LightingMgr().InitiateAction(0, LightingManager::DIM_ACTION, *value); + // The cluster attribute value will be read in RestoreState and the proper action will be taken: e.g. ApplyDim. +#if CONFIG_ENABLE_FEEDBACK + FeedbackMgr().RestoreState(); +#endif } +#endif } - else if (path.mClusterId == ColorControl::Id) + else if (clusterId == ColorControl::Id) { ChipLogProgress(Zcl, "Color Control attribute ID: " ChipLogFormatMEI " Type: %u Value: %u, length %u", - ChipLogValueMEI(path.mAttributeId), type, *value, size); + ChipLogValueMEI(attributeId), type, *value, size); // WIP Apply attribute change to Light } - else if (path.mClusterId == OnOffSwitchConfiguration::Id) + else if (clusterId == OnOffSwitchConfiguration::Id) { ChipLogProgress(Zcl, "OnOff Switch Configuration attribute ID: " ChipLogFormatMEI " Type: %u Value: %u, length %u", - ChipLogValueMEI(path.mAttributeId), type, *value, size); + ChipLogValueMEI(attributeId), type, *value, size); // WIP Apply attribute change to Light } else { - ChipLogProgress(Zcl, "Unknown attribute ID: " ChipLogFormatMEI, ChipLogValueMEI(path.mAttributeId)); + ChipLogProgress(Zcl, "Unknown attribute ID: " ChipLogFormatMEI, ChipLogValueMEI(attributeId)); } } + +chip::DeviceManager::CHIPDeviceManagerCallbacks & chip::NXP::App::GetDeviceCallbacks() +{ + static LightingApp::DeviceCallbacks sDeviceCallbacks; + return sDeviceCallbacks; +} diff --git a/src/platform/nxp/k32w/k32w1/DefaultTestEventTriggerDelegate.h b/examples/lighting-app/nxp/common/include/AppEvent.h similarity index 60% rename from src/platform/nxp/k32w/k32w1/DefaultTestEventTriggerDelegate.h rename to examples/lighting-app/nxp/common/include/AppEvent.h index 0bfd4c5b0f..b292afaddf 100644 --- a/src/platform/nxp/k32w/k32w1/DefaultTestEventTriggerDelegate.h +++ b/examples/lighting-app/nxp/common/include/AppEvent.h @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2022 Project CHIP Authors + * Copyright (c) 2024 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -18,19 +18,10 @@ #pragma once -#include +struct AppEvent; +typedef void (*EventHandler)(const AppEvent &); -namespace chip { - -class DefaultTestEventTriggerDelegate : public TestEventTriggerDelegate +struct AppEvent { -public: - explicit DefaultTestEventTriggerDelegate(const ByteSpan & enableKey) : mEnableKey(enableKey) {} - - bool DoesEnableKeyMatch(const ByteSpan & enableKey) const override; - -private: - ByteSpan mEnableKey; + EventHandler Handler; }; - -} // namespace chip diff --git a/examples/lighting-app/nxp/common/include/AppTask.h b/examples/lighting-app/nxp/common/include/AppTask.h new file mode 100644 index 0000000000..9f73d340f3 --- /dev/null +++ b/examples/lighting-app/nxp/common/include/AppTask.h @@ -0,0 +1,46 @@ +/* + * + * 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 "AppConfig.h" +#include "AppTaskFreeRTOS.h" + +#include + +namespace LightingApp { + +class AppTask : public chip::NXP::App::AppTaskFreeRTOS +{ +public: + // AppTaskFreeRTOS virtual methods + void PreInitMatterStack() override; + + // This returns an instance of this class. + static AppTask & GetDefaultInstance(); +}; + +} // namespace LightingApp + +/** + * Returns the application-specific implementation of the AppTaskBase object. + * + * Applications can use this to gain access to features of the AppTaskBase + * that are specific to the selected application. + */ +chip::NXP::App::AppTaskBase & GetAppTask(); diff --git a/examples/lighting-app/nxp/common/include/DeviceCallbacks.h b/examples/lighting-app/nxp/common/include/DeviceCallbacks.h new file mode 100644 index 0000000000..555021b36e --- /dev/null +++ b/examples/lighting-app/nxp/common/include/DeviceCallbacks.h @@ -0,0 +1,51 @@ +/* + * + * 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. + */ + +/** + * @file DeviceCallbacks.h + * + * Lighting app implementation for the DeviceManager callbacks for all applications + * + **/ + +#pragma once + +#include "CHIPDeviceManager.h" +#include "CommonDeviceCallbacks.h" + +namespace LightingApp { + +class DeviceCallbacks : public chip::NXP::App::CommonDeviceCallbacks +{ +public: + void PostAttributeChangeCallback(chip::EndpointId endpoint, chip::ClusterId clusterId, chip::AttributeId attributeId, + uint8_t type, uint16_t size, uint8_t * value) override; +}; + +} // namespace LightingApp + +namespace chip::NXP::App { +/** + * Returns the application-specific implementation of the CommonDeviceCallbacks object. + * + * Applications can use this to gain access to features of the CommonDeviceCallbacks + * that are specific to the selected application. + */ +chip::DeviceManager::CHIPDeviceManagerCallbacks & GetDeviceCallbacks(); + +} // namespace chip::NXP::App diff --git a/examples/lighting-app/nxp/common/main.cpp b/examples/lighting-app/nxp/common/main.cpp new file mode 100644 index 0000000000..d9672b5402 --- /dev/null +++ b/examples/lighting-app/nxp/common/main.cpp @@ -0,0 +1,39 @@ +/* + * + * 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 "AppTask.h" +#include "FreeRTOS.h" + +#if configAPPLICATION_ALLOCATED_HEAP +uint8_t __attribute__((section(".heap"))) ucHeap[configTOTAL_HEAP_SIZE]; +#endif + +#if FSL_OSA_MAIN_FUNC_ENABLE +extern "C" void main_task(void const * argument) +{ + chip::DeviceLayer::PlatformMgrImpl().HardwareInit(); + chip::NXP::App::GetAppTask().Start(); +} +#else +extern "C" int main(int argc, char * argv[]) +{ + chip::DeviceLayer::PlatformMgrImpl().HardwareInit(); + chip::NXP::App::GetAppTask().Start(); + vTaskStartScheduler(); +} +#endif diff --git a/examples/lighting-app/nxp/k32w/k32w1/BUILD.gn b/examples/lighting-app/nxp/k32w/k32w1/BUILD.gn deleted file mode 100644 index dd40445e0e..0000000000 --- a/examples/lighting-app/nxp/k32w/k32w1/BUILD.gn +++ /dev/null @@ -1,196 +0,0 @@ -# Copyright (c) 2021 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/nxp_sdk.gni") -import("//build_overrides/openthread.gni") -import("${nxp_sdk_build_root}/nxp_sdk.gni") - -import("${nxp_sdk_build_root}/${nxp_sdk_name}/nxp_executable.gni") - -import("${nxp_sdk_build_root}/${nxp_sdk_name}/${nxp_sdk_name}.gni") - -import("${chip_root}/src/crypto/crypto.gni") -import("${chip_root}/src/lib/core/core.gni") -import("${chip_root}/src/platform/device.gni") -import("${chip_root}/src/platform/nxp/${nxp_platform}/args.gni") - -import("${chip_root}/examples/common/pigweed/pigweed_rpcs.gni") - -if (chip_enable_pw_rpc) { - import("//build_overrides/pigweed.gni") - import("$dir_pw_build/target_types.gni") - import("${chip_root}/examples/platform/nxp/pw_rpc_server.gni") -} - -declare_args() { - chip_software_version = 0 - - # Setup discriminator as argument - setup_discriminator = 3840 -} - -assert(current_os == "freertos") - -k32w1_platform_dir = "${chip_root}/examples/platform/nxp/k32w/k32w1" -k32w1_sdk_root = getenv("NXP_K32W1_SDK_ROOT") - -k32w1_sdk("sdk") { - sources = [ - "${k32w1_platform_dir}/app/project_include/OpenThreadConfig.h", - "include/CHIPProjectConfig.h", - "include/FreeRTOSConfig.h", - "main/include/app_config.h", - ] - - public_deps = - [ "${chip_root}/third_party/openthread/platforms:libopenthread-platform" ] - - include_dirs = [ - "main/include", - "main", - "include", - "${k32w1_platform_dir}/app/project_include", - "${k32w1_platform_dir}/app/support", - "${k32w1_platform_dir}/app/ldscripts", - "${k32w1_platform_dir}/util/include", - ] - - defines = [] - if (is_debug) { - defines += [ "BUILD_RELEASE=0" ] - } else { - defines += [ "BUILD_RELEASE=1" ] - } - - if (chip_software_version != 0) { - defines += [ - "CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION=${chip_software_version}", - ] - } - - if (chip_enable_pw_rpc) { - defines += [ - "PW_RPC_ENABLED", - "STREAMER_UART_FLUSH_DELAY_MS=0", - "STREAMER_UART_SERIAL_MANAGER_RING_BUFFER_SIZE=512", - "BOARD_APP_UART_CLK_FREQ=96000000", - ] - } - - defines += [ - "CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR=${setup_discriminator}", - ] -} - -k32w1_executable("light_app") { - output_name = "chip-k32w1-light-example" - - sources = [] - deps = [] - defines = [] - - if (chip_config_dimmable_led) { - defines += [ "CHIP_CONFIG_ENABLE_DIMMABLE_LED = 1" ] - } else { - defines += [ "CHIP_CONFIG_ENABLE_DIMMABLE_LED = 0" ] - } - - if (chip_enable_pw_rpc) { - forward_variables_from(pw_rpc_server, "*") - } else { - cflags = [ "-Wconversion" ] - } - - sources += [ - "${k32w1_platform_dir}/util/LEDWidget.cpp", - "${k32w1_platform_dir}/util/include/LEDWidget.h", - "main/AppTask.cpp", - "main/LightingManager.cpp", - "main/ZclCallbacks.cpp", - "main/include/AppEvent.h", - "main/include/AppTask.h", - "main/include/LightingManager.h", - "main/main.cpp", - ] - - if (chip_config_dimmable_led) { - sources += [ - "${k32w1_platform_dir}/util/LED_Dimmer.cpp", - "${k32w1_platform_dir}/util/include/LED_Dimmer.h", - ] - deps += [ "${chip_root}/examples/lighting-app/lighting-common/" ] - } else { - deps += [ "${chip_root}/examples/lighting-app/nxp/zap/" ] - } - - deps += [ - ":sdk", - "${chip_root}/examples/common/QRCode", - "${chip_root}/examples/providers:device_info_provider", - "${chip_root}/src/lib", - "${chip_root}/src/platform:syscalls_stub", - "${chip_root}/src/platform/logging:default", - "${chip_root}/third_party/mbedtls:mbedtls", - "${k32w1_platform_dir}/app/support:freertos_mbedtls_utils", - ] - - if (chip_openthread_ftd) { - deps += [ - "${openthread_root}:libopenthread-cli-ftd", - "${openthread_root}:libopenthread-ftd", - ] - } else { - deps += [ - "${openthread_root}:libopenthread-cli-mtd", - "${openthread_root}:libopenthread-mtd", - ] - } - - if (use_smu2_static) { - ldscript = "${k32w1_platform_dir}/app/ldscripts/k32w1_app.ld" - base_ldscript_dir = "${k32w1_sdk_root}/middleware/wireless/framework/Common/devices/kw45_k32w1/gcc" - } else { - ldscript = "${k32w1_sdk_root}/middleware/wireless/framework/Common/devices/kw45_k32w1/gcc/connectivity.ld" - } - - inputs = [ ldscript ] - - ldflags = [ - "-Wl,--defsym=__heap_size__=0", - "-Wl,--defsym=__stack_size__=0x480", - "-Wl,--defsym=gUseFactoryData_d=1", - "-Wl,-print-memory-usage", - "-Wl,--no-warn-rwx-segments", - "-T" + rebase_path(ldscript, root_build_dir), - ] - - if (chip_with_factory_data == 1) { - ldflags += [ "-Wl,--defsym=gUseFactoryData_d=1" ] - } - - if (use_smu2_static) { - ldflags += [ "-L" + rebase_path(base_ldscript_dir, root_build_dir) ] - } - - output_dir = root_out_dir -} - -group("k32w1") { - deps = [ ":light_app" ] -} - -group("default") { - deps = [ ":k32w1" ] -} diff --git a/examples/lighting-app/nxp/k32w/k32w1/build_overrides b/examples/lighting-app/nxp/k32w/k32w1/build_overrides deleted file mode 120000 index ad07557834..0000000000 --- a/examples/lighting-app/nxp/k32w/k32w1/build_overrides +++ /dev/null @@ -1 +0,0 @@ -../../../../build_overrides/ \ No newline at end of file diff --git a/examples/lighting-app/nxp/k32w/k32w1/include/FreeRTOSConfig.h b/examples/lighting-app/nxp/k32w/k32w1/include/FreeRTOSConfig.h deleted file mode 100644 index 95279e6337..0000000000 --- a/examples/lighting-app/nxp/k32w/k32w1/include/FreeRTOSConfig.h +++ /dev/null @@ -1,181 +0,0 @@ -/* - * FreeRTOS Kernel V10.2.0 - * Copyright (C) 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of - * this software and associated documentation files (the "Software"), to deal in - * the Software without restriction, including without limitation the rights to - * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of - * the Software, and to permit persons to whom the Software is furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS - * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR - * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER - * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - * http://www.FreeRTOS.org - * http://aws.amazon.com/freertos - * - * 1 tab == 4 spaces! - */ - -#pragma once - -/*----------------------------------------------------------- - * Application specific definitions. - * - * These definitions should be adjusted for your particular hardware and - * application requirements. - * - * THESE PARAMETERS ARE DESCRIBED WITHIN THE 'CONFIGURATION' SECTION OF THE - * FreeRTOS API DOCUMENTATION AVAILABLE ON THE FreeRTOS.org WEB SITE. - * - * See http://www.freertos.org/a00110.html. - *----------------------------------------------------------*/ - -#define configUSE_PREEMPTION 1 -#define configUSE_TICKLESS_IDLE 0 -/* Ensure stdint is only used by the compiler, and not the assembler. */ -#if defined(__ICCARM__) || defined(__ARMCC_VERSION) || defined(__GNUC__) -#include -extern uint32_t SystemCoreClock; -#endif -#define configCPU_CLOCK_HZ (SystemCoreClock) -#define configTICK_RATE_HZ ((TickType_t) 100) -#define configMAX_PRIORITIES (8) -// idle task stack size needs to be increased for OTA EEPROM processing -#define configMINIMAL_STACK_SIZE ((unsigned short) 450) -#define configMAX_TASK_NAME_LEN 20 -#define configUSE_16_BIT_TICKS 0 -#define configIDLE_SHOULD_YIELD 1 -#define configUSE_TASK_NOTIFICATIONS 1 -#define configUSE_MUTEXES 1 -#define configUSE_RECURSIVE_MUTEXES 1 -#define configUSE_COUNTING_SEMAPHORES 1 -#define configUSE_ALTERNATIVE_API 0 /* Deprecated! */ -#define configQUEUE_REGISTRY_SIZE 8 -#define configUSE_QUEUE_SETS 0 -#define configUSE_TIME_SLICING 0 -#define configUSE_NEWLIB_REENTRANT 0 -#define configENABLE_BACKWARD_COMPATIBILITY 1 -#define configNUM_THREAD_LOCAL_STORAGE_POINTERS 5 - -/* Tasks.c additions (e.g. Thread Aware Debug capability) */ -#define configINCLUDE_FREERTOS_TASK_C_ADDITIONS_H 1 - -/* Used memory allocation (heap_x.c) */ -#define configFRTOS_MEMORY_SCHEME 4 - -/* Memory allocation related definitions. */ -#define configSUPPORT_STATIC_ALLOCATION 0 -#define configSUPPORT_DYNAMIC_ALLOCATION 1 -#define configTOTAL_HEAP_SIZE ((size_t) (gTotalHeapSize_c)) -#define configAPPLICATION_ALLOCATED_HEAP 1 - -/* Hook function related definitions. */ -#ifndef configUSE_IDLE_HOOK -#define configUSE_IDLE_HOOK 1 -#endif -#define configUSE_TICK_HOOK 0 -#define configCHECK_FOR_STACK_OVERFLOW 0 -#ifndef configUSE_MALLOC_FAILED_HOOK -#define configUSE_MALLOC_FAILED_HOOK 0 -#endif -#define configUSE_DAEMON_TASK_STARTUP_HOOK 0 - -/* Run time and task stats gathering related definitions. */ -#define configGENERATE_RUN_TIME_STATS 0 -#define configUSE_TRACE_FACILITY 1 -#define configUSE_STATS_FORMATTING_FUNCTIONS 0 - -/* Task aware debugging. */ -#define configRECORD_STACK_HIGH_ADDRESS 1 - -/* Co-routine related definitions. */ -#define configUSE_CO_ROUTINES 0 -#define configMAX_CO_ROUTINE_PRIORITIES 2 - -/* Software timer related definitions. */ -#define configUSE_TIMERS 1 -#define configTIMER_TASK_PRIORITY (configMAX_PRIORITIES - 1) -#define configTIMER_QUEUE_LENGTH 10 -#define configTIMER_TASK_STACK_DEPTH (360) - -/* Define to trap errors during development. */ -#define configASSERT(x) \ - if ((x) == 0) \ - { \ - taskDISABLE_INTERRUPTS(); \ - for (;;) \ - ; \ - } - -/* Optional functions - most linkers will remove unused functions anyway. */ -#define INCLUDE_vTaskPrioritySet 1 -#define INCLUDE_uxTaskPriorityGet 1 -#define INCLUDE_vTaskDelete 1 -#define INCLUDE_vTaskSuspend 1 -#define INCLUDE_xResumeFromISR 1 -#define INCLUDE_vTaskDelayUntil 1 -#define INCLUDE_vTaskDelay 1 -#define INCLUDE_xTaskGetSchedulerState 1 -#define INCLUDE_xTaskGetCurrentTaskHandle 1 -#define INCLUDE_uxTaskGetStackHighWaterMark 1 -#define INCLUDE_xTaskGetIdleTaskHandle 0 -#define INCLUDE_eTaskGetState 0 -#define INCLUDE_xEventGroupSetBitFromISR 1 -#define INCLUDE_xTimerPendFunctionCall 1 -#define INCLUDE_xTaskAbortDelay 0 -#define INCLUDE_xTaskGetHandle 0 -#define INCLUDE_xTaskResumeFromISR 1 -#define INCLUDE_xQueueGetMutexHolder 1 - -/* Interrupt nesting behaviour configuration. Cortex-M specific. */ -#ifdef __NVIC_PRIO_BITS -/* __BVIC_PRIO_BITS will be specified when CMSIS is being used. */ -#define configPRIO_BITS __NVIC_PRIO_BITS -#else -#define configPRIO_BITS 3 -#endif - -/* The lowest interrupt priority that can be used in a call to a "set priority" -function. */ -#define configLIBRARY_LOWEST_INTERRUPT_PRIORITY 0x7 - -/* The highest interrupt priority that can be used by any interrupt service -routine that makes calls to interrupt safe FreeRTOS API functions. DO NOT CALL -INTERRUPT SAFE FREERTOS API FUNCTIONS FROM ANY INTERRUPT THAT HAS A HIGHER -PRIORITY THAN THIS! (higher priorities are lower numeric values. */ -#define configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY 1 - -/* Interrupt priorities used by the kernel port layer itself. These are generic -to all Cortex-M ports, and do not rely on any particular library functions. */ -#define configKERNEL_INTERRUPT_PRIORITY (configLIBRARY_LOWEST_INTERRUPT_PRIORITY << (8 - configPRIO_BITS)) -/* !!!! configMAX_SYSCALL_INTERRUPT_PRIORITY must not be set to zero !!!! -See http://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html. */ -#define configMAX_SYSCALL_INTERRUPT_PRIORITY (configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY << (8 - configPRIO_BITS)) - -#ifndef configENABLE_FPU -#define configENABLE_FPU 0 -#endif -#ifndef configENABLE_MPU -#define configENABLE_MPU 0 -#endif -#ifndef configENABLE_TRUSTZONE -#define configENABLE_TRUSTZONE 0 -#endif -#ifndef configRUN_FREERTOS_SECURE_ONLY -#define configRUN_FREERTOS_SECURE_ONLY 1 -#endif - -/* Definitions that map the FreeRTOS port interrupt handlers to their CMSIS -standard names. */ -#define vPortSVCHandler SVC_Handler -#define xPortPendSVHandler PendSV_Handler -#define xPortSysTickHandler SysTick_Handler diff --git a/examples/lighting-app/nxp/k32w/k32w1/main/AppTask.cpp b/examples/lighting-app/nxp/k32w/k32w1/main/AppTask.cpp deleted file mode 100644 index 4c1d087547..0000000000 --- a/examples/lighting-app/nxp/k32w/k32w1/main/AppTask.cpp +++ /dev/null @@ -1,932 +0,0 @@ -/* - * - * Copyright (c) 2021 Project CHIP Authors - * Copyright (c) 2021 Google LLC. - * 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 "AppTask.h" -#include "AppEvent.h" -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#if defined(USE_SMU2_DYNAMIC) -#include -#endif - -#include -#include -#include -#include - -/* OTA related includes */ -#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR -#include "OtaSupport.h" -#include -#include -#include -#include -#include -#endif - -#include "K32W1PersistentStorageOpKeystore.h" - -#include "LEDWidget.h" -#include "app.h" -#include "app_config.h" -#include "fsl_component_button.h" -#include "fwk_platform.h" - -#if CHIP_CONFIG_ENABLE_DIMMABLE_LED -#include "LED_Dimmer.h" -#endif - -#define FACTORY_RESET_TRIGGER_TIMEOUT 6000 -#define FACTORY_RESET_CANCEL_WINDOW_TIMEOUT 3000 -#define APP_TASK_PRIORITY 2 -#define APP_EVENT_QUEUE_SIZE 10 - -TimerHandle_t sFunctionTimer; // FreeRTOS app sw timer. - -static QueueHandle_t sAppEventQueue; - -/* - * The status LED and the external flash CS pin are wired together. - * The OTA image writing may fail if used together. - */ -#ifndef CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR -static LEDWidget sStatusLED; -#endif -static LEDWidget sLightLED; - -static bool sIsThreadProvisioned = false; -#ifndef CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR -static bool sHaveFullConnectivity = false; -#endif -static bool sHaveBLEConnections = false; - -#if CHIP_DEVICE_CONFIG_THREAD_ENABLE_CLI -extern "C" void otPlatUartProcess(void); -#endif - -using namespace ::chip::Credentials; -using namespace ::chip::DeviceLayer; -using namespace chip; -using namespace chip::app; - -AppTask AppTask::sAppTask; -#if CONFIG_CHIP_LOAD_REAL_FACTORY_DATA -static AppTask::FactoryDataProvider sFactoryDataProvider; -#endif - -// This key is for testing/certification only and should not be used in production devices. -// For production devices this key must be provided from factory data. -uint8_t sTestEventTriggerEnableKey[TestEventTriggerDelegate::kEnableKeyLength] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, - 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff }; - -static Identify gIdentify = { chip::EndpointId{ 1 }, AppTask::OnIdentifyStart, AppTask::OnIdentifyStop, - Clusters::Identify::IdentifyTypeEnum::kVisibleIndicator, AppTask::OnTriggerEffect, - // Use invalid value for identifiers to enable TriggerEffect command - // to stop Identify command for each effect - Clusters::Identify::EffectIdentifierEnum::kUnknownEnumValue, - Clusters::Identify::EffectVariantEnum::kDefault }; - -/* OTA related variables */ -#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR -static DefaultOTARequestor gRequestorCore; -static DefaultOTARequestorStorage gRequestorStorage; -static DeviceLayer::DefaultOTARequestorDriver gRequestorUser; -static BDXDownloader gDownloader; - -constexpr uint16_t requestedOtaBlockSize = 1024; -#endif - -CHIP_ERROR AppTask::StartAppTask() -{ - CHIP_ERROR err = CHIP_NO_ERROR; - - sAppEventQueue = xQueueCreate(APP_EVENT_QUEUE_SIZE, sizeof(AppEvent)); - if (sAppEventQueue == NULL) - { - err = APP_ERROR_EVENT_QUEUE_FAILED; - K32W_LOG("Failed to allocate app event queue"); - assert(err == CHIP_NO_ERROR); - } - - return err; -} - -CHIP_ERROR AppTask::Init() -{ - CHIP_ERROR err = CHIP_NO_ERROR; - - PlatformMgr().AddEventHandler(MatterEventHandler, 0); - - // Init ZCL Data Model and start server - PlatformMgr().ScheduleWork(InitServer, 0); - -#if CONFIG_CHIP_LOAD_REAL_FACTORY_DATA - ReturnErrorOnFailure(sFactoryDataProvider.Init()); - SetDeviceInstanceInfoProvider(&sFactoryDataProvider); - SetDeviceAttestationCredentialsProvider(&sFactoryDataProvider); - SetCommissionableDataProvider(&sFactoryDataProvider); -#else - SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); -#endif // CONFIG_CHIP_LOAD_REAL_FACTORY_DATA - - // QR code will be used with CHIP Tool - AppTask::PrintOnboardingInfo(); - - if (LightingMgr().Init() != 0) - { - K32W_LOG("LightingMgr().Init() failed"); - assert(0); - } - - LightingMgr().SetCallbacks(ActionInitiated, ActionCompleted); - - /* start with all LEDS turnedd off */ -#ifndef CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR - sStatusLED.Init(SYSTEM_STATE_LED, false); -#endif - -#if CHIP_CONFIG_ENABLE_DIMMABLE_LED - init_dimmable(); -#else - sLightLED.Init(LIGHT_STATE_LED, false); -#endif - - UpdateDeviceState(); - - /* intialize the Keyboard and button press callback */ - BUTTON_InstallCallback((button_handle_t) g_buttonHandle[0], KBD_Callback, (void *) BLE_BUTTON); - BUTTON_InstallCallback((button_handle_t) g_buttonHandle[1], KBD_Callback, (void *) LIGHT_BUTTON); - - // Create FreeRTOS sw timer for Function Selection. - sFunctionTimer = xTimerCreate("FnTmr", // Just a text name, not used by the RTOS kernel - 1, // == default timer period (mS) - false, // no timer reload (==one-shot) - (void *) this, // init timer id = app task obj context - TimerEventHandler // timer callback handler - ); - - if (sFunctionTimer == NULL) - { - err = APP_ERROR_CREATE_TIMER_FAILED; - K32W_LOG("app_timer_create() failed"); - assert(err == CHIP_NO_ERROR); - } - - // Print the current software version - char currentSoftwareVer[ConfigurationManager::kMaxSoftwareVersionStringLength + 1] = { 0 }; - err = ConfigurationMgr().GetSoftwareVersionString(currentSoftwareVer, sizeof(currentSoftwareVer)); - if (err != CHIP_NO_ERROR) - { - K32W_LOG("Get version error"); - assert(err == CHIP_NO_ERROR); - } - - uint32_t currentVersion; - err = ConfigurationMgr().GetSoftwareVersion(currentVersion); - - K32W_LOG("Current Software Version: %s, %d", currentSoftwareVer, currentVersion); - - return err; -} - -void LockOpenThreadTask(void) -{ - chip::DeviceLayer::ThreadStackMgr().LockThreadStack(); -} - -void UnlockOpenThreadTask(void) -{ - chip::DeviceLayer::ThreadStackMgr().UnlockThreadStack(); -} - -void AppTask::InitServer(intptr_t arg) -{ - static chip::CommonCaseDeviceServerInitParams initParams; - (void) initParams.InitializeStaticResourcesBeforeServerInit(); - -#if CHIP_CRYPTO_PLATFORM - static chip::K32W1PersistentStorageOpKeystore sK32W1PersistentStorageOpKeystore; - VerifyOrDie((sK32W1PersistentStorageOpKeystore.Init(initParams.persistentStorageDelegate)) == CHIP_NO_ERROR); - initParams.operationalKeystore = &sK32W1PersistentStorageOpKeystore; -#endif - -#if defined(USE_SMU2_DYNAMIC) - VerifyOrDie(SMU2::Init() == CHIP_NO_ERROR); -#endif - - // Init ZCL Data Model and start server - static DefaultTestEventTriggerDelegate sTestEventTriggerDelegate{ ByteSpan(sTestEventTriggerEnableKey) }; - initParams.testEventTriggerDelegate = &sTestEventTriggerDelegate; - chip::Inet::EndPointStateOpenThread::OpenThreadEndpointInitParam nativeParams; - nativeParams.lockCb = LockOpenThreadTask; - nativeParams.unlockCb = UnlockOpenThreadTask; - nativeParams.openThreadInstancePtr = chip::DeviceLayer::ThreadStackMgrImpl().OTInstance(); - initParams.endpointNativeParams = static_cast(&nativeParams); - VerifyOrDie((chip::Server::GetInstance().Init(initParams)) == CHIP_NO_ERROR); -} - -void AppTask::PrintOnboardingInfo() -{ - chip::PayloadContents payload; - CHIP_ERROR err = GetPayloadContents(payload, chip::RendezvousInformationFlags(chip::RendezvousInformationFlag::kBLE)); - if (err != CHIP_NO_ERROR) - { - ChipLogError(AppServer, "GetPayloadContents() failed: %" CHIP_ERROR_FORMAT, err.Format()); - } - payload.commissioningFlow = chip::CommissioningFlow::kUserActionRequired; - PrintOnboardingCodes(payload); -} - -#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR -void AppTask::InitOTA(intptr_t arg) -{ - // Initialize and interconnect the Requestor and Image Processor objects -- START - SetRequestorInstance(&gRequestorCore); - - gRequestorStorage.Init(chip::Server::GetInstance().GetPersistentStorage()); - gRequestorCore.Init(chip::Server::GetInstance(), gRequestorStorage, gRequestorUser, gDownloader); - gRequestorUser.SetMaxDownloadBlockSize(requestedOtaBlockSize); - auto & imageProcessor = OTAImageProcessorImpl::GetDefaultInstance(); - gRequestorUser.Init(&gRequestorCore, &imageProcessor); - CHIP_ERROR err = imageProcessor.Init(&gDownloader); - if (err != CHIP_NO_ERROR) - { - K32W_LOG("Image processor init failed"); - assert(err == CHIP_NO_ERROR); - } - - // Connect the gDownloader and Image Processor objects - gDownloader.SetImageProcessorDelegate(&imageProcessor); - // Initialize and interconnect the Requestor and Image Processor objects -- END -} -#endif - -void AppTask::AppTaskMain(void * pvParameter) -{ - AppEvent event; - - CHIP_ERROR err = sAppTask.Init(); - if (err != CHIP_NO_ERROR) - { - K32W_LOG("AppTask.Init() failed"); - assert(err == CHIP_NO_ERROR); - } - - while (true) - { - BaseType_t eventReceived = xQueueReceive(sAppEventQueue, &event, pdMS_TO_TICKS(10)); - while (eventReceived == pdTRUE) - { - sAppTask.DispatchEvent(&event); - eventReceived = xQueueReceive(sAppEventQueue, &event, 0); - } - - // Collect connectivity and configuration state from the CHIP stack. Because the - // CHIP event loop is being run in a separate task, the stack must be locked - // while these values are queried. However we use a non-blocking lock request - // (TryLockChipStack()) to avoid blocking other UI activities when the CHIP - // task is busy (e.g. with a long crypto operation). - if (PlatformMgr().TryLockChipStack()) - { -#if CHIP_DEVICE_CONFIG_THREAD_ENABLE_CLI - otPlatUartProcess(); -#endif - - sIsThreadProvisioned = ConnectivityMgr().IsThreadProvisioned(); - sHaveBLEConnections = (ConnectivityMgr().NumBLEConnections() != 0); - PlatformMgr().UnlockChipStack(); - } - - // Update the status LED if factory reset or identify process have not been initiated. - // - // If system has "full connectivity", keep the LED On constantly. - // - // If thread and service provisioned, but not attached to the thread network yet OR no - // connectivity to the service OR subscriptions are not fully established - // THEN blink the LED Off for a short period of time. - // - // If the system has ble connection(s) uptill the stage above, THEN blink the LEDs at an even - // rate of 100ms. - // - // Otherwise, blink the LED ON for a very short time. - if (sAppTask.mFunction != kFunction_FactoryReset) - { -#ifndef CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR - if (sHaveFullConnectivity) - { - sStatusLED.Set(true); - } - else if (sIsThreadProvisioned) - { - sStatusLED.Blink(950, 50); - } - else if (sHaveBLEConnections) - { - sStatusLED.Blink(100, 100); - } - else - { - sStatusLED.Blink(50, 950); - } -#endif - } - -#ifndef CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR - sStatusLED.Animate(); -#endif - sLightLED.Animate(); - } -} - -void AppTask::ButtonEventHandler(uint8_t pin_no, uint8_t button_action) -{ - if ((pin_no != RESET_BUTTON) && (pin_no != LIGHT_BUTTON) && (pin_no != SOFT_RESET_BUTTON) && (pin_no != BLE_BUTTON)) - { - return; - } - - AppEvent button_event; - button_event.Type = AppEvent::kEventType_Button; - button_event.ButtonEvent.PinNo = pin_no; - button_event.ButtonEvent.Action = button_action; - - if (pin_no == LIGHT_BUTTON) - { - button_event.Handler = LightActionEventHandler; - } - else if (pin_no == SOFT_RESET_BUTTON) - { - // Soft reset ensures that platform manager shutdown procedure is called. - button_event.Handler = SoftResetHandler; - } - else if (pin_no == BLE_BUTTON) - { - button_event.Handler = BleHandler; - - if (button_action == RESET_BUTTON_PUSH) - { - button_event.Handler = ResetActionEventHandler; - } - } - sAppTask.PostEvent(&button_event); -} - -button_status_t AppTask::KBD_Callback(void * buttonHandle, button_callback_message_t * message, void * callbackParam) -{ - uint32_t pinNb = (uint32_t) callbackParam; - switch (message->event) - { - case kBUTTON_EventOneClick: - case kBUTTON_EventShortPress: - switch (pinNb) - { - case BLE_BUTTON: - // K32W_LOG("pb1 short press"); - if (sAppTask.mResetTimerActive) - { - ButtonEventHandler(BLE_BUTTON, RESET_BUTTON_PUSH); - } - else - { - ButtonEventHandler(BLE_BUTTON, BLE_BUTTON_PUSH); - } - break; - - case LIGHT_BUTTON: - // K32W_LOG("pb2 short press"); - ButtonEventHandler(LIGHT_BUTTON, LIGHT_BUTTON_PUSH); - break; - } - break; - - case kBUTTON_EventLongPress: - switch (pinNb) - { - case BLE_BUTTON: - // K32W_LOG("pb1 long press"); - ButtonEventHandler(BLE_BUTTON, RESET_BUTTON_PUSH); - break; - - case LIGHT_BUTTON: - // K32W_LOG("pb2 long press"); - ButtonEventHandler(SOFT_RESET_BUTTON, SOFT_RESET_BUTTON_PUSH); - break; - } - break; - - default: - /* No action required */ - break; - } - return kStatus_BUTTON_Success; -} - -void AppTask::TimerEventHandler(TimerHandle_t xTimer) -{ - AppEvent event; - event.Type = AppEvent::kEventType_Timer; - event.TimerEvent.Context = (void *) xTimer; - event.Handler = FunctionTimerEventHandler; - sAppTask.PostEvent(&event); -} - -void AppTask::FunctionTimerEventHandler(AppEvent * aEvent) -{ - if (aEvent->Type != AppEvent::kEventType_Timer) - return; - - K32W_LOG("Device will factory reset..."); - - // Actually trigger Factory Reset - chip::Server::GetInstance().ScheduleFactoryReset(); -} - -void AppTask::ResetActionEventHandler(AppEvent * aEvent) -{ - if (aEvent->ButtonEvent.PinNo != RESET_BUTTON && aEvent->ButtonEvent.PinNo != BLE_BUTTON) - return; - - if (sAppTask.mResetTimerActive) - { - sAppTask.CancelTimer(); - sAppTask.mFunction = kFunction_NoneSelected; - - RestoreLightingState(); - - K32W_LOG("Factory Reset was cancelled!"); - } - else - { - uint32_t resetTimeout = FACTORY_RESET_TRIGGER_TIMEOUT; - - if (sAppTask.mFunction != kFunction_NoneSelected) - { - K32W_LOG("Another function is scheduled. Could not initiate Factory Reset!"); - return; - } - - K32W_LOG("Factory Reset Triggered. Push the RESET button within %lu ms to cancel!", resetTimeout); - sAppTask.mFunction = kFunction_FactoryReset; - - /* LEDs will start blinking to signal that a Factory Reset was scheduled */ -#ifndef CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR - sStatusLED.Set(false); -#endif - -#if CHIP_CONFIG_ENABLE_DIMMABLE_LED - sLightLED.SetLevel(0); -#else - sLightLED.Set(false); -#endif - -#ifndef CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR - sStatusLED.Blink(500); -#endif - sLightLED.Blink(500); - - sAppTask.StartTimer(FACTORY_RESET_TRIGGER_TIMEOUT); - } -} - -void AppTask::LightActionEventHandler(AppEvent * aEvent) -{ - LightingManager::Action_t action; - CHIP_ERROR err = CHIP_NO_ERROR; - int32_t actor = 0; - bool initiated = false; - - if (sAppTask.mFunction != kFunction_NoneSelected) - { - K32W_LOG("Another function is scheduled. Could not initiate ON/OFF Light command!"); - return; - } - - if (aEvent->Type == AppEvent::kEventType_TurnOn) - { - action = static_cast(aEvent->LightEvent.Action); - actor = aEvent->LightEvent.Actor; - } - else if (aEvent->Type == AppEvent::kEventType_Button) - { - actor = AppEvent::kEventType_Button; - - if (LightingMgr().IsTurnedOff()) - { - action = LightingManager::TURNON_ACTION; - } - else - { - action = LightingManager::TURNOFF_ACTION; - } - } - else - { - err = APP_ERROR_UNHANDLED_EVENT; - action = LightingManager::INVALID_ACTION; - } - - if (err == CHIP_NO_ERROR) - { - initiated = LightingMgr().InitiateAction(actor, action, LightingMgr().IsTurnedOff() ? 0 : 1); - - if (!initiated) - { - K32W_LOG("Action is already in progress or active."); - } - } -} - -void AppTask::SoftResetHandler(AppEvent * aEvent) -{ - if (aEvent->ButtonEvent.PinNo != SOFT_RESET_BUTTON) - return; - - PlatformMgrImpl().CleanReset(); -} - -void AppTask::BleHandler(AppEvent * aEvent) -{ - if (aEvent->ButtonEvent.PinNo != BLE_BUTTON) - return; - - if (sAppTask.mFunction != kFunction_NoneSelected) - { - K32W_LOG("Another function is scheduled. Could not toggle BLE state!"); - return; - } - PlatformMgr().ScheduleWork(AppTask::BleStartAdvertising, 0); -} - -void AppTask::BleStartAdvertising(intptr_t arg) -{ - if (ConnectivityMgr().IsBLEAdvertisingEnabled()) - { - ConnectivityMgr().SetBLEAdvertisingEnabled(false); - K32W_LOG("Stopped BLE Advertising!"); - } - else - { - ConnectivityMgr().SetBLEAdvertisingEnabled(true); - if (chip::Server::GetInstance().GetCommissioningWindowManager().OpenBasicCommissioningWindow() == CHIP_NO_ERROR) - { - K32W_LOG("Started BLE Advertising!"); - } - else - { - K32W_LOG("OpenBasicCommissioningWindow() failed"); - } - } -} - -void AppTask::MatterEventHandler(const ChipDeviceEvent * event, intptr_t) -{ -#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR - if (event->Type == DeviceEventType::kDnssdInitialized) - { - K32W_LOG("Dnssd platform initialized."); - PlatformMgr().ScheduleWork(InitOTA, 0); - } -#else - if (event->Type == DeviceEventType::kDnssdInitialized) - { - sHaveFullConnectivity = TRUE; - } -#endif -} - -void AppTask::CancelTimer() -{ - if (xTimerStop(sFunctionTimer, 0) == pdFAIL) - { - K32W_LOG("app timer stop() failed"); - } - - mResetTimerActive = false; -} - -void AppTask::StartTimer(uint32_t aTimeoutInMs) -{ - if (xTimerIsTimerActive(sFunctionTimer)) - { - K32W_LOG("app timer already started!"); - CancelTimer(); - } - - // timer is not active, change its period to required value (== restart). - // FreeRTOS- Block for a maximum of 100 ticks if the change period command - // cannot immediately be sent to the timer command queue. - if (xTimerChangePeriod(sFunctionTimer, aTimeoutInMs / portTICK_PERIOD_MS, 100) != pdPASS) - { - K32W_LOG("app timer start() failed"); - } - - mResetTimerActive = true; -} - -void AppTask::ActionInitiated(LightingManager::Action_t aAction, int32_t aActor) -{ - // start flashing the LEDs rapidly to indicate action initiation. - if (aAction == LightingManager::TURNON_ACTION) - { - K32W_LOG("Turn on Action has been initiated") - } - else if (aAction == LightingManager::TURNOFF_ACTION) - { - K32W_LOG("Turn off Action has been initiated") - } - else if (aAction == LightingManager::DIM_ACTION) - { - K32W_LOG("Dim Action has been initiated"); - } - - if (aActor == AppEvent::kEventType_Button) - { - sAppTask.mSyncClusterToButtonAction = true; - } - - sAppTask.mFunction = kFunctionTurnOnTurnOff; -} - -void AppTask::ActionCompleted(LightingManager::Action_t aAction, uint8_t level) -{ - // Turn on the light LED if in a TURNON state OR - // Turn off the light LED if in a TURNOFF state. - if (aAction == LightingManager::TURNON_ACTION) - { - K32W_LOG("Turn on action has been completed") -#if CHIP_CONFIG_ENABLE_DIMMABLE_LED -#else - sLightLED.Set(true); -#endif - } - else if (aAction == LightingManager::TURNOFF_ACTION) - { - K32W_LOG("Turn off action has been completed") -#if CHIP_CONFIG_ENABLE_DIMMABLE_LED -#else - sLightLED.Set(false); -#endif - } - else if (aAction == LightingManager::DIM_ACTION) - { - K32W_LOG("Move to level %d completed", level); - } -#if CHIP_CONFIG_ENABLE_DIMMABLE_LED - sLightLED.SetLevel(LightingMgr().IsTurnedOff() ? 1 : LightingMgr().GetDimLevel()); -#endif - - if (sAppTask.mSyncClusterToButtonAction) - { - sAppTask.UpdateClusterState(); - sAppTask.mSyncClusterToButtonAction = false; - } - - sAppTask.mFunction = kFunction_NoneSelected; -} - -void AppTask::RestoreLightingState(void) -{ -#if CHIP_CONFIG_ENABLE_DIMMABLE_LED - LightingMgr().SetState(!LightingMgr().IsTurnedOff()); -#else - /* restore initial state for the LED indicating Lighting state */ - if (LightingMgr().IsTurnedOff()) - { - sLightLED.Set(false); - } - else - { - sLightLED.Set(true); - } -#endif -} - -void AppTask::OnIdentifyStart(Identify * identify) -{ - if ((kFunction_NoneSelected != sAppTask.mFunction) && (kFunction_TriggerEffect != sAppTask.mFunction)) - { - K32W_LOG("Another function is scheduled. Could not initiate Identify process!"); - return; - } - - if (kFunction_TriggerEffect == sAppTask.mFunction) - { - chip::DeviceLayer::SystemLayer().CancelTimer(OnTriggerEffectComplete, identify); - OnTriggerEffectComplete(&chip::DeviceLayer::SystemLayer(), identify); - } - - ChipLogProgress(Zcl, "Identify process has started. Status LED should blink with a period of 0.5 seconds."); - sAppTask.mFunction = kFunction_Identify; -#if CHIP_CONFIG_ENABLE_DIMMABLE_LED - sLightLED.SetLevel(0); -#else - sLightLED.Set(false); -#endif - sLightLED.Blink(250); -} - -void AppTask::OnIdentifyStop(Identify * identify) -{ - if (kFunction_Identify == sAppTask.mFunction) - { - ChipLogProgress(Zcl, "Identify process has stopped."); - sAppTask.mFunction = kFunction_NoneSelected; - - RestoreLightingState(); - } -} - -void AppTask::OnTriggerEffectComplete(chip::System::Layer * systemLayer, void * appState) -{ - // Let Identify command take over if called during TriggerEffect already running - if (kFunction_TriggerEffect == sAppTask.mFunction) - { - ChipLogProgress(Zcl, "TriggerEffect has stopped."); - sAppTask.mFunction = kFunction_NoneSelected; - - // TriggerEffect finished - reset identifiers - // Use invalid value for identifiers to enable TriggerEffect command - // to stop Identify command for each effect - gIdentify.mCurrentEffectIdentifier = Clusters::Identify::EffectIdentifierEnum::kUnknownEnumValue; - gIdentify.mTargetEffectIdentifier = Clusters::Identify::EffectIdentifierEnum::kUnknownEnumValue; - gIdentify.mEffectVariant = Clusters::Identify::EffectVariantEnum::kDefault; - - RestoreLightingState(); - } -} - -void AppTask::OnTriggerEffect(Identify * identify) -{ - // Allow overlapping TriggerEffect calls - if ((kFunction_NoneSelected != sAppTask.mFunction) && (kFunction_TriggerEffect != sAppTask.mFunction)) - { - K32W_LOG("Another function is scheduled. Could not initiate Identify process!"); - return; - } - - sAppTask.mFunction = kFunction_TriggerEffect; - uint16_t timerDelay = 0; - - ChipLogProgress(Zcl, "TriggerEffect has started."); - - switch (identify->mCurrentEffectIdentifier) - { - case Clusters::Identify::EffectIdentifierEnum::kBlink: - timerDelay = 2; - break; - - case Clusters::Identify::EffectIdentifierEnum::kBreathe: - timerDelay = 15; - break; - - case Clusters::Identify::EffectIdentifierEnum::kOkay: - timerDelay = 4; - break; - - case Clusters::Identify::EffectIdentifierEnum::kChannelChange: - ChipLogProgress(Zcl, "Channel Change effect not supported, using effect %d", - to_underlying(Clusters::Identify::EffectIdentifierEnum::kBlink)); - timerDelay = 2; - break; - - case Clusters::Identify::EffectIdentifierEnum::kFinishEffect: - chip::DeviceLayer::SystemLayer().CancelTimer(OnTriggerEffectComplete, identify); - timerDelay = 1; - break; - - case Clusters::Identify::EffectIdentifierEnum::kStopEffect: - chip::DeviceLayer::SystemLayer().CancelTimer(OnTriggerEffectComplete, identify); - OnTriggerEffectComplete(&chip::DeviceLayer::SystemLayer(), identify); - break; - - default: - ChipLogProgress(Zcl, "Invalid effect identifier."); - } - - if (timerDelay) - { -#if CHIP_CONFIG_ENABLE_DIMMABLE_LED - sLightLED.SetLevel(0); -#else - sLightLED.Set(false); -#endif - sLightLED.Blink(500); - - chip::DeviceLayer::SystemLayer().StartTimer(chip::System::Clock::Seconds16(timerDelay), OnTriggerEffectComplete, identify); - } -} - -void AppTask::PostTurnOnActionRequest(int32_t aActor, LightingManager::Action_t aAction) -{ - AppEvent event; - event.Type = AppEvent::kEventType_TurnOn; - event.LightEvent.Actor = aActor; - event.LightEvent.Action = aAction; - event.Handler = LightActionEventHandler; - PostEvent(&event); -} - -void AppTask::PostEvent(const AppEvent * aEvent) -{ - portBASE_TYPE taskToWake = pdFALSE; - if (sAppEventQueue != NULL) - { - if (__get_IPSR()) - { - if (!xQueueSendToFrontFromISR(sAppEventQueue, aEvent, &taskToWake)) - { - K32W_LOG("Failed to post event to app task event queue"); - } - - portYIELD_FROM_ISR(taskToWake); - } - else - { - if (!xQueueSend(sAppEventQueue, aEvent, 1)) - { - K32W_LOG("Failed to post event to app task event queue"); - } - } - } -} - -void AppTask::DispatchEvent(AppEvent * aEvent) -{ - if (aEvent->Handler) - { - aEvent->Handler(aEvent); - } - else - { - K32W_LOG("Event received with no handler. Dropping event."); - } -} - -void AppTask::UpdateClusterState(void) -{ - PlatformMgr().ScheduleWork(UpdateClusterStateInternal, 0); -} - -void AppTask::UpdateClusterStateInternal(intptr_t arg) -{ - uint8_t newValue = !LightingMgr().IsTurnedOff(); - - // write the new on/off value - Protocols::InteractionModel::Status status = app::Clusters::OnOff::Attributes::OnOff::Set(1, newValue); - if (status != Protocols::InteractionModel::Status::Success) - { - ChipLogError(NotSpecified, "ERR: updating on/off %x", to_underlying(status)); - } -} - -void AppTask::UpdateDeviceState(void) -{ - PlatformMgr().ScheduleWork(UpdateDeviceStateInternal, 0); -} - -void AppTask::UpdateDeviceStateInternal(intptr_t arg) -{ - bool onoffAttrValue = 0; - - /* get onoff attribute value */ - (void) app::Clusters::OnOff::Attributes::OnOff::Get(1, &onoffAttrValue); - - /* set the device state */ -#if CHIP_CONFIG_ENABLE_DIMMABLE_LED -#else - sLightLED.Set(onoffAttrValue); -#endif - LightingMgr().SetState(onoffAttrValue); -} - -extern "C" void OTAIdleActivities(void) -{ -#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR - OTA_TransactionResume(); -#endif -} diff --git a/examples/lighting-app/nxp/k32w/k32w1/main/LightingManager.cpp b/examples/lighting-app/nxp/k32w/k32w1/main/LightingManager.cpp deleted file mode 100644 index 2627138043..0000000000 --- a/examples/lighting-app/nxp/k32w/k32w1/main/LightingManager.cpp +++ /dev/null @@ -1,121 +0,0 @@ -/* - * - * Copyright (c) 2021 Project CHIP Authors - * Copyright (c) 2019 Google LLC. - * 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 "LightingManager.h" - -#if CHIP_CONFIG_ENABLE_DIMMABLE_LED -#include "LED_Dimmer.h" -#endif - -#include "AppTask.h" -#include "FreeRTOS.h" - -#include "app_config.h" - -LightingManager LightingManager::sLight; - -int LightingManager::Init() -{ - mState = kState_On; - - mLevel = kLevel_Max; - - return 0; -} - -void LightingManager::SetCallbacks(Callback_fn_initiated aActionInitiated_CB, Callback_fn_completed aActionCompleted_CB) -{ - mActionInitiated_CB = aActionInitiated_CB; - mActionCompleted_CB = aActionCompleted_CB; -} - -void LightingManager::SetState(bool state) -{ - mState = state ? kState_On : kState_Off; -} - -void LightingManager::SetDimLevel(uint8_t level) -{ - mLevel = level; -} - -bool LightingManager::IsTurnedOff() -{ - return (mState == kState_Off) ? true : false; -} - -uint8_t LightingManager::GetDimLevel() -{ - return mLevel; -} - -bool LightingManager::InitiateAction(int32_t aActor, Action_t aAction, uint8_t kValue) -{ - bool action_initiated = false; - State_t current_state; - - if (mState == kState_On && aAction == TURNOFF_ACTION) - { - action_initiated = true; - current_state = kState_Off; - } - else if (mState == kState_Off && aAction == TURNON_ACTION) - { - action_initiated = true; - current_state = kState_On; - } - - else if (aAction == DIM_ACTION && kValue != mLevel) - { - action_initiated = true; - if (kValue == 1) - { - current_state = kState_Off; - } - else - { - current_state = kState_On; - } - } - - if (action_initiated) - { - if (mActionInitiated_CB) - { - mActionInitiated_CB(aAction, aActor); - } - - if (aAction == TURNON_ACTION || aAction == TURNOFF_ACTION) - { - SetState(current_state == kState_On); - } - else if (aAction == DIM_ACTION) - { - mState = current_state; - SetDimLevel(kValue); - } - - if (mActionCompleted_CB) - { - mActionCompleted_CB(aAction, kValue); - } - } - - return action_initiated; -} diff --git a/examples/lighting-app/nxp/k32w/k32w1/main/include/AppEvent.h b/examples/lighting-app/nxp/k32w/k32w1/main/include/AppEvent.h deleted file mode 100644 index 902c70b3cb..0000000000 --- a/examples/lighting-app/nxp/k32w/k32w1/main/include/AppEvent.h +++ /dev/null @@ -1,57 +0,0 @@ -/* - * - * Copyright (c) 2021 Nest Labs, Inc. - * 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 - -struct AppEvent; -typedef void (*EventHandler)(AppEvent *); - -struct AppEvent -{ - enum AppEventTypes - { - kEventType_None = 0, - kEventType_Button, - kEventType_Timer, - kEventType_TurnOn, - kEventType_Install, - kEventType_OTAResume, - }; - - AppEventTypes Type; - - union - { - struct - { - uint8_t PinNo; - uint8_t Action; - } ButtonEvent; - struct - { - void * Context; - } TimerEvent; - struct - { - uint8_t Action; - int32_t Actor; - } LightEvent; - }; - - EventHandler Handler; -}; diff --git a/examples/lighting-app/nxp/k32w/k32w1/main/include/AppTask.h b/examples/lighting-app/nxp/k32w/k32w1/main/include/AppTask.h deleted file mode 100644 index 096690c680..0000000000 --- a/examples/lighting-app/nxp/k32w/k32w1/main/include/AppTask.h +++ /dev/null @@ -1,126 +0,0 @@ -/* - * - * Copyright (c) 2021 Google LLC. - * 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 "AppEvent.h" -#include "LightingManager.h" - -#include -#include - -#if CONFIG_CHIP_LOAD_REAL_FACTORY_DATA -#include -#endif - -#include "FreeRTOS.h" -#include "fsl_component_button.h" -#include "timers.h" - -// Application-defined error codes in the CHIP_ERROR space. -#define APP_ERROR_EVENT_QUEUE_FAILED CHIP_APPLICATION_ERROR(0x01) -#define APP_ERROR_CREATE_TASK_FAILED CHIP_APPLICATION_ERROR(0x02) -#define APP_ERROR_UNHANDLED_EVENT CHIP_APPLICATION_ERROR(0x03) -#define APP_ERROR_CREATE_TIMER_FAILED CHIP_APPLICATION_ERROR(0x04) -#define APP_ERROR_START_TIMER_FAILED CHIP_APPLICATION_ERROR(0x05) -#define APP_ERROR_STOP_TIMER_FAILED CHIP_APPLICATION_ERROR(0x06) - -class AppTask -{ -public: -#if CONFIG_CHIP_LOAD_REAL_FACTORY_DATA - using FactoryDataProvider = chip::DeviceLayer::FactoryDataProviderImpl; -#endif - CHIP_ERROR StartAppTask(); - static void AppTaskMain(void * pvParameter); - - void PostTurnOnActionRequest(int32_t aActor, LightingManager::Action_t aAction); - void PostEvent(const AppEvent * event); - - void UpdateClusterState(void); - void UpdateDeviceState(void); - - // Identify cluster callbacks. - static void OnIdentifyStart(Identify * identify); - static void OnIdentifyStop(Identify * identify); - static void OnTriggerEffect(Identify * identify); - static void OnTriggerEffectComplete(chip::System::Layer * systemLayer, void * appState); - static void ButtonEventHandler(uint8_t pin_no, uint8_t button_action); - -private: - friend AppTask & GetAppTask(void); - - CHIP_ERROR Init(); - - static void ActionInitiated(LightingManager::Action_t aAction, int32_t aActor); - static void ActionCompleted(LightingManager::Action_t aAction, uint8_t level); - - void CancelTimer(void); - - void DispatchEvent(AppEvent * event); - - static void FunctionTimerEventHandler(AppEvent * aEvent); - static button_status_t KBD_Callback(void * buttonHandle, button_callback_message_t * message, void * callbackParam); - static void SoftResetHandler(AppEvent * aEvent); - static void BleHandler(AppEvent * aEvent); - static void BleStartAdvertising(intptr_t arg); - static void LightActionEventHandler(AppEvent * aEvent); - static void ResetActionEventHandler(AppEvent * aEvent); - static void InstallEventHandler(AppEvent * aEvent); - - static void TimerEventHandler(TimerHandle_t xTimer); - - static void MatterEventHandler(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg); - void StartTimer(uint32_t aTimeoutInMs); - - static void RestoreLightingState(void); - -#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR - static void InitOTA(intptr_t arg); - static void StartOTAQuery(intptr_t arg); -#endif - - static void UpdateClusterStateInternal(intptr_t arg); - static void UpdateDeviceStateInternal(intptr_t arg); - static void InitServer(intptr_t arg); - static void PrintOnboardingInfo(); - - enum Function_t - { - kFunction_NoneSelected = 0, - kFunction_FactoryReset, - kFunctionTurnOnTurnOff, - kFunction_Identify, - kFunction_TriggerEffect, - kFunction_Invalid - } Function; - - Function_t mFunction = kFunction_NoneSelected; - bool mResetTimerActive = false; - bool mSyncClusterToButtonAction = false; - - static AppTask sAppTask; -}; - -inline AppTask & GetAppTask(void) -{ - return AppTask::sAppTask; -} diff --git a/examples/lighting-app/nxp/k32w/k32w1/main/include/LightingManager.h b/examples/lighting-app/nxp/k32w/k32w1/main/include/LightingManager.h deleted file mode 100644 index f96d6c7eca..0000000000 --- a/examples/lighting-app/nxp/k32w/k32w1/main/include/LightingManager.h +++ /dev/null @@ -1,74 +0,0 @@ -/* - * - * Copyright (c) 2021 Google LLC. - * 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 "AppEvent.h" - -#include "FreeRTOS.h" -#include "timers.h" // provides FreeRTOS timer support - -class LightingManager -{ -public: - enum Action_t - { - TURNON_ACTION = 0, - TURNOFF_ACTION, - DIM_ACTION, - INVALID_ACTION - } Action; - - enum State_t - { - kState_On = 0, - kState_Off, - } State; - - static const uint8_t kLevel_Max = 254; - static const uint8_t kLevel_Min = 0; - - int Init(); - bool IsTurnedOff(); - uint8_t GetDimLevel(); - bool InitiateAction(int32_t aActor, Action_t aAction, uint8_t kValue); - - typedef void (*Callback_fn_initiated)(Action_t, int32_t aActor); - typedef void (*Callback_fn_completed)(Action_t, uint8_t level); - void SetCallbacks(Callback_fn_initiated aActionInitiated_CB, Callback_fn_completed aActionCompleted_CB); - void SetState(bool state); - void SetDimLevel(uint8_t level); - -private: - friend LightingManager & LightingMgr(void); - State_t mState; - uint8_t mLevel; - - Callback_fn_initiated mActionInitiated_CB; - Callback_fn_completed mActionCompleted_CB; - - static LightingManager sLight; -}; - -inline LightingManager & LightingMgr(void) -{ - return LightingManager::sLight; -} diff --git a/examples/lighting-app/nxp/k32w/k32w1/main/include/app_config.h b/examples/lighting-app/nxp/k32w/k32w1/main/include/app_config.h deleted file mode 100644 index 1478b53b11..0000000000 --- a/examples/lighting-app/nxp/k32w/k32w1/main/include/app_config.h +++ /dev/null @@ -1,49 +0,0 @@ -/* - * - * Copyright (c) 2021 Google LLC. - * 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 - -// ---- Light Example App Config ---- - -#define RESET_BUTTON 1 -#define LIGHT_BUTTON 2 -#define SOFT_RESET_BUTTON 3 -#define BLE_BUTTON 4 - -#define RESET_BUTTON_PUSH 1 -#define LIGHT_BUTTON_PUSH 2 -#define SOFT_RESET_BUTTON_PUSH 3 -#define BLE_BUTTON_PUSH 4 - -#define APP_BUTTON_PUSH 1 - -#define LIGHT_STATE_LED 1 -#define SYSTEM_STATE_LED 0 - -// Time it takes for the light to switch on/off -#define ACTUATOR_MOVEMENT_PERIOS_MS 50 - -// ---- Light Example SWU Config ---- -#define SWU_INTERVAl_WINDOW_MIN_MS (23 * 60 * 60 * 1000) // 23 hours -#define SWU_INTERVAl_WINDOW_MAX_MS (24 * 60 * 60 * 1000) // 24 hours - -#if K32W_LOG_ENABLED -#define K32W_LOG(...) otPlatLog(OT_LOG_LEVEL_NONE, OT_LOG_REGION_API, ##__VA_ARGS__); -#else -#define K32W_LOG(...) -#endif diff --git a/examples/lighting-app/nxp/k32w/k32w1/main/main.cpp b/examples/lighting-app/nxp/k32w/k32w1/main/main.cpp deleted file mode 100644 index 53a6efbbb3..0000000000 --- a/examples/lighting-app/nxp/k32w/k32w1/main/main.cpp +++ /dev/null @@ -1,156 +0,0 @@ -/* - * - * Copyright (c) 2021 Google LLC. - * 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. - */ - -// ================================================================================ -// Main Code -// ================================================================================ - -#include "openthread/platform/logging.h" -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -#include "FreeRtosHooks.h" -#include "app_config.h" -#include "pin_mux.h" - -using namespace ::chip; -using namespace ::chip::Inet; -using namespace ::chip::DeviceLayer; -using namespace ::chip::Logging; - -#include - -#if PW_RPC_ENABLED -#include "Rpc.h" -#endif - -typedef void (*InitFunc)(void); -extern InitFunc __init_array_start; -extern InitFunc __init_array_end; - -extern "C" void main_task(void const * argument) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - - /* Call C++ constructors */ - InitFunc * pFunc = &__init_array_start; - for (; pFunc < &__init_array_end; ++pFunc) - { - (*pFunc)(); - } - - mbedtls_platform_set_calloc_free(CHIPPlatformMemoryCalloc, CHIPPlatformMemoryFree); - - err = PlatformMgrImpl().InitBoardFwk(); - if (err != CHIP_NO_ERROR) - { - return; - } - - /* Used for HW initializations */ - otSysInit(0, NULL); - -#if PW_RPC_ENABLED - /* set clock */ - CLOCK_SetIpSrc(kCLOCK_Lpuart1, kCLOCK_IpSrcFro192M); - /* enable clock */ - CLOCK_EnableClock(kCLOCK_Lpuart1); - - BOARD_InitPinLPUART1_TX(); - BOARD_InitPinLPUART1_RX(); - chip::rpc::Init(); -#endif - - K32W_LOG("Welcome to NXP Lighting Demo App"); - - /* Mbedtls Threading support is needed because both - * Thread and Matter tasks are using it */ - freertos_mbedtls_mutex_init(); - - // Init Chip memory management before the stack - chip::Platform::MemoryInit(); - - err = PlatformMgr().InitChipStack(); - if (err != CHIP_NO_ERROR) - { - K32W_LOG("Error during PlatformMgr().InitMatterStack()"); - goto exit; - } - - err = ThreadStackMgr().InitThreadStack(); - if (err != CHIP_NO_ERROR) - { - K32W_LOG("Error during ThreadStackMgr().InitThreadStack()"); - goto exit; - } - - err = ConnectivityMgr().SetThreadDeviceType(ConnectivityManager::kThreadDeviceType_Router); - - if (err != CHIP_NO_ERROR) - { - goto exit; - } - - // Start OpenThread task - err = ThreadStackMgrImpl().StartThreadTask(); - if (err != CHIP_NO_ERROR) - { - K32W_LOG("Error during ThreadStackMgrImpl().StartThreadTask()"); - goto exit; - } - - err = GetAppTask().StartAppTask(); - if (err != CHIP_NO_ERROR) - { - K32W_LOG("Error during GetAppTask().StartAppTask()"); - goto exit; - } - - err = PlatformMgr().StartEventLoopTask(); - if (err != CHIP_NO_ERROR) - { - K32W_LOG("Error during PlatformMgr().StartEventLoopTask();"); - goto exit; - } - - GetAppTask().AppTaskMain(NULL); - -exit: - return; -} - -/** - * Glue function called directly by the OpenThread stack - * when system event processing work is pending. - */ -extern "C" void otSysEventSignalPending(void) -{ - { - BaseType_t yieldRequired = ThreadStackMgrImpl().SignalThreadActivityPendingFromISR(); - portYIELD_FROM_ISR(yieldRequired); - } -} diff --git a/examples/lighting-app/nxp/k32w/k32w1/third_party/connectedhomeip b/examples/lighting-app/nxp/k32w/k32w1/third_party/connectedhomeip deleted file mode 120000 index 305f2077ff..0000000000 --- a/examples/lighting-app/nxp/k32w/k32w1/third_party/connectedhomeip +++ /dev/null @@ -1 +0,0 @@ -../../../../../.. \ No newline at end of file diff --git a/examples/lighting-app/nxp/k32w/k32w1/.gn b/examples/lighting-app/nxp/k32w1/.gn similarity index 93% rename from examples/lighting-app/nxp/k32w/k32w1/.gn rename to examples/lighting-app/nxp/k32w1/.gn index a88f6f5aa7..afa5bfea46 100644 --- a/examples/lighting-app/nxp/k32w/k32w1/.gn +++ b/examples/lighting-app/nxp/k32w1/.gn @@ -27,5 +27,5 @@ default_args = { import("//args.gni") # Import default platform configs - import("${chip_root}/src/platform/nxp/k32w/k32w1/args.gni") + import("${chip_root}/src/platform/nxp/k32w1/args.gni") } diff --git a/examples/lighting-app/nxp/k32w1/BUILD.gn b/examples/lighting-app/nxp/k32w1/BUILD.gn new file mode 100644 index 0000000000..b6e6db814a --- /dev/null +++ b/examples/lighting-app/nxp/k32w1/BUILD.gn @@ -0,0 +1,268 @@ +# Copyright (c) 2021 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/nxp_sdk.gni") +import("//build_overrides/openthread.gni") + +import("${nxp_sdk_build_root}/nxp_sdk.gni") + +import("${nxp_sdk_build_root}/${nxp_sdk_name}/nxp_executable.gni") + +import("${nxp_sdk_build_root}/${nxp_sdk_name}/${nxp_sdk_name}.gni") + +import("${chip_root}/src/crypto/crypto.gni") +import("${chip_root}/src/platform/device.gni") +import("${chip_root}/src/platform/nxp/${nxp_platform}/args.gni") + +import("${chip_root}/examples/common/pigweed/pigweed_rpcs.gni") + +if (chip_enable_pw_rpc) { + import("//build_overrides/pigweed.gni") + import("$dir_pw_build/target_types.gni") + import("${chip_root}/examples/platform/nxp/pw_rpc_server.gni") +} + +declare_args() { + # Setup discriminator as argument + setup_discriminator = 3840 +} + +assert(current_os == "freertos") +assert(target_os == "freertos") + +example_platform_dir = "${chip_root}/examples/platform/nxp/${nxp_platform}" +common_example_dir = "${chip_root}/examples/platform/nxp/common" + +k32w1_sdk("sdk") { + defines = [] + include_dirs = [] + sources = [] + + # Indicate the path to CHIPProjectConfig.h + include_dirs += [ "include/config" ] + + # Indicate the default path to FreeRTOSConfig.h + include_dirs += [ "${example_platform_dir}/app/project_include/freeRTOS" ] + + # Indicate the default path to OpenThreadConfig.h + include_dirs += [ "${example_platform_dir}/app/project_include/openthread" ] + + include_dirs += [ + "${k32w1_sdk_root}/middleware/wireless/framework/boards/kw45_k32w1", + "${k32w1_sdk_root}/middleware/wireless/framework/boards/kw45_k32w1/K32W1480", + ] + + sources += [ + "${k32w1_sdk_root}/middleware/wireless/framework/boards/kw45_k32w1/K32W1480/clock_config.c", + "${k32w1_sdk_root}/middleware/wireless/framework/boards/kw45_k32w1/K32W1480/pin_mux.c", + "${k32w1_sdk_root}/middleware/wireless/framework/boards/kw45_k32w1/app_services_init.c", + "${k32w1_sdk_root}/middleware/wireless/framework/boards/kw45_k32w1/board.c", + "${k32w1_sdk_root}/middleware/wireless/framework/boards/kw45_k32w1/board_comp.c", + "${k32w1_sdk_root}/middleware/wireless/framework/boards/kw45_k32w1/board_dcdc.c", + "${k32w1_sdk_root}/middleware/wireless/framework/boards/kw45_k32w1/board_extflash.c", + "${k32w1_sdk_root}/middleware/wireless/framework/boards/kw45_k32w1/board_lp.c", + "${k32w1_sdk_root}/middleware/wireless/framework/boards/kw45_k32w1/hardware_init.c", + ] + + if (is_debug) { + defines += [ "BUILD_RELEASE=0" ] + } else { + defines += [ "BUILD_RELEASE=1" ] + } + + if (chip_enable_pw_rpc) { + defines += [ + "CONFIG_ENABLE_PW_RPC", + "STREAMER_UART_FLUSH_DELAY_MS=0", + "STREAMER_UART_SERIAL_MANAGER_RING_BUFFER_SIZE=512", + "BOARD_APP_UART_CLK_FREQ=96000000", + ] + } + + defines += [ + "CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR=${setup_discriminator}", + ] + + if (chip_key_storage == "littlefs") { + include_dirs += [ "${example_platform_dir}/board" ] + sources += [ + "${example_platform_dir}/board/peripherals.c", + "${example_platform_dir}/board/peripherals.h", + ] + } +} + +k32w1_executable("light_app") { + output_name = "chip-k32w1-light-example" + + defines = [] + deps = [] + sources = [] + + if (chip_enable_pw_rpc) { + forward_variables_from(pw_rpc_server, "*") + } else { + include_dirs = [] + cflags = [ "-Wconversion" ] + } + + # Defines used by common code + defines += [ + "CONFIG_NET_L2_OPENTHREAD=1", + "CONFIG_NETWORK_LAYER_BLE=1", + "CONFIG_OPERATIONAL_KEYSTORE=1", + "CONFIG_ENABLE_FEEDBACK=1", + "APP_QUEUE_TICKS_TO_WAIT=pdMS_TO_TICKS(10)", + "EXTERNAL_FACTORY_DATA_PROVIDER_HEADER=\"platform/nxp/common/legacy/FactoryDataProvider.h\"", + ] + + # App common files + include_dirs += [ + "${common_example_dir}/app_task/include", + "${common_example_dir}/matter_button/include", + "${common_example_dir}/clusters/include", + "${common_example_dir}/device_callbacks/include", + "${common_example_dir}/device_manager/include", + "${common_example_dir}/factory_data/include", + "${common_example_dir}/led_widget/include", + "${common_example_dir}/operational_keystore/include", + "${common_example_dir}/rpc/include", + "${common_example_dir}/ui_feedback/include", + ] + + sources += [ + "${common_example_dir}/app_task/source/AppTaskBase.cpp", + "${common_example_dir}/app_task/source/AppTaskFreeRTOS.cpp", + "${common_example_dir}/clusters/source/ZclCallbacks.cpp", + "${common_example_dir}/device_callbacks/source/CommonDeviceCallbacks.cpp", + "${common_example_dir}/device_manager/source/CHIPDeviceManager.cpp", + "${example_platform_dir}/factory_data/source/AppFactoryDataExample.cpp", + ] + + if (chip_enable_ota_requestor) { + defines += [ + "CONFIG_CHIP_OTA_IMAGE_PROCESSOR_HEADER=\"platform/nxp/common/legacy/OTAImageProcessorImpl.h\"", + + # The status LED and the external flash CS pin are wired together. The OTA image writing may fail if used together. + "LED_MANAGER_ENABLE_STATUS_LED=0", + ] + + include_dirs += [ "${common_example_dir}/ota_requestor/include" ] + sources += [ "${common_example_dir}/ota_requestor/source/OTARequestorInitiatorMultiImage.cpp" ] + deps += [ "${chip_root}/src/platform/nxp:nxp_ota" ] + } + + # Platform specific files + include_dirs += [ + "${example_platform_dir}/util", + "${example_platform_dir}/app/support", + "${example_platform_dir}/button", + ] + + sources += [ + "${example_platform_dir}/button/ButtonManager.cpp", + "${example_platform_dir}/clusters/Identify.cpp", + "${example_platform_dir}/operational_keystore/OperationalKeystore.cpp", + ] + + if (chip_enable_ota_requestor) { + sources += [ "${example_platform_dir}/ota/OtaUtils.cpp" ] + } + + if (chip_enable_pw_rpc) { + sources += [ "${example_platform_dir}/rpc/AppRpc.cpp" ] + } + + if (chip_with_factory_data == 1) { + include_dirs += [ "${chip_root}/src/platform/nxp/common/legacy" ] + deps += [ "${chip_root}/src/platform/nxp:nxp_factory_data" ] + } + + sources += [ + "../common/AppTask.cpp", + "../common/DeviceCallbacks.cpp", + "../common/main.cpp", + ] + + include_dirs += [ + "../common", + "../common/include", + "include/config", + ] + + deps += [ + "${chip_root}/examples/providers:device_info_provider", + "${chip_root}/src/platform/logging:default", + ] + + if (chip_config_dimmable_led) { + defines += [ "LIGHTING_MANAGER_ENABLE_DIMMABLE_LED=1" ] + sources += [ + "${common_example_dir}/led_widget/include/LedDimmer.h", + "${example_platform_dir}/util/LedDimmer.cpp", + "${example_platform_dir}/util/LightingManagerDimmable.cpp", + ] + deps += [ "${chip_root}/examples/lighting-app/lighting-common/" ] + } else { + sources += [ + "${common_example_dir}/ui_feedback/source/LedManager.cpp", + "${example_platform_dir}/util/LedOnOff.cpp", + ] + deps += [ "${chip_root}/examples/lighting-app/nxp/zap/" ] + } + + if (chip_openthread_ftd) { + deps += [ + "${openthread_root}:libopenthread-cli-ftd", + "${openthread_root}:libopenthread-ftd", + ] + } else { + deps += [ + "${openthread_root}:libopenthread-cli-mtd", + "${openthread_root}:libopenthread-mtd", + ] + } + + if (use_smu2_static) { + ldscript = "${example_platform_dir}/app/ldscripts/k32w1_app.ld" + base_ldscript_dir = "${k32w1_sdk_root}/middleware/wireless/framework/Common/devices/kw45_k32w1/gcc" + } else { + ldscript = "${k32w1_sdk_root}/middleware/wireless/framework/Common/devices/kw45_k32w1/gcc/connectivity.ld" + } + + inputs = [ ldscript ] + + ldflags = [ + "-Wl,--defsym=__heap_size__=0", + "-Wl,--defsym=__stack_size__=0x480", + "-Wl,-print-memory-usage", + "-Wl,--no-warn-rwx-segments", + "-T" + rebase_path(ldscript, root_build_dir), + ] + + if (chip_with_factory_data == 1) { + ldflags += [ "-Wl,--defsym=gUseFactoryData_d=1" ] + } + + if (use_smu2_static) { + ldflags += [ "-L" + rebase_path(base_ldscript_dir, root_build_dir) ] + } + + output_dir = root_out_dir +} + +group("default") { + deps = [ ":light_app" ] +} diff --git a/examples/lighting-app/nxp/k32w/k32w1/README.md b/examples/lighting-app/nxp/k32w1/README.md similarity index 80% rename from examples/lighting-app/nxp/k32w/k32w1/README.md rename to examples/lighting-app/nxp/k32w1/README.md index 3bf2ab8105..349deef640 100644 --- a/examples/lighting-app/nxp/k32w/k32w1/README.md +++ b/examples/lighting-app/nxp/k32w1/README.md @@ -16,30 +16,32 @@ into an existing Matter network and can be controlled by this network.
- [Matter K32W1 Lighting Example Application](#matter-k32w1-lighting-example-application) -- [Introduction](#introduction) - - [Bluetooth LE Advertising](#bluetooth-le-advertising) - - [Bluetooth LE Rendezvous](#bluetooth-le-rendezvous) -- [Device UI](#device-ui) -- [Building](#building) - - [SMU2](#smu2-memory) - - [LED PWM](#led-pwm) -- [Manufacturing data](#manufacturing-data) -- [Flashing](#flashing) - - [Flashing the NBU image](#flashing-the-nbu-image) - - [Flashing the host image](#flashing-the-host-image) -- [Debugging](#debugging) -- [OTA](#ota) - - [Convert srec into sb3 file](#convert-srec-into-sb3-file) - - [Convert sb3 into ota file](#convert-sb3-into-ota-file) - - [Running OTA](#running-ota) - - [Known issues](#known-issues) -- [Running RPC console](#running-rpc-console) + - [Introduction](#introduction) + - [Bluetooth LE Advertising](#bluetooth-le-advertising) + - [Bluetooth LE Rendezvous](#bluetooth-le-rendezvous) + - [Thread Provisioning](#thread-provisioning) + - [Device UI](#device-ui) + - [Building](#building) + - [`SMU2` Memory](#smu2-memory) + - [LED PWM](#led-pwm) + - [Manufacturing data](#manufacturing-data) + - [Flashing](#flashing) + - [Flashing the `NBU` image](#flashing-the-nbu-image) + - [Flashing the host image](#flashing-the-host-image) + - [Debugging](#debugging) + - [OTA](#ota) + - [Convert `srec` into `sb3` file](#convert-srec-into-sb3-file) + - [Convert `sb3` into `ota` file](#convert-sb3-into-ota-file) + - [OTA factory data](#ota-factory-data) + - [Running OTA](#running-ota) + - [Known issues](#known-issues) + - [Running RPC console](#running-rpc-console) ## Introduction -![K32W1 EVK](../../../../platform/nxp/k32w/k32w1/doc/images/k32w1-evk.jpg) +![K32W1 EVK](../../../platform/nxp/k32w1/doc/images/k32w1-evk.jpg) The K32W1 lighting example application provides a working demonstration of a light bulb device, built using the Matter codebase and the NXP K32W1 SDK. The @@ -119,26 +121,52 @@ does a clean soft reset that takes into account Matter shutdown procedure. ## Building -In order to build the Matter example, we recommend using a Linux distribution -(the demo-application was compiled on Ubuntu 20.04). +In order to build the Project CHIP example, we recommend using a Linux +distribution. Supported Operating Systems and prerequisites are listed in +[BUILDING](../../../../docs/guides/BUILDING.md). -- Download [K32W1 SDK for Matter](https://mcuxpresso.nxp.com/). Creating an - nxp.com account is required before being able to download the SDK. Once the - account is created, login and follow the steps for downloading K32W148-EVK - MCUXpresso SDK. The SDK Builder UI selection should be similar with the one - from the image below. +- Make sure that below prerequisites are correctly installed - ![MCUXpresso SDK Download](../../../../platform/nxp/k32w/k32w1/doc/images/mcux-sdk-download.jpg) +``` +sudo apt-get install git gcc g++ pkg-config libssl-dev libdbus-1-dev \ + libglib2.0-dev libavahi-client-dev ninja-build python3-venv python3-dev \ + python3-pip unzip libgirepository1.0-dev libcairo2-dev libreadline-dev +``` - Please refer to Matter release notes for getting the latest released SDK. +- Step 1: checkout NXP specific submodules only ``` -user@ubuntu:~/Desktop/git/connectedhomeip$ export NXP_K32W1_SDK_ROOT=/home/user/Desktop/SDK_K32W1/ -user@ubuntu:~/Desktop/git/connectedhomeip$ source ./scripts/activate.sh user@ubuntu:~/Desktop/git/connectedhomeip$ scripts/checkout_submodules.py --shallow --platform nxp --recursive -user@ubuntu:~/Desktop/git/connectedhomeip$ cd examples/lighting-app/nxp/k32w/k32w1 -user@ubuntu:~/Desktop/git/connectedhomeip/examples/lighting-app/nxp/k32w/k32w1$ gn gen out/debug -user@ubuntu:~/Desktop/git/connectedhomeip/examples/lighting-app/nxp/k32w/k32w1$ ninja -C out/debug +``` + +- Step 2: activate local environment + +``` +user@ubuntu:~/Desktop/git/connectedhomeip$ source scripts/activate.sh +``` + +If the script says the environment is out of date, you can update it by running +the following command: + +``` +user@ubuntu:~/Desktop/git/connectedhomeip$ source scripts/bootstrap.sh +``` + +- Step 3: Init NXP SDK(s) + +``` +user@ubuntu:~/Desktop/git/connectedhomeip$ scripts/setup/nxp/update_nxp_sdk.py --platform common_sdk +``` + +Note: By default setup/nxp/update_nxp_sdk.py will try to initialize all NXP +SDKs. Arg "-- help" could be used to view all available options. + +- Start building the application. + +``` +user@ubuntu:~/Desktop/git/connectedhomeip$ cd examples/lighting-app/nxp/k32w1 +user@ubuntu:~/Desktop/git/connectedhomeip/examples/lighting-app/nxp/k32w1$ gn gen out/debug +user@ubuntu:~/Desktop/git/connectedhomeip/examples/lighting-app/nxp/k32w1$ ninja -C out/debug ``` In case that Openthread CLI is needed, `chip_with_ot_cli` build argument must be @@ -162,8 +190,8 @@ memory: These instances and global variables are placed in `SMU2` memory through name matching in the application linker script. They should not be changed or, if changed, the names must be updated in `k32w1_app.ld`. See -[k32w1_app.ld](../../../../platform/nxp/k32w/k32w1/app/ldscripts/k32w1_app.ld) -for names and `SMU2` memory range size. +[k32w1_app.ld](../../../platform/nxp/k32w1/app/ldscripts/k32w1_app.ld) for names +and `SMU2` memory range size. The OpenThread buffers can be allocated from a 13KB `SMU2` range after a successful commissioning process until a factory reset is initiated. This way, @@ -171,6 +199,8 @@ the OpenThread buffers will be dynamically allocated instead of statically, freeing some `SRAM`. To enable this feature compile with OpenThread FTD support (`chip_openthread_ftd=true`) and with `use_smu2_dynamic=true`. +`use_smu2_static` and `use_smu2_dynamic` are set to `true` by default. + ### LED PWM In the default configuration, the onboard RGB LED pins are configured as GPIO @@ -180,14 +210,14 @@ this feature, compile the application with: `chip_config_dimmable_led=true` If the feature is enabled, the LED brightness can be controlled using **Level control** cluster -[commands](../../../../../docs/guides/chip_tool_guide.md#step-7-control-application-data-model-clusters). +[commands](../../../../docs/guides/chip_tool_guide.md#step-7-control-application-data-model-clusters). ## Manufacturing data Use `chip_with_factory_data=1` 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/guides/nxp/nxp_manufacturing_flow.md). +[Guide for writing manufacturing data on NXP devices](../../../../docs/guides/nxp/nxp_manufacturing_flow.md). ## Flashing @@ -250,7 +280,7 @@ One option for debugging would be to use MCUXpresso IDE. - Drag-and-drop the zip file containing the NXP SDK in the "Installed SDKs" tab: -![Installed SDKs](../../../../platform/nxp/k32w/k32w1/doc/images/installed_sdks.jpg) +![Installed SDKs](../../../platform/nxp/k32w1/doc/images/installed_sdks.jpg) - Import any demo application from the installed SDK: @@ -258,7 +288,7 @@ One option for debugging would be to use MCUXpresso IDE. Import SDK example(s).. -> choose a demo app (demo_apps -> hello_world) -> Finish ``` -![Import demo](../../../../platform/nxp/k32w/k32w1/doc/images/import_demo.jpg) +![Import demo](../../../platform/nxp/k32w1/doc/images/import_demo.jpg) - Flash the previously imported demo application on the board: @@ -277,7 +307,7 @@ resulted after ot-nxp compilation. File -> Import -> C/C++ -> Existing Code as Makefile Project ``` -![New Project](../../../../platform/nxp/k32w/k32w1/doc/images/new_project.jpg) +![New Project](../../../platform/nxp/k32w1/doc/images/new_project.jpg) - Replace the path of the existing demo application with the path of the K32W1 application: @@ -286,7 +316,7 @@ File -> Import -> C/C++ -> Existing Code as Makefile Project Run -> Debug Configurations... -> C/C++ Application ``` -![Debug K32W1](../../../../platform/nxp/k32w/k32w1/doc/images/debug_k32w1.jpg) +![Debug K32W1](../../../platform/nxp/k32w1/doc/images/debug_k32w1.jpg) ## OTA @@ -314,16 +344,21 @@ In `OTAP` application In order to build an OTA image, use NXP wrapper over the standard tool `src/app/ota_image_tool.py`: -- `scripts/tools/nxp/factory_data_generator/ota_image_tool.py` The tool can be - used to generate an OTA image with the following format: - `| OTA image header | TLV1 | TLV2 | ... | TLVn |` where each TLV is in the - form `|tag|length|value|` +- `scripts/tools/nxp/factory_data_generator/ota_image_tool.py` + +The tool can be used to generate an OTA image with the following format: + +``` + | OTA image header | TLV1 | TLV2 | ... | TLVn | +``` + +where each TLV is in the form `|tag|length|value|`. Note that "standard" TLV format is used. Matter TLV format is only used for factory data TLV value. Please see more in the -[OTA image tool guide](../../../../../scripts/tools/nxp/ota/README.md). +[OTA image tool guide](../../../../scripts/tools/nxp/ota/README.md). Here is an example that generates an OTA image with application update TLV from a sb3 file: @@ -340,12 +375,24 @@ having a correct OTA process, the OTA header version should be the same as the binary embedded software version. A user can set a custom software version in the gn build args by setting `chip_software_version` to the wanted version. +### OTA factory data + +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 + update processor (disabled by default). + +The OTA image used must be updated to include the new factory data. + +[OTA image tool guide](../../../../scripts/tools/nxp/ota/README.md). + ### Running OTA The OTA topology used for OTA testing is illustrated in the figure below. Topology is similar with the one used for Matter Test Events. -![OTA_TOPOLOGY](../../../../platform/nxp/k32w/k32w1/doc/images/ota_topology.JPG) +![OTA_TOPOLOGY](../../../platform/nxp/k32w1/doc/images/ota_topology.JPG) The concept for OTA is the next one: @@ -460,10 +507,16 @@ by running: `chip-console --device /dev/tty. -b 115200 -o pw_log.out` The console should already have been installed in the virtual environment. From -the `chip-console`, a user can send specific commands to the device, e.g.: +the `chip-console`, a user can send specific commands to the device. + +For button commands, please run `rpcs.chip.rpc.Button.Event(index)` based on the +table below: + +| index | action | +| ----- | --------------------------------------------- | +| 0 | Start/stop BLE advertising | +| 1 | Factory reset the device | +| 2 | Application specific action (e.g. toggle LED) | +| 3 | Soft reset the device | -- To toggle the LED (`#define LIGHT_BUTTON 2` in `app_config.h`) - `rpcs.chip.rpc.Button.Event(idx=2)` -- To start BLE advertising (`#define BLE_BUTTON 4` in `app_config.h`) - `rpcs.chip.rpc.Button.Event(idx=4)` -- To reboot the device `rpcs.chip.rpc.Device.Reboot()` +To reboot the device, please run `rpcs.chip.rpc.Device.Reboot()`. diff --git a/examples/lighting-app/nxp/k32w/k32w1/args.gni b/examples/lighting-app/nxp/k32w1/args.gni similarity index 74% rename from examples/lighting-app/nxp/k32w/k32w1/args.gni rename to examples/lighting-app/nxp/k32w1/args.gni index d0c28a1e04..7d5e752aae 100644 --- a/examples/lighting-app/nxp/k32w/k32w1/args.gni +++ b/examples/lighting-app/nxp/k32w1/args.gni @@ -13,9 +13,11 @@ # limitations under the License. import("//build_overrides/chip.gni") +import("${chip_root}/config/standalone/args.gni") # SDK target. This is overridden to add our SDK app_config.h & defines. -k32w1_sdk_target = get_label_info(":sdk", "label_no_toolchain") +nxp_sdk_target = get_label_info(":sdk", "label_no_toolchain") +nxp_device = "K32W1480" chip_config_dimmable_led = false chip_enable_ota_requestor = true @@ -27,3 +29,10 @@ is_debug = false chip_crypto = "platform" chip_openthread_ftd = true chip_with_ot_cli = 0 + +chip_system_config_provide_statistics = false +chip_system_config_use_open_thread_inet_endpoints = true +chip_with_lwip = false + +use_smu2_static = false +use_smu2_dynamic = false diff --git a/examples/lighting-app/nxp/k32w1/build_overrides b/examples/lighting-app/nxp/k32w1/build_overrides new file mode 120000 index 0000000000..ee19c065d6 --- /dev/null +++ b/examples/lighting-app/nxp/k32w1/build_overrides @@ -0,0 +1 @@ +../../../build_overrides/ \ No newline at end of file diff --git a/examples/lighting-app/nxp/k32w1/include/config/AppConfig.h b/examples/lighting-app/nxp/k32w1/include/config/AppConfig.h new file mode 100644 index 0000000000..6dcccf749b --- /dev/null +++ b/examples/lighting-app/nxp/k32w1/include/config/AppConfig.h @@ -0,0 +1,29 @@ +/* + * Copyright 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 + +/* ---- App Config ---- */ +#define APP_DEVICE_TYPE_ENDPOINT 1 +#define APP_CLUSTER_ATTRIBUTE chip::app::Clusters::OnOff::Attributes::OnOff + +/* ---- Button Manager Config ---- */ +#define BUTTON_MANAGER_FACTORY_RESET_TIMEOUT_MS 6000 + +/* ---- LED Manager Config ---- */ +#define LED_MANAGER_STATUS_LED_INDEX 0 +#define LED_MANAGER_LIGHT_LED_INDEX 1 diff --git a/examples/lighting-app/nxp/k32w/k32w1/include/CHIPProjectConfig.h b/examples/lighting-app/nxp/k32w1/include/config/CHIPProjectConfig.h similarity index 100% rename from examples/lighting-app/nxp/k32w/k32w1/include/CHIPProjectConfig.h rename to examples/lighting-app/nxp/k32w1/include/config/CHIPProjectConfig.h diff --git a/examples/lighting-app/nxp/k32w1/third_party/connectedhomeip b/examples/lighting-app/nxp/k32w1/third_party/connectedhomeip new file mode 120000 index 0000000000..59307833b4 --- /dev/null +++ b/examples/lighting-app/nxp/k32w1/third_party/connectedhomeip @@ -0,0 +1 @@ +../../../../.. \ No newline at end of file diff --git a/examples/lighting-app/nxp/k32w/k32w1/with_pw_rpc.gni b/examples/lighting-app/nxp/k32w1/with_pw_rpc.gni similarity index 84% rename from examples/lighting-app/nxp/k32w/k32w1/with_pw_rpc.gni rename to examples/lighting-app/nxp/k32w1/with_pw_rpc.gni index d6bea63f84..c2dc195054 100644 --- a/examples/lighting-app/nxp/k32w/k32w1/with_pw_rpc.gni +++ b/examples/lighting-app/nxp/k32w1/with_pw_rpc.gni @@ -17,17 +17,21 @@ import("//build_overrides/chip.gni") import("${chip_root}/config/nxp/lib/pw_rpc/pw_rpc.gni") -import("${chip_root}/examples/platform/nxp/k32w/k32w1/args.gni") -k32w1_sdk_target = get_label_info(":sdk", "label_no_toolchain") +nxp_sdk_target = get_label_info(":sdk", "label_no_toolchain") -chip_enable_ota_requestor = true -chip_stack_lock_tracking = "fatal" +chip_crypto = "platform" chip_enable_ble = true +chip_enable_ota_requestor = true chip_enable_pw_rpc = true -chip_with_ot_cli = 0 -is_debug = false chip_openthread_ftd = true -chip_crypto = "platform" +chip_stack_lock_tracking = "fatal" + +chip_system_config_provide_statistics = false +chip_system_config_use_open_thread_inet_endpoints = true + +chip_with_lwip = false +chip_with_ot_cli = 0 cpp_standard = "gnu++17" +is_debug = false diff --git a/examples/platform/nxp/Rpc.cpp b/examples/platform/nxp/Rpc.cpp index 262825386e..c0cb0b933f 100644 --- a/examples/platform/nxp/Rpc.cpp +++ b/examples/platform/nxp/Rpc.cpp @@ -16,7 +16,7 @@ * limitations under the License. */ -#include "AppTask.h" +#include "AppRpc.h" #include "FreeRTOS.h" #include "PigweedLogger.h" #include "PigweedLoggerMutex.h" @@ -43,8 +43,14 @@ #include "pigweed/rpc_services/Locking.h" #endif // defined(PW_RPC_LOCKING_SERVICE) && PW_RPC_LOCKING_SERVICE +#ifndef RPC_TASK_STACK_SIZE #define RPC_TASK_STACK_SIZE 2048 +#endif + +#ifndef RPC_TASK_PRIORITY #define RPC_TASK_PRIORITY 1 +#endif + TaskHandle_t RpcTaskHandle; namespace chip { @@ -56,7 +62,7 @@ class NxpButton final : public Button public: pw::Status Event(const chip_rpc_ButtonEvent & request, pw_protobuf_Empty & response) override { - GetAppTask().ButtonEventHandler(request.idx, request.idx); + chip::NXP::App::Rpc::ButtonHandler(request); return pw::OkStatus(); } }; @@ -77,7 +83,7 @@ class NxpDevice final : public Device static constexpr TickType_t kRebootTimerPeriodTicks = 300; TimerHandle_t mRebootTimer; - static void RebootHandler(TimerHandle_t) { NVIC_SystemReset(); } + static void RebootHandler(TimerHandle_t) { chip::NXP::App::Rpc::Reboot(); } }; #endif // defined(PW_RPC_DEVICE_SERVICE) && PW_RPC_DEVICE_SERVICE diff --git a/examples/platform/nxp/common/app_task/include/AppTaskBase.h b/examples/platform/nxp/common/app_task/include/AppTaskBase.h index 98cec56832..76e18df7f4 100644 --- a/examples/platform/nxp/common/app_task/include/AppTaskBase.h +++ b/examples/platform/nxp/common/app_task/include/AppTaskBase.h @@ -27,9 +27,8 @@ #include #include -namespace chip { -namespace NXP { -namespace App { +namespace chip::NXP::App { + class AppTaskBase { public: @@ -97,6 +96,44 @@ class AppTaskBase */ virtual void AppMatter_RegisterCustomCliCommands(void){}; + /** + * \brief Disallow entering low power mode. + * + * This function can be overridden in order to implement a specific disallow mechanism. + * + */ + virtual void AppMatter_DisallowDeviceToSleep(void) {} + + /** + * \brief Allow entering low power mode. + * + * This function can be overridden in order to implement a specific allow mechanism. + * + */ + virtual void AppMatter_AllowDeviceToSleep(void) {} + + /** + * \brief Print onboarding information. + * + * It can be overwritten by derived classes for custom information, + * such as setting the commissioning flow to kUserActionRequired. + * + */ + virtual void PrintOnboardingInfo(); + + /** + * \brief Print current software version string and software version. + * + * It uses the ConfigurationManager API to extract the information. + */ + virtual void PrintCurrentVersion(); + + /** + * \brief Send event to the event queue. + * + */ + virtual void PostEvent(const AppEvent & event){}; + /** * \brief This function could be overridden in order to dispatch event. * @@ -142,6 +179,7 @@ class AppTaskBase private: inline static chip::CommonCaseDeviceServerInitParams initParams; + /* Functions used by the public commisioning handlers */ static void StartCommissioning(intptr_t arg); static void StopCommissioning(intptr_t arg); @@ -154,6 +192,5 @@ class AppTaskBase * Applications can use this to gain access to features of the AppTaskBase. */ extern AppTaskBase & GetAppTask(); -} // namespace App -} // namespace NXP -} // namespace chip + +} // namespace chip::NXP::App diff --git a/examples/platform/nxp/common/app_task/include/AppTaskFreeRTOS.h b/examples/platform/nxp/common/app_task/include/AppTaskFreeRTOS.h index 7ebc4a7430..0dd5c0d206 100644 --- a/examples/platform/nxp/common/app_task/include/AppTaskFreeRTOS.h +++ b/examples/platform/nxp/common/app_task/include/AppTaskFreeRTOS.h @@ -21,9 +21,8 @@ #include "AppTaskBase.h" -namespace chip { -namespace NXP { -namespace App { +namespace chip::NXP::App { + class AppTaskFreeRTOS : public AppTaskBase { public: @@ -53,7 +52,7 @@ class AppTaskFreeRTOS : public AppTaskBase * \brief Send event to the event queue. * */ - void PostEvent(const AppEvent & event); + void PostEvent(const AppEvent & event) override; /** * \brief Return a pointer to the NXP Wifi Driver instance. @@ -72,9 +71,20 @@ class AppTaskFreeRTOS : public AppTaskBase */ virtual CHIP_ERROR AppMatter_Register(void) override; + /** + * \brief The app event queue handle should be static such that the concrete + * application task can initialize it during Start() call. + */ + QueueHandle_t appEventQueue; + + /** + * \brief This value is used when xQueueReceive is called to specify + * the maximum amount of time the task should block waiting for an event. + * This can be modified according to the application needs. + */ + TickType_t ticksToWait; + private: void DispatchEvent(const AppEvent & event); }; -} // namespace App -} // namespace NXP -} // namespace chip +} // namespace chip::NXP::App diff --git a/examples/platform/nxp/common/app_task/include/AppTaskZephyr.h b/examples/platform/nxp/common/app_task/include/AppTaskZephyr.h index 77cfaa0e46..9a333a768e 100644 --- a/examples/platform/nxp/common/app_task/include/AppTaskZephyr.h +++ b/examples/platform/nxp/common/app_task/include/AppTaskZephyr.h @@ -21,9 +21,8 @@ #include "AppTaskBase.h" -namespace chip { -namespace NXP { -namespace App { +namespace chip::NXP::App { + class AppTaskZephyr : public AppTaskBase { public: @@ -43,7 +42,7 @@ class AppTaskZephyr : public AppTaskBase * \brief Send event to the event queue. * */ - void PostEvent(const AppEvent & event); + void PostEvent(const AppEvent & event) override; /** * \brief Return a pointer to the NXP Wifi Driver instance. @@ -65,6 +64,5 @@ class AppTaskZephyr : public AppTaskBase private: void DispatchEvent(const AppEvent & event); }; -} // namespace App -} // namespace NXP -} // namespace chip + +} // namespace chip::NXP::App diff --git a/examples/platform/nxp/common/app_task/source/AppTaskBase.cpp b/examples/platform/nxp/common/app_task/source/AppTaskBase.cpp index 9ba90e6c14..10422121e5 100644 --- a/examples/platform/nxp/common/app_task/source/AppTaskBase.cpp +++ b/examples/platform/nxp/common/app_task/source/AppTaskBase.cpp @@ -26,7 +26,6 @@ #include #include -#include #include #include @@ -37,7 +36,18 @@ #include -#ifdef EMBER_AF_PLUGIN_BINDING +#if defined(MATTER_DM_PLUGIN_USER_LABEL) || defined(MATTER_DM_PLUGIN_FIXED_LABEL) +#ifndef CONFIG_DEVICE_INFO_PROVIDER_IMPL +#define CONFIG_DEVICE_INFO_PROVIDER_IMPL 1 +#endif +#endif + +#if CONFIG_DEVICE_INFO_PROVIDER_IMPL +#include +#endif + +/* Flag generated by Zap */ +#ifdef MATTER_DM_PLUGIN_BINDING #include "binding-handler.h" #endif @@ -50,10 +60,22 @@ #include "TcpDownload.h" #endif +#if CONFIG_OPERATIONAL_KEYSTORE +#include "OperationalKeystore.h" +#endif + #if CONFIG_CHIP_OTA_PROVIDER #include #endif +#if CONFIG_DIAG_LOGS_DEMO +#include "DiagnosticLogsDemo.h" +#endif + +#if CONFIG_LOW_POWER +#include "LowPower.h" +#endif + #if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR #include "OTARequestorInitiator.h" #endif @@ -66,6 +88,19 @@ #include #endif +#ifdef SMOKE_CO_ALARM +#include +#include +#endif + +#if CHIP_CONFIG_ENABLE_ICD_SERVER +#include +#endif + +#ifndef CONFIG_THREAD_DEVICE_TYPE +#define CONFIG_THREAD_DEVICE_TYPE kThreadDeviceType_Router +#endif + using namespace chip; using namespace chip::TLV; using namespace ::chip::Credentials; @@ -73,14 +108,16 @@ using namespace ::chip::DeviceLayer; using namespace ::chip::DeviceManager; using namespace ::chip::app::Clusters; +#if CONFIG_DEVICE_INFO_PROVIDER_IMPL chip::DeviceLayer::DeviceInfoProviderImpl gExampleDeviceInfoProvider; +#endif #if CONFIG_CHIP_WIFI || CHIP_DEVICE_CONFIG_ENABLE_WPA app::Clusters::NetworkCommissioning::Instance sNetworkCommissioningInstance(0, chip::NXP::App::GetAppTask().GetWifiDriverInstance()); #endif -#if CONFIG_CHIP_TEST_EVENT && CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR +#if CHIP_CONFIG_ENABLE_ICD_SERVER || (CONFIG_CHIP_TEST_EVENT && CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR) static uint8_t sTestEventTriggerEnableKey[TestEventTriggerDelegate::kEnableKeyLength] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff }; @@ -89,12 +126,14 @@ static uint8_t sTestEventTriggerEnableKey[TestEventTriggerDelegate::kEnableKeyLe #if CONFIG_NET_L2_OPENTHREAD void LockOpenThreadTask(void) { + chip::NXP::App::GetAppTask().AppMatter_DisallowDeviceToSleep(); chip::DeviceLayer::ThreadStackMgr().LockThreadStack(); } void UnlockOpenThreadTask(void) { chip::DeviceLayer::ThreadStackMgr().UnlockThreadStack(); + chip::NXP::App::GetAppTask().AppMatter_AllowDeviceToSleep(); } #endif @@ -106,7 +145,26 @@ void chip::NXP::App::AppTaskBase::InitServer(intptr_t arg) static OTATestEventTriggerDelegate testEventTriggerDelegate{ ByteSpan(sTestEventTriggerEnableKey) }; initParams.testEventTriggerDelegate = &testEventTriggerDelegate; #endif + +#ifdef SMOKE_CO_ALARM + static SimpleTestEventTriggerDelegate sTestEventTriggerDelegate{}; + static SmokeCOTestEventTriggerHandler sSmokeCOTestEventTriggerHandler{}; + VerifyOrDie(sTestEventTriggerDelegate.Init(ByteSpan(sTestEventTriggerEnableKey)) == CHIP_NO_ERROR); + VerifyOrDie(sTestEventTriggerDelegate.AddHandler(&sSmokeCOTestEventTriggerHandler) == CHIP_NO_ERROR); + initParams.testEventTriggerDelegate = &sTestEventTriggerDelegate; +#endif + +#if CHIP_CONFIG_ENABLE_ICD_SERVER + static SimpleTestEventTriggerDelegate sTestEventTriggerDelegate{}; + VerifyOrDie(sTestEventTriggerDelegate.Init(ByteSpan(sTestEventTriggerEnableKey)) == CHIP_NO_ERROR); + initParams.testEventTriggerDelegate = &sTestEventTriggerDelegate; +#endif + +#if CONFIG_OPERATIONAL_KEYSTORE + initParams.operationalKeystore = chip::NXP::App::OperationalKeystore::GetInstance(); +#endif (void) initParams.InitializeStaticResourcesBeforeServerInit(); + #if CONFIG_NET_L2_OPENTHREAD // Init ZCL Data Model and start server chip::Inet::EndPointStateOpenThread::OpenThreadEndpointInitParam nativeParams; @@ -117,12 +175,22 @@ void chip::NXP::App::AppTaskBase::InitServer(intptr_t arg) #endif VerifyOrDie((chip::Server::GetInstance().Init(initParams)) == CHIP_NO_ERROR); + auto * persistentStorage = &Server::GetInstance().GetPersistentStorage(); +#if CONFIG_OPERATIONAL_KEYSTORE + chip::NXP::App::OperationalKeystore::Init(persistentStorage); +#endif - gExampleDeviceInfoProvider.SetStorageDelegate(&Server::GetInstance().GetPersistentStorage()); +#if CONFIG_DEVICE_INFO_PROVIDER_IMPL + gExampleDeviceInfoProvider.SetStorageDelegate(persistentStorage); chip::DeviceLayer::SetDeviceInfoProvider(&gExampleDeviceInfoProvider); +#endif GetAppTask().PostInitMatterServerInstance(); +#if CONFIG_DIAG_LOGS_DEMO + chip::NXP::App::DiagnosticLogsDemo::DisplayUsage(); +#endif + #if CONFIG_CHIP_OTA_PROVIDER InitOTAServer(); #endif @@ -135,6 +203,10 @@ CHIP_ERROR chip::NXP::App::AppTaskBase::Init() /* Init Chip memory management before the stack */ chip::Platform::MemoryInit(); +#if CONFIG_LOW_POWER + chip::NXP::App::LowPower::Init(); +#endif + /* Initialize Matter factory data before initializing the Matter stack */ err = AppFactoryData_PreMatterStackInit(); @@ -187,7 +259,7 @@ CHIP_ERROR chip::NXP::App::AppTaskBase::Init() return err; } - err = ConnectivityMgr().SetThreadDeviceType(ConnectivityManager::kThreadDeviceType_Router); + err = ConnectivityMgr().SetThreadDeviceType(ConnectivityManager::CONFIG_THREAD_DEVICE_TYPE); if (err != CHIP_NO_ERROR) { return err; @@ -200,7 +272,8 @@ CHIP_ERROR chip::NXP::App::AppTaskBase::Init() */ PlatformMgr().ScheduleWork(InitServer, 0); -#ifdef EMBER_AF_PLUGIN_BINDING +/* Flag generated by Zap */ +#ifdef MATTER_DM_PLUGIN_BINDING /* Init binding handlers */ err = InitBindingHandlers(); if (err != CHIP_NO_ERROR) @@ -227,11 +300,9 @@ CHIP_ERROR chip::NXP::App::AppTaskBase::Init() ConfigurationMgr().LogDeviceConfig(); // QR code will be used with CHIP Tool -#if CONFIG_NETWORK_LAYER_BLE - PrintOnboardingCodes(chip::RendezvousInformationFlag(chip::RendezvousInformationFlag::kBLE)); -#else - PrintOnboardingCodes(chip::RendezvousInformationFlag(chip::RendezvousInformationFlag::kOnNetwork)); -#endif /* CONFIG_NETWORK_LAYER_BLE */ + PrintOnboardingInfo(); + + PrintCurrentVersion(); /* Start a task to run the CHIP Device event loop. */ err = PlatformMgr().StartEventLoopTask(); @@ -333,3 +404,37 @@ void chip::NXP::App::AppTaskBase::FactoryResetHandler(void) chip::Server::GetInstance().GenerateShutDownEvent(); chip::Server::GetInstance().ScheduleFactoryReset(); } + +void chip::NXP::App::AppTaskBase::PrintOnboardingInfo() +{ +#if CONFIG_NETWORK_LAYER_BLE + auto flags = chip::RendezvousInformationFlags(chip::RendezvousInformationFlag::kBLE); +#else + auto flags = chip::RendezvousInformationFlags(chip::RendezvousInformationFlag::kOnNetwork); +#endif /* CONFIG_NETWORK_LAYER_BLE */ + + chip::PayloadContents payload; + CHIP_ERROR err = GetPayloadContents(payload, flags); + if (err != CHIP_NO_ERROR) + { + ChipLogError(AppServer, "GetPayloadContents() failed: %" CHIP_ERROR_FORMAT, err.Format()); + } +#if CONFIG_USER_ACTION_REQUIRED + payload.commissioningFlow = chip::CommissioningFlow::kUserActionRequired; +#endif + PrintOnboardingCodes(payload); +} + +void chip::NXP::App::AppTaskBase::PrintCurrentVersion() +{ + // Print the current software version + char currentSoftwareVer[ConfigurationManager::kMaxSoftwareVersionStringLength + 1] = { 0 }; + auto err = ConfigurationMgr().GetSoftwareVersionString(currentSoftwareVer, sizeof(currentSoftwareVer)); + ReturnOnFailure(err); + + uint32_t currentVersion; + err = ConfigurationMgr().GetSoftwareVersion(currentVersion); + ReturnOnFailure(err); + + ChipLogProgress(DeviceLayer, "Current Software Version: %s, %d", currentSoftwareVer, static_cast(currentVersion)); +} diff --git a/examples/platform/nxp/common/app_task/source/AppTaskFreeRTOS.cpp b/examples/platform/nxp/common/app_task/source/AppTaskFreeRTOS.cpp index c48894ed64..5b8e3eab70 100644 --- a/examples/platform/nxp/common/app_task/source/AppTaskFreeRTOS.cpp +++ b/examples/platform/nxp/common/app_task/source/AppTaskFreeRTOS.cpp @@ -34,6 +34,14 @@ #include "AppCLIBase.h" #endif +#if CONFIG_ENABLE_FEEDBACK +#include "UserInterfaceFeedback.h" +#endif + +#if CONFIG_ENABLE_PW_RPC +#include "AppRpc.h" +#endif + #include #include @@ -45,12 +53,18 @@ #ifndef APP_TASK_STACK_SIZE #define APP_TASK_STACK_SIZE ((configSTACK_DEPTH_TYPE) 6144 / sizeof(portSTACK_TYPE)) #endif + #ifndef APP_TASK_PRIORITY #define APP_TASK_PRIORITY 2 #endif + +#ifndef APP_EVENT_QUEUE_SIZE #define APP_EVENT_QUEUE_SIZE 10 +#endif -static QueueHandle_t sAppEventQueue; +#ifndef APP_QUEUE_TICKS_TO_WAIT +#define APP_QUEUE_TICKS_TO_WAIT portMAX_DELAY +#endif using namespace chip; using namespace chip::TLV; @@ -71,12 +85,18 @@ chip::DeviceLayer::NetworkCommissioning::WiFiDriver * chip::NXP::App::AppTaskFre CHIP_ERROR chip::NXP::App::AppTaskFreeRTOS::AppMatter_Register() { CHIP_ERROR err = CHIP_NO_ERROR; + /* Register Matter CLI cmds */ #ifdef ENABLE_CHIP_SHELL err = chip::NXP::App::GetAppCLI().Init(); VerifyOrReturnError(err == CHIP_NO_ERROR, err, ChipLogError(DeviceLayer, "Error during CLI init")); AppMatter_RegisterCustomCliCommands(); #endif + +#if CONFIG_ENABLE_FEEDBACK + FeedbackMgr().Init(); +#endif + /* Register Matter buttons */ err = AppMatterButton_registerButtons(); if (err != CHIP_NO_ERROR) @@ -92,14 +112,30 @@ CHIP_ERROR chip::NXP::App::AppTaskFreeRTOS::Start() CHIP_ERROR err = CHIP_NO_ERROR; TaskHandle_t taskHandle; - sAppEventQueue = xQueueCreate(APP_EVENT_QUEUE_SIZE, sizeof(AppEvent)); - if (sAppEventQueue == NULL) +#if CONFIG_ENABLE_PW_RPC + chip::NXP::App::Rpc::Init(); +#endif + + appEventQueue = xQueueCreate(APP_EVENT_QUEUE_SIZE, sizeof(AppEvent)); + if (appEventQueue == NULL) { err = CHIP_ERROR_NO_MEMORY; ChipLogError(DeviceLayer, "Failed to allocate app event queue"); assert(err == CHIP_NO_ERROR); } + ticksToWait = APP_QUEUE_TICKS_TO_WAIT; + +#if FSL_OSA_MAIN_FUNC_ENABLE + /* When OSA is used, this code will be called from within the startup_task + * and the scheduler will be started at this point. Just call AppTaskMain to + * start the main loop instead of creating a task, since we are already in it. + * Task parameters are configured through SDK flags: + * - gMainThreadPriority_c + * - gMainThreadStackSize_c + */ + AppTaskFreeRTOS::AppTaskMain(this); +#else /* AppTaskMain function will loss actual object instance, give it as parameter */ if (xTaskCreate(&AppTaskFreeRTOS::AppTaskMain, "AppTaskMain", APP_TASK_STACK_SIZE, this, APP_TASK_PRIORITY, &taskHandle) != pdPASS) @@ -108,6 +144,7 @@ CHIP_ERROR chip::NXP::App::AppTaskFreeRTOS::Start() ChipLogError(DeviceLayer, "Failed to start app task"); assert(err == CHIP_NO_ERROR); } +#endif // FSL_OSA_TASK_ENABLE return err; } @@ -122,31 +159,43 @@ void chip::NXP::App::AppTaskFreeRTOS::AppTaskMain(void * pvParameter) sAppTask->PreInitMatterStack(); err = sAppTask->Init(); + VerifyOrDieWithMsg(err == CHIP_NO_ERROR, DeviceLayer, "AppTask.Init() failed"); sAppTask->PostInitMatterStack(); - if (err != CHIP_NO_ERROR) - { - ChipLogError(DeviceLayer, "AppTask.Init() failed"); - assert(err == CHIP_NO_ERROR); - } while (true) { - BaseType_t eventReceived = xQueueReceive(sAppEventQueue, &event, portMAX_DELAY); + BaseType_t eventReceived = xQueueReceive(sAppTask->appEventQueue, &event, sAppTask->ticksToWait); while (eventReceived == pdTRUE) { sAppTask->DispatchEvent(event); - eventReceived = xQueueReceive(sAppEventQueue, &event, 0); + eventReceived = xQueueReceive(sAppTask->appEventQueue, &event, 0); } +#if CONFIG_ENABLE_FEEDBACK + FeedbackMgr().DisplayInLoop(); +#endif } } void chip::NXP::App::AppTaskFreeRTOS::PostEvent(const AppEvent & event) { - if (sAppEventQueue != NULL) + if (appEventQueue != NULL) { - if (!xQueueSend(sAppEventQueue, &event, 0)) + if (__get_IPSR()) + { + portBASE_TYPE taskToWake = pdFALSE; + if (!xQueueSendToFrontFromISR(appEventQueue, &event, &taskToWake)) + { + ChipLogError(DeviceLayer, "Failed to post event to app task event queue from ISR"); + } + + portYIELD_FROM_ISR(taskToWake); + } + else { - ChipLogError(DeviceLayer, "Failed to post event to app task event queue"); + if (!xQueueSend(appEventQueue, &event, 0)) + { + ChipLogError(DeviceLayer, "Failed to post event to app task event queue"); + } } } } diff --git a/examples/platform/nxp/common/clusters/include/Identify.h b/examples/platform/nxp/common/clusters/include/Identify.h new file mode 100644 index 0000000000..a742e38087 --- /dev/null +++ b/examples/platform/nxp/common/clusters/include/Identify.h @@ -0,0 +1,31 @@ +/* + * 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::NXP::App { + +// Identify cluster callbacks. +void OnIdentifyStart(Identify * identify); +void OnIdentifyStop(Identify * identify); +void OnTriggerEffect(Identify * identify); +void OnTriggerEffectComplete(chip::System::Layer * systemLayer, void * appState); + +} // namespace chip::NXP::App diff --git a/examples/platform/nxp/common/clusters/source/ZclCallbacks.cpp b/examples/platform/nxp/common/clusters/source/ZclCallbacks.cpp new file mode 100644 index 0000000000..99329a818c --- /dev/null +++ b/examples/platform/nxp/common/clusters/source/ZclCallbacks.cpp @@ -0,0 +1,52 @@ +/* + * + * Copyright (c) 2021-2023 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 "CHIPDeviceManager.h" + +#include + +#if CONFIG_DIAG_LOGS_DEMO +#include "DiagnosticLogsProviderDelegateImpl.h" +#include +#endif + +void MatterPostAttributeChangeCallback(const chip::app::ConcreteAttributePath & path, uint8_t type, uint16_t size, uint8_t * value) +{ + chip::DeviceManager::CHIPDeviceManagerCallbacks * cb = + chip::DeviceManager::CHIPDeviceManager::GetInstance().GetCHIPDeviceManagerCallbacks(); + if (cb != nullptr) + { + // propagate event to device manager + cb->PostAttributeChangeCallback(path.mEndpointId, path.mClusterId, path.mAttributeId, type, size, value); + } +} + +#if CONFIG_DIAG_LOGS_DEMO +/** @brief DiagnosticLogs Cluster Init + * + * This function is called when a specific cluster is initialized. It gives the + * application an opportunity to take care of cluster initialization procedures. + * It is called exactly once for each endpoint where cluster is present. + */ +void emberAfDiagnosticLogsClusterInitCallback(chip::EndpointId endpoint) +{ + auto & logProvider = chip::app::Clusters::DiagnosticLogs::LogProvider::GetInstance(); + auto & server = chip::app::Clusters::DiagnosticLogs::DiagnosticLogsServer::Instance(); + server.SetDiagnosticLogsProviderDelegate(endpoint, &logProvider); +} +#endif diff --git a/examples/platform/nxp/common/device_callbacks/source/CommonDeviceCallbacks.cpp b/examples/platform/nxp/common/device_callbacks/source/CommonDeviceCallbacks.cpp index d38d6f59f8..bc7a8dca43 100644 --- a/examples/platform/nxp/common/device_callbacks/source/CommonDeviceCallbacks.cpp +++ b/examples/platform/nxp/common/device_callbacks/source/CommonDeviceCallbacks.cpp @@ -33,7 +33,6 @@ #include #if CHIP_ENABLE_OPENTHREAD && CHIP_DEVICE_CONFIG_CHIPOBLE_DISABLE_ADVERTISING_WHEN_PROVISIONED #include "openthread-system.h" -#include "ot_platform_common.h" #endif /* CHIP_ENABLE_OPENTHREAD && CHIP_DEVICE_CONFIG_CHIPOBLE_DISABLE_ADVERTISING_WHEN_PROVISIONED */ #if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR diff --git a/examples/platform/nxp/common/diagnostic_logs/include/DiagnosticLogsDemo.h b/examples/platform/nxp/common/diagnostic_logs/include/DiagnosticLogsDemo.h new file mode 100644 index 0000000000..e801837e09 --- /dev/null +++ b/examples/platform/nxp/common/diagnostic_logs/include/DiagnosticLogsDemo.h @@ -0,0 +1,31 @@ +/* + * 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::NXP::App::DiagnosticLogsDemo { + +/** + * @brief Display a demo usage of the diagnostic logs provider. + * + */ +CHIP_ERROR DisplayUsage(); + +} // namespace chip::NXP::App::DiagnosticLogsDemo diff --git a/examples/platform/nxp/common/diagnostic_logs/DiagnosticLogsProviderDelegateImpl.h b/examples/platform/nxp/common/diagnostic_logs/include/DiagnosticLogsProviderDelegateImpl.h similarity index 100% rename from examples/platform/nxp/common/diagnostic_logs/DiagnosticLogsProviderDelegateImpl.h rename to examples/platform/nxp/common/diagnostic_logs/include/DiagnosticLogsProviderDelegateImpl.h diff --git a/examples/platform/nxp/common/diagnostic_logs/source/DiagnosticLogsDemo.cpp b/examples/platform/nxp/common/diagnostic_logs/source/DiagnosticLogsDemo.cpp new file mode 100644 index 0000000000..3599526093 --- /dev/null +++ b/examples/platform/nxp/common/diagnostic_logs/source/DiagnosticLogsDemo.cpp @@ -0,0 +1,47 @@ +/* + * 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 "DiagnosticLogsDemo.h" +#include "DiagnosticLogsProviderDelegateImpl.h" + +#include + +CHIP_ERROR chip::NXP::App::DiagnosticLogsDemo::DisplayUsage() +{ + char diagLog[CHIP_DEVICE_CONFIG_MAX_DIAG_LOG_SIZE]; + uint16_t diagLogSize = CHIP_DEVICE_CONFIG_MAX_DIAG_LOG_SIZE; + + chip::StorageKeyName keyUser = chip::app::Clusters::DiagnosticLogs::LogProvider::GetKeyDiagUserSupport(); + chip::StorageKeyName keyNwk = chip::app::Clusters::DiagnosticLogs::LogProvider::GetKeyDiagNetwork(); + chip::StorageKeyName keyCrash = chip::app::Clusters::DiagnosticLogs::LogProvider::GetKeyDiagCrashLog(); + + auto & persistentStorage = chip::Server::GetInstance().GetPersistentStorage(); + /* The KVS wear stats are stored in the user diagnostic log key hence only + * initialize this key if the KVS wear stats are not enabled. */ +#if (CHIP_DEVICE_CONFIG_KVS_WEAR_STATS != 1) + memset(diagLog, 0, diagLogSize); + persistentStorage.SyncSetKeyValue(keyUser.KeyName(), diagLog, diagLogSize); +#endif + + memset(diagLog, 1, diagLogSize); + persistentStorage.SyncSetKeyValue(keyNwk.KeyName(), diagLog, diagLogSize); + + memset(diagLog, 2, diagLogSize); + persistentStorage.SyncSetKeyValue(keyCrash.KeyName(), diagLog, diagLogSize); + + return CHIP_NO_ERROR; +} diff --git a/examples/platform/nxp/common/diagnostic_logs/DiagnosticLogsProviderDelegateImpl.cpp b/examples/platform/nxp/common/diagnostic_logs/source/DiagnosticLogsProviderDelegateImpl.cpp similarity index 98% rename from examples/platform/nxp/common/diagnostic_logs/DiagnosticLogsProviderDelegateImpl.cpp rename to examples/platform/nxp/common/diagnostic_logs/source/DiagnosticLogsProviderDelegateImpl.cpp index 359edc3ded..929905afad 100644 --- a/examples/platform/nxp/common/diagnostic_logs/DiagnosticLogsProviderDelegateImpl.cpp +++ b/examples/platform/nxp/common/diagnostic_logs/source/DiagnosticLogsProviderDelegateImpl.cpp @@ -142,7 +142,7 @@ size_t LogProvider::GetSizeForIntent(IntentEnum intent) VerifyOrReturnValue(buffer.Get() != nullptr, 0); err = Server::GetInstance().GetPersistentStorage().SyncGetKeyValue(key.KeyName(), buffer.Get(), sizeForIntent); - VerifyOrReturnValue(err == CHIP_NO_ERROR, 0); + VerifyOrReturnValue(err == CHIP_ERROR_BUFFER_TOO_SMALL, 0); return sizeForIntent; } diff --git a/examples/platform/nxp/common/factory_data/source/AppFactoryDataDefaultImpl.cpp b/examples/platform/nxp/common/factory_data/source/AppFactoryDataDefaultImpl.cpp index 4fd176075f..c1b8560422 100644 --- a/examples/platform/nxp/common/factory_data/source/AppFactoryDataDefaultImpl.cpp +++ b/examples/platform/nxp/common/factory_data/source/AppFactoryDataDefaultImpl.cpp @@ -24,7 +24,10 @@ #include #if CONFIG_CHIP_PLAT_LOAD_REAL_FACTORY_DATA -#include "FactoryDataProvider.h" +#ifndef EXTERNAL_FACTORY_DATA_PROVIDER_HEADER +#define EXTERNAL_FACTORY_DATA_PROVIDER_HEADER "platform/nxp/common/factory_data/FactoryDataProvider.h" +#endif +#include EXTERNAL_FACTORY_DATA_PROVIDER_HEADER #if CONFIG_CHIP_ENCRYPTED_FACTORY_DATA /* * Test key used to encrypt factory data before storing it to the flash. @@ -64,7 +67,7 @@ CHIP_ERROR chip::NXP::App::AppFactoryData_PostMatterStackInit(void) FactoryDataPrvdImpl().SetAes128Key(&aes128TestKey[0]); #endif /* CONFIG_CHIP_ENCRYPTED_FACTORY_DATA */ - ReturnErrorOnFailure(FactoryDataPrvdImpl().Init()); + ReturnErrorOnFailure(FactoryDataPrvd().Init()); SetDeviceInstanceInfoProvider(&FactoryDataPrvd()); SetDeviceAttestationCredentialsProvider(&FactoryDataPrvd()); diff --git a/examples/platform/nxp/common/led_widget/include/LedDimmer.h b/examples/platform/nxp/common/led_widget/include/LedDimmer.h new file mode 100644 index 0000000000..83632738ba --- /dev/null +++ b/examples/platform/nxp/common/led_widget/include/LedDimmer.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 "LedWidgetInterface.h" + +namespace chip::NXP::App { + +/** + * @brief + * A class that manages dimmer LED operations. + */ +class LedDimmer : public LedWidgetInterface +{ +public: + void Init(uint8_t index = 0, bool inverted = false) override; + void Set(uint8_t level = 0) override; + void Animate(uint32_t onTimeMS = 0, uint32_t offTimeMS = 0) override {} +}; + +} // namespace chip::NXP::App diff --git a/examples/platform/nxp/common/led_widget/include/LedOnOff.h b/examples/platform/nxp/common/led_widget/include/LedOnOff.h new file mode 100644 index 0000000000..128bbb89aa --- /dev/null +++ b/examples/platform/nxp/common/led_widget/include/LedOnOff.h @@ -0,0 +1,47 @@ +/* + * + * 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 "LedWidgetInterface.h" + +namespace chip::NXP::App { + +/** + * @brief + * A base class that manages an on-off LED on a board. + */ +class LedOnOff : public LedWidgetInterface +{ +public: + void Init(uint8_t index = 0, bool inverted = 0) override; + void Set(uint8_t level = 0) override; + void Animate(uint32_t onTimeMS = 0, uint32_t offTimeMS = 0) override; + +private: + uint64_t mLastChangeTimeMS = 0; + uint32_t mOnTimeMS = 0; + uint32_t mOffTimeMS = 0; + uint8_t mIndex = 0; + + bool mOnLogic = true; + + void DoSet(bool state); +}; + +} // namespace chip::NXP::App diff --git a/examples/platform/nxp/k32w/k32w1/util/include/LEDWidget.h b/examples/platform/nxp/common/led_widget/include/LedWidgetInterface.h similarity index 55% rename from examples/platform/nxp/k32w/k32w1/util/include/LEDWidget.h rename to examples/platform/nxp/common/led_widget/include/LedWidgetInterface.h index a73ab8a904..155da65eea 100644 --- a/examples/platform/nxp/k32w/k32w1/util/include/LEDWidget.h +++ b/examples/platform/nxp/common/led_widget/include/LedWidgetInterface.h @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2020 Google LLC. + * Copyright (c) 2024 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -16,28 +16,29 @@ * limitations under the License. */ -// #include "LED.h" -#include "EmbeddedTypes.h" #pragma once -class LEDWidget +#include "EmbeddedTypes.h" + +namespace chip::NXP::App { + +/** + * @brief + * An interface that defines LED operations. + */ +class LedWidgetInterface { public: - void Init(uint8_t gpioNum, bool inverted); - void Set(bool state); - void SetLevel(uint8_t level); - void Invert(void); - void Blink(uint32_t changeRateMS); - void Blink(uint32_t onTimeMS, uint32_t offTimeMS); - void Animate(); - -private: - uint64_t mLastChangeTimeMS; - uint32_t mBlinkOnTimeMS; - uint32_t mBlinkOffTimeMS; - uint8_t mGPIONum; - bool mState; - bool mOnLogic; - - void DoSet(bool state); + virtual ~LedWidgetInterface() {} + + virtual void Init(uint8_t index = 0, bool inverted = false) = 0; + virtual void Set(uint8_t level = 0) = 0; + virtual void Animate(uint32_t onTimeMS = 0, uint32_t offTimeMS = 0) = 0; + + bool IsTurnedOff() { return !mState; } + +protected: + bool mState = false; }; + +} // namespace chip::NXP::App diff --git a/examples/platform/nxp/common/low_power/include/LowPower.h b/examples/platform/nxp/common/low_power/include/LowPower.h new file mode 100644 index 0000000000..fc2bdd8ff0 --- /dev/null +++ b/examples/platform/nxp/common/low_power/include/LowPower.h @@ -0,0 +1,32 @@ +/* + * 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 chip::NXP::App::LowPower { + +/** + * @brief Low-power related init function. + * + * For example, it can be used to register an enter/exit low power callback. + * + */ +CHIP_ERROR Init(); + +} // namespace chip::NXP::App::LowPower diff --git a/examples/platform/nxp/common/low_power/source/LowPower.cpp b/examples/platform/nxp/common/low_power/source/LowPower.cpp new file mode 100644 index 0000000000..9b5afd19b1 --- /dev/null +++ b/examples/platform/nxp/common/low_power/source/LowPower.cpp @@ -0,0 +1,48 @@ +/* + * 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 "LowPower.h" +#include "fsl_pm_core.h" + +#include + +#define APP_ERROR_PM_REGISTER_LP_CALLBACK_FAILED CHIP_APPLICATION_ERROR(0x01) + +static status_t LowPowerCallback(pm_event_type_t type, uint8_t state, void * data); + +static pm_notify_element_t appNotifyElement = { + .notifyCallback = LowPowerCallback, + .data = NULL, +}; + +static status_t LowPowerCallback(pm_event_type_t type, uint8_t state, void * data) +{ + // This is just an example. It does nothing by default. + return kStatus_Success; +} + +namespace chip::NXP::App::LowPower { + +CHIP_ERROR Init() +{ + status_t status = PM_RegisterNotify(kPM_NotifyGroup2, &appNotifyElement); + VerifyOrReturnError(status == kStatus_Success, APP_ERROR_PM_REGISTER_LP_CALLBACK_FAILED); + + return CHIP_NO_ERROR; +} + +} // namespace chip::NXP::App::LowPower diff --git a/examples/platform/nxp/common/operational_keystore/include/OperationalKeystore.h b/examples/platform/nxp/common/operational_keystore/include/OperationalKeystore.h new file mode 100644 index 0000000000..4bb3582fc6 --- /dev/null +++ b/examples/platform/nxp/common/operational_keystore/include/OperationalKeystore.h @@ -0,0 +1,41 @@ +/* + * 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::NXP::App::OperationalKeystore { + +/** + * @brief Getter for operational keystore instance. + * + * It can be overwritten to return an instance of a dervied keystore implementation. + * + */ +chip::Crypto::OperationalKeystore * GetInstance(); + +/** + * @brief Initialization entry for specific operational keystore actions. + * + * For example, it can be overwritten to register a persistent storage delegate. + * + */ +CHIP_ERROR Init(PersistentStorageDelegate * delegate); + +} // namespace chip::NXP::App::OperationalKeystore diff --git a/examples/platform/nxp/common/operational_keystore/source/OperationalKeystoreEmpty.cpp b/examples/platform/nxp/common/operational_keystore/source/OperationalKeystoreEmpty.cpp new file mode 100644 index 0000000000..6d69720bc0 --- /dev/null +++ b/examples/platform/nxp/common/operational_keystore/source/OperationalKeystoreEmpty.cpp @@ -0,0 +1,31 @@ +/* + * 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 "OperationalKeystore.h" + +chip::Crypto::OperationalKeystore * chip::NXP::App::OperationalKeystore::GetInstance() +{ + // Default implementation returns a null pointer. + // Applications that have a specific operational keystore defined should implement + // this function and return a pointer to that instance. + return nullptr; +} + +CHIP_ERROR chip::NXP::App::OperationalKeystore::Init(PersistentStorageDelegate * delegate) +{ + return CHIP_NO_ERROR; +} diff --git a/examples/platform/nxp/common/ota_requestor/source/OTARequestorInitiatorMultiImage.cpp b/examples/platform/nxp/common/ota_requestor/source/OTARequestorInitiatorMultiImage.cpp new file mode 100644 index 0000000000..527b416a86 --- /dev/null +++ b/examples/platform/nxp/common/ota_requestor/source/OTARequestorInitiatorMultiImage.cpp @@ -0,0 +1,43 @@ +/* + * + * 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 "OTARequestorInitiator.h" + +using namespace chip; + +constexpr uint16_t requestedOtaBlockSize = 1024; + +void chip::NXP::App::OTARequestorInitiator::InitOTA(intptr_t context) +{ + auto * otaRequestorInit = reinterpret_cast(context); + // Set the global instance of the OTA requestor core component + SetRequestorInstance(&otaRequestorInit->gRequestorCore); + + otaRequestorInit->gRequestorStorage.Init(chip::Server::GetInstance().GetPersistentStorage()); + otaRequestorInit->gRequestorCore.Init(chip::Server::GetInstance(), otaRequestorInit->gRequestorStorage, + otaRequestorInit->gRequestorUser, otaRequestorInit->gDownloader); + otaRequestorInit->gRequestorUser.SetMaxDownloadBlockSize(requestedOtaBlockSize); + + auto & imageProcessor = OTAImageProcessorImpl::GetDefaultInstance(); + otaRequestorInit->gRequestorUser.Init(&otaRequestorInit->gRequestorCore, &imageProcessor); + imageProcessor.Init(&otaRequestorInit->gDownloader); + // Set the image processor instance used for handling image being downloaded + otaRequestorInit->gDownloader.SetImageProcessorDelegate(&imageProcessor); +} + +void chip::NXP::App::OTARequestorInitiator::HandleSelfTest() {} diff --git a/examples/platform/nxp/common/rpc/include/AppRpc.h b/examples/platform/nxp/common/rpc/include/AppRpc.h new file mode 100644 index 0000000000..9e56a8b80d --- /dev/null +++ b/examples/platform/nxp/common/rpc/include/AppRpc.h @@ -0,0 +1,56 @@ +/* + * 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 + +#if defined(PW_RPC_BUTTON_SERVICE) && PW_RPC_BUTTON_SERVICE +#include "pigweed/rpc_services/Button.h" +#endif + +namespace chip::NXP::App::Rpc { + +/** + * @brief Initialization of RPC-related board code. + * + * For example, enabling clock for UART interface + * and initializing board pins. + * + */ +CHIP_ERROR Init(); + +#if defined(PW_RPC_DEVICE_SERVICE) && PW_RPC_DEVICE_SERVICE +/** + * @brief Rebooting the device. + * + * RPC implementation will delegate reboot procedure to this function. + * + */ +void Reboot(); +#endif + +#if defined(PW_RPC_BUTTON_SERVICE) && PW_RPC_BUTTON_SERVICE +/** + * @brief Handles button events. + * + * RPC implementation will delegate handling events to this function. + */ +void ButtonHandler(const chip_rpc_ButtonEvent & request); +#endif + +} // namespace chip::NXP::App::Rpc diff --git a/examples/platform/nxp/common/ui_feedback/include/LedManager.h b/examples/platform/nxp/common/ui_feedback/include/LedManager.h new file mode 100644 index 0000000000..b14fae7aeb --- /dev/null +++ b/examples/platform/nxp/common/ui_feedback/include/LedManager.h @@ -0,0 +1,91 @@ +/* + * + * 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 "AppConfig.h" +#include "LedOnOff.h" +#include "LedWidgetInterface.h" +#include "UserInterfaceFeedback.h" + +#include +#include + +using namespace chip::NXP::App; + +/** + * @brief Specifies the array index of the status LED. + * + * The status LED is usually used to indicate additional information + * related to the connectivity status of the application. + */ +#ifndef LED_MANAGER_STATUS_LED_INDEX +#define LED_MANAGER_STATUS_LED_INDEX 0 +#endif + +/** + * @brief Specifies the array index of the light LED. + * + * The light LED is usually used to indicate the state of some cluster + * attribute: e.g OnOff attribute from OnOff cluster. + */ +#ifndef LED_MANAGER_LIGHT_LED_INDEX +#define LED_MANAGER_LIGHT_LED_INDEX 1 +#endif + +/** + * @brief Enable status LED. + * + */ +#ifndef LED_MANAGER_ENABLE_STATUS_LED +#define LED_MANAGER_ENABLE_STATUS_LED 0 +#endif + +/** + * @brief Manager of LedWidgetInterface concrete classes. + * + * It implements the UserInterfaceFeedback abstract interface. + */ +class LedManager : public UserInterfaceFeedback +{ +public: + void Init() override; + void DisplayInLoop() override; + void DisplayOnAction(Action action) override; + void RestoreState() override; + +private: + void ApplyTurnOn(); + void ApplyTurnOff(); + void AnimateOnAction(uint32_t onTimeMS, uint32_t offTimeMS); + +#if LED_MANAGER_ENABLE_STATUS_LED + void UpdateStatus(); + + LedOnOff statusLed; +#endif + LedOnOff lightLed; + + friend LedManager & LightingMgr(void); + static LedManager sLedManager; +}; + +inline LedManager & LightingMgr(void) +{ + return LedManager::sLedManager; +} diff --git a/examples/platform/nxp/common/ui_feedback/include/UserInterfaceFeedback.h b/examples/platform/nxp/common/ui_feedback/include/UserInterfaceFeedback.h new file mode 100644 index 0000000000..9e844a73d9 --- /dev/null +++ b/examples/platform/nxp/common/ui_feedback/include/UserInterfaceFeedback.h @@ -0,0 +1,72 @@ +/* + * 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 + +/** + * @brief Defines an abstract interface for providing feedback to the user. + * + * For example, the feedback can be provided through a logging mechanism or + * through LED animation. + */ +class UserInterfaceFeedback +{ +public: + /** + * @brief Set of possible actions handled by the DisplayOnAction method. + * + */ + enum class Action : uint8_t + { + kFactoryReset = 0, + kTriggerEffect, + kIdentify + }; + + virtual ~UserInterfaceFeedback() = default; + + virtual void Init() = 0; + + /** + * @brief Provide feedback in app task main loop. + * + * For a concrete example, this can be a LED animation command. + */ + virtual void DisplayInLoop() = 0; + + /** + * @brief Provide feedback on a specific action. + * + */ + virtual void DisplayOnAction(Action action) = 0; + + /** + * @brief Restore feedback state based on a default config. + * + * For example, the restoration can be based on a cluster attribute + * value, such as OnOff value in case of a LightingManager. + */ + virtual void RestoreState() = 0; +}; + +/** + * @brief Getter for the concrete class that implements the interface. + * + * It returns a reference to UserInterfaceFeedback, such that only the + * public API can be used regardless of the actual concrete class. + */ +extern UserInterfaceFeedback & FeedbackMgr(); diff --git a/examples/platform/nxp/common/ui_feedback/source/LedManager.cpp b/examples/platform/nxp/common/ui_feedback/source/LedManager.cpp new file mode 100644 index 0000000000..ac2456f327 --- /dev/null +++ b/examples/platform/nxp/common/ui_feedback/source/LedManager.cpp @@ -0,0 +1,150 @@ +/* + * + * Copyright (c) 2021, 2024 Project CHIP Authors + * Copyright (c) 2019 Google LLC. + * 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 "LedManager.h" + +#include "AppConfig.h" +#include "AppTask.h" + +#include +#include +#include +#include +#include + +LedManager LedManager::sLedManager; + +#if CONFIG_ENABLE_FEEDBACK +UserInterfaceFeedback & FeedbackMgr() +{ + return LightingMgr(); +} +#endif + +void LedManager::ApplyTurnOn() +{ + if (!lightLed.IsTurnedOff()) + return; + + lightLed.Set(true); +} + +void LedManager::ApplyTurnOff() +{ + if (lightLed.IsTurnedOff()) + return; + + lightLed.Set(false); +} + +void LedManager::Init() +{ + /* start with all LEDS turned off */ +#if LED_MANAGER_ENABLE_STATUS_LED + statusLed.Init(LED_MANAGER_STATUS_LED_INDEX, false); +#endif + /* The parameters will not be used by the dimmer init. */ + lightLed.Init(LED_MANAGER_LIGHT_LED_INDEX, false); + + RestoreState(); +} + +void LedManager::DisplayInLoop() +{ +#if LED_MANAGER_ENABLE_STATUS_LED + UpdateStatus(); + statusLed.Animate(); +#endif + lightLed.Animate(); +} + +void LedManager::DisplayOnAction(Action action) +{ + switch (action) + { + case UserInterfaceFeedback::Action::kFactoryReset: + case UserInterfaceFeedback::Action::kTriggerEffect: + AnimateOnAction(500, 500); + break; + case UserInterfaceFeedback::Action::kIdentify: + AnimateOnAction(250, 250); + break; + default: + break; + } +} + +void LedManager::RestoreState() +{ + /* restore initial state for the LED indicating Lighting state */ + lightLed.Set(false); + + chip::DeviceLayer::PlatformMgr().ScheduleWork([](intptr_t arg) { + bool val = false; + APP_CLUSTER_ATTRIBUTE::Get(APP_DEVICE_TYPE_ENDPOINT, &val); + if (val) + LightingMgr().ApplyTurnOn(); + else + LightingMgr().ApplyTurnOff(); + }); +} + +void LedManager::AnimateOnAction(uint32_t onTimeMS, uint32_t offTimeMS) +{ +#if LED_MANAGER_ENABLE_STATUS_LED + statusLed.Set(false); + statusLed.Animate(onTimeMS, offTimeMS); +#endif + + lightLed.Set(false); + lightLed.Animate(onTimeMS, offTimeMS); +} + +#if LED_MANAGER_ENABLE_STATUS_LED +void LedManager::UpdateStatus() +{ + bool isThreadProvisioned = false; + uint16_t bleConnections = 0; + + // Collect connectivity and configuration state from the CHIP stack. Because the + // CHIP event loop is being run in a separate task, the stack must be locked + // while these values are queried. However we use a non-blocking lock request + // (TryLockChipStack()) to avoid blocking other UI activities when the CHIP + // task is busy (e.g. with a long crypto operation). + if (chip::DeviceLayer::PlatformMgr().TryLockChipStack()) + { + isThreadProvisioned = chip::DeviceLayer::ConnectivityMgr().IsThreadProvisioned(); + bleConnections = chip::DeviceLayer::ConnectivityMgr().NumBLEConnections(); + chip::DeviceLayer::PlatformMgr().UnlockChipStack(); + } + + if (isThreadProvisioned) + { + statusLed.Animate(950, 50); + } + else if (bleConnections != 0) + { + statusLed.Animate(100, 100); + } + else + { + statusLed.Animate(50, 950); + } +} +#endif diff --git a/examples/platform/nxp/k32w/k32w1/BUILD.gn b/examples/platform/nxp/k32w/k32w1/BUILD.gn deleted file mode 100644 index 5cd2a8b313..0000000000 --- a/examples/platform/nxp/k32w/k32w1/BUILD.gn +++ /dev/null @@ -1,35 +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. - -import("//build_overrides/chip.gni") -import("//build_overrides/nxp_sdk.gni") - -import("${nxp_sdk_build_root}/nxp_sdk.gni") - -import("${nxp_sdk_build_root}/${nxp_sdk_name}/${nxp_sdk_name}.gni") - -config("chip_examples_project_config") { - include_dirs = [ - "app/project_include", - "${chip_root}", - ] -} - -source_set("openthread_core_config_k32w1_chip_examples") { - sources = [ "app/project_include/OpenThreadConfig.h" ] - - public_deps = [ "${chip_root}/third_party/openthread/platforms/nxp/k32w/k32w1:openthread_core_config_k32w1" ] - - public_configs = [ ":chip_examples_project_config" ] -} diff --git a/examples/platform/nxp/k32w/k32w1/app/BUILD.gn b/examples/platform/nxp/k32w/k32w1/app/BUILD.gn deleted file mode 100644 index 6671d14068..0000000000 --- a/examples/platform/nxp/k32w/k32w1/app/BUILD.gn +++ /dev/null @@ -1,27 +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. - -import("//build_overrides/chip.gni") - -config("chip_examples_project_config") { - include_dirs = [ "app/project_include" ] -} - -source_set("openthread_core_config_k32w1_chip_examples") { - sources = [ "app/project_include/OpenThreadConfig.h" ] - - public_deps = [ "${chip_root}/third_party/openthread/platforms/nxp/k32w/k32w1:openthread_core_config_k32w1" ] - - public_configs = [ ":chip_examples_project_config" ] -} diff --git a/examples/platform/nxp/k32w/k32w1/app/args.gni b/examples/platform/nxp/k32w/k32w1/app/args.gni deleted file mode 100644 index 2705c251fb..0000000000 --- a/examples/platform/nxp/k32w/k32w1/app/args.gni +++ /dev/null @@ -1,28 +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. - -import("//build_overrides/chip.gni") - -import("${chip_root}/src/platform/nxp/k32w/k32w1/args.gni") - -openthread_project_core_config_file = "OpenThreadConfig.h" - -chip_ble_project_config_include = "" -chip_device_project_config_include = "" -chip_project_config_include = "" -chip_inet_project_config_include = "" -chip_system_project_config_include = "" - -chip_system_config_provide_statistics = false -chip_with_nlfaultinjection = true diff --git a/examples/platform/nxp/k32w/k32w1/args.gni b/examples/platform/nxp/k32w/k32w1/args.gni deleted file mode 100644 index f7d9dccd82..0000000000 --- a/examples/platform/nxp/k32w/k32w1/args.gni +++ /dev/null @@ -1,38 +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. - -import("//build_overrides/chip.gni") - -import("${chip_root}/src/platform/nxp/k32w/k32w1/args.gni") - -arm_float_abi = "hard" -arm_cpu = "cortex-m33" -arm_fpu = "fpv5-sp-d16" -arm_arch = "armv8-m.main+dsp+fp" - -chip_openthread_ftd = false -openthread_core_config_deps = [] -openthread_core_config_deps = [ "${chip_root}/examples/platform/nxp/k32w/k32w1:openthread_core_config_k32w1_chip_examples" ] - -chip_ble_project_config_include = "" -chip_device_project_config_include = "" -chip_project_config_include = "" -chip_inet_project_config_include = "" -chip_system_project_config_include = "" - -chip_system_config_provide_statistics = false -chip_with_nlfaultinjection = true - -chip_system_config_use_open_thread_inet_endpoints = true -chip_with_lwip = false diff --git a/examples/platform/nxp/k32w/k32w1/app/ldscripts/k32w1_app.ld b/examples/platform/nxp/k32w1/app/ldscripts/k32w1_app.ld similarity index 100% rename from examples/platform/nxp/k32w/k32w1/app/ldscripts/k32w1_app.ld rename to examples/platform/nxp/k32w1/app/ldscripts/k32w1_app.ld diff --git a/examples/contact-sensor-app/nxp/k32w/k32w1/include/FreeRTOSConfig.h b/examples/platform/nxp/k32w1/app/project_include/freeRTOS/FreeRTOSConfig.h similarity index 97% rename from examples/contact-sensor-app/nxp/k32w/k32w1/include/FreeRTOSConfig.h rename to examples/platform/nxp/k32w1/app/project_include/freeRTOS/FreeRTOSConfig.h index a4e2047006..286566a027 100644 --- a/examples/contact-sensor-app/nxp/k32w/k32w1/include/FreeRTOSConfig.h +++ b/examples/platform/nxp/k32w1/app/project_include/freeRTOS/FreeRTOSConfig.h @@ -85,14 +85,9 @@ extern uint32_t SystemCoreClock; /* Tasks.c additions (e.g. Thread Aware Debug capability) */ #define configINCLUDE_FREERTOS_TASK_C_ADDITIONS_H 1 -/* Used memory allocation (heap_x.c) */ -#define configFRTOS_MEMORY_SCHEME 4 - /* Memory allocation related definitions. */ #define configSUPPORT_STATIC_ALLOCATION 0 #define configSUPPORT_DYNAMIC_ALLOCATION 1 -#define configTOTAL_HEAP_SIZE ((size_t) (gTotalHeapSize_c)) -#define configAPPLICATION_ALLOCATED_HEAP 1 /* Hook function related definitions. */ #ifndef configUSE_IDLE_HOOK diff --git a/examples/platform/nxp/k32w/k32w1/app/project_include/OpenThreadConfig.h b/examples/platform/nxp/k32w1/app/project_include/openthread/OpenThreadConfig.h similarity index 100% rename from examples/platform/nxp/k32w/k32w1/app/project_include/OpenThreadConfig.h rename to examples/platform/nxp/k32w1/app/project_include/openthread/OpenThreadConfig.h diff --git a/examples/platform/nxp/k32w/k32w1/app/support/BUILD.gn b/examples/platform/nxp/k32w1/app/support/BUILD.gn similarity index 78% rename from examples/platform/nxp/k32w/k32w1/app/support/BUILD.gn rename to examples/platform/nxp/k32w1/app/support/BUILD.gn index dc688edc2c..96d05e9ba2 100644 --- a/examples/platform/nxp/k32w/k32w1/app/support/BUILD.gn +++ b/examples/platform/nxp/k32w1/app/support/BUILD.gn @@ -15,8 +15,12 @@ import("//build_overrides/chip.gni") 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 = [ "../../../../.." ] + include_dirs = [ "${chip_root}" ] # Link options that provides replace dynamic memory operations in standard # library with the FreeRTOS malloc in platform code. @@ -29,7 +33,7 @@ config("support_config") { "-Wl,--wrap=MemoryAlloc", # Wrap these in case internal newlib call them (e.g. strdup will) - # directly call _malloc_r) + # directly call _malloc_r "-Wl,--wrap=_malloc_r", "-Wl,--wrap=_realloc_r", "-Wl,--wrap=_free_r", @@ -38,7 +42,7 @@ config("support_config") { ] } -source_set("freertos_mbedtls_utils") { +source_set("freertos_memory_utils") { sources = [ "FreeRtosHooks.c", "FreeRtosHooks.h", @@ -49,5 +53,11 @@ source_set("freertos_mbedtls_utils") { cflags = [ "-Wconversion" ] + if (chip_key_storage == "fwk_nvm") { + defines = [ "CHIP_PLAT_NVM_SUPPORT=1" ] + } else if (chip_key_storage == "littlefs") { + defines = [ "CHIP_PLAT_NVM_SUPPORT=3" ] + } + public_configs = [ ":support_config" ] } diff --git a/examples/platform/nxp/k32w/k32w1/app/support/FreeRtosHooks.c b/examples/platform/nxp/k32w1/app/support/FreeRtosHooks.c similarity index 96% rename from examples/platform/nxp/k32w/k32w1/app/support/FreeRtosHooks.c rename to examples/platform/nxp/k32w1/app/support/FreeRtosHooks.c index a7c78a7744..72d5f1acc6 100644 --- a/examples/platform/nxp/k32w/k32w1/app/support/FreeRtosHooks.c +++ b/examples/platform/nxp/k32w1/app/support/FreeRtosHooks.c @@ -27,7 +27,11 @@ #include #include +#if (CHIP_PLAT_NVM_SUPPORT == 1) #include "NVM_Interface.h" +#elif (CHIP_PLAT_NVM_SUPPORT == 3) +#include "fwk_file_cache.h" +#endif #include "PWR_Interface.h" #include "board.h" #include "fsl_os_abstraction.h" @@ -139,8 +143,10 @@ void vApplicationIdleHook(void) // to ensure there is no context switch during the actual // writing, thus avoiding race conditions. OSA_InterruptDisable(); -#if CHIP_PLAT_NVM_SUPPORT +#if (CHIP_PLAT_NVM_SUPPORT == 1) NvIdle(); +#elif (CHIP_PLAT_NVM_SUPPORT == 3) + FC_Process(); #endif OSA_InterruptEnable(); diff --git a/examples/platform/nxp/k32w/k32w1/app/support/FreeRtosHooks.h b/examples/platform/nxp/k32w1/app/support/FreeRtosHooks.h similarity index 100% rename from examples/platform/nxp/k32w/k32w1/app/support/FreeRtosHooks.h rename to examples/platform/nxp/k32w1/app/support/FreeRtosHooks.h diff --git a/examples/platform/nxp/k32w/k32w1/app/support/Memconfig.cpp b/examples/platform/nxp/k32w1/app/support/Memconfig.cpp similarity index 100% rename from examples/platform/nxp/k32w/k32w1/app/support/Memconfig.cpp rename to examples/platform/nxp/k32w1/app/support/Memconfig.cpp diff --git a/examples/platform/nxp/k32w1/board/peripherals.c b/examples/platform/nxp/k32w1/board/peripherals.c new file mode 100644 index 0000000000..f66203bfe2 --- /dev/null +++ b/examples/platform/nxp/k32w1/board/peripherals.c @@ -0,0 +1,66 @@ +/* + * + * Copyright (c) 2024 Project CHIP Authors + * Copyright (c) 2024 NXP + * 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. + */ + +/*********************************************************************************************************************** + * Included files + **********************************************************************************************************************/ +#include "peripherals.h" + +/*********************************************************************************************************************** + * BOARD_InitPeripherals functional group + **********************************************************************************************************************/ + +/* LittleFS context */ +extern struct lfs_mflash_ctx LittleFS_ctx; +const struct lfs_config LittleFS_config = { .context = (void *) &LittleFS_ctx, + .read = lfs_mflash_read, + .prog = lfs_mflash_prog, + .erase = lfs_mflash_erase, + .sync = lfs_mflash_sync, +#ifdef LFS_THREADSAFE + .lock = lfs_mutex_lock, + .unlock = lfs_mutex_unlock, +#endif + .read_size = LITTLEFS_READ_SIZE, + .prog_size = LITTLEFS_PROG_SIZE, + .block_size = LITTLEFS_BLOCK_SIZE, + .block_count = LITTLEFS_BLOCK_COUNT, + .block_cycles = LITTLEFS_BLOCK_CYCLES, + .cache_size = LITTLEFS_CACHE_SIZE, + .lookahead_size = LITTLEFS_LOOKAHEAD_SIZE }; + +/* Empty initialization function (commented out) +static void LittleFS_init(void) { +} */ + +/*********************************************************************************************************************** + * Initialization functions + **********************************************************************************************************************/ +void BOARD_InitPeripherals(void) +{ + /* Initialize components */ +} + +/*********************************************************************************************************************** + * BOARD_InitBootPeripherals function + **********************************************************************************************************************/ +void BOARD_InitBootPeripherals(void) +{ + BOARD_InitPeripherals(); +} diff --git a/examples/platform/nxp/k32w1/board/peripherals.h b/examples/platform/nxp/k32w1/board/peripherals.h new file mode 100644 index 0000000000..38caf2657c --- /dev/null +++ b/examples/platform/nxp/k32w1/board/peripherals.h @@ -0,0 +1,101 @@ +/* + * + * Copyright (c) 2024 Project CHIP Authors + * Copyright (c) 2024 NXP + * 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. + */ + +#ifndef _PERIPHERALS_H_ +#define _PERIPHERALS_H_ + +/*********************************************************************************************************************** + * Included files + **********************************************************************************************************************/ +#include "fsl_common.h" + +#include "lfs.h" + +#if defined(__cplusplus) +extern "C" { +#endif /* __cplusplus */ + +/*********************************************************************************************************************** + * User definitions + **********************************************************************************************************************/ +extern uint32_t NV_STORAGE_START_ADDRESS[]; +extern uint32_t NV_STORAGE_MAX_SECTORS[]; + +#define LITTLEFS_START_ADDR (uint32_t)(NV_STORAGE_START_ADDRESS) + +/*********************************************************************************************************************** + * Definitions + **********************************************************************************************************************/ +/* Definitions for BOARD_InitPeripherals functional group */ +/* Maximum block read size definition */ +#define LITTLEFS_READ_SIZE 16 +/* Maximum block program size definition */ +#define LITTLEFS_PROG_SIZE 128 +/* Erasable block size definition */ +#define LITTLEFS_BLOCK_SIZE 8192 +/* Block count definition */ +#define LITTLEFS_BLOCK_COUNT (uint32_t)(NV_STORAGE_MAX_SECTORS) +/* Block cycles definition */ +#define LITTLEFS_BLOCK_CYCLES 100 +/* Minimum block cache size definition */ +#define LITTLEFS_CACHE_SIZE 1024 +/* Minimum lookahead buffer size definition */ +#define LITTLEFS_LOOKAHEAD_SIZE 16 +/* Block starting address definition */ +#define LITTLEFS_START_ADDR (uint32_t)(NV_STORAGE_START_ADDRESS) + +/*********************************************************************************************************************** + * Global variables + **********************************************************************************************************************/ +/* LittleFS configuration */ +extern const struct lfs_config LittleFS_config; + +/*********************************************************************************************************************** + * Callback functions + **********************************************************************************************************************/ +/* LittleFS read a block region callback*/ +extern int lfs_mflash_read(const struct lfs_config *, lfs_block_t, lfs_off_t, void *, lfs_size_t); +/* LittleFS program a block region callback*/ +extern int lfs_mflash_prog(const struct lfs_config *, lfs_block_t, lfs_off_t, const void *, lfs_size_t); +/* LittleFS erase a block callback*/ +extern int lfs_mflash_erase(const struct lfs_config *, lfs_block_t); +/* LittleFS state sync callback*/ +extern int lfs_mflash_sync(const struct lfs_config *); +/* LittleFS state lock callback*/ +extern int lfs_mutex_lock(const struct lfs_config *); +/* LittleFS state unlock callback*/ +extern int lfs_mutex_unlock(const struct lfs_config *); + +/*********************************************************************************************************************** + * Initialization functions + **********************************************************************************************************************/ + +void BOARD_InitPeripherals(void); + +/*********************************************************************************************************************** + * BOARD_InitBootPeripherals function + **********************************************************************************************************************/ + +void BOARD_InitBootPeripherals(void); + +#if defined(__cplusplus) +} +#endif + +#endif /* _PERIPHERALS_H_ */ diff --git a/examples/platform/nxp/k32w1/button/ButtonManager.cpp b/examples/platform/nxp/k32w1/button/ButtonManager.cpp new file mode 100644 index 0000000000..47e5f9fd4b --- /dev/null +++ b/examples/platform/nxp/k32w1/button/ButtonManager.cpp @@ -0,0 +1,215 @@ +/* + * + * 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 "ButtonManager.h" +#include "AppConfig.h" +#include "AppMatterButton.h" +#include "AppTask.h" +#include "UserInterfaceFeedback.h" + +#include + +extern "C" { +#include "app.h" +#include "board_comp.h" +} + +CHIP_ERROR chip::NXP::App::AppMatterButton_registerButtons(void) +{ + /* Board buttons are initialized in otSysInit, when APP_InitServices is called. */ + button_status_t bStatus; + + bStatus = BUTTON_InstallCallback((button_handle_t) g_buttonHandle[0], ButtonManager::BleCallback, NULL); + VerifyOrReturnError(bStatus == kStatus_BUTTON_Success, CHIP_ERROR_UNEXPECTED_EVENT, + ChipLogError(DeviceLayer, "button init error")); + + bStatus = BUTTON_InstallCallback((button_handle_t) g_buttonHandle[1], ButtonManager::AppActionCallback, NULL); + VerifyOrReturnError(bStatus == kStatus_BUTTON_Success, CHIP_ERROR_UNEXPECTED_EVENT, + ChipLogError(DeviceLayer, "button init error")); + + ReturnErrorOnFailure(ButtonMgr().Init()); + + return CHIP_NO_ERROR; +} + +ButtonManager ButtonManager::sInstance; + +TimerHandle_t resetTimer; + +CHIP_ERROR ButtonManager::Init() +{ + resetTimer = xTimerCreate("FnTmr", 1, false, (void *) this, [](TimerHandle_t xTimer) { + AppEvent event; + event.Handler = FunctionTimerEventHandler; + chip::NXP::App::GetAppTask().PostEvent(event); + }); + VerifyOrReturnError(resetTimer != NULL, APP_ERROR_CREATE_TIMER_FAILED); + + return CHIP_NO_ERROR; +} + +button_status_t ButtonManager::BleCallback(void * handle, button_callback_message_t * message, void * param) +{ + AppEvent event; + + switch (message->event) + { + case kBUTTON_EventOneClick: + case kBUTTON_EventShortPress: + event.Handler = ButtonManager::BleHandler; + break; + case kBUTTON_EventLongPress: + event.Handler = ButtonManager::ResetActionEventHandler; + break; + default: + /* No action required */ + break; + } + + chip::NXP::App::GetAppTask().PostEvent(event); + + return kStatus_BUTTON_Success; +} + +button_status_t ButtonManager::AppActionCallback(void * handle, button_callback_message_t * message, void * param) +{ + AppEvent event; + + switch (message->event) + { + case kBUTTON_EventOneClick: + case kBUTTON_EventShortPress: + event.Handler = ButtonManager::AppActionEventHandler; + break; + case kBUTTON_EventLongPress: + // Soft reset ensures that platform manager shutdown procedure is called. + event.Handler = ButtonManager::SoftResetHandler; + break; + default: + /* No action required */ + break; + } + + chip::NXP::App::GetAppTask().PostEvent(event); + + return kStatus_BUTTON_Success; +} + +void ButtonManager::FunctionTimerEventHandler(const AppEvent & event) +{ + ChipLogProgress(DeviceLayer, "Device will factory reset..."); + + // Actually trigger Factory Reset + chip::Server::GetInstance().ScheduleFactoryReset(); +} + +void ButtonManager::ResetActionEventHandler(const AppEvent & event) +{ + if (xTimerIsTimerActive(resetTimer)) + { + ButtonMgr().CancelTimer(); +#if CONFIG_ENABLE_FEEDBACK + FeedbackMgr().RestoreState(); +#endif + ChipLogProgress(DeviceLayer, "Factory Reset was cancelled!"); + } + else + { + uint32_t resetTimeout = BUTTON_MANAGER_FACTORY_RESET_TIMEOUT_MS; + ChipLogProgress(DeviceLayer, "Factory Reset Triggered. Push the RESET button within %lu ms to cancel!", resetTimeout); + +#if CONFIG_ENABLE_FEEDBACK + FeedbackMgr().DisplayOnAction(UserInterfaceFeedback::Action::kFactoryReset); +#endif + ButtonMgr().StartTimer(resetTimeout); + } +} + +void ButtonManager::AppActionEventHandler(const AppEvent & event) +{ + chip::DeviceLayer::PlatformMgr().ScheduleWork( + [](intptr_t arg) { + bool val = false; + APP_CLUSTER_ATTRIBUTE::Get(APP_DEVICE_TYPE_ENDPOINT, &val); + auto status = APP_CLUSTER_ATTRIBUTE::Set(APP_DEVICE_TYPE_ENDPOINT, (bool) !val); + if (status != chip::Protocols::InteractionModel::Status::Success) + { + ChipLogProgress(DeviceLayer, "Error when updating cluster attribute"); + } + }, + (intptr_t) nullptr); +} + +void ButtonManager::SoftResetHandler(const AppEvent & event) +{ + chip::DeviceLayer::PlatformMgrImpl().CleanReset(); +} + +#if CHIP_CONFIG_ENABLE_ICD_LIT +static void UserActiveModeHandler(const AppEvent & event) +{ + chip::DeviceLayer::PlatformMgr().ScheduleWork( + [](intptr_t arg) { chip::app::ICDNotifier::GetInstance().NotifyNetworkActivityNotification(); }, 0); +} +#endif + +void ButtonManager::BleHandler(const AppEvent & event) +{ + if (xTimerIsTimerActive(resetTimer)) + { + // If a factory reset is scheduled, pressing the BLE button will cancel it. + ResetActionEventHandler(event); + return; + } + +#if CHIP_CONFIG_ENABLE_ICD_LIT + if (chip::DeviceLayer::ConfigurationMgr().IsFullyProvisioned()) + { + // If the device is commissioned and a factory reset is not scheduled, switch to active mode. + UserActiveModeHandler(event); + return; + } +#endif + + chip::NXP::App::GetAppTask().SwitchCommissioningStateHandler(); +} + +void ButtonManager::CancelTimer() +{ + if (xTimerStop(resetTimer, 0) == pdFAIL) + { + ChipLogProgress(DeviceLayer, "app timer stop() failed"); + } +} + +void ButtonManager::StartTimer(uint32_t aTimeoutInMs) +{ + if (xTimerIsTimerActive(resetTimer)) + { + ChipLogProgress(DeviceLayer, "app timer already started!"); + CancelTimer(); + } + + // timer is not active, change its period to required value (== restart). + // FreeRTOS- Block for a maximum of 100 ticks if the change period command + // cannot immediately be sent to the timer command queue. + if (xTimerChangePeriod(resetTimer, aTimeoutInMs / portTICK_PERIOD_MS, 100) != pdPASS) + { + ChipLogProgress(DeviceLayer, "app timer start() failed"); + } +} diff --git a/examples/platform/nxp/k32w1/button/ButtonManager.h b/examples/platform/nxp/k32w1/button/ButtonManager.h new file mode 100644 index 0000000000..aec2411e10 --- /dev/null +++ b/examples/platform/nxp/k32w1/button/ButtonManager.h @@ -0,0 +1,108 @@ +/* + * + * 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 "AppEvent.h" + +#include "FreeRTOS.h" +#include "timers.h" + +#include "fsl_component_button.h" + +#include + +// Application-defined error codes in the CHIP_ERROR space. +#define APP_ERROR_CREATE_TIMER_FAILED CHIP_APPLICATION_ERROR(0x01) + +/** + * @brief Timeout (ms) for factory data reset action. + * + * During this timeout, the factory reset action can be cancelled by pressing a button. + */ +#ifndef BUTTON_MANAGER_FACTORY_RESET_TIMEOUT_MS +#define BUTTON_MANAGER_FACTORY_RESET_TIMEOUT_MS 6000 +#endif + +/** + * @brief This class describes a manager for button callbacks. + * + */ +class ButtonManager +{ +public: + CHIP_ERROR Init(); + + // These are the callbacks registered with the buttons. They will delegate actions + // to other methods based on the button event: short press, long press etc. + static button_status_t BleCallback(void * handle, button_callback_message_t * message, void * param); + static button_status_t AppActionCallback(void * handle, button_callback_message_t * message, void * param); + +private: + /** + * @brief This callback performs a soft reset. + * + * This can be used when the user wants to clean reset the device, + * meaning that Matter is properly shutdown, unlike a RESET button + * press, where the device resets without calling the shutdown procedure. + */ + static void SoftResetHandler(const AppEvent & event); + + /** + * @brief This callback toggles between BLE start/stop advertising. + * + * It is used during commissioning to ensure a user-intent commissioning flow. + */ + static void BleHandler(const AppEvent & event); + + /** + * @brief This callback updates the application state. + * + * An example of application state would be the lighting manager light LED state. + * This handler will toggle the light LED state. + */ + static void AppActionEventHandler(const AppEvent & event); + + /** + * @brief This callback schedules a factory reset. + * + * The factory reset is scheduled based on the value of BUTTON_MANAGER_FACTORY_RESET_TIMEOUT_MS. + * Until the timer expires, the user can cancel the factory reset operation by doing an action. + * In this reference app, the action would be pressing again the factory reset button. + */ + static void ResetActionEventHandler(const AppEvent & event); + + /** + * @brief This callback performs a factory reset. + * + * This is the callback registered with the timer scheduled in ResetActionEventHandler. + * It will schedule a factory reset using the Matter server instance. + */ + static void FunctionTimerEventHandler(const AppEvent & event); + + void CancelTimer(); + void StartTimer(uint32_t aTimeoutInMs); + + friend ButtonManager & ButtonMgr(); + static ButtonManager sInstance; +}; + +inline ButtonManager & ButtonMgr() +{ + return ButtonManager::sInstance; +} diff --git a/examples/platform/nxp/k32w1/clusters/Identify.cpp b/examples/platform/nxp/k32w1/clusters/Identify.cpp new file mode 100644 index 0000000000..2d309f975e --- /dev/null +++ b/examples/platform/nxp/k32w1/clusters/Identify.cpp @@ -0,0 +1,123 @@ +/* + * 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 "Identify.h" +#include "AppTask.h" +#include "UserInterfaceFeedback.h" + +#include + +using namespace chip; +using namespace chip::app; + +static Identify gIdentify = { EndpointId{ 1 }, NXP::App::OnIdentifyStart, NXP::App::OnIdentifyStop, + Clusters::Identify::IdentifyTypeEnum::kVisibleIndicator, NXP::App::OnTriggerEffect, + // Use invalid value for identifiers to enable TriggerEffect command + // to stop Identify command for each effect + Clusters::Identify::EffectIdentifierEnum::kUnknownEnumValue, + Clusters::Identify::EffectVariantEnum::kDefault }; + +namespace chip::NXP::App { + +void OnIdentifyStart(Identify * identify) +{ + chip::DeviceLayer::SystemLayer().CancelTimer(OnTriggerEffectComplete, identify); + OnTriggerEffectComplete(&chip::DeviceLayer::SystemLayer(), identify); + + ChipLogProgress(Zcl, "Identify process has started. Status LED should blink with a period of 0.5 seconds."); + +#if CONFIG_ENABLE_FEEDBACK + FeedbackMgr().DisplayOnAction(UserInterfaceFeedback::Action::kIdentify); +#endif +} + +void OnIdentifyStop(Identify * identify) +{ + ChipLogProgress(Zcl, "Identify process has stopped."); + +#if CONFIG_ENABLE_FEEDBACK + FeedbackMgr().RestoreState(); +#endif +} + +void OnTriggerEffectComplete(chip::System::Layer * systemLayer, void * appState) +{ + // Let Identify command take over if called during TriggerEffect already running + ChipLogProgress(Zcl, "TriggerEffect has stopped."); + + // TriggerEffect finished - reset identifiers + // Use invalid value for identifiers to enable TriggerEffect command + // to stop Identify command for each effect + gIdentify.mCurrentEffectIdentifier = Clusters::Identify::EffectIdentifierEnum::kUnknownEnumValue; + gIdentify.mTargetEffectIdentifier = Clusters::Identify::EffectIdentifierEnum::kUnknownEnumValue; + gIdentify.mEffectVariant = Clusters::Identify::EffectVariantEnum::kDefault; + +#if CONFIG_ENABLE_FEEDBACK + FeedbackMgr().RestoreState(); +#endif +} + +void OnTriggerEffect(Identify * identify) +{ + uint16_t timerDelay = 0; + + ChipLogProgress(Zcl, "TriggerEffect has started."); + + switch (identify->mCurrentEffectIdentifier) + { + case Clusters::Identify::EffectIdentifierEnum::kBlink: + timerDelay = 2; + break; + + case Clusters::Identify::EffectIdentifierEnum::kBreathe: + timerDelay = 15; + break; + + case Clusters::Identify::EffectIdentifierEnum::kOkay: + timerDelay = 4; + break; + + case Clusters::Identify::EffectIdentifierEnum::kChannelChange: + ChipLogProgress(Zcl, "Channel Change effect not supported, using effect %d", + to_underlying(Clusters::Identify::EffectIdentifierEnum::kBlink)); + timerDelay = 2; + break; + + case Clusters::Identify::EffectIdentifierEnum::kFinishEffect: + chip::DeviceLayer::SystemLayer().CancelTimer(OnTriggerEffectComplete, identify); + timerDelay = 1; + break; + + case Clusters::Identify::EffectIdentifierEnum::kStopEffect: + chip::DeviceLayer::SystemLayer().CancelTimer(OnTriggerEffectComplete, identify); + OnTriggerEffectComplete(&chip::DeviceLayer::SystemLayer(), identify); + break; + + default: + ChipLogProgress(Zcl, "Invalid effect identifier."); + } + + if (timerDelay) + { +#if CONFIG_ENABLE_FEEDBACK + FeedbackMgr().DisplayOnAction(UserInterfaceFeedback::Action::kTriggerEffect); +#endif + chip::DeviceLayer::SystemLayer().StartTimer(chip::System::Clock::Seconds16(timerDelay), OnTriggerEffectComplete, identify); + } +} + +} // namespace chip::NXP::App diff --git a/examples/platform/nxp/k32w/k32w1/doc/images/debug_k32w1.jpg b/examples/platform/nxp/k32w1/doc/images/debug_k32w1.jpg similarity index 100% rename from examples/platform/nxp/k32w/k32w1/doc/images/debug_k32w1.jpg rename to examples/platform/nxp/k32w1/doc/images/debug_k32w1.jpg diff --git a/examples/platform/nxp/k32w/k32w1/doc/images/import_demo.jpg b/examples/platform/nxp/k32w1/doc/images/import_demo.jpg similarity index 100% rename from examples/platform/nxp/k32w/k32w1/doc/images/import_demo.jpg rename to examples/platform/nxp/k32w1/doc/images/import_demo.jpg diff --git a/examples/platform/nxp/k32w/k32w1/doc/images/installed_sdks.jpg b/examples/platform/nxp/k32w1/doc/images/installed_sdks.jpg similarity index 100% rename from examples/platform/nxp/k32w/k32w1/doc/images/installed_sdks.jpg rename to examples/platform/nxp/k32w1/doc/images/installed_sdks.jpg diff --git a/examples/platform/nxp/k32w/k32w1/doc/images/k32w1-evk.jpg b/examples/platform/nxp/k32w1/doc/images/k32w1-evk.jpg similarity index 100% rename from examples/platform/nxp/k32w/k32w1/doc/images/k32w1-evk.jpg rename to examples/platform/nxp/k32w1/doc/images/k32w1-evk.jpg diff --git a/examples/platform/nxp/k32w/k32w1/doc/images/mcux-sdk-download.jpg b/examples/platform/nxp/k32w1/doc/images/mcux-sdk-download.jpg similarity index 100% rename from examples/platform/nxp/k32w/k32w1/doc/images/mcux-sdk-download.jpg rename to examples/platform/nxp/k32w1/doc/images/mcux-sdk-download.jpg diff --git a/examples/platform/nxp/k32w/k32w1/doc/images/new_project.jpg b/examples/platform/nxp/k32w1/doc/images/new_project.jpg similarity index 100% rename from examples/platform/nxp/k32w/k32w1/doc/images/new_project.jpg rename to examples/platform/nxp/k32w1/doc/images/new_project.jpg diff --git a/examples/platform/nxp/k32w/k32w1/doc/images/ota_topology.JPG b/examples/platform/nxp/k32w1/doc/images/ota_topology.JPG similarity index 100% rename from examples/platform/nxp/k32w/k32w1/doc/images/ota_topology.JPG rename to examples/platform/nxp/k32w1/doc/images/ota_topology.JPG diff --git a/examples/platform/nxp/k32w1/factory_data/source/AppFactoryDataExample.cpp b/examples/platform/nxp/k32w1/factory_data/source/AppFactoryDataExample.cpp new file mode 100644 index 0000000000..dbccc2fd7d --- /dev/null +++ b/examples/platform/nxp/k32w1/factory_data/source/AppFactoryDataExample.cpp @@ -0,0 +1,76 @@ +/* + * + * Copyright (c) 2023 Project CHIP Authors + * Copyright 2023-2024 NXP + * 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 "AppFactoryData.h" + +#include +#include +#include + +#if CONFIG_CHIP_PLAT_LOAD_REAL_FACTORY_DATA +#include "FactoryDataDriver.h" +#include "FactoryDataProvider.h" +#else +#include +#endif + +using namespace chip; +using namespace ::chip::Credentials; +using namespace ::chip::DeviceLayer; + +#if CONFIG_CHIP_LOAD_REAL_FACTORY_DATA && CONFIG_CHIP_OTA_FACTORY_DATA_PROCESSOR +/** + * Custom factory data restore mechanism. This function must be implemented by vendors. + */ +CHIP_ERROR CustomFactoryDataRestoreMechanism(void) +{ + ChipLogProgress(DeviceLayer, "This is a custom factory data restore mechanism."); + + return CHIP_NO_ERROR; +} +#endif + +/** + * Allows to register Matter factory data before initializing the Matter stack + */ +CHIP_ERROR NXP::App::AppFactoryData_PreMatterStackInit(void) +{ + return CHIP_NO_ERROR; +} + +/** + * Allows to register Matter factory data after initializing the Matter stack + */ +CHIP_ERROR NXP::App::AppFactoryData_PostMatterStackInit(void) +{ +#if CONFIG_CHIP_LOAD_REAL_FACTORY_DATA + ReturnErrorOnFailure(FactoryDataDrv().Init()); +#if CONFIG_CHIP_OTA_FACTORY_DATA_PROCESSOR + FactoryDataPrvd().RegisterRestoreMechanism(CustomFactoryDataRestoreMechanism); +#endif + ReturnErrorOnFailure(FactoryDataPrvd().Init()); + SetDeviceInstanceInfoProvider(&FactoryDataPrvd()); + SetDeviceAttestationCredentialsProvider(&FactoryDataPrvd()); + SetCommissionableDataProvider(&FactoryDataPrvd()); +#else + // Initialize device attestation with example one (only for debug purpose) + SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); +#endif + return CHIP_NO_ERROR; +} diff --git a/examples/platform/nxp/k32w1/operational_keystore/OperationalKeystore.cpp b/examples/platform/nxp/k32w1/operational_keystore/OperationalKeystore.cpp new file mode 100644 index 0000000000..ecd7226617 --- /dev/null +++ b/examples/platform/nxp/k32w1/operational_keystore/OperationalKeystore.cpp @@ -0,0 +1,34 @@ +/* + * 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 "OperationalKeystore.h" +#include "K32W1PersistentStorageOpKeystore.h" + +static chip::K32W1PersistentStorageOpKeystore sInstance; + +chip::Crypto::OperationalKeystore * chip::NXP::App::OperationalKeystore::GetInstance() +{ + return &sInstance; +} + +CHIP_ERROR chip::NXP::App::OperationalKeystore::Init(PersistentStorageDelegate * delegate) +{ + VerifyOrReturnError(delegate != nullptr, CHIP_ERROR_INTERNAL); + sInstance.Init(delegate); + + return CHIP_NO_ERROR; +} diff --git a/examples/platform/nxp/k32w/k32w1/util/include/LED_Dimmer.h b/examples/platform/nxp/k32w1/ota/OtaUtils.cpp similarity index 81% rename from examples/platform/nxp/k32w/k32w1/util/include/LED_Dimmer.h rename to examples/platform/nxp/k32w1/ota/OtaUtils.cpp index 424ffa20c9..4088196ba3 100644 --- a/examples/platform/nxp/k32w/k32w1/util/include/LED_Dimmer.h +++ b/examples/platform/nxp/k32w1/ota/OtaUtils.cpp @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2020 Google LLC. + * Copyright (c) 2024 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -16,6 +16,9 @@ * limitations under the License. */ -void init_dimmable(); -void init_tpm(); -void move_to_level(uint8_t level); +#include "OtaSupport.h" + +extern "C" void OTAIdleActivities(void) +{ + OTA_TransactionResume(); +} diff --git a/examples/platform/nxp/k32w1/rpc/AppRpc.cpp b/examples/platform/nxp/k32w1/rpc/AppRpc.cpp new file mode 100644 index 0000000000..beea840843 --- /dev/null +++ b/examples/platform/nxp/k32w1/rpc/AppRpc.cpp @@ -0,0 +1,75 @@ +/* + * 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 "AppRpc.h" +#include "ButtonManager.h" +#include "clock_config.h" +#include "pin_mux.h" + +#include "Rpc.h" + +CHIP_ERROR chip::NXP::App::Rpc::Init() +{ + /* set clock */ + CLOCK_SetIpSrc(kCLOCK_Lpuart1, kCLOCK_IpSrcFro192M); + /* enable clock */ + CLOCK_EnableClock(kCLOCK_Lpuart1); + + BOARD_InitPinLPUART1_TX(); + BOARD_InitPinLPUART1_RX(); + chip::rpc::Init(); + + return CHIP_NO_ERROR; +} + +#if defined(PW_RPC_DEVICE_SERVICE) && PW_RPC_DEVICE_SERVICE +void chip::NXP::App::Rpc::Reboot() +{ + NVIC_SystemReset(); +} +#endif + +#if defined(PW_RPC_BUTTON_SERVICE) && PW_RPC_BUTTON_SERVICE +void chip::NXP::App::Rpc::ButtonHandler(const chip_rpc_ButtonEvent & request) +{ + button_callback_message_t * message = new button_callback_message_t; + + switch (request.idx) + { + case 0: + message->event = kBUTTON_EventShortPress; + ButtonMgr().BleCallback(nullptr, message, nullptr); + break; + case 1: + message->event = kBUTTON_EventLongPress; + ButtonMgr().BleCallback(nullptr, message, nullptr); + break; + case 2: + message->event = kBUTTON_EventShortPress; + ButtonMgr().AppActionCallback(nullptr, message, nullptr); + break; + case 3: + message->event = kBUTTON_EventLongPress; + ButtonMgr().AppActionCallback(nullptr, message, nullptr); + break; + default: + break; + } + + delete message; +} +#endif diff --git a/examples/platform/nxp/k32w/k32w1/util/LED_Dimmer.cpp b/examples/platform/nxp/k32w1/util/LedDimmer.cpp similarity index 97% rename from examples/platform/nxp/k32w/k32w1/util/LED_Dimmer.cpp rename to examples/platform/nxp/k32w1/util/LedDimmer.cpp index 02a6272471..c682abb5c1 100644 --- a/examples/platform/nxp/k32w/k32w1/util/LED_Dimmer.cpp +++ b/examples/platform/nxp/k32w1/util/LedDimmer.cpp @@ -17,7 +17,7 @@ * limitations under the License. */ -#include "LED_Dimmer.h" +#include "LedDimmer.h" #include "fsl_common.h" #include "fsl_port.h" #include "fsl_tpm.h" @@ -36,9 +36,11 @@ #define DEMO_PWM_FREQUENCY (24000U) #endif +namespace chip::NXP::App { + volatile uint8_t updatedDutycycle = 0U; -void init_dimmable() +static void initConfig() { const port_pin_config_t porta20_pin17_config = { /* Internal pull-up/down resistor is disabled */ (uint16_t) kPORT_PullDisable, @@ -105,15 +107,15 @@ void init_dimmable() }; /* PORTA19 (pin 14) is configured as TPM0_CH0 */ PORT_SetPinConfig(PORTA, 19U, &porta19_pin14_config); - - init_tpm(); } -void init_tpm() +void LedDimmer::Init(uint8_t index, bool inverted) { tpm_config_t tpmInfo; tpm_chnl_pwm_signal_param_t tpmParam[3]; + initConfig(); + /* TPM 0 Clock Gate Control: Clock enabled */ CLOCK_EnableClock(kCLOCK_Tpm0); /* Set the source for the LPIT module */ @@ -157,10 +159,12 @@ void init_tpm() TPM_StartTimer(BOARD_TPM_BASEADDR, kTPM_SystemClock); } -void move_to_level(uint8_t level) +void LedDimmer::Set(uint8_t level) { uint8_t control; + mState = level != 0; + updatedDutycycle = static_cast(level * 90) / 255; control = TPM_GetChannelContorlBits(BOARD_TPM_BASEADDR, (tpm_chnl_t) BOARD_FIRST_TPM_CHANNEL); @@ -191,3 +195,5 @@ void move_to_level(uint8_t level) TPM_EnableChannel(BOARD_TPM_BASEADDR, (tpm_chnl_t) BOARD_SECOND_TPM_CHANNEL, control); TPM_EnableChannel(BOARD_TPM_BASEADDR, (tpm_chnl_t) BOARD_THIRD_TPM_CHANNEL, control); } + +} // namespace chip::NXP::App diff --git a/examples/platform/nxp/k32w/k32w1/util/LEDWidget.cpp b/examples/platform/nxp/k32w1/util/LedOnOff.cpp similarity index 53% rename from examples/platform/nxp/k32w/k32w1/util/LEDWidget.cpp rename to examples/platform/nxp/k32w1/util/LedOnOff.cpp index 695da50e3d..92b1f41ebf 100644 --- a/examples/platform/nxp/k32w/k32w1/util/LEDWidget.cpp +++ b/examples/platform/nxp/k32w1/util/LedOnOff.cpp @@ -17,93 +17,69 @@ * limitations under the License. */ -#include "LEDWidget.h" +#include "LedOnOff.h" +#include "app.h" #include -#include "app.h" - -#if CHIP_CONFIG_ENABLE_DIMMABLE_LED -#include "LED_Dimmer.h" -#endif +namespace chip::NXP::App { #if (defined(gAppLedCnt_c) && (gAppLedCnt_c > 0)) -void LEDWidget::Init(uint8_t led, bool inverted) +void LedOnOff::Init(uint8_t index, bool inverted) { mLastChangeTimeMS = 0; - mBlinkOnTimeMS = 0; - mBlinkOffTimeMS = 0; - mGPIONum = led; + mOnTimeMS = 0; + mOffTimeMS = 0; + mIndex = index; mState = false; mOnLogic = !inverted; Set(false); } -void LEDWidget::Invert(void) -{ - Set(!mState); -} - -void LEDWidget::Set(bool state) -{ - mLastChangeTimeMS = mBlinkOnTimeMS = mBlinkOffTimeMS = 0; - DoSet(state); -} - -void LEDWidget::SetLevel(uint8_t level) +void LedOnOff::Set(uint8_t level) { -#if CHIP_CONFIG_ENABLE_DIMMABLE_LED - move_to_level(level); -#endif + mLastChangeTimeMS = mOnTimeMS = mOffTimeMS = 0; + DoSet(level != 0); } -void LEDWidget::Blink(uint32_t changeRateMS) +void LedOnOff::Animate(uint32_t onTimeMS, uint32_t offTimeMS) { - Blink(changeRateMS, changeRateMS); -} - -void LEDWidget::Blink(uint32_t onTimeMS, uint32_t offTimeMS) -{ - mBlinkOnTimeMS = onTimeMS; - mBlinkOffTimeMS = offTimeMS; - Animate(); -} + if (onTimeMS && offTimeMS) + { + mOnTimeMS = onTimeMS; + mOffTimeMS = offTimeMS; + } -void LEDWidget::Animate() -{ - if (mBlinkOnTimeMS != 0 && mBlinkOffTimeMS != 0) + if (mOnTimeMS && mOffTimeMS) { uint64_t nowMS = chip::System::SystemClock().GetMonotonicMilliseconds64().count(); - uint64_t stateDurMS = mState ? mBlinkOnTimeMS : mBlinkOffTimeMS; + uint64_t stateDurMS = mState ? mOnTimeMS : mOffTimeMS; uint64_t nextChangeTimeMS = mLastChangeTimeMS + stateDurMS; if (nextChangeTimeMS < nowMS) { -#if CHIP_CONFIG_ENABLE_DIMMABLE_LED - SetLevel(!mState * 254); - mState = !mState; -#else DoSet(!mState); -#endif mLastChangeTimeMS = nowMS; } } } -void LEDWidget::DoSet(bool state) +void LedOnOff::DoSet(bool state) { mState = state; if (state) { - (void) LED_TurnOnOff((led_handle_t) g_ledHandle[mGPIONum], mOnLogic); + (void) LED_TurnOnOff((led_handle_t) g_ledHandle[mIndex], mOnLogic); } else { - (void) LED_TurnOnOff((led_handle_t) g_ledHandle[mGPIONum], !mOnLogic); + (void) LED_TurnOnOff((led_handle_t) g_ledHandle[mIndex], !mOnLogic); } } #endif /* (defined(gAppLedCnt_c) && (gAppLedCnt_c > 0)) */ + +} // namespace chip::NXP::App diff --git a/examples/platform/nxp/k32w1/util/LightingManagerDimmable.cpp b/examples/platform/nxp/k32w1/util/LightingManagerDimmable.cpp new file mode 100644 index 0000000000..8476101f5d --- /dev/null +++ b/examples/platform/nxp/k32w1/util/LightingManagerDimmable.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 "LightingManagerDimmable.h" + +#include "AppConfig.h" +#include "AppTask.h" + +#include +#include +#include +#include +#include + +LightingManagerDimmable LightingManagerDimmable::sLightingManager; + +#if CONFIG_ENABLE_FEEDBACK +UserInterfaceFeedback & FeedbackMgr() +{ + return LightingMgr(); +} +#endif + +void LightingManagerDimmable::ApplyDim(uint8_t value) +{ + ChipLogProgress(DeviceLayer, "Dim action has been initiated"); + LightingManagerDimmable::lightLed.Set(LightingManagerDimmable::lightLed.IsTurnedOff() ? 1 : value); + ChipLogProgress(DeviceLayer, "Move to level %d completed", value); +} + +void LightingManagerDimmable::Init() +{ + /* The parameters will not be used by the dimmer init. */ + lightLed.Init(LIGHTING_MANAGER_LIGHT_LED_INDEX, false); + + RestoreState(); +} + +void LightingManagerDimmable::DisplayInLoop() +{ + lightLed.Animate(); +} + +void LightingManagerDimmable::DisplayOnAction(Action action) +{ + // Do nothing for now. +} + +void LightingManagerDimmable::RestoreState() +{ + /* restore initial state for the LED indicating Lighting state */ + lightLed.Set(false); + + chip::DeviceLayer::PlatformMgr().ScheduleWork([](intptr_t arg) { + chip::app::DataModel::Nullable currentLevel; + chip::app::Clusters::LevelControl::Attributes::CurrentLevel::Get(LIGHTING_MANAGER_APP_DEVICE_TYPE_ENDPOINT, currentLevel); + LightingMgr().ApplyDim(currentLevel.Value()); + }); +} + +void LightingManagerDimmable::UpdateState() +{ + // Do nothing for now. +} diff --git a/examples/platform/nxp/k32w1/util/LightingManagerDimmable.h b/examples/platform/nxp/k32w1/util/LightingManagerDimmable.h new file mode 100644 index 0000000000..0cd4475ebf --- /dev/null +++ b/examples/platform/nxp/k32w1/util/LightingManagerDimmable.h @@ -0,0 +1,85 @@ +/* + * + * 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 "AppConfig.h" +#include "LedDimmer.h" +#include "LedWidgetInterface.h" +#include "UserInterfaceFeedback.h" + +#include +#include + +using namespace chip::NXP::App; + +/* These flags can be overwritten in AppConfig.h */ +/** + * @brief Specifies the endpoint on which Application Device Type cluster is present. + * + * For example, this should be 1 for Contact Sensor and Lighting App reference apps. + */ +#ifndef LIGHTING_MANAGER_APP_DEVICE_TYPE_ENDPOINT +#define LIGHTING_MANAGER_APP_DEVICE_TYPE_ENDPOINT 1 +#endif + +/** + * @brief Specifies the array index of the light LED. + * + * The light LED is usually used to indicate the state of some cluster + * attribute: e.g OnOff attribute from OnOff cluster. + */ +#ifndef LIGHTING_MANAGER_LIGHT_LED_INDEX +#define LIGHTING_MANAGER_LIGHT_LED_INDEX 1 +#endif + +/** + * @brief Enable dimmable LED instead of a simple on/off LED. + * + */ +#ifndef LIGHTING_MANAGER_ENABLE_DIMMABLE_LED +#define LIGHTING_MANAGER_ENABLE_DIMMABLE_LED 1 +#endif + +/** + * @brief Manager of LedDimmer instance. + * + * It implements the UserInterfaceFeedback abstract interface. + */ +class LightingManagerDimmable : public UserInterfaceFeedback +{ +public: + void Init() override; + void DisplayInLoop() override; + void DisplayOnAction(Action action) override; + void RestoreState() override; + void UpdateState() override; + +private: + void ApplyDim(uint8_t value); + + LedDimmer lightLed; + + friend LightingManagerDimmable & LightingMgr(void); + static LightingManagerDimmable sLightingManager; +}; + +inline LightingManagerDimmable & LightingMgr(void) +{ + return LightingManagerDimmable::sLightingManager; +} diff --git a/examples/platform/nxp/pw_rpc_server.gni b/examples/platform/nxp/pw_rpc_server.gni index 0ec2d3b121..7133b44bf2 100644 --- a/examples/platform/nxp/pw_rpc_server.gni +++ b/examples/platform/nxp/pw_rpc_server.gni @@ -48,6 +48,7 @@ pw_rpc_server = { ] deps = [ + "$dir_pw_hdlc:default_addresses", "$dir_pw_hdlc:rpc_channel_output", "$dir_pw_stream:sys_io_stream", "$dir_pw_trace", diff --git a/scripts/build/builders/nxp.py b/scripts/build/builders/nxp.py index e119a78b5e..00678e8b0c 100644 --- a/scripts/build/builders/nxp.py +++ b/scripts/build/builders/nxp.py @@ -56,7 +56,7 @@ def FolderName(self, os_env): if self == NxpBoard.K32W0: return 'k32w0' elif self == NxpBoard.K32W1: - return 'k32w/k32w1' + return 'k32w1' elif self == NxpBoard.RW61X: if os_env == NxpOsUsed.ZEPHYR: return 'zephyr' @@ -250,7 +250,8 @@ def generate(self): cmd += 'export NXP_K32W0_SDK_ROOT="' + str(p.sdk_storage_location_abspath) + '" \n ' elif p.sdk_name == 'common': cmd += 'export NXP_SDK_ROOT="' + str(p.sdk_storage_location_abspath) + '" \n ' - cmd += 'gn gen --check --fail-on-unused-args --export-compile-commands --root=%s' % self.root + # 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 extra_args = [] diff --git a/scripts/tools/nxp/factory_data_generator/generate.py b/scripts/tools/nxp/factory_data_generator/generate.py index 0d905d41fa..b3ee98562b 100755 --- a/scripts/tools/nxp/factory_data_generator/generate.py +++ b/scripts/tools/nxp/factory_data_generator/generate.py @@ -22,6 +22,7 @@ import subprocess import sys +from crc import Calculator, Crc16 from custom import (CertDeclaration, DacCert, DacPKey, Discriminator, HardwareVersion, HardwareVersionStr, IterationCount, ManufacturingDate, PaiCert, PartNumber, ProductFinish, ProductId, ProductLabel, ProductName, ProductPrimaryColor, ProductURL, Salt, SerialNum, SetupPasscode, StrArgument, UniqueId, VendorId, VendorName, @@ -133,6 +134,15 @@ def to_bin(self, klv, out, aes128_key): size = len(fullContent) + if (self.args.hw_params): + calculator = Calculator(Crc16.XMODEM) + crc_sum = calculator.checksum(fullContent) + + fullContent = bytearray(b"APP_FACT_DATA: ") + size.to_bytes(4, 'little') + \ + fullContent + crc_sum.to_bytes(2, 'little') + + size = len(fullContent) + logging.info("Size of final generated binary is: {} bytes".format(size)) file.write(fullContent) else: @@ -235,6 +245,8 @@ def main(): help="[str] Visible finish of the product") optional.add_argument("--product_primary_color", type=ProductPrimaryColor, metavar=ProductPrimaryColor.VALUES, help="[str] Representative color of the visible parts of the product") + optional.add_argument("--hw_params", action='store_true', + help="[bool] If present, store factory data in HWParameters APP section") args = parser.parse_args() diff --git a/scripts/tools/nxp/ota/README.md b/scripts/tools/nxp/ota/README.md index d96ab70d63..5c3a12adba 100644 --- a/scripts/tools/nxp/ota/README.md +++ b/scripts/tools/nxp/ota/README.md @@ -14,7 +14,7 @@ thus the `OTAImageProcessorImpl` instance should take this into account. ## Supported platforms - K32W0 - - [K32W OTA README](../../../../src/platform/nxp/k32w/common/K32W_OTA_README.md) + [K32W OTA README](../../../../src/platform/nxp/common/legacy/OTA_README.md) ## Usage diff --git a/src/lib/shell/streamer_nxp.cpp b/src/lib/shell/streamer_nxp.cpp index e46fce8407..355015ce8f 100644 --- a/src/lib/shell/streamer_nxp.cpp +++ b/src/lib/shell/streamer_nxp.cpp @@ -66,7 +66,7 @@ #endif // pw RPC uses UART DMA by default -#ifdef PW_RPC_ENABLED +#ifdef CONFIG_ENABLE_PW_RPC #define CONSUMER_TASK_HANDLE RpcTaskHandle #ifndef STREAMER_UART_USE_DMA #define STREAMER_UART_USE_DMA 1 @@ -76,7 +76,7 @@ #ifndef STREAMER_UART_USE_DMA #define STREAMER_UART_USE_DMA 0 #endif -#endif // PW_RPC_ENABLED +#endif // CONFIG_ENABLE_PW_RPC #if STREAMER_UART_USE_DMA typedef serial_port_uart_dma_config_t streamer_serial_port_uart_config_t; diff --git a/src/platform/nxp/BUILD.gn b/src/platform/nxp/BUILD.gn index b60e57af6a..0865a1d36d 100644 --- a/src/platform/nxp/BUILD.gn +++ b/src/platform/nxp/BUILD.gn @@ -26,9 +26,24 @@ source_set("logging") { "${chip_root}/src/platform/logging:headers", ] - if (nxp_platform == "k32w/k32w0" || nxp_platform == "k32w/k32w1") { + if (nxp_platform == "k32w/k32w0" || nxp_platform == "k32w1") { sources = [ "${chip_root}/src/platform/nxp/${nxp_platform}/Logging.cpp" ] } else { sources = [ "${chip_root}/src/platform/nxp/common/Logging.cpp" ] } } + +# The application can use this target to integrate the default, platform-specific +# NXP factory data provider. Each platform should define an "nxp_factory_data" source set. +# Usage: deps += [ "${chip_root}/src/platform/nxp:nxp_factory_data" ] +group("nxp_factory_data") { + public_deps = + [ "${chip_root}/src/platform/nxp/${nxp_platform}:nxp_factory_data" ] +} + +# The application can use this target to integrate the default, platform-specific +# NXP OTA implementation. Each platform should define an "nxp_ota" source set. +# Usage: deps += [ "${chip_root}/src/platform/nxp:nxp_ota" ] +group("nxp_ota") { + public_deps = [ "${chip_root}/src/platform/nxp/${nxp_platform}:nxp_ota" ] +} diff --git a/src/platform/nxp/common/NXPConfig.cpp b/src/platform/nxp/common/NXPConfig.cpp index b047d8afeb..029c5e1766 100644 --- a/src/platform/nxp/common/NXPConfig.cpp +++ b/src/platform/nxp/common/NXPConfig.cpp @@ -21,8 +21,6 @@ * Utilities for accessing persisted device configuration on * platforms based on the NXP SDK. */ -/* this file behaves like a config.h, comes first */ -#include #include "NXPConfig.h" @@ -30,6 +28,7 @@ #include "FunctionLib.h" #include "board.h" #include +#include #include /* FS Writes in Idle task only - LittleFS only , already enabled by default on NVM */ diff --git a/src/platform/nxp/common/NXPConfig.h b/src/platform/nxp/common/NXPConfig.h index c20dc7e507..432acfa196 100644 --- a/src/platform/nxp/common/NXPConfig.h +++ b/src/platform/nxp/common/NXPConfig.h @@ -23,10 +23,9 @@ #pragma once -#include - #include "FreeRTOS.h" #include +#include #define CHIP_PLAT_NO_NVM 0 #define CHIP_PLAT_NVM_FWK 1 diff --git a/src/platform/nxp/common/NXPConfigKS.cpp b/src/platform/nxp/common/NXPConfigKS.cpp index f7dd6bdc97..1940a8081c 100644 --- a/src/platform/nxp/common/NXPConfigKS.cpp +++ b/src/platform/nxp/common/NXPConfigKS.cpp @@ -20,8 +20,6 @@ * Utilities for accessing persisted device configuration on * platforms based on the NXP SDK. */ -/* this file behaves like a config.h, comes first */ -#include #include "NXPConfig.h" @@ -29,6 +27,7 @@ #include "FunctionLib.h" #include "board.h" #include +#include #include #include "fwk_file_cache.h" diff --git a/src/platform/nxp/common/NXPConfigNVS.cpp b/src/platform/nxp/common/NXPConfigNVS.cpp new file mode 100644 index 0000000000..34d98a36d2 --- /dev/null +++ b/src/platform/nxp/common/NXPConfigNVS.cpp @@ -0,0 +1,347 @@ +/* + * + * Copyright (c) 2020-2022 Project CHIP Authors + * Copyright 2024 NXP + * + * 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 "NXPConfig.h" +#include +#include +#include +#include + +/* Only for flash init, to be move to sdk framework */ +#include "port/nvs_port.h" + +// These can be overridden by the application as needed. +#ifndef CHIP_DEVICE_INTEGER_SETTINGS_KEY +/// Key for all integer keys +#define CHIP_DEVICE_INTEGER_SETTINGS_KEY "mt_i" +#endif // CHIP_DEVICE_CONFIG_SETTINGS_KEY +#ifndef CHIP_DEVICE_STRING_SETTINGS_KEY +/// Key for all string keys +#define CHIP_DEVICE_STRING_SETTINGS_KEY "mt_s" +#endif // CHIP_DEVICE_CONFIG_SETTINGS_KEY + +namespace chip { +namespace DeviceLayer { +namespace Internal { + +namespace { + +struct ReadRequest +{ + void * const destination; // NOTE: can be nullptr in which case `configSize` should still be returned + const size_t bufferSize; // size of destination buffer + CHIP_ERROR result; // [out] read result + size_t configSize; // [out] size of configuration value +}; + +struct DeleteSubtreeEntry +{ + int result; +}; + +// Callback for settings_load_subtree_direct() function +int ConfigValueCallback(const char * name, size_t configSize, settings_read_cb readCb, void * cbArg, void * param) +{ + // If requested config key X, process just node X and ignore all its descendants: X/* + if (name != nullptr && *name != '\0') + return 0; + + ReadRequest & request = *reinterpret_cast(param); + + if (!request.destination || configSize > request.bufferSize) + { + request.result = CHIP_ERROR_BUFFER_TOO_SMALL; + request.configSize = configSize; + return 1; + } + + // Found requested key + const ssize_t bytesRead = readCb(cbArg, request.destination, request.bufferSize); + request.result = bytesRead > 0 ? CHIP_NO_ERROR : CHIP_ERROR_PERSISTED_STORAGE_FAILED; + request.configSize = bytesRead > 0 ? bytesRead : 0; + + // Return 1 to stop processing further keys + return 1; +} + +// Read configuration value of maximum size `bufferSize` and store the actual size in `configSize`. +CHIP_ERROR ReadConfigValueImpl(const NXPConfig::Key key, void * const destination, const size_t bufferSize, size_t & configSize) +{ + ReadRequest request{ destination, bufferSize, CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND, 0 }; + char key_name[SETTINGS_MAX_NAME_LEN + 1]; + + sprintf(key_name, CHIP_DEVICE_INTEGER_SETTINGS_KEY "/%04x", key); + settings_load_subtree_direct(key_name, ConfigValueCallback, &request); + configSize = request.configSize; + return request.result; +} + +CHIP_ERROR WriteConfigValueImpl(const NXPConfig::Key key, const void * const source, const size_t length) +{ + char key_name[SETTINGS_MAX_NAME_LEN + 1]; + sprintf(key_name, CHIP_DEVICE_INTEGER_SETTINGS_KEY "/%04x", key); + if (settings_save_one(key_name, source, length) != 0) + return CHIP_ERROR_PERSISTED_STORAGE_FAILED; +#if (DEBUG_NVM > 0) + ChipLogProgress(DeviceLayer, "WriteConfigValue done"); +#endif + return CHIP_NO_ERROR; +} + +template +inline CHIP_ERROR ReadSimpleConfigValue(const NXPConfig::Key key, T & value) +{ + CHIP_ERROR result; + T tempValue; + size_t configSize; + + result = ReadConfigValueImpl(key, &tempValue, sizeof(T), configSize); + SuccessOrExit(result); + + // For simple types require that size of the output variable matches size of the configuration value + VerifyOrExit(configSize == sizeof(T), result = CHIP_ERROR_INVALID_ARGUMENT); + value = tempValue; +exit: + return result; +} + +int DeleteSubtreeCallback(const char * name, size_t /* entrySize */, settings_read_cb /* readCb */, void * /* cbArg */, + void * param) +{ + + DeleteSubtreeEntry & entry = *static_cast(param); + char fullKey[SETTINGS_MAX_NAME_LEN + 1]; + (void) snprintf(fullKey, sizeof(fullKey), CHIP_DEVICE_STRING_SETTINGS_KEY "/%s", StringOrNullMarker(name)); + const int result = settings_delete(fullKey); + + // Return the first error, but continue removing remaining keys anyway. + if (entry.result == 0) + { + entry.result = result; + } + + return 0; +} +} // namespace + +CHIP_ERROR NXPConfig::Init() +{ + /* Only for flash init, to be move to sdk framework */ + /* Initialize flash components */ + const struct flash_area * fa; + + ReturnErrorCodeIf(flash_area_open(SETTINGS_PARTITION, &fa), CHIP_ERROR_PERSISTED_STORAGE_FAILED); + ReturnErrorCodeIf(flash_init(fa->fa_dev), CHIP_ERROR_PERSISTED_STORAGE_FAILED); + /* End flash init */ + + ReturnErrorCodeIf(settings_subsys_init(), CHIP_ERROR_PERSISTED_STORAGE_FAILED); + + return CHIP_NO_ERROR; +} + +CHIP_ERROR NXPConfig::ReadConfigValue(Key key, bool & val) +{ + ReturnErrorCodeIf(!ValidConfigKey(key), CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND); // Verify key id. + return ReadSimpleConfigValue(key, val); +} + +CHIP_ERROR NXPConfig::ReadConfigValue(Key key, uint32_t & val) +{ + ReturnErrorCodeIf(!ValidConfigKey(key), CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND); // Verify key id. + return ReadSimpleConfigValue(key, val); +} + +CHIP_ERROR NXPConfig::ReadConfigValue(Key key, uint64_t & val) +{ + ReturnErrorCodeIf(!ValidConfigKey(key), CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND); // Verify key id. + return ReadSimpleConfigValue(key, val); +} + +CHIP_ERROR NXPConfig::ReadConfigValueStr(Key key, char * buf, size_t bufSize, size_t & outLen) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + ReturnErrorCodeIf(!ValidConfigKey(key), err = CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND); // Verify key id. + // Pretend that the buffer is smaller by 1 to secure space for null-character + err = ReadConfigValueImpl(key, buf, bufSize ? bufSize - 1 : 0, outLen); + + if (err == CHIP_NO_ERROR) + { + if (buf[outLen - 1]) // CHIP_NO_ERROR implies outLen > 0 + buf[outLen] = 0; + else + outLen--; + } + return err; +} + +CHIP_ERROR NXPConfig::ReadConfigValueBin(Key key, uint8_t * buf, size_t bufSize, size_t & outLen) +{ + return ReadConfigValueImpl(key, buf, bufSize, outLen); +} + +CHIP_ERROR NXPConfig::ReadConfigValueBin(const char * keyString, uint8_t * buf, size_t bufSize, size_t & outLen) +{ + ReadRequest request{ buf, bufSize, CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND, 0 }; + char key_name[SETTINGS_MAX_NAME_LEN + 1]; + unsigned key_name_len; + + // to be able to concat CHIP_DEVICE_STRING_SETTINGS_KEY"/" and keyString, + 1 for end char + key_name_len = strlen(keyString) + strlen(CHIP_DEVICE_STRING_SETTINGS_KEY) + 1; + ReturnErrorCodeIf(key_name_len > (SETTINGS_MAX_NAME_LEN + 1), CHIP_ERROR_PERSISTED_STORAGE_FAILED); + + sprintf(key_name, CHIP_DEVICE_STRING_SETTINGS_KEY "/%s", keyString); + settings_load_subtree_direct(key_name, ConfigValueCallback, &request); + outLen = request.configSize; + return request.result; +} + +CHIP_ERROR NXPConfig::ReadConfigValueCounter(uint8_t counterIdx, uint32_t & val) +{ + Key key = kMinConfigKey_ChipCounter + counterIdx; + return ReadConfigValue(key, val); +} + +CHIP_ERROR NXPConfig::WriteConfigValue(Key key, bool val) +{ + return WriteConfigValueImpl(key, &val, sizeof(bool)); +} + +CHIP_ERROR NXPConfig::WriteConfigValue(Key key, uint32_t val) +{ + return WriteConfigValueImpl(key, &val, sizeof(uint32_t)); +} + +CHIP_ERROR NXPConfig::WriteConfigValue(Key key, uint64_t val) +{ + return WriteConfigValueImpl(key, &val, sizeof(uint64_t)); +} + +CHIP_ERROR NXPConfig::WriteConfigValueStr(Key key, const char * str) +{ + return WriteConfigValueStr(key, str, str ? strlen(str) : 0); +} + +CHIP_ERROR NXPConfig::WriteConfigValueStr(Key key, const char * str, size_t strLen) +{ + ReturnErrorCodeIf(!ValidConfigKey(key), CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND); // Verify key id. + return WriteConfigValueImpl(key, str, strLen); +} + +CHIP_ERROR NXPConfig::WriteConfigValueBin(Key key, const uint8_t * data, size_t dataLen) +{ + return WriteConfigValueStr(key, (char *) data, dataLen); +} + +CHIP_ERROR NXPConfig::WriteConfigValueBin(const char * keyString, const uint8_t * data, size_t dataLen) +{ + char key_name[SETTINGS_MAX_NAME_LEN + 1]; + unsigned key_name_len; + + // to be able to concat CHIP_DEVICE_STRING_SETTINGS_KEY"/" and keyString, + 1 for end char + key_name_len = strlen(keyString) + strlen(CHIP_DEVICE_STRING_SETTINGS_KEY) + 1; + ReturnErrorCodeIf(key_name_len > (SETTINGS_MAX_NAME_LEN + 1), CHIP_ERROR_PERSISTED_STORAGE_FAILED); + + sprintf(key_name, CHIP_DEVICE_STRING_SETTINGS_KEY "/%s", keyString); + if (settings_save_one(key_name, data, dataLen) != 0) + return CHIP_ERROR_PERSISTED_STORAGE_FAILED; + + return CHIP_NO_ERROR; +} + +CHIP_ERROR NXPConfig::WriteConfigValueCounter(uint8_t counterIdx, uint32_t val) +{ + Key key = kMinConfigKey_ChipCounter + counterIdx; + return WriteConfigValue(key, val); +} + +CHIP_ERROR NXPConfig::ClearConfigValue(Key key) +{ + char key_name[SETTINGS_MAX_NAME_LEN + 1]; + sprintf(key_name, CHIP_DEVICE_INTEGER_SETTINGS_KEY "/%04x", key); + return ClearConfigValue(key_name); +} + +CHIP_ERROR NXPConfig::ClearConfigValue(const char * keyString) +{ + char key_name[SETTINGS_MAX_NAME_LEN]; + unsigned key_name_len; + + // to be able to concat CHIP_DEVICE_STRING_SETTINGS_KEY"/" and keyString, + 1 for end char + key_name_len = strlen(keyString) + strlen(CHIP_DEVICE_STRING_SETTINGS_KEY) + 1; + ReturnErrorCodeIf(key_name_len > (SETTINGS_MAX_NAME_LEN + 1), CHIP_ERROR_PERSISTED_STORAGE_FAILED); + + sprintf(key_name, CHIP_DEVICE_STRING_SETTINGS_KEY "/%s", keyString); + if (settings_delete(key_name) != 0) + return CHIP_ERROR_PERSISTED_STORAGE_FAILED; + + return CHIP_NO_ERROR; +} + +bool NXPConfig::ConfigValueExists(Key key) +{ + bool err = false; + if (ValidConfigKey(key)) + { + size_t configSize; + err = ReadConfigValueImpl(key, nullptr, 0, configSize) == CHIP_ERROR_BUFFER_TOO_SMALL; + } + return err; +} + +CHIP_ERROR NXPConfig::FactoryResetConfig(void) +{ + DeleteSubtreeEntry entry{ /* success */ 0 }; + // Clear CHIP_DEVICE_STRING_SETTINGS_KEY/* keys + int result = settings_load_subtree_direct(CHIP_DEVICE_STRING_SETTINGS_KEY, DeleteSubtreeCallback, &entry); + + if (result == 0) + { + result = entry.result; + } + + char key_name[SETTINGS_MAX_NAME_LEN + 1]; + for (Key key = kMinConfigKey_ChipConfig; key <= kMaxConfigKey_ChipConfig; key++) + { + sprintf(key_name, CHIP_DEVICE_INTEGER_SETTINGS_KEY "/%04x", key); + if (settings_delete(key_name) != 0) + return CHIP_ERROR_PERSISTED_STORAGE_FAILED; + } + + // Clear RebootCount, TotalOperationalHours, UpTime counters during factory reset + for (Key key = kMinConfigKey_ChipCounter; key <= (kMinConfigKey_ChipCounter + 3); key++) + { + sprintf(key_name, CHIP_DEVICE_INTEGER_SETTINGS_KEY "/%04x", key); + if (settings_delete(key_name) != 0) + return CHIP_ERROR_PERSISTED_STORAGE_FAILED; + } + return CHIP_NO_ERROR; +} + +bool NXPConfig::ValidConfigKey(Key key) +{ + // Returns true if the key is in the valid CHIP Config PDM key range. + return (key >= kMinConfigKey_ChipFactory) && (key <= kMaxConfigKey_KVS); +} + +void NXPConfig::RunConfigUnitTest(void) {} + +void NXPConfig::RunSystemIdleTask(void) {} + +} // namespace Internal +} // namespace DeviceLayer +} // namespace chip diff --git a/src/platform/nxp/k32w/common/BLEManagerCommon.cpp b/src/platform/nxp/k32w/common/BLEManagerCommon.cpp deleted file mode 100644 index d9dbde88f3..0000000000 --- a/src/platform/nxp/k32w/common/BLEManagerCommon.cpp +++ /dev/null @@ -1,1435 +0,0 @@ -/* - * - * Copyright (c) 2020-2021 Project CHIP Authors - * Copyright (c) 2020 Nest Labs, Inc. - * 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 - * Provides an implementation of the BLEManager singleton object - * for the K32W platforms. - */ - -/* this file behaves like a config.h, comes first */ -#include - -#include - -#include - -#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE - -#include - -#include "board.h" -#include "gatt_db_app_interface.h" -#include "gatt_db_handles.h" -#include "stdio.h" -#include "timers.h" - -#if defined(CPU_JN518X) && defined(chip_with_low_power) && (chip_with_low_power == 1) -#include "PWR_Configuration.h" -#endif - -#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING -#include -#include -#endif - -/******************************************************************************* - * Local data types - *******************************************************************************/ -extern "C" bool_t Ble_ConfigureHostStackConfig(void); - -#if defined(chip_with_low_power) && (chip_with_low_power == 1) -extern "C" void PWR_DisallowDeviceToSleep(void); -extern "C" void PWR_AllowDeviceToSleep(void); -#endif - -using namespace ::chip; -using namespace ::chip::Ble; - -namespace chip { -namespace DeviceLayer { -namespace Internal { - -namespace { -/******************************************************************************* - * Macros & Constants definitions - *******************************************************************************/ -/* Timeout of BLE commands */ -#define CHIP_BLE_KW_EVNT_TIMEOUT 1000 / portTICK_PERIOD_MS - -/** BLE advertisement state changed */ -#define CHIP_BLE_KW_EVNT_ADV_CHANGED 0x0001 -/** BLE advertisement command failed */ -#define CHIP_BLE_KW_EVNT_ADV_FAILED 0x0002 -/** BLE advertisement setup failed */ -#define CHIP_BLE_KW_EVNT_ADV_SETUP_FAILED 0x0004 -/** BLE advertisement parameters setup complete */ -#define CHIP_BLE_KW_EVNT_ADV_PAR_SETUP_COMPLETE 0x0008 -/** BLE advertisement data setup complete */ -#define CHIP_BLE_KW_EVNT_ADV_DAT_SETUP_COMPLETE 0x0010 -/** BLE random address set */ -#define CHIP_BLE_KW_EVNT_RND_ADDR_SET 0x0020 -/** BLE Initialization complete */ -#define CHIP_BLE_KW_EVNT_INIT_COMPLETE 0x0040 -/** BLE Received a handle value confirmation from the client */ -#define CHIP_BLE_KW_EVNT_INDICATION_CONFIRMED 0x0080 -/** BLE send indication failed */ -#define CHIP_BLE_KW_EVNT_INDICATION_FAILED 0x0100 -/** TX Power Level Set */ -#define CHIP_BLE_KW_EVNT_POWER_LEVEL_SET 0x0200 -/** Maximal time of connection without activity */ -#define CHIP_BLE_KW_CONN_TIMEOUT 60000 -/** Maximum number of pending BLE events */ -#define CHIP_BLE_EVENT_QUEUE_MAX_ENTRIES 10 - -#define LOOP_EV_BLE (0x08) - -/* controller task configuration */ -#define CONTROLLER_TASK_PRIORITY (6U) -#define CONTROLLER_TASK_STACK_SIZE (gControllerTaskStackSize_c / sizeof(StackType_t)) - -/* host task configuration */ -#define HOST_TASK_PRIORITY (4U) -#define HOST_TASK_STACK_SIZE (gHost_TaskStackSize_c / sizeof(StackType_t)) - -/* advertising configuration */ -#define BLEKW_ADV_MAX_NO (2) -#define BLEKW_SCAN_RSP_MAX_NO (2) -#define BLEKW_MAX_ADV_DATA_LEN (31) -#define CHIP_ADV_SHORT_UUID_LEN (2) - -/* FreeRTOS sw timer */ -TimerHandle_t sbleAdvTimeoutTimer; - -/* Queue used to synchronize asynchronous messages from the KW BLE tasks */ -QueueHandle_t sBleEventQueue; - -/* Used to manage asynchronous events from BLE Stack: e.g.: GAP setup finished */ -EventGroupHandle_t sEventGroup; - -TimerHandle_t connectionTimeout; - -const uint8_t ShortUUID_CHIPoBLEService[] = { 0xF6, 0xFF }; - -#if defined(chip_with_low_power) && (chip_with_low_power == 1) -static bool bleAppStopInProgress; -#endif - -BLEManagerCommon * sImplInstance = nullptr; - -} // namespace - -CHIP_ERROR BLEManagerCommon::_Init() -{ - CHIP_ERROR err = CHIP_NO_ERROR; - EventBits_t eventBits; - uint16_t attChipRxHandle[1] = { (uint16_t) value_chipoble_rx }; - -#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING - uint16_t attChipC3Handle[1] = { (uint16_t) value_chipoble_c3 }; -#endif - - mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Enabled; - - // Check if BLE stack is initialized - VerifyOrExit(!mFlags.Has(Flags::kK32WBLEStackInitialized), err = CHIP_ERROR_INCORRECT_STATE); - - // Initialize the Chip BleLayer. - err = BleLayer::Init(this, this, &DeviceLayer::SystemLayer()); - SuccessOrExit(err); - - /* Initialization of message wait events - - * used for receiving BLE Stack events */ - sEventGroup = xEventGroupCreate(); - VerifyOrExit(sEventGroup != NULL, err = CHIP_ERROR_INCORRECT_STATE); - - /* Prepare callback input queue.*/ - sBleEventQueue = xQueueCreate(CHIP_BLE_EVENT_QUEUE_MAX_ENTRIES, sizeof(blekw_msg_t *)); - VerifyOrExit(sBleEventQueue != NULL, err = CHIP_ERROR_INCORRECT_STATE); - - /* Create the connection timeout timer. */ - connectionTimeout = - xTimerCreate("bleTimeoutTmr", pdMS_TO_TICKS(CHIP_BLE_KW_CONN_TIMEOUT), pdFALSE, (void *) 0, blekw_connection_timeout_cb); - VerifyOrExit(connectionTimeout != NULL, err = CHIP_ERROR_INCORRECT_STATE); - - sImplInstance = GetImplInstance(); - - /* BLE platform code initialization */ - SuccessOrExit(err = InitHostController(&blekw_generic_cb)); - - /* Register the GATT server callback */ - VerifyOrExit(GattServer_RegisterCallback(blekw_gatt_server_cb) == gBleSuccess_c, err = CHIP_ERROR_INCORRECT_STATE); - - /* Wait until BLE Stack is ready */ - eventBits = xEventGroupWaitBits(sEventGroup, CHIP_BLE_KW_EVNT_INIT_COMPLETE, pdTRUE, pdTRUE, CHIP_BLE_KW_EVNT_TIMEOUT); - VerifyOrExit(eventBits & CHIP_BLE_KW_EVNT_INIT_COMPLETE, err = CHIP_ERROR_INCORRECT_STATE); - -#if BLE_HIGH_TX_POWER - /* Set Adv Power */ - Gap_SetTxPowerLevel(gAdvertisingPowerLeveldBm_c, gTxPowerAdvChannel_c); - eventBits = xEventGroupWaitBits(sEventGroup, CHIP_BLE_KW_EVNT_POWER_LEVEL_SET, pdTRUE, pdTRUE, CHIP_BLE_KW_EVNT_TIMEOUT); - VerifyOrExit(eventBits & CHIP_BLE_KW_EVNT_POWER_LEVEL_SET, err = CHIP_ERROR_INCORRECT_STATE); - - /* Set Connect Power */ - Gap_SetTxPowerLevel(gConnectPowerLeveldBm_c, gTxPowerConnChannel_c); - eventBits = xEventGroupWaitBits(sEventGroup, CHIP_BLE_KW_EVNT_POWER_LEVEL_SET, pdTRUE, pdTRUE, CHIP_BLE_KW_EVNT_TIMEOUT); - 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) - PWR_ChangeDeepSleepMode(cPWR_PowerDown_RamRet); -#endif - - GattServer_RegisterHandlesForWriteNotifications(1, attChipRxHandle); -#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING - VerifyOrExit(GattServer_RegisterHandlesForReadNotifications(1, attChipC3Handle) == gBleSuccess_c, - err = CHIP_ERROR_INCORRECT_STATE); -#endif - - mFlags.Set(Flags::kK32WBLEStackInitialized); - mFlags.Set(Flags::kAdvertisingEnabled, CHIP_DEVICE_CONFIG_CHIPOBLE_ENABLE_ADVERTISING_AUTOSTART ? true : false); - mFlags.Set(Flags::kFastAdvertisingEnabled); - - // Create FreeRTOS sw timer for BLE timeouts and interval change. - sbleAdvTimeoutTimer = xTimerCreate("BleAdvTimer", // Just a text name, not used by the RTOS kernel - pdMS_TO_TICKS(100), // == default timer period (mS) - false, // no timer reload (==one-shot) - (void *) this, // init timer id = ble obj context - BleAdvTimeoutHandler // timer callback handler - ); - VerifyOrExit(sbleAdvTimeoutTimer != NULL, err = CHIP_ERROR_INCORRECT_STATE); - -exit: - return err; -} - -uint16_t BLEManagerCommon::_NumConnections(void) -{ - return static_cast(mDeviceConnected == true); -} - -bool BLEManagerCommon::_IsAdvertisingEnabled(void) -{ - return mFlags.Has(Flags::kAdvertisingEnabled); -} - -bool BLEManagerCommon::_IsAdvertising(void) -{ - return mFlags.Has(Flags::kAdvertising); -} - -CHIP_ERROR BLEManagerCommon::_SetAdvertisingEnabled(bool val) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - - VerifyOrExit(mServiceMode != ConnectivityManager::kCHIPoBLEServiceMode_NotSupported, err = CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE); - - if (mFlags.Has(Flags::kAdvertisingEnabled) != val) - { - mFlags.Set(Flags::kAdvertisingEnabled, val); - PlatformMgr().ScheduleWork(DriveBLEState, 0); - } - -exit: - return err; -} - -CHIP_ERROR BLEManagerCommon::_SetAdvertisingMode(BLEAdvertisingMode mode) -{ - switch (mode) - { - case BLEAdvertisingMode::kFastAdvertising: - mFlags.Set(Flags::kFastAdvertisingEnabled); - break; - case BLEAdvertisingMode::kSlowAdvertising: { - // We are in FreeRTOS timer service context, which is a default daemon task and has - // the highest priority. Stop advertising should be scheduled to run from Matter task. - mFlags.Clear(Flags::kFastAdvertisingEnabled); - PlatformMgr().ScheduleWork(StopAdvertisingPriorToSwitchingMode, 0); - break; - } - default: - return CHIP_ERROR_INVALID_ARGUMENT; - } - mFlags.Set(Flags::kRestartAdvertising); - PlatformMgr().ScheduleWork(DriveBLEState, 0); - return CHIP_NO_ERROR; -} - -CHIP_ERROR BLEManagerCommon::_GetDeviceName(char * buf, size_t bufSize) -{ - if (strlen(mDeviceName) >= bufSize) - { - return CHIP_ERROR_BUFFER_TOO_SMALL; - } - strcpy(buf, mDeviceName); - return CHIP_NO_ERROR; -} - -CHIP_ERROR BLEManagerCommon::_SetDeviceName(const char * deviceName) -{ - if (mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_NotSupported) - { - return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; - } - if (deviceName != NULL && deviceName[0] != 0) - { - if (strlen(deviceName) >= kMaxDeviceNameLength) - { - return CHIP_ERROR_INVALID_ARGUMENT; - } - memset(mDeviceName, 0, kMaxDeviceNameLength); - strcpy(mDeviceName, deviceName); - mFlags.Set(Flags::kDeviceNameSet); - ChipLogProgress(DeviceLayer, "Setting device name to : \"%s\"", deviceName); - } - else - { - mDeviceName[0] = 0; - mFlags.Clear(Flags::kDeviceNameSet); - } - - return CHIP_NO_ERROR; -} - -void BLEManagerCommon::_OnPlatformEvent(const ChipDeviceEvent * event) -{ - switch (event->Type) - { - case DeviceEventType::kCHIPoBLESubscribe: - ChipDeviceEvent connEstEvent; - - HandleSubscribeReceived(event->CHIPoBLESubscribe.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); - connEstEvent.Type = DeviceEventType::kCHIPoBLEConnectionEstablished; - PlatformMgr().PostEventOrDie(&connEstEvent); - break; - - case DeviceEventType::kCHIPoBLEUnsubscribe: - HandleUnsubscribeReceived(event->CHIPoBLEUnsubscribe.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); - break; - - case DeviceEventType::kCHIPoBLEWriteReceived: - HandleWriteReceived(event->CHIPoBLEWriteReceived.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_1_UUID, - PacketBufferHandle::Adopt(event->CHIPoBLEWriteReceived.Data)); - break; - - case DeviceEventType::kCHIPoBLEConnectionError: - HandleConnectionError(event->CHIPoBLEConnectionError.ConId, event->CHIPoBLEConnectionError.Reason); - break; - - case DeviceEventType::kCHIPoBLEIndicateConfirm: - HandleIndicationConfirmation(event->CHIPoBLEIndicateConfirm.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); - break; - - default: - break; - } -} - -CHIP_ERROR BLEManagerCommon::SubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, - const ChipBleUUID * charId) -{ - ChipLogProgress(DeviceLayer, "BLEManagerCommon::SubscribeCharacteristic() not supported"); - return CHIP_ERROR_NOT_IMPLEMENTED; -} - -CHIP_ERROR BLEManagerCommon::UnsubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, - const ChipBleUUID * charId) -{ - ChipLogProgress(DeviceLayer, "BLEManagerCommon::UnsubscribeCharacteristic() not supported"); - return CHIP_ERROR_NOT_IMPLEMENTED; -} - -CHIP_ERROR BLEManagerCommon::CloseConnection(BLE_CONNECTION_OBJECT conId) -{ - return blekw_stop_connection_internal(conId); -} - -uint16_t BLEManagerCommon::GetMTU(BLE_CONNECTION_OBJECT conId) const -{ - uint16_t tempMtu = 0; - (void) Gatt_GetMtu(conId, &tempMtu); - - return tempMtu; -} - -CHIP_ERROR BLEManagerCommon::SendWriteRequest(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId, - PacketBufferHandle pBuf) -{ - ChipLogProgress(DeviceLayer, "BLEManagerCommon::SendWriteRequest() not supported"); - return CHIP_ERROR_NOT_IMPLEMENTED; -} - -void BLEManagerCommon::NotifyChipConnectionClosed(BLE_CONNECTION_OBJECT conId) -{ - BLEMgrImpl().CloseConnection(conId); -} - -CHIP_ERROR BLEManagerCommon::SendIndication(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId, - PacketBufferHandle data) -{ - VerifyOrReturnError(UUIDsMatch(&Ble::CHIP_BLE_CHAR_2_UUID, charId), BLE_ERROR_GATT_WRITE_FAILED); - - CHIP_ERROR err = CHIP_NO_ERROR; - - if (blekw_send_event(conId, value_chipoble_tx, data->Start(), data->DataLength()) != BLE_OK) - { - err = CHIP_ERROR_SENDING_BLOCKED; - } - else - { - ChipDeviceEvent event; - event.Type = DeviceEventType::kCHIPoBLEIndicateConfirm; - event.CHIPoBLEIndicateConfirm.ConId = conId; - err = PlatformMgr().PostEvent(&event); - } - - return err; -} - -BLEManagerCommon::ble_err_t BLEManagerCommon::blekw_send_event(int8_t connection_handle, uint16_t handle, uint8_t * data, - uint32_t len) -{ - EventBits_t eventBits; - -#if CHIP_DEVICE_CHIP0BLE_DEBUG - ChipLogProgress(DeviceLayer, "Trying to send event."); -#endif - - if (connection_handle < 0 || handle <= 0) - { - ChipLogProgress(DeviceLayer, "BLE Event - Bad Handle"); - return BLE_E_FAIL; - } - - if (len > 0 && data == NULL) - { - ChipLogProgress(DeviceLayer, "BLE Event - Invalid Data"); - return BLE_E_FAIL; - } - - /************* Send the indication *************/ - xEventGroupClearBits(sEventGroup, CHIP_BLE_KW_EVNT_INDICATION_CONFIRMED | CHIP_BLE_KW_EVNT_INDICATION_FAILED); - - if (GattServer_SendInstantValueIndication(connection_handle, handle, len, data) != gBleSuccess_c) - { - ChipLogProgress(DeviceLayer, "BLE Event - Can't sent indication"); - return BLE_E_FAIL; - } - - /* Wait until BLE Stack is ready */ - eventBits = xEventGroupWaitBits(sEventGroup, CHIP_BLE_KW_EVNT_INDICATION_CONFIRMED | CHIP_BLE_KW_EVNT_INDICATION_FAILED, pdTRUE, - pdFALSE, CHIP_BLE_KW_EVNT_TIMEOUT); - - if (eventBits & CHIP_BLE_KW_EVNT_INDICATION_FAILED) - { - ChipLogProgress(DeviceLayer, "BLE Event - Sent Failed"); - return BLE_E_FAIL; - } - -#if CHIP_DEVICE_CHIP0BLE_DEBUG - ChipLogProgress(DeviceLayer, "BLE Event - Sent :-) "); -#endif - - return BLE_OK; -} -/******************************************************************************* - * Private functions - *******************************************************************************/ - -BLEManagerCommon::ble_err_t BLEManagerCommon::blekw_start_advertising(gapAdvertisingParameters_t * adv_params, - gapAdvertisingData_t * adv, gapScanResponseData_t * scnrsp) -{ - EventBits_t eventBits; - - /************* Set the advertising parameters *************/ - xEventGroupClearBits(sEventGroup, CHIP_BLE_KW_EVNT_ADV_SETUP_FAILED | CHIP_BLE_KW_EVNT_ADV_PAR_SETUP_COMPLETE); - - /* Set the advertising parameters */ - if (Gap_SetAdvertisingParameters(adv_params) != gBleSuccess_c) - { - vTaskDelay(1); - - /* Retry, just to make sure before giving up and sending an error. */ - if (Gap_SetAdvertisingParameters(adv_params) != gBleSuccess_c) - { - return BLE_E_SET_ADV_PARAMS; - } - } - - eventBits = xEventGroupWaitBits(sEventGroup, CHIP_BLE_KW_EVNT_ADV_SETUP_FAILED | CHIP_BLE_KW_EVNT_ADV_PAR_SETUP_COMPLETE, - pdTRUE, pdFALSE, CHIP_BLE_KW_EVNT_TIMEOUT); - - if (!(eventBits & CHIP_BLE_KW_EVNT_ADV_PAR_SETUP_COMPLETE)) - { - return BLE_E_ADV_PARAMS_FAILED; - } - - /************* Set the advertising data *************/ - xEventGroupClearBits(sEventGroup, CHIP_BLE_KW_EVNT_ADV_SETUP_FAILED | CHIP_BLE_KW_EVNT_ADV_DAT_SETUP_COMPLETE); - - /* Set the advertising data */ - if (Gap_SetAdvertisingData(adv, scnrsp) != gBleSuccess_c) - { - return BLE_E_SET_ADV_DATA; - } - - eventBits = xEventGroupWaitBits(sEventGroup, CHIP_BLE_KW_EVNT_ADV_SETUP_FAILED | CHIP_BLE_KW_EVNT_ADV_DAT_SETUP_COMPLETE, - pdTRUE, pdFALSE, CHIP_BLE_KW_EVNT_TIMEOUT); - - if (!(eventBits & CHIP_BLE_KW_EVNT_ADV_DAT_SETUP_COMPLETE)) - { - return BLE_E_ADV_SETUP_FAILED; - } - - /************* Start the advertising *************/ - xEventGroupClearBits(sEventGroup, CHIP_BLE_KW_EVNT_ADV_CHANGED | CHIP_BLE_KW_EVNT_ADV_FAILED); - - if (gBleSuccess_c != Gap_CreateRandomDeviceAddress(NULL, NULL)) - { - return BLE_E_SET_ADV_PARAMS; - } - - eventBits = xEventGroupWaitBits(sEventGroup, CHIP_BLE_KW_EVNT_RND_ADDR_SET, pdTRUE, pdTRUE, CHIP_BLE_KW_EVNT_TIMEOUT); - - if (!(eventBits & CHIP_BLE_KW_EVNT_RND_ADDR_SET)) - { - return BLE_E_ADV_PARAMS_FAILED; - } - - /* Start the advertising */ - if (Gap_StartAdvertising(blekw_gap_advertising_cb, blekw_gap_connection_cb) != gBleSuccess_c) - { - return BLE_E_START_ADV; - } - -#if defined(chip_with_low_power) && (chip_with_low_power == 1) - PWR_DisallowDeviceToSleep(); -#endif - - eventBits = xEventGroupWaitBits(sEventGroup, CHIP_BLE_KW_EVNT_ADV_CHANGED | CHIP_BLE_KW_EVNT_ADV_FAILED, pdTRUE, pdFALSE, - CHIP_BLE_KW_EVNT_TIMEOUT); - if (!(eventBits & CHIP_BLE_KW_EVNT_ADV_CHANGED)) - { -#if defined(chip_with_low_power) && (chip_with_low_power == 1) - PWR_AllowDeviceToSleep(); -#endif - return BLE_E_START_ADV_FAILED; - } - -#if defined(chip_with_low_power) && (chip_with_low_power == 1) - PWR_AllowDeviceToSleep(); -#endif - - return BLE_OK; -} - -BLEManagerCommon::ble_err_t BLEManagerCommon::blekw_stop_advertising(void) -{ - EventBits_t eventBits; - bleResult_t res; - - xEventGroupClearBits(sEventGroup, CHIP_BLE_KW_EVNT_ADV_CHANGED | CHIP_BLE_KW_EVNT_ADV_FAILED); - - /* Stop the advertising data */ - res = Gap_StopAdvertising(); - if (res != gBleSuccess_c) - { - ChipLogProgress(DeviceLayer, "Failed to stop advertising %d", res); - return BLE_E_STOP; - } - - eventBits = xEventGroupWaitBits(sEventGroup, CHIP_BLE_KW_EVNT_ADV_CHANGED | CHIP_BLE_KW_EVNT_ADV_FAILED, pdTRUE, pdFALSE, - CHIP_BLE_KW_EVNT_TIMEOUT); - - if (eventBits & CHIP_BLE_KW_EVNT_ADV_FAILED) - { - ChipLogProgress(DeviceLayer, "Stop advertising flat out failed."); - return BLE_E_ADV_FAILED; - } - else if (!(eventBits & CHIP_BLE_KW_EVNT_ADV_CHANGED)) - { - ChipLogProgress(DeviceLayer, "Stop advertising event timeout."); - return BLE_E_ADV_CHANGED; - } - - return BLE_OK; -} - -CHIP_ERROR BLEManagerCommon::ConfigureAdvertisingData(void) -{ - ble_err_t err; - CHIP_ERROR chipErr; - uint16_t discriminator; - uint16_t advInterval = 0; - gapAdvertisingData_t adv = { 0 }; - gapAdStructure_t adv_data[BLEKW_ADV_MAX_NO] = { { 0 } }; - gapAdStructure_t scan_rsp_data[BLEKW_SCAN_RSP_MAX_NO] = { { 0 } }; - uint8_t advPayload[BLEKW_MAX_ADV_DATA_LEN] = { 0 }; - gapScanResponseData_t scanRsp = { 0 }; - gapAdvertisingParameters_t adv_params = { 0 }; - uint8_t chipAdvDataFlags = (gLeGeneralDiscoverableMode_c | gBrEdrNotSupported_c); - uint8_t chipOverBleService[2]; - ChipBLEDeviceIdentificationInfo mDeviceIdInfo = { 0 }; - uint8_t mDeviceIdInfoLength = 0; - - chipErr = GetCommissionableDataProvider()->GetSetupDiscriminator(discriminator); - if (chipErr != CHIP_NO_ERROR) - { - return chipErr; - } - - if (!mFlags.Has(Flags::kDeviceNameSet)) - { - memset(mDeviceName, 0, kMaxDeviceNameLength); - snprintf(mDeviceName, kMaxDeviceNameLength, "%s%04u", CHIP_DEVICE_CONFIG_BLE_DEVICE_NAME_PREFIX, discriminator); - } - - /**************** Prepare advertising data *******************************************/ - adv.cNumAdStructures = BLEKW_ADV_MAX_NO; - - chipErr = ConfigurationMgr().GetBLEDeviceIdentificationInfo(mDeviceIdInfo); - SuccessOrExit(chipErr); - mDeviceIdInfoLength = sizeof(mDeviceIdInfo); - - if ((mDeviceIdInfoLength + CHIP_ADV_SHORT_UUID_LEN + 1) > BLEKW_MAX_ADV_DATA_LEN) - { - return CHIP_ERROR_INCORRECT_STATE; - } - - adv_data[0].length = 0x02; - adv_data[0].adType = gAdFlags_c; - adv_data[0].aData = (uint8_t *) (&chipAdvDataFlags); - - adv_data[1].length = static_cast(mDeviceIdInfoLength + CHIP_ADV_SHORT_UUID_LEN + 1); - adv_data[1].adType = gAdServiceData16bit_c; - memcpy(advPayload, ShortUUID_CHIPoBLEService, CHIP_ADV_SHORT_UUID_LEN); - memcpy(&advPayload[CHIP_ADV_SHORT_UUID_LEN], (void *) &mDeviceIdInfo, mDeviceIdInfoLength); - adv_data[1].aData = advPayload; - - adv.aAdStructures = adv_data; - -#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING - ReturnErrorOnFailure(EncodeAdditionalDataTlv()); -#endif - - /**************** Prepare scan response data *******************************************/ - scanRsp.cNumAdStructures = BLEKW_SCAN_RSP_MAX_NO; - - scan_rsp_data[0].length = static_cast(strlen(mDeviceName) + 1); - scan_rsp_data[0].adType = gAdCompleteLocalName_c; - scan_rsp_data[0].aData = (uint8_t *) mDeviceName; - - scan_rsp_data[1].length = sizeof(chipOverBleService) + 1; - scan_rsp_data[1].adType = gAdComplete16bitServiceList_c; - chipOverBleService[0] = ShortUUID_CHIPoBLEService[0]; - chipOverBleService[1] = ShortUUID_CHIPoBLEService[1]; - scan_rsp_data[1].aData = (uint8_t *) chipOverBleService; - - scanRsp.aAdStructures = scan_rsp_data; - - /**************** Prepare advertising parameters *************************************/ - if (mFlags.Has(Flags::kFastAdvertisingEnabled)) - { - advInterval = CHIP_DEVICE_CONFIG_BLE_FAST_ADVERTISING_INTERVAL_MAX; - } - else - { - advInterval = CHIP_DEVICE_CONFIG_BLE_SLOW_ADVERTISING_INTERVAL_MAX; - } - advInterval = (uint16_t) (advInterval * 0.625F); - - adv_params.minInterval = adv_params.maxInterval = advInterval; - adv_params.advertisingType = gAdvConnectableUndirected_c; - adv_params.ownAddressType = gBleAddrTypeRandom_c; - adv_params.peerAddressType = gBleAddrTypePublic_c; - memset(adv_params.peerAddress, 0, gcBleDeviceAddressSize_c); - adv_params.channelMap = (gapAdvertisingChannelMapFlags_t) (gAdvChanMapFlag37_c | gAdvChanMapFlag38_c | gAdvChanMapFlag39_c); - adv_params.filterPolicy = gProcessAll_c; - - err = blekw_start_advertising(&adv_params, &adv, &scanRsp); - if (err == BLE_OK) - { - ChipLogProgress(DeviceLayer, "Started Advertising at %d ms", advInterval); - } - else - { - ChipLogProgress(DeviceLayer, "Advertising error 0x%x!", err); - mFlags.Clear(Flags::kAdvertising); - return CHIP_ERROR_INCORRECT_STATE; - } - -exit: - return chipErr; -} - -#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING -CHIP_ERROR BLEManagerCommon::EncodeAdditionalDataTlv() -{ - CHIP_ERROR err = CHIP_NO_ERROR; - BitFlags dataFields; - AdditionalDataPayloadGeneratorParams params; - -#if CHIP_ENABLE_ROTATING_DEVICE_ID && defined(CHIP_DEVICE_CONFIG_ROTATING_DEVICE_ID_UNIQUE_ID) - uint8_t rotatingDeviceIdUniqueId[ConfigurationManager::kRotatingDeviceIDUniqueIDLength] = {}; - MutableByteSpan rotatingDeviceIdUniqueIdSpan(rotatingDeviceIdUniqueId); - - err = DeviceLayer::GetDeviceInstanceInfoProvider()->GetRotatingDeviceIdUniqueId(rotatingDeviceIdUniqueIdSpan); - SuccessOrExit(err); - err = ConfigurationMgr().GetLifetimeCounter(params.rotatingDeviceIdLifetimeCounter); - SuccessOrExit(err); - params.rotatingDeviceIdUniqueId = rotatingDeviceIdUniqueIdSpan; - dataFields.Set(AdditionalDataFields::RotatingDeviceId); -#endif /* CHIP_ENABLE_ROTATING_DEVICE_ID && defined(CHIP_DEVICE_CONFIG_ROTATING_DEVICE_ID_UNIQUE_ID) */ - err = AdditionalDataPayloadGenerator().generateAdditionalDataPayload(params, sImplInstance->c3AdditionalDataBufferHandle, - dataFields); - -exit: - if (err != CHIP_NO_ERROR) - { - ChipLogError(DeviceLayer, "Failed to generate TLV encoded Additional Data (%s)", __func__); - } - - return err; -} - -void BLEManagerCommon::HandleC3ReadRequest(blekw_msg_t * msg) -{ - bleResult_t result; - blekw_att_read_data_t * att_rd_data = (blekw_att_read_data_t *) msg->data.data; - deviceId_t deviceId = att_rd_data->device_id; - uint16_t handle = att_rd_data->handle; - uint16_t length = sImplInstance->c3AdditionalDataBufferHandle->DataLength(); - const uint8_t * data = (const uint8_t *) sImplInstance->c3AdditionalDataBufferHandle->Start(); - - result = GattDb_WriteAttribute(handle, length, data); - if (result != gBleSuccess_c) - { - ChipLogError(DeviceLayer, "Failed to write C3 characteristic: %d", result); - } - - result = GattServer_SendAttributeReadStatus(deviceId, handle, gAttErrCodeNoError_c); - if (result != gBleSuccess_c) - { - ChipLogError(DeviceLayer, "Failed to send response to C3 read request: %d", result); - } -} -#endif /* CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING */ - -CHIP_ERROR BLEManagerCommon::StartAdvertising(void) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - - mFlags.Set(Flags::kAdvertising); - mFlags.Clear(Flags::kRestartAdvertising); - - if (mFlags.Has(Flags::kFastAdvertisingEnabled)) - { - StartBleAdvTimeoutTimer(CHIP_DEVICE_CONFIG_BLE_FAST_ADVERTISING_TIMEOUT); - } - - err = ConfigureAdvertisingData(); - - if (err == CHIP_NO_ERROR) - /* schedule NFC emulation stop */ - { - ChipDeviceEvent advChange; - advChange.Type = DeviceEventType::kCHIPoBLEAdvertisingChange; - advChange.CHIPoBLEAdvertisingChange.Result = kActivity_Started; - err = PlatformMgr().PostEvent(&advChange); - } - - return err; -} - -CHIP_ERROR BLEManagerCommon::StopAdvertising(void) -{ - CHIP_ERROR error = CHIP_NO_ERROR; - - if (mFlags.Has(Flags::kAdvertising)) - { - mFlags.Clear(Flags::kAdvertising); - mFlags.Clear(Flags::kRestartAdvertising); - - if (!mDeviceConnected) - { - ble_err_t err = blekw_stop_advertising(); - VerifyOrReturnError(err == BLE_OK, CHIP_ERROR_INCORRECT_STATE); - CancelBleAdvTimeoutTimer(); - } - -#if CONFIG_CHIP_NFC_COMMISSIONING - /* schedule NFC emulation stop */ - ChipDeviceEvent advChange; - advChange.Type = DeviceEventType::kCHIPoBLEAdvertisingChange; - advChange.CHIPoBLEAdvertisingChange.Result = kActivity_Stopped; - error = PlatformMgr().PostEvent(&advChange); -#endif - } - - return error; -} - -void BLEManagerCommon::DriveBLEState(void) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - - // Check if BLE stack is initialized - VerifyOrExit(mFlags.Has(Flags::kK32WBLEStackInitialized), err = CHIP_ERROR_INCORRECT_STATE); - - // Start advertising if needed... - if (mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_Enabled && mFlags.Has(Flags::kAdvertisingEnabled)) - { - // Start/re-start advertising if not already started, or if there is a pending change - // to the advertising configuration. - if (!mFlags.Has(Flags::kAdvertising) || mFlags.Has(Flags::kRestartAdvertising)) - { - err = StartAdvertising(); - SuccessOrExit(err); - } - } - // Otherwise, stop advertising if it is enabled. - else if (mFlags.Has(Flags::kAdvertising)) - { - err = StopAdvertising(); - SuccessOrExit(err); - // Reset to fast advertising mode only if SetBLEAdvertisingEnabled(false) was called (usually from app). - mFlags.Set(Flags::kFastAdvertisingEnabled); - } - -exit: - if (err != CHIP_NO_ERROR) - { - ChipLogError(DeviceLayer, "Disabling CHIPoBLE service due to error: %s", ErrorStr(err)); - mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Disabled; - } -} - -void BLEManagerCommon::DriveBLEState(intptr_t arg) -{ - sImplInstance->DriveBLEState(); -} - -void BLEManagerCommon::StopAdvertisingPriorToSwitchingMode(intptr_t arg) -{ - if (CHIP_NO_ERROR != sImplInstance->StopAdvertising()) - { - ChipLogProgress(DeviceLayer, "Failed to stop advertising"); - } -} - -void BLEManagerCommon::DoBleProcessing(void) -{ - blekw_msg_t * msg = NULL; - - while ((xQueueReceive(sBleEventQueue, &msg, 0) == pdTRUE) && msg) - { - if (msg->type == BLE_KW_MSG_ERROR) - { - if (msg->data.u8 == BLE_KW_MSG_2M_UPGRADE_ERROR) - { - ChipLogProgress(DeviceLayer, - "Warning. BLE is using 1Mbps. Couldn't upgrade to 2Mbps, " - "maybe the peer is missing 2Mbps support."); - } - else - { - ChipLogProgress(DeviceLayer, "BLE Error: %d.\n", msg->data.u8); - } - } - else if (msg->type == BLE_KW_MSG_CONNECTED) - { - sImplInstance->HandleConnectEvent(msg); - } - else if (msg->type == BLE_KW_MSG_DISCONNECTED) - { - sImplInstance->HandleConnectionCloseEvent(msg); - } - else if (msg->type == BLE_KW_MSG_MTU_CHANGED) - { - blekw_start_connection_timeout(); - ChipLogProgress(DeviceLayer, "BLE MTU size has been changed to %d.", msg->data.u16); - } - else if (msg->type == BLE_KW_MSG_ATT_WRITTEN || msg->type == BLE_KW_MSG_ATT_LONG_WRITTEN || - msg->type == BLE_KW_MSG_ATT_CCCD_WRITTEN) - { - sImplInstance->HandleWriteEvent(msg); - } - else if (msg->type == BLE_KW_MSG_ATT_READ) - { -#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING - blekw_att_read_data_t * att_rd_data = (blekw_att_read_data_t *) msg->data.data; - if (value_chipoble_c3 == att_rd_data->handle) - sImplInstance->HandleC3ReadRequest(msg); -#endif - } - else if (msg->type == BLE_KW_MSG_FORCE_DISCONNECT) - { - sImplInstance->HandleForceDisconnect(); - } - - /* Free the message from the queue */ - free(msg); - msg = NULL; - } -} - -void BLEManagerCommon::RegisterAppCallbacks(BLECallbackDelegate::GapGenericCallback gapCallback, - BLECallbackDelegate::GattServerCallback gattCallback) -{ - callbackDelegate.gapCallback = gapCallback; - callbackDelegate.gattCallback = gattCallback; -} - -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) - PWR_DisallowDeviceToSleep(); -#endif - - mDeviceId = deviceId; - mDeviceConnected = true; - - blekw_start_connection_timeout(); - PlatformMgr().ScheduleWork(DriveBLEState, 0); -} - -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) - PWR_AllowDeviceToSleep(); -#endif - - mDeviceConnected = false; - - ChipDeviceEvent event; - event.Type = DeviceEventType::kCHIPoBLEConnectionClosed; - event.CHIPoBLEConnectionError.ConId = deviceId; - event.CHIPoBLEConnectionError.Reason = BLE_ERROR_REMOTE_DEVICE_DISCONNECTED; - - CancelBleAdvTimeoutTimer(); - - PlatformMgr().PostEventOrDie(&event); - mFlags.Set(Flags::kRestartAdvertising); - mFlags.Set(Flags::kFastAdvertisingEnabled); - PlatformMgr().ScheduleWork(DriveBLEState, 0); -} - -void BLEManagerCommon::HandleWriteEvent(blekw_msg_t * msg) -{ - blekw_att_written_data_t * att_wr_data = (blekw_att_written_data_t *) msg->data.data; - attErrorCode_t status = gAttErrCodeNoError_c; - -#if CHIP_DEVICE_CHIP0BLE_DEBUG - ChipLogProgress(DeviceLayer, "Attribute write request(device: %d,handle: %d).", att_wr_data->device_id, att_wr_data->handle); -#endif - - blekw_start_connection_timeout(); - - if (value_chipoble_rx == att_wr_data->handle) - { - sImplInstance->HandleRXCharWrite(msg); - } - else if (cccd_chipoble_tx == att_wr_data->handle) - { - sImplInstance->HandleTXCharCCCDWrite(msg); - } - - /* TODO: do we need to send the status also for CCCD_WRITTEN? */ - if (msg->type != BLE_KW_MSG_ATT_CCCD_WRITTEN) - { - bleResult_t res = GattServer_SendAttributeWrittenStatus(att_wr_data->device_id, att_wr_data->handle, status); - - if (res != gBleSuccess_c) - { - ChipLogProgress(DeviceLayer, "GattServer_SendAttributeWrittenStatus returned %d", res); - } - } -} - -void BLEManagerCommon::HandleTXCharCCCDWrite(blekw_msg_t * msg) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - blekw_att_written_data_t * att_wr_data = (blekw_att_written_data_t *) msg->data.data; - ChipDeviceEvent event; - - VerifyOrExit(att_wr_data->length != 0, err = CHIP_ERROR_INCORRECT_STATE); - VerifyOrExit(att_wr_data->data != nullptr, err = CHIP_ERROR_INCORRECT_STATE); - -#if CHIP_DEVICE_CHIP0BLE_DEBUG - ChipLogProgress(DeviceLayer, "CHIPoBLE %s received", *att_wr_data->data ? "subscribe" : "unsubscribe"); -#endif - - if (*att_wr_data->data) - { - if (!mDeviceSubscribed) - { - mDeviceSubscribed = true; - event.Type = DeviceEventType::kCHIPoBLESubscribe; - event.CHIPoBLESubscribe.ConId = att_wr_data->device_id; - err = PlatformMgr().PostEvent(&event); - } - } - else - { - mDeviceSubscribed = false; - event.Type = DeviceEventType::kCHIPoBLEUnsubscribe; - event.CHIPoBLESubscribe.ConId = att_wr_data->device_id; - err = PlatformMgr().PostEvent(&event); - } - -exit: - if (err != CHIP_NO_ERROR) - { - ChipLogError(DeviceLayer, "HandleTXCharCCCDWrite() failed: %s", ErrorStr(err)); - } -} - -void BLEManagerCommon::HandleRXCharWrite(blekw_msg_t * msg) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - System::PacketBufferHandle buf; - blekw_att_written_data_t * att_wr_data = (blekw_att_written_data_t *) msg->data.data; - - VerifyOrExit(att_wr_data->length != 0, err = CHIP_ERROR_INCORRECT_STATE); - VerifyOrExit(att_wr_data->data != nullptr, err = CHIP_ERROR_INCORRECT_STATE); - - // Copy the data to a PacketBuffer. - buf = System::PacketBufferHandle::NewWithData(att_wr_data->data, att_wr_data->length); - VerifyOrExit(!buf.IsNull(), err = CHIP_ERROR_NO_MEMORY); - -#if CHIP_DEVICE_CHIP0BLE_DEBUG - ChipLogDetail(DeviceLayer, - "Write request/command received for" - "CHIPoBLE RX characteristic (con %u, len %u)", - att_wr_data->device_id, buf->DataLength()); -#endif - - // Post an event to the CHIP queue to deliver the data into the CHIP stack. - { - ChipDeviceEvent event; - event.Type = DeviceEventType::kCHIPoBLEWriteReceived; - event.CHIPoBLEWriteReceived.ConId = att_wr_data->device_id; - event.CHIPoBLEWriteReceived.Data = std::move(buf).UnsafeRelease(); - err = PlatformMgr().PostEvent(&event); - } -exit: - if (err != CHIP_NO_ERROR) - { - ChipLogError(DeviceLayer, "HandleRXCharWrite() failed: %s", ErrorStr(err)); - } -} - -void BLEManagerCommon::HandleForceDisconnect() -{ - ChipLogProgress(DeviceLayer, "BLE connection timeout: Forcing disconnection."); - - /* Set the advertising parameters */ - if (Gap_Disconnect(mDeviceId) != gBleSuccess_c) - { - ChipLogProgress(DeviceLayer, "Gap_Disconnect() failed."); - } - -#if defined(chip_with_low_power) && (chip_with_low_power == 1) - PWR_AllowDeviceToSleep(); -#endif -} - -/******************************************************************************* - * BLE stack callbacks - *******************************************************************************/ -void BLEManagerCommon::blekw_generic_cb(gapGenericEvent_t * pGenericEvent) -{ - /* Call BLE Conn Manager */ - BleConnManager_GenericEvent(pGenericEvent); - - if (sImplInstance && sImplInstance->callbackDelegate.gapCallback) - { - sImplInstance->callbackDelegate.gapCallback(pGenericEvent); - } - - switch (pGenericEvent->eventType) - { - case gInternalError_c: - /* Notify the CHIP that the BLE hardware report fail */ - ChipLogProgress(DeviceLayer, "BLE Internal Error: Code 0x%04X, Source 0x%08X, HCI OpCode %d.\n", - pGenericEvent->eventData.internalError.errorCode, pGenericEvent->eventData.internalError.errorSource, - pGenericEvent->eventData.internalError.hciCommandOpcode); - if ((gHciUnsupportedRemoteFeature_c == pGenericEvent->eventData.internalError.errorCode) && - (gLeSetPhy_c == pGenericEvent->eventData.internalError.errorSource)) - { - (void) blekw_msg_add_u8(BLE_KW_MSG_ERROR, BLE_KW_MSG_2M_UPGRADE_ERROR); - } - else - { - (void) blekw_msg_add_u8(BLE_KW_MSG_ERROR, BLE_INTERNAL_ERROR); - } - break; - - case gAdvertisingSetupFailed_c: - xEventGroupSetBits(sEventGroup, CHIP_BLE_KW_EVNT_ADV_SETUP_FAILED); - break; - - case gAdvertisingParametersSetupComplete_c: - xEventGroupSetBits(sEventGroup, CHIP_BLE_KW_EVNT_ADV_PAR_SETUP_COMPLETE); - break; - - case gAdvertisingDataSetupComplete_c: - xEventGroupSetBits(sEventGroup, CHIP_BLE_KW_EVNT_ADV_DAT_SETUP_COMPLETE); - break; - - case gRandomAddressReady_c: - Gap_SetRandomAddress(pGenericEvent->eventData.addrReady.aAddress); - break; - - case gRandomAddressSet_c: - xEventGroupSetBits(sEventGroup, CHIP_BLE_KW_EVNT_RND_ADDR_SET); - break; - -#if BLE_HIGH_TX_POWER - case gTxPowerLevelSetComplete_c: - if (gBleSuccess_c == pGenericEvent->eventData.txPowerLevelSetStatus) - { - xEventGroupSetBits(sEventGroup, CHIP_BLE_KW_EVNT_POWER_LEVEL_SET); - } - break; -#endif - - case gInitializationComplete_c: - /* Common GAP configuration */ - BleConnManager_GapCommonConfig(); - - /* Set the local synchronization event */ - xEventGroupSetBits(sEventGroup, CHIP_BLE_KW_EVNT_INIT_COMPLETE); - break; - default: - break; - } -} - -void BLEManagerCommon::blekw_gap_advertising_cb(gapAdvertisingEvent_t * pAdvertisingEvent) -{ - if (pAdvertisingEvent->eventType == gAdvertisingStateChanged_c) - { - /* Set the local synchronization event */ - xEventGroupSetBits(sEventGroup, CHIP_BLE_KW_EVNT_ADV_CHANGED); - } - else - { - /* The advertisement start failed */ - ChipLogProgress(DeviceLayer, "Advertising failed: event=%d reason=0x%04X\n", pAdvertisingEvent->eventType, - pAdvertisingEvent->eventData.failReason); - - /* Set the local synchronization event */ - xEventGroupSetBits(sEventGroup, CHIP_BLE_KW_EVNT_ADV_FAILED); - } -} - -void BLEManagerCommon::blekw_gap_connection_cb(deviceId_t deviceId, gapConnectionEvent_t * pConnectionEvent) -{ - /* Call BLE Conn Manager */ - BleConnManager_GapPeripheralEvent(deviceId, pConnectionEvent); - - if (pConnectionEvent->eventType == gConnEvtConnected_c) - { -#if CHIP_DEVICE_K32W1 -#if defined(chip_with_low_power) && (chip_with_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(); -#endif -#endif - -#if CHIP_DEVICE_CONFIG_BLE_SET_PHY_2M_REQ - ChipLogProgress(DeviceLayer, "BLE K32W: Trying to set the PHY to 2M"); - - (void) Gap_LeSetPhy(FALSE, deviceId, 0, gConnPhyUpdateReqTxPhySettings_c, gConnPhyUpdateReqRxPhySettings_c, - (uint16_t) gConnPhyUpdateReqPhyOptions_c); -#endif - - /* 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) - PWR_AllowDeviceToSleep(); -#endif - } - else if (pConnectionEvent->eventType == gConnEvtDisconnected_c) - { - blekw_stop_connection_timeout(); - - /* 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 (bleAppStopInProgress == TRUE) - { - bleAppStopInProgress = FALSE; - PWR_AllowDeviceToSleep(); - } -#endif - } - else if (pConnectionEvent->eventType == gConnEvtPairingRequest_c) - { - /* Reject request for pairing */ - Gap_RejectPairing(deviceId, gPairingNotSupported_c); - } - else if (pConnectionEvent->eventType == gConnEvtAuthenticationRejected_c) - { - ChipLogProgress(DeviceLayer, "BLE Authentication rejected (reason:%d).\n", - pConnectionEvent->eventData.authenticationRejectedEvent.rejectReason); - } -} - -void BLEManagerCommon::blekw_connection_timeout_cb(TimerHandle_t timer) -{ - (void) blekw_msg_add_u8(BLE_KW_MSG_FORCE_DISCONNECT, 0); -} - -void BLEManagerCommon::blekw_start_connection_timeout(void) -{ - xTimerReset(connectionTimeout, 0); -} - -void BLEManagerCommon::blekw_stop_connection_timeout(void) -{ - ChipLogProgress(DeviceLayer, "Stopped connectionTimeout timer."); - xTimerStop(connectionTimeout, 0); -} - -void BLEManagerCommon::blekw_gatt_server_cb(deviceId_t deviceId, gattServerEvent_t * pServerEvent) -{ - if (sImplInstance && sImplInstance->callbackDelegate.gattCallback) - { - sImplInstance->callbackDelegate.gattCallback(deviceId, pServerEvent); - } - - switch (pServerEvent->eventType) - { - case gEvtMtuChanged_c: { - uint16_t tempMtu = 0; - - (void) Gatt_GetMtu(deviceId, &tempMtu); - blekw_msg_add_u16(BLE_KW_MSG_MTU_CHANGED, tempMtu); - break; - } - - case gEvtAttributeWritten_c: - blekw_msg_add_att_written(BLE_KW_MSG_ATT_WRITTEN, deviceId, pServerEvent->eventData.attributeWrittenEvent.handle, - pServerEvent->eventData.attributeWrittenEvent.aValue, - pServerEvent->eventData.attributeWrittenEvent.cValueLength); - break; - - case gEvtLongCharacteristicWritten_c: - blekw_msg_add_att_written(BLE_KW_MSG_ATT_LONG_WRITTEN, deviceId, pServerEvent->eventData.longCharWrittenEvent.handle, - pServerEvent->eventData.longCharWrittenEvent.aValue, - pServerEvent->eventData.longCharWrittenEvent.cValueLength); - break; - - case gEvtAttributeRead_c: - blekw_msg_add_att_read(BLE_KW_MSG_ATT_READ, deviceId, pServerEvent->eventData.attributeReadEvent.handle); - break; - - case gEvtCharacteristicCccdWritten_c: { - uint16_t cccd_val = pServerEvent->eventData.charCccdWrittenEvent.newCccd; - - blekw_msg_add_att_written(BLE_KW_MSG_ATT_CCCD_WRITTEN, deviceId, pServerEvent->eventData.charCccdWrittenEvent.handle, - (uint8_t *) &cccd_val, 2); - break; - } - - case gEvtHandleValueConfirmation_c: - /* Set the local synchronization event */ - xEventGroupSetBits(sEventGroup, CHIP_BLE_KW_EVNT_INDICATION_CONFIRMED); - break; - - case gEvtError_c: - if (pServerEvent->eventData.procedureError.procedureType == gSendIndication_c) - { - /* Set the local synchronization event */ - xEventGroupSetBits(sEventGroup, CHIP_BLE_KW_EVNT_INDICATION_FAILED); - } - else - { - ChipLogProgress(DeviceLayer, "BLE Gatt Server Error: Code 0x%04X, Source %d.\n", - pServerEvent->eventData.procedureError.error, pServerEvent->eventData.procedureError.procedureType); - - /* Notify CHIP BLE App Task that the BLE hardware report fail */ - (void) blekw_msg_add_u8(BLE_KW_MSG_ERROR, BLE_INTERNAL_GATT_ERROR); - } - break; - - default: - break; - } -} -/******************************************************************************* - * Add to message queue functions - *******************************************************************************/ -CHIP_ERROR BLEManagerCommon::blekw_msg_add_att_written(blekw_msg_type_t type, uint8_t device_id, uint16_t handle, uint8_t * data, - uint16_t length) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - blekw_msg_t * msg = NULL; - blekw_att_written_data_t * att_wr_data; - - /* Allocate a buffer with enough space to store the packet */ - msg = (blekw_msg_t *) malloc(sizeof(blekw_msg_t) + sizeof(blekw_att_written_data_t) + length); - VerifyOrExit(msg, err = CHIP_ERROR_NO_MEMORY); - - msg->type = type; - msg->length = sizeof(blekw_att_written_data_t) + length; - att_wr_data = (blekw_att_written_data_t *) msg->data.data; - att_wr_data->device_id = device_id; - att_wr_data->handle = handle; - att_wr_data->length = length; - FLib_MemCpy(att_wr_data->data, data, length); - - VerifyOrExit(xQueueSend(sBleEventQueue, &msg, 0) == pdTRUE, err = CHIP_ERROR_NO_MEMORY); - otTaskletsSignalPending(NULL); - -exit: - return err; -} - -CHIP_ERROR BLEManagerCommon::blekw_msg_add_att_read(blekw_msg_type_t type, uint8_t device_id, uint16_t handle) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - blekw_msg_t * msg = NULL; - blekw_att_read_data_t * att_rd_data; - - /* Allocate a buffer with enough space to store the packet */ - msg = (blekw_msg_t *) malloc(sizeof(blekw_msg_t) + sizeof(blekw_att_read_data_t)); - VerifyOrExit(msg, err = CHIP_ERROR_NO_MEMORY); - - msg->type = type; - msg->length = sizeof(blekw_att_read_data_t); - att_rd_data = (blekw_att_read_data_t *) msg->data.data; - att_rd_data->device_id = device_id; - att_rd_data->handle = handle; - - VerifyOrExit(xQueueSend(sBleEventQueue, &msg, 0) == pdTRUE, err = CHIP_ERROR_NO_MEMORY); - otTaskletsSignalPending(NULL); - -exit: - return err; -} - -CHIP_ERROR BLEManagerCommon::blekw_msg_add_u8(blekw_msg_type_t type, uint8_t data) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - blekw_msg_t * msg = NULL; - - /* Allocate a buffer with enough space to store the packet */ - msg = (blekw_msg_t *) malloc(sizeof(blekw_msg_t)); - VerifyOrExit(msg, err = CHIP_ERROR_NO_MEMORY); - - msg->type = type; - msg->length = 0; - msg->data.u8 = data; - - VerifyOrExit(xQueueSend(sBleEventQueue, &msg, 0) == pdTRUE, err = CHIP_ERROR_NO_MEMORY); - otTaskletsSignalPending(NULL); - -exit: - return err; -} - -CHIP_ERROR BLEManagerCommon::blekw_msg_add_u16(blekw_msg_type_t type, uint16_t data) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - blekw_msg_t * msg = NULL; - - /* Allocate a buffer with enough space to store the packet */ - msg = (blekw_msg_t *) malloc(sizeof(blekw_msg_t)); - VerifyOrExit(msg, err = CHIP_ERROR_NO_MEMORY); - - msg->type = type; - msg->length = 0; - msg->data.u16 = data; - - VerifyOrExit(xQueueSend(sBleEventQueue, &msg, 0) == pdTRUE, err = CHIP_ERROR_NO_MEMORY); - otTaskletsSignalPending(NULL); - -exit: - return err; -} - -void BLEManagerCommon::BleAdvTimeoutHandler(TimerHandle_t xTimer) -{ - if (BLEMgrImpl().mFlags.Has(Flags::kFastAdvertisingEnabled)) - { - ChipLogDetail(DeviceLayer, "Start slow advertisement"); - BLEMgr().SetAdvertisingMode(BLEAdvertisingMode::kSlowAdvertising); - } -} - -void BLEManagerCommon::CancelBleAdvTimeoutTimer(void) -{ - if (xTimerStop(sbleAdvTimeoutTimer, 0) == pdFAIL) - { - ChipLogError(DeviceLayer, "Failed to stop BledAdv timeout timer"); - } -} - -void BLEManagerCommon::StartBleAdvTimeoutTimer(uint32_t aTimeoutInMs) -{ - if (xTimerIsTimerActive(sbleAdvTimeoutTimer)) - { - CancelBleAdvTimeoutTimer(); - } - - // timer is not active, change its period to required value (== restart). - // FreeRTOS- Block for a maximum of 100 ticks if the change period command - // cannot immediately be sent to the timer command queue. - if (xTimerChangePeriod(sbleAdvTimeoutTimer, aTimeoutInMs / portTICK_PERIOD_MS, 100) != pdPASS) - { - ChipLogError(DeviceLayer, "Failed to start BledAdv timeout timer"); - } -} - -CHIP_ERROR BLEManagerCommon::blekw_stop_connection_internal(BLE_CONNECTION_OBJECT conId) -{ - ChipLogProgress(DeviceLayer, "Closing BLE GATT connection (con %u)", conId); - - if (Gap_Disconnect(conId) != gBleSuccess_c) - { - ChipLogProgress(DeviceLayer, "Gap_Disconnect() failed."); - return CHIP_ERROR_INTERNAL; - } -#if defined(chip_with_low_power) && (chip_with_low_power == 1) - else - { - bleAppStopInProgress = TRUE; - PWR_DisallowDeviceToSleep(); - } -#endif - - return CHIP_NO_ERROR; -} - -} // namespace Internal -} // namespace DeviceLayer -} // namespace chip -#endif // CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE diff --git a/src/platform/nxp/k32w/common/BLEManagerCommon.h b/src/platform/nxp/k32w/common/BLEManagerCommon.h deleted file mode 100644 index b7fc1275d2..0000000000 --- a/src/platform/nxp/k32w/common/BLEManagerCommon.h +++ /dev/null @@ -1,249 +0,0 @@ -/* - * - * Copyright (c) 2020-2021 Project CHIP Authors - * Copyright (c) 2020 Nest Labs, Inc. - * 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 - * Provides an implementation of the BLEManager singleton object - * for the K32W platforms. - */ - -#pragma once - -#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE - -#include "fsl_os_abstraction.h" - -#include "ble_conn_manager.h" -#include "ble_general.h" -#include "ble_host_task_config.h" -#include "ble_host_tasks.h" -#include "gap_interface.h" -#include "gatt_db_dynamic.h" -#include "gatt_server_interface.h" - -#include "FreeRTOS.h" -#include "event_groups.h" -#include "timers.h" - -namespace chip { -namespace DeviceLayer { -namespace Internal { - -using namespace chip::Ble; - -/** - * A delegate class that can be used by the application to subscribe to BLE events. - */ -struct BLECallbackDelegate -{ - using GapGenericCallback = void (*)(gapGenericEvent_t * event); - using GattServerCallback = void (*)(deviceId_t id, gattServerEvent_t * event); - - GapGenericCallback gapCallback = nullptr; - GattServerCallback gattCallback = nullptr; -}; - -/** - * Base class for different platform implementations (K32W0 and K32W1 for now). - */ -class BLEManagerCommon : public BLEManager, protected BleLayer, private BlePlatformDelegate, private BleApplicationDelegate -{ -protected: - // ===== Members that implement the BLEManager internal interface. - - CHIP_ERROR _Init(void); - CHIP_ERROR _Shutdown() { return CHIP_NO_ERROR; } - CHIPoBLEServiceMode _GetCHIPoBLEServiceMode(void); - CHIP_ERROR _SetCHIPoBLEServiceMode(CHIPoBLEServiceMode val); - bool _IsAdvertisingEnabled(void); - CHIP_ERROR _SetAdvertisingEnabled(bool val); - bool _IsAdvertising(void); - CHIP_ERROR _SetAdvertisingMode(BLEAdvertisingMode mode); - CHIP_ERROR _GetDeviceName(char * buf, size_t bufSize); - CHIP_ERROR _SetDeviceName(const char * deviceName); - uint16_t _NumConnections(void); - void _OnPlatformEvent(const ChipDeviceEvent * event); - - // ===== Members that implement virtual methods on BlePlatformDelegate. - - CHIP_ERROR SubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const Ble::ChipBleUUID * svcId, - const Ble::ChipBleUUID * charId) override; - CHIP_ERROR UnsubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const Ble::ChipBleUUID * svcId, - const Ble::ChipBleUUID * charId) override; - CHIP_ERROR CloseConnection(BLE_CONNECTION_OBJECT conId) override; - uint16_t GetMTU(BLE_CONNECTION_OBJECT conId) const override; - CHIP_ERROR SendIndication(BLE_CONNECTION_OBJECT conId, const Ble::ChipBleUUID * svcId, const Ble::ChipBleUUID * charId, - System::PacketBufferHandle pBuf) override; - CHIP_ERROR SendWriteRequest(BLE_CONNECTION_OBJECT conId, const Ble::ChipBleUUID * svcId, const Ble::ChipBleUUID * charId, - System::PacketBufferHandle pBuf) override; - - // ===== Members that implement virtual methods on BleApplicationDelegate. - - void NotifyChipConnectionClosed(BLE_CONNECTION_OBJECT conId) override; - - // ===== Private members reserved for use by this class only. - - enum class Flags : uint8_t - { - kAdvertisingEnabled = 0x0001, - kFastAdvertisingEnabled = 0x0002, - kAdvertising = 0x0004, - kRestartAdvertising = 0x0008, - kK32WBLEStackInitialized = 0x0010, - kDeviceNameSet = 0x0020, - }; - BitFlags mFlags; - - enum - { - kMaxDeviceNameLength = 16, - kUnusedIndex = 0xFF, - }; - - typedef enum - { - BLE_KW_MSG_ERROR = 0x01, - BLE_KW_MSG_CONNECTED, - BLE_KW_MSG_DISCONNECTED, - BLE_KW_MSG_MTU_CHANGED, - BLE_KW_MSG_ATT_WRITTEN, - BLE_KW_MSG_ATT_LONG_WRITTEN, - BLE_KW_MSG_ATT_READ, - BLE_KW_MSG_ATT_CCCD_WRITTEN, - BLE_KW_MSG_FORCE_DISCONNECT, - } blekw_msg_type_t; - - typedef struct hk_ble_kw_msg_s - { - blekw_msg_type_t type; - uint16_t length; - union - { - uint8_t u8; - uint16_t u16; - uint32_t u32; - uint8_t data[1]; - char * str; - } data; - } blekw_msg_t; - - typedef enum ble_err_t - { - BLE_OK = 0, - BLE_INTERNAL_GATT_ERROR, - BLE_E_SET_ADV_PARAMS, - BLE_E_ADV_PARAMS_FAILED, - BLE_E_SET_ADV_DATA, - BLE_E_ADV_CHANGED, - BLE_E_ADV_FAILED, - BLE_E_ADV_SETUP_FAILED, - BLE_E_START_ADV, - BLE_E_STOP, - BLE_E_FAIL, - BLE_E_START_ADV_FAILED, - BLE_KW_MSG_2M_UPGRADE_ERROR, - BLE_INTERNAL_ERROR, - } ble_err_t; - - typedef struct ble_att_written_data_s - { - uint8_t device_id; - uint16_t handle; - uint16_t length; - uint8_t data[1]; - } blekw_att_written_data_t; - - typedef struct hk_ble_att_read_data_s - { - uint8_t device_id; - uint16_t handle; - } blekw_att_read_data_t; - - CHIPoBLEServiceMode mServiceMode; - char mDeviceName[kMaxDeviceNameLength + 1]; -#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING - chip::System::PacketBufferHandle c3AdditionalDataBufferHandle; -#endif - uint8_t mDeviceId; - bool mDeviceSubscribed = false; - bool mDeviceConnected = false; - - void DriveBLEState(void); - CHIP_ERROR ConfigureAdvertising(void); - CHIP_ERROR ConfigureAdvertisingData(void); - CHIP_ERROR StartAdvertising(void); - CHIP_ERROR StopAdvertising(void); - - void HandleConnectEvent(blekw_msg_t * msg); - void HandleConnectionCloseEvent(blekw_msg_t * msg); - void HandleWriteEvent(blekw_msg_t * msg); - void HandleRXCharWrite(blekw_msg_t * msg); - void HandleTXCharCCCDWrite(blekw_msg_t * msg); - void HandleForceDisconnect(); - -#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING - CHIP_ERROR EncodeAdditionalDataTlv(); - void HandleC3ReadRequest(blekw_msg_t * msg); -#endif - BLEManagerCommon::ble_err_t blekw_send_event(int8_t connection_handle, uint16_t handle, uint8_t * data, uint32_t len); - - static void DriveBLEState(intptr_t arg); - static void StopAdvertisingPriorToSwitchingMode(intptr_t arg); - static void BleAdvTimeoutHandler(TimerHandle_t xTimer); - static void CancelBleAdvTimeoutTimer(void); - static void StartBleAdvTimeoutTimer(uint32_t aTimeoutInMs); - - static void blekw_connection_timeout_cb(TimerHandle_t timer); - static void blekw_generic_cb(gapGenericEvent_t * pGenericEvent); - static void blekw_gatt_server_cb(deviceId_t deviceId, gattServerEvent_t * pServerEvent); - static CHIP_ERROR blekw_msg_add_u8(blekw_msg_type_t type, uint8_t data); - static CHIP_ERROR blekw_msg_add_u16(blekw_msg_type_t type, uint16_t data); - static CHIP_ERROR blekw_msg_add_att_written(blekw_msg_type_t type, uint8_t device_id, uint16_t handle, uint8_t * data, - uint16_t length); - static CHIP_ERROR blekw_msg_add_att_read(blekw_msg_type_t type, uint8_t device_id, uint16_t handle); - static BLEManagerCommon::ble_err_t blekw_start_advertising(gapAdvertisingParameters_t * adv_params, gapAdvertisingData_t * adv, - gapScanResponseData_t * scnrsp); - static BLEManagerCommon::ble_err_t blekw_stop_advertising(void); - static void blekw_gap_advertising_cb(gapAdvertisingEvent_t * pAdvertisingEvent); - static void blekw_gap_connection_cb(deviceId_t deviceId, gapConnectionEvent_t * pConnectionEvent); - static void blekw_start_connection_timeout(void); - static void blekw_stop_connection_timeout(void); - static CHIP_ERROR blekw_stop_connection_internal(BLE_CONNECTION_OBJECT conId); - -public: - virtual CHIP_ERROR InitHostController(BLECallbackDelegate::GapGenericCallback cb_fp) = 0; - virtual BLEManagerCommon * GetImplInstance() = 0; - virtual CHIP_ERROR ResetController() { return CHIP_NO_ERROR; } - void DoBleProcessing(void); - - BLECallbackDelegate callbackDelegate; - void RegisterAppCallbacks(BLECallbackDelegate::GapGenericCallback gapCallback, - BLECallbackDelegate::GattServerCallback gattCallback); -}; - -inline BLEManager::CHIPoBLEServiceMode BLEManagerCommon::_GetCHIPoBLEServiceMode(void) -{ - return mServiceMode; -} - -} // namespace Internal -} // namespace DeviceLayer -} // namespace chip - -#endif // CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE diff --git a/src/platform/nxp/k32w/common/CHIPDevicePlatformRamStorageConfig.h b/src/platform/nxp/k32w/common/CHIPDevicePlatformRamStorageConfig.h deleted file mode 100644 index bcb9ecdd82..0000000000 --- a/src/platform/nxp/k32w/common/CHIPDevicePlatformRamStorageConfig.h +++ /dev/null @@ -1,173 +0,0 @@ -/* - * - * Copyright (c) 2022 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 - * Configuration of RAM storage metadata: key IDs and NVM IDs. - */ - -#pragma once - -/* Base key IDs used when creating new keys for RAM storage instances. */ -/** - * @def kKeyId_Factory - * - * Base key id used for factory RAM storage. - */ -#ifndef kKeyId_Factory -#define kKeyId_Factory (uint8_t) 0x01 -#endif - -/** - * @def kKeyId_Config - * - * Base key id used for config RAM storage. - */ -#ifndef kKeyId_Config -#define kKeyId_Config (uint8_t) 0x02 -#endif - -/** - * @def kKeyId_Counter - * - * Base key id used for counter RAM storage. - */ -#ifndef kKeyId_Counter -#define kKeyId_Counter (uint8_t) 0x03 -#endif - -/** - * @def kKeyId_KvsKeys - * - * Base key id used for KVS keys RAM storage. - */ -#ifndef kKeyId_KvsKeys -#define kKeyId_KvsKeys (uint8_t) 0x04 -#endif - -/** - * @def kKeyId_KvsValues - * - * Base key id used for KVS values RAM storage. - */ -#ifndef kKeyId_KvsValues -#define kKeyId_KvsValues (uint8_t) 0x05 -#endif - -/* PDM IDs used when defining RAM storage instances or RAM buffers (OT). */ -/** - * @def kNvmId_Factory - * - * PDM ID used for factory RAM storage. - */ -#ifndef kNvmId_Factory -#define kNvmId_Factory (uint16_t) 0x5001 -#endif - -/** - * @def kNvmId_Config - * - * PDM ID used for config RAM storage. - */ -#ifndef kNvmId_Config -#define kNvmId_Config (uint16_t) 0x5002 -#endif - -/** - * @def kNvmId_Counter - * - * PDM ID used for counter RAM storage. - */ -#ifndef kNvmId_Counter -#define kNvmId_Counter (uint16_t) 0x5003 -#endif - -/** - * @def kNvmId_KvsKeys - * - * PDM ID used for KVS keys RAM storage. - */ -#ifndef kNvmId_KvsKeys -#define kNvmId_KvsKeys (uint16_t) 0x6000 -#endif - -/** - * @def kNvmId_KvsValues - * - * PDM ID used for KVS values RAM storage. - * KVS buffer can become quite big, so this PDM - * id is used as base id for subsequent PDM ids - * used to store data in chunks of PDM page size. - * This will use the extended search feature, so - * subsequent PDM ids should not be used. - */ -#ifndef kNvmId_KvsValues -#define kNvmId_KvsValues (uint16_t) 0x6001 -#endif - -/** - * @def kNvmId_KvsSubscription - * - * PDM ID used for KVS subscription RAM storage. - * It will store both keys and values for those keys. - */ -#ifndef kNvmId_KvsSubscription -#define kNvmId_KvsSubscription (uint16_t) 0x6100 -#endif - -/** - * @def kNvmId_KvsGroups - * - * PDM ID used for KVS groups RAM storage. - * It will store both keys and values for those keys. - * This will use the extended search feature, so - * subsequent PDM ids should not be used. - */ -#ifndef kNvmId_KvsGroups -#define kNvmId_KvsGroups (uint16_t) 0x6200 -#endif - -/** - * @def kNvmId_OTConfigData - * - * PDM ID used for OT RAM buffer. - */ -#ifndef kNvmId_OTConfigData -#define kNvmId_OTConfigData (uint16_t) 0x4F00 -#endif - -/** - * @def kNvmId_ApplicationBase - * - * Base PDM ID to be used by applications to define their own - * PDM IDs by using an offset. - */ -#ifndef kNvmId_ApplicationBase -#define kNvmId_ApplicationBase (uint16_t) 0xA000 -#endif - -#if CONFIG_CHIP_LOAD_REAL_FACTORY_DATA -/** - * @def kNvmId_FactoryDataBackup - * - * PDM ID used for factory data backup in FactoryDataProvider. - */ -#ifndef kNvmId_FactoryDataBackup -#define kNvmId_FactoryDataBackup (uint16_t) 0x7000 -#endif -#endif // CONFIG_CHIP_LOAD_REAL_FACTORY_DATA diff --git a/src/platform/nxp/k32w/common/FactoryDataProvider.cpp b/src/platform/nxp/k32w/common/FactoryDataProvider.cpp deleted file mode 100644 index dd79b020c8..0000000000 --- a/src/platform/nxp/k32w/common/FactoryDataProvider.cpp +++ /dev/null @@ -1,368 +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. - */ - -#if (!CONFIG_CHIP_LOAD_REAL_FACTORY_DATA || !(defined CONFIG_CHIP_LOAD_REAL_FACTORY_DATA)) -#include -#include -#include -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -namespace chip { -namespace DeviceLayer { - -static constexpr size_t kSpake2pSerializedVerifier_MaxBase64Len = - BASE64_ENCODED_LEN(chip::Crypto::kSpake2p_VerifierSerialized_Length) + 1; -static constexpr size_t kSpake2pSalt_MaxBase64Len = BASE64_ENCODED_LEN(chip::Crypto::kSpake2p_Max_PBKDF_Salt_Length) + 1; -/* Secure subsystem private key blob size is 32 + 24 = 56. - * DAC private key may be used to store an SSS exported blob instead of the private key. - */ -static constexpr size_t kDacPrivateKey_MaxLen = Crypto::kP256_PrivateKey_Length + 24; - -uint32_t FactoryDataProvider::kFactoryDataStart = (uint32_t) __MATTER_FACTORY_DATA_START; -uint32_t FactoryDataProvider::kFactoryDataSize = (uint32_t) __MATTER_FACTORY_DATA_SIZE; -uint32_t FactoryDataProvider::kFactoryDataPayloadStart = kFactoryDataStart + sizeof(FactoryDataProvider::Header); - -FactoryDataProvider::~FactoryDataProvider() {} - -CHIP_ERROR FactoryDataProvider::Validate() -{ - uint8_t output[Crypto::kSHA256_Hash_Length] = { 0 }; - - memcpy(&mHeader, (void *) kFactoryDataStart, sizeof(Header)); - ReturnErrorCodeIf(mHeader.hashId != kHashId, CHIP_FACTORY_DATA_HASH_ID); - - ReturnErrorOnFailure(Crypto::Hash_SHA256((uint8_t *) kFactoryDataPayloadStart, mHeader.size, output)); - ReturnErrorCodeIf(memcmp(output, mHeader.hash, kHashLen) != 0, CHIP_FACTORY_DATA_SHA_CHECK); - - return CHIP_NO_ERROR; -} - -CHIP_ERROR FactoryDataProvider::SearchForId(uint8_t searchedType, uint8_t * pBuf, size_t bufLength, uint16_t & length, - uint32_t * offset) -{ - uint32_t addr = kFactoryDataPayloadStart; - uint8_t type = 0; - - while (addr < (kFactoryDataPayloadStart + mHeader.size)) - { - memcpy(&type, (void *) addr, sizeof(type)); - memcpy(&length, (void *) (addr + 1), sizeof(length)); - - if (searchedType == type) - { - ReturnErrorCodeIf(bufLength < length, CHIP_ERROR_BUFFER_TOO_SMALL); - memcpy(pBuf, (void *) (addr + kValueOffset), length); - - if (offset) - *offset = (addr - kFactoryDataPayloadStart); - - return CHIP_NO_ERROR; - } - else - { - /* Jump past 3 bytes of length and then use length to jump to next data */ - addr = addr + kValueOffset + length; - } - } - - return CHIP_ERROR_NOT_FOUND; -} - -CHIP_ERROR FactoryDataProvider::GetCertificationDeclaration(MutableByteSpan & outBuffer) -{ -#if CHIP_USE_DEVICE_CONFIG_CERTIFICATION_DECLARATION - constexpr uint8_t kCdForAllExamples[] = CHIP_DEVICE_CONFIG_CERTIFICATION_DECLARATION; - - return CopySpanToMutableSpan(ByteSpan{ kCdForAllExamples }, outBuffer); -#else - uint16_t declarationSize = 0; - ReturnErrorOnFailure(SearchForId(FactoryDataId::kCertDeclarationId, outBuffer.data(), outBuffer.size(), declarationSize)); - outBuffer.reduce_size(declarationSize); - - return CHIP_NO_ERROR; -#endif -} - -CHIP_ERROR FactoryDataProvider::GetFirmwareInformation(MutableByteSpan & out_firmware_info_buffer) -{ - return CHIP_NO_ERROR; -} - -CHIP_ERROR FactoryDataProvider::GetDeviceAttestationCert(MutableByteSpan & outBuffer) -{ - uint16_t certificateSize = 0; - ReturnErrorOnFailure(SearchForId(FactoryDataId::kDacCertificateId, outBuffer.data(), outBuffer.size(), certificateSize)); - outBuffer.reduce_size(certificateSize); - return CHIP_NO_ERROR; -} - -CHIP_ERROR FactoryDataProvider::GetProductAttestationIntermediateCert(MutableByteSpan & outBuffer) -{ - uint16_t certificateSize = 0; - ReturnErrorOnFailure(SearchForId(FactoryDataId::kPaiCertificateId, outBuffer.data(), outBuffer.size(), certificateSize)); - outBuffer.reduce_size(certificateSize); - return CHIP_NO_ERROR; -} - -CHIP_ERROR FactoryDataProvider::SignWithDeviceAttestationKey(const ByteSpan & messageToSign, MutableByteSpan & outSignBuffer) -{ - return SignWithDacKey(messageToSign, outSignBuffer); -} - -CHIP_ERROR FactoryDataProvider::GetSetupDiscriminator(uint16_t & setupDiscriminator) -{ - uint32_t discriminator = 0; - uint16_t temp = 0; - - ReturnErrorOnFailure(SearchForId(FactoryDataId::kDiscriminatorId, (uint8_t *) &discriminator, sizeof(discriminator), temp)); - setupDiscriminator = (uint16_t) (discriminator & 0x0000FFFF); - - return CHIP_NO_ERROR; -} - -CHIP_ERROR FactoryDataProvider::SetSetupDiscriminator(uint16_t setupDiscriminator) -{ - return CHIP_ERROR_NOT_IMPLEMENTED; -} - -CHIP_ERROR FactoryDataProvider::GetSpake2pIterationCount(uint32_t & iterationCount) -{ - uint16_t temp = 0; - ReturnErrorOnFailure(SearchForId(FactoryDataId::kIcId, (uint8_t *) &iterationCount, sizeof(iterationCount), temp)); - - return CHIP_NO_ERROR; -} - -CHIP_ERROR FactoryDataProvider::GetSpake2pSalt(MutableByteSpan & saltBuf) -{ - char saltB64[kSpake2pSalt_MaxBase64Len] = { 0 }; - uint16_t saltB64Len = 0; - - ReturnErrorOnFailure(SearchForId(FactoryDataId::kSaltId, (uint8_t *) (&saltB64[0]), sizeof(saltB64), saltB64Len)); - size_t saltLen = chip::Base64Decode32(saltB64, saltB64Len, reinterpret_cast(saltB64)); - - ReturnErrorCodeIf(saltLen > saltBuf.size(), CHIP_ERROR_BUFFER_TOO_SMALL); - memcpy(saltBuf.data(), saltB64, saltLen); - saltBuf.reduce_size(saltLen); - - return CHIP_NO_ERROR; -} - -CHIP_ERROR FactoryDataProvider::GetSpake2pVerifier(MutableByteSpan & verifierBuf, size_t & verifierLen) -{ - char verifierB64[kSpake2pSerializedVerifier_MaxBase64Len] = { 0 }; - uint16_t verifierB64Len = 0; - ReturnErrorOnFailure(SearchForId(FactoryDataId::kVerifierId, (uint8_t *) &verifierB64[0], sizeof(verifierB64), verifierB64Len)); - - verifierLen = chip::Base64Decode32(verifierB64, verifierB64Len, reinterpret_cast(verifierB64)); - ReturnErrorCodeIf(verifierLen > verifierBuf.size(), CHIP_ERROR_BUFFER_TOO_SMALL); - memcpy(verifierBuf.data(), verifierB64, verifierLen); - verifierBuf.reduce_size(verifierLen); - - return CHIP_NO_ERROR; -} - -CHIP_ERROR FactoryDataProvider::GetSetupPasscode(uint32_t & setupPasscode) -{ - uint16_t length = 0; - ReturnErrorOnFailure(SearchForId(FactoryDataId::kSetupPasscodeId, (uint8_t *) &setupPasscode, sizeof(setupPasscode), length)); - - return CHIP_NO_ERROR; -} - -CHIP_ERROR FactoryDataProvider::SetSetupPasscode(uint32_t setupPasscode) -{ - return CHIP_ERROR_NOT_IMPLEMENTED; -} - -CHIP_ERROR FactoryDataProvider::GetVendorName(char * buf, size_t bufSize) -{ - uint16_t length = 0; - ReturnErrorOnFailure(SearchForId(FactoryDataId::kVendorNameId, (uint8_t *) buf, bufSize, length)); - buf[length] = '\0'; - - return CHIP_NO_ERROR; -} - -CHIP_ERROR FactoryDataProvider::GetVendorId(uint16_t & vendorId) -{ - uint16_t length = 0; - ReturnErrorOnFailure(SearchForId(FactoryDataId::kVidId, (uint8_t *) &vendorId, sizeof(vendorId), length)); - - return CHIP_NO_ERROR; -} - -CHIP_ERROR FactoryDataProvider::GetProductName(char * buf, size_t bufSize) -{ - uint16_t length = 0; - ReturnErrorOnFailure(SearchForId(FactoryDataId::kProductNameId, (uint8_t *) buf, bufSize, length)); - buf[length] = '\0'; - - return CHIP_NO_ERROR; -} - -CHIP_ERROR FactoryDataProvider::GetProductId(uint16_t & productId) -{ - uint16_t length = 0; - ReturnErrorOnFailure(SearchForId(FactoryDataId::kPidId, (uint8_t *) &productId, sizeof(productId), length)); - - return CHIP_NO_ERROR; -} - -CHIP_ERROR FactoryDataProvider::GetPartNumber(char * buf, size_t bufSize) -{ - uint16_t length = 0; - ReturnErrorOnFailure(SearchForId(FactoryDataId::kPartNumber, (uint8_t *) buf, bufSize, length)); - buf[length] = '\0'; - - return CHIP_NO_ERROR; -} - -CHIP_ERROR FactoryDataProvider::GetProductURL(char * buf, size_t bufSize) -{ - uint16_t length = 0; - ReturnErrorOnFailure(SearchForId(FactoryDataId::kProductURL, (uint8_t *) buf, bufSize, length)); - buf[length] = '\0'; - - return CHIP_NO_ERROR; -} - -CHIP_ERROR FactoryDataProvider::GetProductLabel(char * buf, size_t bufSize) -{ - uint16_t length = 0; - ReturnErrorOnFailure(SearchForId(FactoryDataId::kProductLabel, (uint8_t *) buf, bufSize, length)); - buf[length] = '\0'; - - return CHIP_NO_ERROR; -} - -CHIP_ERROR FactoryDataProvider::GetSerialNumber(char * buf, size_t bufSize) -{ - uint16_t length = 0; - ReturnErrorOnFailure(SearchForId(FactoryDataId::kSerialNumberId, (uint8_t *) buf, bufSize, length)); - buf[length] = '\0'; - - return CHIP_NO_ERROR; -} - -CHIP_ERROR FactoryDataProvider::GetManufacturingDate(uint16_t & year, uint8_t & month, uint8_t & day) -{ - uint16_t length = 0; - uint8_t date[ConfigurationManager::kMaxManufacturingDateLength]; - - ReturnErrorOnFailure( - SearchForId(FactoryDataId::kManufacturingDateId, date, ConfigurationManager::kMaxManufacturingDateLength, length)); - date[length] = '\0'; - - if (length == 10 && isdigit(date[0]) && isdigit(date[1]) && isdigit(date[2]) && isdigit(date[3]) && date[4] == '-' && - isdigit(date[5]) && isdigit(date[6]) && date[7] == '-' && isdigit(date[8]) && isdigit(date[9])) - { - year = 1000 * (date[0] - '0') + 100 * (date[1] - '0') + 10 * (date[2] - '0') + date[3] - '0'; - month = 10 * (date[5] - '0') + date[6] - '0'; - day = 10 * (date[8] - '0') + date[9] - '0'; - } - else - { - ChipLogError(DeviceLayer, "Manufacturing date is not formatted correctly: YYYY-MM-DD."); - return CHIP_ERROR_INVALID_ARGUMENT; - } - - return CHIP_NO_ERROR; -} - -CHIP_ERROR FactoryDataProvider::GetHardwareVersion(uint16_t & hardwareVersion) -{ - uint16_t length = 0; - ReturnErrorOnFailure( - SearchForId(FactoryDataId::kHardwareVersionId, (uint8_t *) &hardwareVersion, sizeof(hardwareVersion), length)); - - return CHIP_NO_ERROR; -} - -CHIP_ERROR FactoryDataProvider::GetHardwareVersionString(char * buf, size_t bufSize) -{ - uint16_t length = 0; - ReturnErrorOnFailure(SearchForId(FactoryDataId::kHardwareVersionStrId, (uint8_t *) buf, bufSize, length)); - buf[length] = '\0'; - - return CHIP_NO_ERROR; -} - -CHIP_ERROR FactoryDataProvider::GetRotatingDeviceIdUniqueId(MutableByteSpan & uniqueIdSpan) -{ - CHIP_ERROR err = CHIP_ERROR_NOT_IMPLEMENTED; -#if CHIP_ENABLE_ROTATING_DEVICE_ID - static_assert(ConfigurationManager::kRotatingDeviceIDUniqueIDLength >= ConfigurationManager::kMinRotatingDeviceIDUniqueIDLength, - "Length of unique ID for rotating device ID is smaller than minimum."); - uint16_t uniqueIdLen = 0; - err = SearchForId(FactoryDataId::kUniqueId, (uint8_t *) uniqueIdSpan.data(), uniqueIdSpan.size(), uniqueIdLen); -#if defined(CHIP_DEVICE_CONFIG_ROTATING_DEVICE_ID_UNIQUE_ID) - if (err != CHIP_NO_ERROR) - { - constexpr uint8_t uniqueId[] = CHIP_DEVICE_CONFIG_ROTATING_DEVICE_ID_UNIQUE_ID; - - ReturnErrorCodeIf(sizeof(uniqueId) > uniqueIdSpan.size(), CHIP_ERROR_BUFFER_TOO_SMALL); - memcpy(uniqueIdSpan.data(), uniqueId, sizeof(uniqueId)); - uniqueIdLen = sizeof(uniqueId); - err = CHIP_NO_ERROR; - } -#endif // CHIP_DEVICE_CONFIG_ROTATING_DEVICE_ID_UNIQUE_ID - ReturnErrorOnFailure(err); - uniqueIdSpan.reduce_size(uniqueIdLen); -#endif - - return err; -} - -CHIP_ERROR FactoryDataProvider::GetProductFinish(app::Clusters::BasicInformation::ProductFinishEnum * finish) -{ - uint8_t productFinish; - uint16_t length = 0; - auto err = SearchForId(FactoryDataId::kProductFinish, &productFinish, sizeof(productFinish), length); - ReturnErrorCodeIf(err != CHIP_NO_ERROR, CHIP_ERROR_NOT_IMPLEMENTED); - - *finish = static_cast(productFinish); - - return CHIP_NO_ERROR; -} - -CHIP_ERROR FactoryDataProvider::GetProductPrimaryColor(app::Clusters::BasicInformation::ColorEnum * primaryColor) -{ - uint8_t color; - uint16_t length = 0; - auto err = SearchForId(FactoryDataId::kProductPrimaryColor, &color, sizeof(color), length); - ReturnErrorCodeIf(err != CHIP_NO_ERROR, CHIP_ERROR_NOT_IMPLEMENTED); - - *primaryColor = static_cast(color); - - return CHIP_NO_ERROR; -} - -} // namespace DeviceLayer -} // namespace chip diff --git a/src/platform/nxp/k32w/common/FactoryDataProvider.h b/src/platform/nxp/k32w/common/FactoryDataProvider.h deleted file mode 100644 index 03ccf370f7..0000000000 --- a/src/platform/nxp/k32w/common/FactoryDataProvider.h +++ /dev/null @@ -1,151 +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 -#include -#include -#include - -#include - -#include "CHIPPlatformConfig.h" - -#include - -/* Grab symbol for the base address from the linker file. */ -extern uint32_t __MATTER_FACTORY_DATA_START[]; -extern uint32_t __MATTER_FACTORY_DATA_SIZE[]; - -namespace chip { -namespace DeviceLayer { - -#define CHIP_FACTORY_DATA_ERROR(e) \ - ChipError(ChipError::Range::kLastRange, ((uint8_t) ChipError::Range::kLastRange << 2) | e, __FILE__, __LINE__) - -#define CHIP_FACTORY_DATA_SHA_CHECK CHIP_FACTORY_DATA_ERROR(0x01) -#define CHIP_FACTORY_DATA_HEADER_READ CHIP_FACTORY_DATA_ERROR(0x02) -#define CHIP_FACTORY_DATA_HASH_ID CHIP_FACTORY_DATA_ERROR(0x03) -#define CHIP_FACTORY_DATA_PDM_RESTORE CHIP_FACTORY_DATA_ERROR(0x04) -#define CHIP_FACTORY_DATA_NULL CHIP_FACTORY_DATA_ERROR(0x05) -#define CHIP_FACTORY_DATA_FLASH_ERASE CHIP_FACTORY_DATA_ERROR(0x06) -#define CHIP_FACTORY_DATA_FLASH_PROGRAM CHIP_FACTORY_DATA_ERROR(0x07) -#define CHIP_FACTORY_DATA_INTERNAL_FLASH_READ CHIP_FACTORY_DATA_ERROR(0x08) -#define CHIP_FACTORY_DATA_PDM_SAVE_RECORD CHIP_FACTORY_DATA_ERROR(0x09) -#define CHIP_FACTORY_DATA_PDM_READ_RECORD CHIP_FACTORY_DATA_ERROR(0x0A) -#define CHIP_FACTORY_DATA_RESTORE_MECHANISM CHIP_FACTORY_DATA_ERROR(0x0B) - -/** - * @brief This class provides Commissionable data, Device Attestation Credentials, - * and Device Instance Info. - */ - -class FactoryDataProvider : public DeviceInstanceInfoProvider, - public CommissionableDataProvider, - public Credentials::DeviceAttestationCredentialsProvider -{ -public: - struct Header - { - uint32_t hashId; - uint32_t size; - uint8_t hash[4]; - }; - - // Default factory data IDs - enum FactoryDataId - { - kVerifierId = 1, - kSaltId, - kIcId, - kDacPrivateKeyId, - kDacCertificateId, - kPaiCertificateId, - kDiscriminatorId, - kSetupPasscodeId, - kVidId, - kPidId, - kCertDeclarationId, - kVendorNameId, - kProductNameId, - kSerialNumberId, - kManufacturingDateId, - kHardwareVersionId, - kHardwareVersionStrId, - kUniqueId, - kPartNumber, - kProductURL, - kProductLabel, - kProductFinish, - kProductPrimaryColor, - kMaxId - }; - - static uint32_t kFactoryDataStart; - static uint32_t kFactoryDataSize; - static uint32_t kFactoryDataPayloadStart; - static constexpr uint32_t kLengthOffset = 1; - static constexpr uint32_t kValueOffset = 3; - static constexpr uint32_t kHashLen = 4; - static constexpr size_t kHashId = 0xCE47BA5E; - - virtual ~FactoryDataProvider(); - - virtual CHIP_ERROR Init() = 0; - virtual CHIP_ERROR SignWithDacKey(const ByteSpan & messageToSign, MutableByteSpan & outSignBuffer) = 0; - CHIP_ERROR Validate(); - - CHIP_ERROR SearchForId(uint8_t searchedType, uint8_t * pBuf, size_t bufLength, uint16_t & length, uint32_t * offset = nullptr); - - // ===== Members functions that implement the CommissionableDataProvider - CHIP_ERROR GetSetupDiscriminator(uint16_t & setupDiscriminator) override; - CHIP_ERROR SetSetupDiscriminator(uint16_t setupDiscriminator) override; - CHIP_ERROR GetSpake2pIterationCount(uint32_t & iterationCount) override; - CHIP_ERROR GetSpake2pSalt(MutableByteSpan & saltBuf) override; - CHIP_ERROR GetSpake2pVerifier(MutableByteSpan & verifierBuf, size_t & verifierLen) override; - CHIP_ERROR GetSetupPasscode(uint32_t & setupPasscode) override; - CHIP_ERROR SetSetupPasscode(uint32_t setupPasscode) override; - - // ===== Members functions that implement the DeviceAttestationCredentialsProvider - CHIP_ERROR GetCertificationDeclaration(MutableByteSpan & outBuffer) override; - CHIP_ERROR GetFirmwareInformation(MutableByteSpan & out_firmware_info_buffer) override; - CHIP_ERROR GetDeviceAttestationCert(MutableByteSpan & outBuffer) override; - CHIP_ERROR GetProductAttestationIntermediateCert(MutableByteSpan & outBuffer) override; - CHIP_ERROR SignWithDeviceAttestationKey(const ByteSpan & messageToSign, MutableByteSpan & outSignBuffer) override; - - // ===== Members functions that implement the GenericDeviceInstanceInfoProvider - CHIP_ERROR GetVendorName(char * buf, size_t bufSize) override; - CHIP_ERROR GetVendorId(uint16_t & vendorId) override; - CHIP_ERROR GetProductName(char * buf, size_t bufSize) override; - CHIP_ERROR GetProductId(uint16_t & productId) override; - CHIP_ERROR GetPartNumber(char * buf, size_t bufSize) override; - CHIP_ERROR GetProductURL(char * buf, size_t bufSize) override; - CHIP_ERROR GetProductLabel(char * buf, size_t bufSize) override; - CHIP_ERROR GetHardwareVersionString(char * buf, size_t bufSize) override; - CHIP_ERROR GetSerialNumber(char * buf, size_t bufSize) override; - CHIP_ERROR GetManufacturingDate(uint16_t & year, uint8_t & month, uint8_t & day) override; - CHIP_ERROR GetHardwareVersion(uint16_t & hardwareVersion) override; - CHIP_ERROR GetRotatingDeviceIdUniqueId(MutableByteSpan & uniqueIdSpan) override; - CHIP_ERROR GetProductFinish(app::Clusters::BasicInformation::ProductFinishEnum * finish) override; - CHIP_ERROR GetProductPrimaryColor(app::Clusters::BasicInformation::ColorEnum * primaryColor) override; - -protected: - Header mHeader; -}; - -} // namespace DeviceLayer -} // namespace chip diff --git a/src/platform/nxp/k32w/common/K32W_OTA_README.md b/src/platform/nxp/k32w/common/K32W_OTA_README.md deleted file mode 100644 index 0c9715b461..0000000000 --- a/src/platform/nxp/k32w/common/K32W_OTA_README.md +++ /dev/null @@ -1,149 +0,0 @@ -# K32W OTA - -The OTA processing is now delegated to instances of `OTATlvProcessor` derived -classes. These instances are registered with the `OTAImageProcessorImpl` -instance, which manages the selection of processors that should process the next -blocks, until a full TLV block was transferred. - -The application is able to define its own processors, thus extending the default -OTA functionality. The application can also opt to disable the default -processors (application, SSBL and factory data). - -Please note that if an OTA image containing multiple TLV is transferred, then -the action for each TLV is applied sequentially, If one of the actions fails, -the remaining actions will not be applied and OTA abort is called. TBD: should -all actions be applied only if there is no error? Or should each action be -applied separately? - -## Default processors - -The default processors for K32W0 are already implemented in: - -- `OTAFirmwareProcessor` for application/SSBL update. Enabled by default. -- `OTAFactoryDataProcessor` for factory data update. Disabled by default, user - has to specify `chip_ota_enable_factory_data_processor=1` in the build args. - -Some SDK OTA module flags are defined to support additional features: - -- `gOTAAllowCustomStartAddress=1` - enable `EEPROM` offset value. Used - internally by SDK OTA module. -- `gOTAUseCustomOtaEntry=1` - support custom OTA entry for multi-image. -- `gOTACustomOtaEntryMemory=1` - K32W0 uses `OTACustomStorage_ExtFlash` (1) by - default. - -## Implementing custom processors - -A custom processor should implement the abstract interface defined in -`OTATlvProcessor.h`. Below is a compact version: - -``` -class OTATlvProcessor -{ -public: - virtual CHIP_ERROR Init() = 0; - virtual CHIP_ERROR Clear() = 0; - virtual CHIP_ERROR ApplyAction() = 0; - virtual CHIP_ERROR AbortAction() = 0; - virtual CHIP_ERROR ExitAction(); - - CHIP_ERROR Process(ByteSpan & block); - void RegisterDescriptorCallback(ProcessDescriptor callback); -protected: - virtual CHIP_ERROR ProcessInternal(ByteSpan & block) = 0; -}; - -``` - -Some details regarding the interface: - -- `Init` will be called whenever the processor is selected. -- `Clear` will be called when abort occurs or after the apply action takes - place. -- `ApplyAction` will be called in `OTAImageProcessorImpl::HandleApply`, before - the board is reset. -- `AbortAction` will be called in `OTAImageProcessorImpl::HandleAbort`. - Processors should reset state here. -- `ExitAction` is optional and should be implemented by the processors that - want to execute an action after all data has been transferred, but before - `HandleApply` is called. It's called before the new processor selection - takes place. This is useful in the context of multiple TLV transferred in a - single OTA process. -- `Process` is the public API used inside `OTAImageProcessorImpl` for data - processing. This is a wrapper over `ProcessInternal`, which can return - `CHIP_OTA_CHANGE_PROCESSOR` to notify a new processor should be selected for - the remaining data. -- `RegisterDescriptorCallback` can be used to register a callback for - processing the descriptor. It's optional. -- `ProcessInternal` should return: _ `CHIP_NO_ERROR` if block was processed - successfully. _ `CHIP_ERROR_BUFFER_TOO_SMALL` if current block doesn't - contain all necessary data. This can happen when a TLV value field has a - header, but it is split across two blocks. \* - `CHIP_OTA_FETCH_ALREADY_SCHEDULED` if block was processed successfully and - the fetching is already scheduled by the processor. This happens in the - default application processor, because the next data fetching is scheduled - through a callback (called when enough external flash was erased). - -Furthermore, a processor can use an instance of `OTADataAccumulator` to -accumulate data until a given threshold. This is useful when a custom payload -contains metadata that need parsing: accumulate data until the threshold is -reached or return `CHIP_ERROR_BUFFER_TOO_SMALL` to signal -`OTAImageProcessorImpl` more data is needed. - -``` -/** - * This class can be used to accumulate data until a given threshold. - * Should be used by OTATlvProcessor derived classes if they need - * metadata accumulation (e.g. for custom header decoding). - */ -class OTADataAccumulator -{ -public: - void Init(uint32_t threshold); - void Clear(); - CHIP_ERROR Accumulate(ByteSpan & block); - - inline uint8_t* data() { return mBuffer.Get(); } - -private: - uint32_t mThreshold; - uint32_t mBufferOffset; - Platform::ScopedMemoryBuffer mBuffer; -}; -``` - -## SSBL max entries example - -`CONFIG_CHIP_K32W0_MAX_ENTRIES_TEST` can be set to 1 to enable max entries test. -There will be 8 additional processors registered in default `OtaHooks` -implementation. The OTA image should be generated with the -`create_ota_images.sh` script from `./scripts/tools/nxp/ota/examples`. - -## Factory data restore mechanism - -Prior to factory data update, the old factory data is backed up in external -flash. If anything interrupts the update (e.g. power loss), there is a slight -chance the internal flash factory data section is erased and has to be restored -at next boot. The `FactoryDataProvider` offers a default restore mechanism and -support for registering additional restore mechanisms or overwriting the default -one. - -Prior to factory data update, the old factory data is backed up in external -flash. If anything interrupts the update (e.g. power loss), there is a slight -chance the internal flash factory data section is erased and has to be restored -at next boot. The `FactoryDataProvider` offers a default restore mechanism and -support for registering additional restore mechanisms or overwriting the default -one. - -Restore mechanisms are just functions that have this signature: -`CHIP_ERROR (*)(void)`. Any such function can be registered through -`FactoryDataProvider::RegisterRestoreMechanism`. - -The default restore mechanism is implemented as a weak function: -`FactoryDataDefaultRestoreMechanism`. It is registered in -`FactoryDataProvider::Init`, before factory data validation, and it can be -overwritten at application level. When doing the actual restore, the mechanisms -are called in the order they were registered. - -Please note that the restore mechanisms registration order matters. Once a -restore mechanism is successful (`CHIP_NO_ERROR` is returned), the restore -process has finished and subsequent restore mechanisms will not be called. diff --git a/src/platform/nxp/k32w/common/OTAImageProcessorImpl.cpp b/src/platform/nxp/k32w/common/OTAImageProcessorImpl.cpp deleted file mode 100644 index e972550c53..0000000000 --- a/src/platform/nxp/k32w/common/OTAImageProcessorImpl.cpp +++ /dev/null @@ -1,424 +0,0 @@ -/* - * - * Copyright (c) 2021-2023 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 - -using namespace chip::DeviceLayer; -using namespace ::chip::DeviceLayer::Internal; - -#if USE_SMU2_STATIC -// The attribute specifier should not be changed. -static chip::OTAImageProcessorImpl gImageProcessor __attribute__((section(".smu2"))); -#else -static chip::OTAImageProcessorImpl gImageProcessor; -#endif - -namespace chip { - -CHIP_ERROR OTAImageProcessorImpl::Init(OTADownloader * downloader) -{ - ReturnErrorCodeIf(downloader == nullptr, CHIP_ERROR_INVALID_ARGUMENT); - mDownloader = downloader; - - OtaHookInit(); - - return CHIP_NO_ERROR; -} - -void OTAImageProcessorImpl::Clear() -{ - mHeaderParser.Clear(); - mAccumulator.Clear(); - mParams.totalFileBytes = 0; - mParams.downloadedBytes = 0; - mCurrentProcessor = nullptr; - - ReleaseBlock(); -} - -CHIP_ERROR OTAImageProcessorImpl::PrepareDownload() -{ - DeviceLayer::PlatformMgr().ScheduleWork(HandlePrepareDownload, reinterpret_cast(this)); - return CHIP_NO_ERROR; -} - -CHIP_ERROR OTAImageProcessorImpl::Finalize() -{ - DeviceLayer::PlatformMgr().ScheduleWork(HandleFinalize, reinterpret_cast(this)); - return CHIP_NO_ERROR; -} - -CHIP_ERROR OTAImageProcessorImpl::Apply() -{ - DeviceLayer::PlatformMgr().ScheduleWork(HandleApply, reinterpret_cast(this)); - return CHIP_NO_ERROR; -} - -CHIP_ERROR OTAImageProcessorImpl::Abort() -{ - DeviceLayer::PlatformMgr().ScheduleWork(HandleAbort, reinterpret_cast(this)); - return CHIP_NO_ERROR; -} - -CHIP_ERROR OTAImageProcessorImpl::ProcessBlock(ByteSpan & block) -{ - if ((block.data() == nullptr) || block.empty()) - { - return CHIP_ERROR_INVALID_ARGUMENT; - } - - // Store block data for HandleProcessBlock to access - CHIP_ERROR err = SetBlock(block); - if (err != CHIP_NO_ERROR) - { - ChipLogError(SoftwareUpdate, "Cannot set block data: %" CHIP_ERROR_FORMAT, err.Format()); - } - - DeviceLayer::PlatformMgr().ScheduleWork(HandleProcessBlock, reinterpret_cast(this)); - return CHIP_NO_ERROR; -} - -void OTAImageProcessorImpl::HandlePrepareDownload(intptr_t context) -{ - auto * imageProcessor = reinterpret_cast(context); - - VerifyOrReturn(imageProcessor != nullptr, ChipLogError(SoftwareUpdate, "ImageProcessor context is null")); - - VerifyOrReturn(imageProcessor->mDownloader != nullptr, ChipLogError(SoftwareUpdate, "mDownloader is null")); - - GetRequestorInstance()->GetProviderLocation(imageProcessor->mBackupProviderLocation); - - imageProcessor->mHeaderParser.Init(); - imageProcessor->mAccumulator.Init(sizeof(OTATlvHeader)); - imageProcessor->mDownloader->OnPreparedForDownload(CHIP_NO_ERROR); -} - -CHIP_ERROR OTAImageProcessorImpl::ProcessHeader(ByteSpan & block) -{ - OTAImageHeader header; - ReturnErrorOnFailure(mHeaderParser.AccumulateAndDecode(block, header)); - - mParams.totalFileBytes = header.mPayloadSize; - mHeaderParser.Clear(); - ChipLogError(SoftwareUpdate, "Processed header successfully"); - - return CHIP_NO_ERROR; -} - -CHIP_ERROR OTAImageProcessorImpl::ProcessPayload(ByteSpan & block) -{ - CHIP_ERROR status = CHIP_NO_ERROR; - - while (true) - { - if (!mCurrentProcessor) - { - ReturnErrorOnFailure(mAccumulator.Accumulate(block)); - ByteSpan tlvHeader{ mAccumulator.data(), sizeof(OTATlvHeader) }; - ReturnErrorOnFailure(SelectProcessor(tlvHeader)); - ReturnErrorOnFailure(mCurrentProcessor->Init()); - } - - status = mCurrentProcessor->Process(block); - if (status == CHIP_ERROR_OTA_CHANGE_PROCESSOR) - { - mAccumulator.Clear(); - mAccumulator.Init(sizeof(OTATlvHeader)); - - mCurrentProcessor = nullptr; - - // If the block size is 0, it means that the processed data was a multiple of - // received BDX block size (e.g. 8 blocks of 1024 bytes were transferred). - // After state for selecting next processor is reset, a request for fetching next - // data must be sent. - if (block.size() == 0) - { - status = CHIP_NO_ERROR; - break; - } - } - else - { - break; - } - } - - return status; -} - -CHIP_ERROR OTAImageProcessorImpl::SelectProcessor(ByteSpan & block) -{ - OTATlvHeader header; - Encoding::LittleEndian::Reader reader(block.data(), sizeof(header)); - - ReturnErrorOnFailure(reader.Read32(&header.tag).StatusCode()); - ReturnErrorOnFailure(reader.Read32(&header.length).StatusCode()); - - auto pair = mProcessorMap.find(header.tag); - if (pair == mProcessorMap.end()) - { - ChipLogError(SoftwareUpdate, "There is no registered processor for tag: %" PRIu32, header.tag); - return CHIP_ERROR_OTA_PROCESSOR_NOT_REGISTERED; - } - - ChipLogDetail(SoftwareUpdate, "Selected processor with tag: %ld", pair->first); - mCurrentProcessor = pair->second; - mCurrentProcessor->SetLength(header.length); - mCurrentProcessor->SetWasSelected(true); - - return CHIP_NO_ERROR; -} - -CHIP_ERROR OTAImageProcessorImpl::RegisterProcessor(uint32_t tag, OTATlvProcessor * processor) -{ - auto pair = mProcessorMap.find(tag); - if (pair != mProcessorMap.end()) - { - ChipLogError(SoftwareUpdate, "A processor for tag %" PRIu32 " is already registered.", tag); - return CHIP_ERROR_OTA_PROCESSOR_ALREADY_REGISTERED; - } - - mProcessorMap.insert({ tag, processor }); - - return CHIP_NO_ERROR; -} - -void OTAImageProcessorImpl::HandleAbort(intptr_t context) -{ - ChipLogError(SoftwareUpdate, "OTA was aborted"); - auto * imageProcessor = reinterpret_cast(context); - if (imageProcessor != nullptr) - { - imageProcessor->AbortAllProcessors(); - } - imageProcessor->Clear(); - - OtaHookAbort(); -} - -void OTAImageProcessorImpl::HandleProcessBlock(intptr_t context) -{ - auto * imageProcessor = reinterpret_cast(context); - - VerifyOrReturn(imageProcessor != nullptr, ChipLogError(SoftwareUpdate, "ImageProcessor context is null")); - - VerifyOrReturn(imageProcessor->mDownloader != nullptr, ChipLogError(SoftwareUpdate, "mDownloader is null")); - - CHIP_ERROR status; - auto block = ByteSpan(imageProcessor->mBlock.data(), imageProcessor->mBlock.size()); - - if (imageProcessor->mHeaderParser.IsInitialized()) - { - status = imageProcessor->ProcessHeader(block); - if (status != CHIP_NO_ERROR) - { - imageProcessor->HandleStatus(status); - } - } - - status = imageProcessor->ProcessPayload(block); - imageProcessor->HandleStatus(status); -} - -void OTAImageProcessorImpl::HandleStatus(CHIP_ERROR status) -{ - if (status == CHIP_NO_ERROR || status == CHIP_ERROR_BUFFER_TOO_SMALL) - { - mParams.downloadedBytes += mBlock.size(); - FetchNextData(0); - } - else if (status == CHIP_ERROR_OTA_FETCH_ALREADY_SCHEDULED) - { - mParams.downloadedBytes += mBlock.size(); - } - else - { - ChipLogError(SoftwareUpdate, "Image update canceled. Failed to process OTA block: %s", ErrorStr(status)); - GetRequestorInstance()->CancelImageUpdate(); - } -} - -void OTAImageProcessorImpl::AbortAllProcessors() -{ - ChipLogError(SoftwareUpdate, "All selected processors will call abort action"); - - for (auto const & pair : mProcessorMap) - { - if (pair.second->WasSelected()) - { - pair.second->AbortAction(); - pair.second->Clear(); - pair.second->SetWasSelected(false); - } - } -} - -bool OTAImageProcessorImpl::IsFirstImageRun() -{ - OTARequestorInterface * requestor = chip::GetRequestorInstance(); - if (requestor == nullptr) - { - return false; - } - - return requestor->GetCurrentUpdateState() == OTARequestorInterface::OTAUpdateStateEnum::kApplying; -} - -CHIP_ERROR OTAImageProcessorImpl::ConfirmCurrentImage() -{ - uint32_t currentVersion; - uint32_t targetVersion; - - OTARequestorInterface * requestor = chip::GetRequestorInstance(); - ReturnErrorCodeIf(requestor == nullptr, CHIP_ERROR_INTERNAL); - - targetVersion = requestor->GetTargetVersion(); - ReturnErrorOnFailure(DeviceLayer::ConfigurationMgr().GetSoftwareVersion(currentVersion)); - if (currentVersion != targetVersion) - { - ChipLogError(SoftwareUpdate, "Current sw version %" PRIu32 " is different than the expected sw version = %" PRIu32, - currentVersion, targetVersion); - return CHIP_ERROR_INCORRECT_STATE; - } - - return CHIP_NO_ERROR; -} - -CHIP_ERROR OTAImageProcessorImpl::SetBlock(ByteSpan & block) -{ - if (!IsSpanUsable(block)) - { - return CHIP_NO_ERROR; - } - - if (mBlock.size() < block.size()) - { - if (!mBlock.empty()) - { - ReleaseBlock(); - } - uint8_t * mBlock_ptr = static_cast(chip::Platform::MemoryAlloc(block.size())); - if (mBlock_ptr == nullptr) - { - return CHIP_ERROR_NO_MEMORY; - } - mBlock = MutableByteSpan(mBlock_ptr, block.size()); - } - - CHIP_ERROR err = CopySpanToMutableSpan(block, mBlock); - if (err != CHIP_NO_ERROR) - { - ChipLogError(SoftwareUpdate, "Cannot copy block data: %" CHIP_ERROR_FORMAT, err.Format()); - return err; - } - return CHIP_NO_ERROR; -} - -void OTAImageProcessorImpl::HandleFinalize(intptr_t context) -{ - auto * imageProcessor = reinterpret_cast(context); - if (imageProcessor == nullptr) - { - return; - } - - imageProcessor->ReleaseBlock(); -} - -void OTAImageProcessorImpl::HandleApply(intptr_t context) -{ - CHIP_ERROR error = CHIP_NO_ERROR; - auto * imageProcessor = reinterpret_cast(context); - if (imageProcessor == nullptr) - { - return; - } - - for (auto const & pair : imageProcessor->mProcessorMap) - { - if (pair.second->WasSelected()) - { - error = pair.second->ApplyAction(); - if (error != CHIP_NO_ERROR) - { - ChipLogError(SoftwareUpdate, "Apply action for tag %d processor failed.", (uint8_t) pair.first); - // Revert all previously applied actions if current apply action fails. - // Reset image processor and requestor states. - imageProcessor->AbortAllProcessors(); - imageProcessor->Clear(); - GetRequestorInstance()->Reset(); - - return; - } - } - } - - for (auto const & pair : imageProcessor->mProcessorMap) - { - pair.second->Clear(); - pair.second->SetWasSelected(false); - } - - imageProcessor->mAccumulator.Clear(); - - ConfigurationManagerImpl().StoreSoftwareUpdateCompleted(); - PlatformMgr().HandleServerShuttingDown(); - - // Set the necessary information to inform the SSBL that a new image is available - // and trigger the actual device reboot after some time, to take into account - // queued actions, e.g. sending events to a subscription - SystemLayer().StartTimer( - chip::System::Clock::Milliseconds32(CHIP_DEVICE_LAYER_OTA_REBOOT_DELAY), - [](chip::System::Layer *, void *) { OtaHookReset(); }, nullptr); -} - -CHIP_ERROR OTAImageProcessorImpl::ReleaseBlock() -{ - if (mBlock.data() != nullptr) - { - chip::Platform::MemoryFree(mBlock.data()); - } - - mBlock = MutableByteSpan(); - return CHIP_NO_ERROR; -} - -void OTAImageProcessorImpl::FetchNextData(uint32_t context) -{ - auto * imageProcessor = &OTAImageProcessorImpl::GetDefaultInstance(); - SystemLayer().ScheduleLambda([imageProcessor] { - if (imageProcessor->mDownloader) - { - imageProcessor->mDownloader->FetchNextData(); - } - }); -} - -OTAImageProcessorImpl & OTAImageProcessorImpl::GetDefaultInstance() -{ - return gImageProcessor; -} - -} // namespace chip diff --git a/src/platform/nxp/k32w/common/OTAImageProcessorImpl.h b/src/platform/nxp/k32w/common/OTAImageProcessorImpl.h deleted file mode 100644 index 4eea088891..0000000000 --- a/src/platform/nxp/k32w/common/OTAImageProcessorImpl.h +++ /dev/null @@ -1,114 +0,0 @@ -/* - * - * Copyright (c) 2021-2023 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 - -/* - * OTA hooks that can be overwritten by application. - * Default behavior is implemented as WEAK symbols in platform OtaHooks.cpp. - */ - -/* - * This hook is called at the end of OTAImageProcessorImpl::Init. - * It should generally register the OTATlvProcessor instances. - */ -extern "C" CHIP_ERROR OtaHookInit(); - -/* - * This hook is called at the end of OTAImageProcessorImpl::HandleApply. - * The default implementation saves the internal OTA entry structure and resets the device. - */ -extern "C" void OtaHookReset(); - -/* - * This hook is called at the end of OTAImageProcessorImpl::HandleAbort. - * For example, it can be used to schedule a retry. - */ -extern "C" void OtaHookAbort(); - -namespace chip { - -class OTAImageProcessorImpl : public OTAImageProcessorInterface -{ -public: - using ProviderLocation = chip::OTARequestorInterface::ProviderLocationType; - - CHIP_ERROR Init(OTADownloader * downloader); - void Clear(); - - //////////// OTAImageProcessorInterface Implementation /////////////// - CHIP_ERROR PrepareDownload() override; - CHIP_ERROR Finalize() override; - CHIP_ERROR Apply() override; - CHIP_ERROR Abort() override; - CHIP_ERROR ProcessBlock(ByteSpan & block) override; - bool IsFirstImageRun() override; - CHIP_ERROR ConfirmCurrentImage() override; - - CHIP_ERROR ProcessHeader(ByteSpan & block); - CHIP_ERROR ProcessPayload(ByteSpan & block); - CHIP_ERROR SelectProcessor(ByteSpan & block); - CHIP_ERROR RegisterProcessor(uint32_t tag, OTATlvProcessor * processor); - Optional & GetBackupProvider() { return mBackupProviderLocation; } - - static void FetchNextData(uint32_t context); - static OTAImageProcessorImpl & GetDefaultInstance(); - -private: - //////////// Actual handlers for the OTAImageProcessorInterface /////////////// - static void HandlePrepareDownload(intptr_t context); - static void HandleFinalize(intptr_t context); - static void HandleApply(intptr_t context); - static void HandleAbort(intptr_t context); - static void HandleProcessBlock(intptr_t context); - - void HandleStatus(CHIP_ERROR status); - - /** - * Called to allocate memory for mBlock if necessary and set it to block - */ - CHIP_ERROR SetBlock(ByteSpan & block); - - /** - * Called to release allocated memory for mBlock - */ - CHIP_ERROR ReleaseBlock(); - - /** - * Call AbortAction for all processors that were used - */ - void AbortAllProcessors(); - - MutableByteSpan mBlock; - OTADownloader * mDownloader; - OTAImageHeaderParser mHeaderParser; - OTATlvProcessor * mCurrentProcessor = nullptr; - OTADataAccumulator mAccumulator; - std::map mProcessorMap; - Optional mBackupProviderLocation; -}; - -} // namespace chip diff --git a/src/platform/nxp/k32w/common/OTATlvProcessor.cpp b/src/platform/nxp/k32w/common/OTATlvProcessor.cpp deleted file mode 100644 index 5dc0eaebd8..0000000000 --- a/src/platform/nxp/k32w/common/OTATlvProcessor.cpp +++ /dev/null @@ -1,178 +0,0 @@ -/* - * - * Copyright (c) 2023 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 -#if OTA_ENCRYPTION_ENABLE -#include "OtaUtils.h" -#include "rom_aes.h" -#endif -namespace chip { - -#if OTA_ENCRYPTION_ENABLE -constexpr uint8_t au8Iv[] = { 0x00, 0x00, 0x00, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x00, 0x00, 0x00, 0x00 }; -#endif - -CHIP_ERROR OTATlvProcessor::ApplyAction() -{ - return mApplyState == ApplyState::kApply ? CHIP_NO_ERROR : CHIP_ERROR_OTA_PROCESSOR_DO_NOT_APPLY; -} - -CHIP_ERROR OTATlvProcessor::Process(ByteSpan & block) -{ - CHIP_ERROR status = CHIP_NO_ERROR; - uint32_t bytes = chip::min(mLength - mProcessedLength, static_cast(block.size())); - ByteSpan relevantData = block.SubSpan(0, bytes); - - status = ProcessInternal(relevantData); - if (!IsError(status)) - { - mProcessedLength += bytes; - block = block.SubSpan(bytes); - if (mProcessedLength == mLength) - { - status = ExitAction(); - if (!IsError(status)) - { - // If current block was processed fully and the block still contains data, it - // means that the block contains another TLV's data and the current processor - // should be changed by OTAImageProcessorImpl. - return CHIP_ERROR_OTA_CHANGE_PROCESSOR; - } - } - } - - return status; -} - -void OTATlvProcessor::ClearInternal() -{ - mLength = 0; - mProcessedLength = 0; - mWasSelected = false; - mApplyState = ApplyState::kApply; -#if OTA_ENCRYPTION_ENABLE - mIVOffset = 0; -#endif -} - -bool OTATlvProcessor::IsError(CHIP_ERROR & status) -{ - return status != CHIP_NO_ERROR && status != CHIP_ERROR_BUFFER_TOO_SMALL && status != CHIP_ERROR_OTA_FETCH_ALREADY_SCHEDULED; -} - -void OTADataAccumulator::Init(uint32_t threshold) -{ - mThreshold = threshold; - mBufferOffset = 0; - mBuffer.Alloc(mThreshold); -} - -void OTADataAccumulator::Clear() -{ - mThreshold = 0; - mBufferOffset = 0; - mBuffer.Free(); -} - -CHIP_ERROR OTADataAccumulator::Accumulate(ByteSpan & block) -{ - uint32_t numBytes = chip::min(mThreshold - mBufferOffset, static_cast(block.size())); - memcpy(&mBuffer[mBufferOffset], block.data(), numBytes); - mBufferOffset += numBytes; - block = block.SubSpan(numBytes); - - if (mBufferOffset < mThreshold) - { - return CHIP_ERROR_BUFFER_TOO_SMALL; - } - - return CHIP_NO_ERROR; -} - -#if OTA_ENCRYPTION_ENABLE -CHIP_ERROR OTATlvProcessor::vOtaProcessInternalEncryption(MutableByteSpan & block) -{ - uint8_t iv[16]; - uint8_t key[kOTAEncryptionKeyLength]; - uint8_t dataOut[16] = { 0 }; - uint32_t u32IVCount; - uint32_t Offset = 0; - uint8_t data; - tsReg128 sKey; - aesContext_t Context; - - memcpy(iv, au8Iv, sizeof(au8Iv)); - - u32IVCount = (((uint32_t) iv[12]) << 24) | (((uint32_t) iv[13]) << 16) | (((uint32_t) iv[14]) << 8) | (iv[15]); - u32IVCount += (mIVOffset >> 4); - - iv[12] = (uint8_t) ((u32IVCount >> 24) & 0xff); - iv[13] = (uint8_t) ((u32IVCount >> 16) & 0xff); - iv[14] = (uint8_t) ((u32IVCount >> 8) & 0xff); - iv[15] = (uint8_t) (u32IVCount & 0xff); - - if (Encoding::HexToBytes(OTA_ENCRYPTION_KEY, strlen(OTA_ENCRYPTION_KEY), key, kOTAEncryptionKeyLength) != - kOTAEncryptionKeyLength) - { - // Failed to convert the OTAEncryptionKey string to octstr type value - return CHIP_ERROR_INVALID_STRING_LENGTH; - } - - ByteSpan KEY = ByteSpan(key); - Encoding::LittleEndian::Reader reader_key(KEY.data(), KEY.size()); - ReturnErrorOnFailure(reader_key.Read32(&sKey.u32register0) - .Read32(&sKey.u32register1) - .Read32(&sKey.u32register2) - .Read32(&sKey.u32register3) - .StatusCode()); - - while (Offset + 16 <= block.size()) - { - /*Encrypt the IV*/ - Context.mode = AES_MODE_ECB_ENCRYPT; - Context.pSoftwareKey = (uint32_t *) &sKey; - AES_128_ProcessBlocks(&Context, (uint32_t *) &iv[0], (uint32_t *) &dataOut[0], 1); - - /* Decrypt a block of the buffer */ - for (uint8_t i = 0; i < 16; i++) - { - data = block[Offset + i] ^ dataOut[i]; - memcpy(&block[Offset + i], &data, sizeof(uint8_t)); - } - - /* increment the IV for the next block */ - u32IVCount++; - - iv[12] = (uint8_t) ((u32IVCount >> 24) & 0xff); - iv[13] = (uint8_t) ((u32IVCount >> 16) & 0xff); - iv[14] = (uint8_t) ((u32IVCount >> 8) & 0xff); - iv[15] = (uint8_t) (u32IVCount & 0xff); - - Offset += 16; /* increment the buffer offset */ - mIVOffset += 16; - } - - return CHIP_NO_ERROR; -} -#endif -} // namespace chip diff --git a/src/platform/nxp/k32w/common/OTATlvProcessor.h b/src/platform/nxp/k32w/common/OTATlvProcessor.h deleted file mode 100644 index f1faef7e8e..0000000000 --- a/src/platform/nxp/k32w/common/OTATlvProcessor.h +++ /dev/null @@ -1,180 +0,0 @@ -/* - * - * Copyright (c) 2023 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 - -namespace chip { - -#define CHIP_ERROR_TLV_PROCESSOR(e) \ - ChipError(ChipError::Range::kLastRange, ((uint8_t) ChipError::Range::kLastRange << 3) | e, __FILE__, __LINE__) - -#define CHIP_ERROR_OTA_CHANGE_PROCESSOR CHIP_ERROR_TLV_PROCESSOR(0x02) -#define CHIP_ERROR_OTA_PROCESSOR_NOT_REGISTERED CHIP_ERROR_TLV_PROCESSOR(0x03) -#define CHIP_ERROR_OTA_PROCESSOR_ALREADY_REGISTERED CHIP_ERROR_TLV_PROCESSOR(0x04) -#define CHIP_ERROR_OTA_PROCESSOR_CLIENT_INIT CHIP_ERROR_TLV_PROCESSOR(0x05) -#define CHIP_ERROR_OTA_PROCESSOR_MAKE_ROOM CHIP_ERROR_TLV_PROCESSOR(0x06) -#define CHIP_ERROR_OTA_PROCESSOR_PUSH_CHUNK CHIP_ERROR_TLV_PROCESSOR(0x07) -#define CHIP_ERROR_OTA_PROCESSOR_IMG_AUTH CHIP_ERROR_TLV_PROCESSOR(0x08) -#define CHIP_ERROR_OTA_FETCH_ALREADY_SCHEDULED CHIP_ERROR_TLV_PROCESSOR(0x09) -#define CHIP_ERROR_OTA_PROCESSOR_IMG_COMMIT CHIP_ERROR_TLV_PROCESSOR(0x0A) -#define CHIP_ERROR_OTA_PROCESSOR_CB_NOT_REGISTERED CHIP_ERROR_TLV_PROCESSOR(0x0B) -#define CHIP_ERROR_OTA_PROCESSOR_EEPROM_OFFSET CHIP_ERROR_TLV_PROCESSOR(0x0C) -#define CHIP_ERROR_OTA_PROCESSOR_EXTERNAL_STORAGE CHIP_ERROR_TLV_PROCESSOR(0x0D) -#define CHIP_ERROR_OTA_PROCESSOR_START_IMAGE CHIP_ERROR_TLV_PROCESSOR(0x0E) -#define CHIP_ERROR_OTA_PROCESSOR_DO_NOT_APPLY CHIP_ERROR_TLV_PROCESSOR(0x0F) - -// Descriptor constants -constexpr size_t kVersionStringSize = 64; -constexpr size_t kBuildDateSize = 64; - -constexpr uint16_t requestedOtaMaxBlockSize = 1024; - -/** - * Used alongside RegisterDescriptorCallback to register - * a custom descriptor processing function with a certain - * TLV processor. - */ -typedef CHIP_ERROR (*ProcessDescriptor)(void * descriptor); - -struct OTATlvHeader -{ - uint32_t tag; - uint32_t length; -}; - -/** - * This class defines an interface for a Matter TLV processor. - * Instances of derived classes can be registered as processors - * in OTAImageProcessorImpl. Based on the TLV type, a certain - * processor is used to process subsequent blocks until the number - * of bytes found in the metadata is processed. In case a block contains - * data from two different TLVs, the processor should ensure the remaining - * data is returned in the block passed as input. - * The default processors: application, SSBL and factory data are registered - * in OTAImageProcessorImpl::Init through OtaHookInit. - * Applications should use OTAImageProcessorImpl::RegisterProcessor - * to register additional processors. - */ -class OTATlvProcessor -{ -public: - enum class ApplyState : uint8_t - { - kApply = 0, - kDoNotApply - }; - - virtual ~OTATlvProcessor() {} - - virtual CHIP_ERROR Init() = 0; - virtual CHIP_ERROR Clear() = 0; - virtual CHIP_ERROR AbortAction() = 0; - virtual CHIP_ERROR ExitAction() { return CHIP_NO_ERROR; } - virtual CHIP_ERROR ApplyAction(); - - CHIP_ERROR Process(ByteSpan & block); - void RegisterDescriptorCallback(ProcessDescriptor callback) { mCallbackProcessDescriptor = callback; } - void SetLength(uint32_t length) { mLength = length; } - void SetWasSelected(bool selected) { mWasSelected = selected; } - bool WasSelected() { return mWasSelected; } -#if OTA_ENCRYPTION_ENABLE - CHIP_ERROR vOtaProcessInternalEncryption(MutableByteSpan & block); -#endif - -protected: - /** - * @brief Process custom TLV payload - * - * The method takes subsequent chunks of the Matter OTA image file and processes them. - * If more image chunks are needed, CHIP_ERROR_BUFFER_TOO_SMALL error is returned. - * Other error codes indicate that an error occurred during processing. Fetching - * next data is scheduled automatically by OTAImageProcessorImpl if the return value - * is neither an error code, nor CHIP_ERROR_OTA_FETCH_ALREADY_SCHEDULED (which implies the - * scheduling is done inside ProcessInternal or will be done in the future, through a - * callback). - * - * @param block Byte span containing a subsequent Matter OTA image chunk. When the method - * returns CHIP_NO_ERROR, the byte span is used to return a remaining part - * of the chunk, not used by current TLV processor. - * - * @retval CHIP_NO_ERROR Block was processed successfully. - * @retval CHIP_ERROR_BUFFER_TOO_SMALL Provided buffers are insufficient to decode some - * metadata (e.g. a descriptor). - * @retval CHIP_ERROR_OTA_FETCH_ALREADY_SCHEDULED Should be returned if ProcessInternal schedules - * fetching next data (e.g. through a callback). - * @retval Error code Something went wrong. Current OTA process will be - * canceled. - */ - virtual CHIP_ERROR ProcessInternal(ByteSpan & block) = 0; - - void ClearInternal(); - - bool IsError(CHIP_ERROR & status); - -#if OTA_ENCRYPTION_ENABLE - /*ota decryption*/ - uint32_t mIVOffset = 0; - /* Expected byte size of the OTAEncryptionKeyLength */ - static constexpr size_t kOTAEncryptionKeyLength = 16; -#endif - uint32_t mLength = 0; - uint32_t mProcessedLength = 0; - bool mWasSelected = false; - - /** - * @brief A flag to account for corner cases during OTA apply - * - * Used by the default ApplyAction implementation. - * - * If something goes wrong during ExitAction of the TLV processor, - * then mApplyState should be set to kDoNotApply and the image processor - * should abort. In this case, the BDX transfer was already finished - * and calling CancelImageUpdate will not abort the transfer, hence - * the device will reboot even though it should not have. If ApplyAction - * fails during HandleApply, then the process will be aborted. - */ - ApplyState mApplyState = ApplyState::kApply; - ProcessDescriptor mCallbackProcessDescriptor = nullptr; -}; - -/** - * This class can be used to accumulate data until a given threshold. - * Should be used by OTATlvProcessor derived classes if they need - * metadata accumulation (e.g. for custom header decoding). - */ -class OTADataAccumulator -{ -public: - void Init(uint32_t threshold); - void Clear(); - CHIP_ERROR Accumulate(ByteSpan & block); - - inline uint8_t * data() { return mBuffer.Get(); } - inline uint32_t GetThreshold() { return mThreshold; } - -private: - uint32_t mThreshold; - uint32_t mBufferOffset; - Platform::ScopedMemoryBuffer mBuffer; -}; - -} // namespace chip diff --git a/src/platform/nxp/k32w/k32w1/BUILD.gn b/src/platform/nxp/k32w/k32w1/BUILD.gn deleted file mode 100644 index 028bd2a1cd..0000000000 --- a/src/platform/nxp/k32w/k32w1/BUILD.gn +++ /dev/null @@ -1,153 +0,0 @@ -# Copyright (c) 2021 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/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") - -assert(chip_device_platform == "nxp") -assert(nxp_platform == "k32w/k32w1") - -if (chip_enable_openthread) { - import("//build_overrides/openthread.gni") -} - -if (chip_crypto == "platform") { - import("//build_overrides/mbedtls.gni") -} - -static_library("nxp_platform") { - defines = [ "CHIP_DEVICE_K32W1=1" ] - - sources = [ - "../../../SingletonConfigurationManager.cpp", - "../common/BLEManagerCommon.cpp", - "../common/BLEManagerCommon.h", - "BLEManagerImpl.cpp", - "BLEManagerImpl.h", - "CHIPDevicePlatformConfig.h", - "CHIPDevicePlatformEvent.h", - "ConfigurationManagerImpl.cpp", - "ConfigurationManagerImpl.h", - "ConnectivityManagerImpl.cpp", - "ConnectivityManagerImpl.h", - "DefaultTestEventTriggerDelegate.cpp", - "DefaultTestEventTriggerDelegate.h", - "DiagnosticDataProviderImpl.cpp", - "DiagnosticDataProviderImpl.h", - "K32W1Config.cpp", - "K32W1Config.h", - "KeyValueStoreManagerImpl.cpp", - "KeyValueStoreManagerImpl.h", - "PlatformManagerImpl.cpp", - "PlatformManagerImpl.h", - "SystemTimeSupport.cpp", - "ble_function_mux.c", - "ram_storage.c", - "ram_storage.h", - ] - - if (chip_use_plain_dac_key) { - defines += [ "CHIP_USE_PLAIN_DAC_KEY=1" ] - } else { - defines += [ "CHIP_USE_PLAIN_DAC_KEY=0" ] - } - - public = [ - "${chip_root}/src/credentials/DeviceAttestationCredsProvider.h", - "${chip_root}/src/credentials/examples/DeviceAttestationCredsExample.h", - "${chip_root}/src/credentials/examples/ExampleDACs.h", - "${chip_root}/src/credentials/examples/ExamplePAI.h", - "${chip_root}/src/platform/nxp/k32w/k32w1/BLEManagerImpl.h", - "${chip_root}/src/platform/nxp/k32w/k32w1/DefaultTestEventTriggerDelegate.h", - "${chip_root}/src/platform/nxp/k32w/k32w1/SMU2Manager.h", - ] - - public_deps = [ - "${chip_root}/src/app:test-event-trigger", - "${chip_root}/src/platform:platform_base", - ] - - if (chip_with_low_power != 0) { - sources += [ "LowPowerHooks.cpp" ] - } - - if (chip_enable_ota_requestor) { - public += [ "../common/OTAImageProcessorImpl.h" ] - - sources += [ - "../common/OTAImageProcessorImpl.cpp", - "../common/OTAImageProcessorImpl.h", - "../common/OTATlvProcessor.cpp", - "../common/OTATlvProcessor.h", - "OTAFirmwareProcessor.cpp", - "OTAFirmwareProcessor.h", - "OTAHooks.cpp", - ] - } - - if (chip_crypto == "platform") { - sources += [ - "CHIPCryptoPalK32W1.cpp", - "K32W1PersistentStorageOpKeystore.cpp", - "K32W1PersistentStorageOpKeystore.h", - ] - - if (chip_with_factory_data == 1) { - sources += [ - "../common/FactoryDataProvider.cpp", - "FactoryDataProviderImpl.cpp", - ] - public += [ - "${chip_root}/src/credentials/CHIPCert.h", - "${chip_root}/src/credentials/CertificationDeclaration.h", - ] - } - - public_deps += [ "${mbedtls_root}:mbedtls" ] - } - - deps = [] - - if (chip_enable_openthread) { - sources += [ - "../../../OpenThread/OpenThreadUtils.cpp", - "ThreadStackManagerImpl.cpp", - "ThreadStackManagerImpl.h", - ] - - if (chip_mdns == "platform") { - sources += [ - "../../../OpenThread/DnssdImpl.cpp", - "../../../OpenThread/OpenThreadDnssdImpl.cpp", - "../../../OpenThread/OpenThreadDnssdImpl.h", - ] - deps += [ "${chip_root}/src/lib/dnssd:platform_header" ] - } - - if (use_smu2_dynamic) { - sources += [ - "SMU2Manager.cpp", - "SMU2Manager.h", - ] - } - } - - public_deps += [ - "${chip_root}/src/crypto", - "${chip_root}/src/platform/logging:headers", - ] -} diff --git a/src/platform/nxp/k32w/k32w1/SoftwareUpdateManagerImpl.cpp b/src/platform/nxp/k32w/k32w1/SoftwareUpdateManagerImpl.cpp deleted file mode 100644 index c464bb327c..0000000000 --- a/src/platform/nxp/k32w/k32w1/SoftwareUpdateManagerImpl.cpp +++ /dev/null @@ -1,46 +0,0 @@ -/* - * - * Copyright (c) 2020 Project CHIP Authors - * Copyright (c) 2020 Google LLC. - * 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. - */ -/* this file behaves like a config.h, comes first */ -#include - -#if CHIP_DEVICE_CONFIG_ENABLE_SOFTWARE_UPDATE_MANAGER - -#include -#include - -#include -#include - -namespace chip { -namespace DeviceLayer { - -SoftwareUpdateManagerImpl SoftwareUpdateManagerImpl::sInstance; - -CHIP_ERROR SoftwareUpdateManagerImpl::_Init(void) -{ - Internal::GenericSoftwareUpdateManagerImpl_BDX::DoInit(); - Internal::GenericSoftwareUpdateManagerImpl::DoInit(); - - return CHIP_NO_ERROR; -} - -} // namespace DeviceLayer -} // namespace chip - -#endif // CHIP_DEVICE_CONFIG_ENABLE_SOFTWARE_UPDATE_MANAGER diff --git a/src/platform/nxp/k32w/k32w1/SoftwareUpdateManagerImpl.h b/src/platform/nxp/k32w/k32w1/SoftwareUpdateManagerImpl.h deleted file mode 100644 index f040254359..0000000000 --- a/src/platform/nxp/k32w/k32w1/SoftwareUpdateManagerImpl.h +++ /dev/null @@ -1,89 +0,0 @@ -/* - * - * Copyright (c) 2020 Project CHIP Authors - * Copyright (c) 2020 Google LLC. - * 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 - -#if CHIP_DEVICE_CONFIG_ENABLE_SOFTWARE_UPDATE_MANAGER - -#include -#include - -namespace chip { -namespace DeviceLayer { - -/** - * Concrete implementation of the SoftwareUpdateManager singleton object for the - * NXP K32W platforms. - */ -class SoftwareUpdateManagerImpl final : public SoftwareUpdateManager, - public Internal::GenericSoftwareUpdateManagerImpl, - public Internal::GenericSoftwareUpdateManagerImpl_BDX -{ - // Allow the SoftwareUpdateManager interface class to delegate method calls to - // the implementation methods provided by this class. - friend class SoftwareUpdateManager; - - // Allow the GenericSoftwareUpdateManagerImpl base class to access helper methods - // and types defined on this class. - friend class Internal::GenericSoftwareUpdateManagerImpl; - - // Allow the GenericSoftwareUpdateManagerImpl_BDX base class to access helper methods - // and types defined on this class. - friend class Internal::GenericSoftwareUpdateManagerImpl_BDX; - -public: - // ===== Members for internal use by the following friends. - - friend ::chip::DeviceLayer::SoftwareUpdateManager & SoftwareUpdateMgr(void); - friend SoftwareUpdateManagerImpl & SoftwareUpdateMgrImpl(void); - - static SoftwareUpdateManagerImpl sInstance; - -private: - // ===== Members that implement the SoftwareUpdateManager abstract interface. - - CHIP_ERROR _Init(void); -}; - -/** - * Returns a reference to the public interface of the SoftwareUpdateManager singleton object. - * - * Internal components should use this to access features of the SoftwareUpdateManager object - * that are common to all platforms. - */ -inline SoftwareUpdateManager & SoftwareUpdateMgr(void) -{ - return SoftwareUpdateManagerImpl::sInstance; -} - -/** - * Returns the platform-specific implementation of the SoftwareUpdateManager singleton object. - * - * Internal components can use this to gain access to features of the SoftwareUpdateManager - * that are specific to the K32W platform. - */ -inline SoftwareUpdateManagerImpl & SoftwareUpdateMgrImpl(void) -{ - return SoftwareUpdateManagerImpl::sInstance; -} - -} // namespace DeviceLayer -} // namespace chip - -#endif // CHIP_DEVICE_CONFIG_ENABLE_SOFTWARE_UPDATE_MANAGER diff --git a/src/platform/nxp/k32w0/BUILD.gn b/src/platform/nxp/k32w0/BUILD.gn index 41a80a77a7..a1b40506d6 100644 --- a/src/platform/nxp/k32w0/BUILD.gn +++ b/src/platform/nxp/k32w0/BUILD.gn @@ -25,6 +25,11 @@ if (chip_enable_openthread) { import("//build_overrides/openthread.gni") } +source_set("nxp_factory_data") { +} +source_set("nxp_ota") { +} + static_library("nxp_platform") { defines = [] sources = [ diff --git a/src/platform/nxp/k32w/k32w1/BLEManagerImpl.cpp b/src/platform/nxp/k32w1/BLEManagerImpl.cpp similarity index 97% rename from src/platform/nxp/k32w/k32w1/BLEManagerImpl.cpp rename to src/platform/nxp/k32w1/BLEManagerImpl.cpp index 88d5c00400..fe3ebd0c0b 100644 --- a/src/platform/nxp/k32w/k32w1/BLEManagerImpl.cpp +++ b/src/platform/nxp/k32w1/BLEManagerImpl.cpp @@ -28,7 +28,7 @@ messaging_t gHci2Host_TaskQueue; /*! Event for the Host Task Queue */ OSA_EVENT_HANDLE_DEFINE(gHost_TaskEvent); -#include +#include extern "C" bleResult_t Hci_Reset(void); @@ -52,7 +52,6 @@ CHIP_ERROR BLEManagerImpl::InitHostController(BLECallbackDelegate::GapGenericCal PLATFORM_InitBle(); (void) RNG_Init(); - RNG_SetPseudoRandomNoSeed(NULL); /* Has to be called after RNG_Init(), once seed is generated. */ (void) Controller_SetRandomSeed(); diff --git a/src/platform/nxp/k32w/k32w1/BLEManagerImpl.h b/src/platform/nxp/k32w1/BLEManagerImpl.h similarity index 97% rename from src/platform/nxp/k32w/k32w1/BLEManagerImpl.h rename to src/platform/nxp/k32w1/BLEManagerImpl.h index 59bda33db0..d2b38cdeda 100644 --- a/src/platform/nxp/k32w/k32w1/BLEManagerImpl.h +++ b/src/platform/nxp/k32w1/BLEManagerImpl.h @@ -31,7 +31,7 @@ #include "controller_api.h" #include "controller_interface.h" -#include +#include /* host task configuration */ #define HOST_TASK_PRIORITY (4U) diff --git a/src/platform/nxp/k32w1/BUILD.gn b/src/platform/nxp/k32w1/BUILD.gn new file mode 100644 index 0000000000..89e9ad06e9 --- /dev/null +++ b/src/platform/nxp/k32w1/BUILD.gn @@ -0,0 +1,211 @@ +# Copyright (c) 2021 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/nxp_sdk.gni") +import("//build_overrides/openthread.gni") + +import("${chip_root}/src/crypto/crypto.gni") +import("${chip_root}/src/platform/device.gni") + +import("${nxp_sdk_build_root}/nxp_sdk.gni") + +import("${nxp_sdk_build_root}/${nxp_sdk_name}/${nxp_sdk_name}.gni") + +assert(chip_device_platform == "nxp") +assert(nxp_platform == "k32w1") + +assert(chip_with_low_power == 0 || + (chip_with_low_power == 1 && chip_with_ot_cli == 0), + "Please disable low power if openthread CLI is needed!") + +source_set("nxp_factory_data") { + sources = [ + "../common/legacy/FactoryDataDriver.cpp", + "../common/legacy/FactoryDataProvider.cpp", + "FactoryDataDriverImpl.cpp", + "FactoryDataProviderImpl.cpp", + ] + + public = [ + "${chip_root}/src/credentials/CHIPCert.h", + "${chip_root}/src/credentials/CertificationDeclaration.h", + ] + + defines = [ "PLATFORM_FACTORY_DATA_PROVIDER_IMPL_HEADER=\"platform/nxp/k32w1/FactoryDataProviderImpl.h\"" ] + + deps = [ + ":nxp_platform", + "${chip_root}/src/credentials:credentials", + ] +} + +source_set("nxp_ota") { + public = [ "../common/legacy/OTAImageProcessorImpl.h" ] + + sources = [ + "../common/legacy/OTAImageProcessorImpl.cpp", + "../common/legacy/OTAImageProcessorImpl.h", + "../common/legacy/OTATlvProcessor.cpp", + "../common/legacy/OTATlvProcessor.h", + "OTAFirmwareProcessor.cpp", + "OTAFirmwareProcessor.h", + "OTAHooks.cpp", + ] + + if (chip_with_factory_data == 1 && + chip_enable_ota_factory_data_processor == 1) { + sources += [ + "../common/legacy/OTAFactoryDataProcessor.cpp", + "../common/legacy/OTAFactoryDataProcessor.h", + ] + } + + deps = [ + ":nxp_platform", + "${chip_root}/src/platform:platform", + ] +} + +static_library("nxp_platform") { + deps = [] + defines = [ "CHIP_DEVICE_K32W1=1" ] + + sources = [ + "../../SingletonConfigurationManager.cpp", + "../common/legacy/BLEManagerCommon.cpp", + "../common/legacy/BLEManagerCommon.h", + "BLEManagerImpl.cpp", + "BLEManagerImpl.h", + "CHIPDevicePlatformConfig.h", + "CHIPDevicePlatformEvent.h", + "ConfigurationManagerImpl.cpp", + "ConfigurationManagerImpl.h", + "ConnectivityManagerImpl.cpp", + "ConnectivityManagerImpl.h", + "DiagnosticDataProviderImpl.cpp", + "DiagnosticDataProviderImpl.h", + "PlatformManagerImpl.cpp", + "PlatformManagerImpl.h", + "SystemTimeSupport.cpp", + "ble_function_mux.c", + ] + + if (chip_key_storage == "fwk_nvm") { + defines += [ "CHIP_PLAT_NVM_SUPPORT=1" ] + + sources += [ + "K32W1Config.cpp", + "K32W1Config.h", + "KeyValueStoreManagerImpl.cpp", + "KeyValueStoreManagerImpl.h", + "ram_storage.c", + "ram_storage.h", + ] + } else if (chip_key_storage == "littlefs") { + defines += [ + "CHIP_PLAT_NVM_SUPPORT=3", + "EXTERNAL_KEYVALUESTOREMANAGERIMPL_HEADER=\"platform/nxp/common/KeyValueStoreManagerImpl.h\"", + ] + + sources += [ + "../common/KeyValueStoreManagerImpl.cpp", + "../common/KeyValueStoreManagerImpl.h", + "../common/NXPConfig.h", + "../common/NXPConfigKS.cpp", + ] + } else if (chip_key_storage == "nvs") { + defines += [ + "gAppNvsExternalFlash_c=0", + "gAppNvsInternalFlash_c=1", + "CONFIG_SETTINGS_RUNTIME=1", + ] + + sources += [ + "../common/KeyValueStoreManagerImpl.cpp", + "../common/KeyValueStoreManagerImpl.h", + "../common/NXPConfig.h", + "../common/NXPConfigNVS.cpp", + ] + } + + if (chip_use_plain_dac_key) { + defines += [ "CHIP_USE_PLAIN_DAC_KEY=1" ] + } else { + defines += [ "CHIP_USE_PLAIN_DAC_KEY=0" ] + } + + public = [ + "${chip_root}/src/credentials/DeviceAttestationCredsProvider.h", + "${chip_root}/src/credentials/examples/DeviceAttestationCredsExample.h", + "${chip_root}/src/credentials/examples/ExampleDACs.h", + "${chip_root}/src/credentials/examples/ExamplePAI.h", + "${chip_root}/src/platform/nxp/k32w1/BLEManagerImpl.h", + "${chip_root}/src/platform/nxp/k32w1/SMU2Manager.h", + ] + + public_deps = [ "${chip_root}/src/platform:platform_base" ] + + if (chip_with_low_power != 0) { + sources += [ "LowPowerHooks.cpp" ] + } + + if (chip_crypto == "platform") { + sources += [ + "CHIPCryptoPalK32W1.cpp", + "K32W1PersistentStorageOpKeystore.cpp", + "K32W1PersistentStorageOpKeystore.h", + ] + + if (chip_with_ot_cli == 1) { + defines += [ "CHIP_DEVICE_CONFIG_THREAD_ENABLE_CLI=1" ] + } + } + + if (chip_enable_openthread) { + sources += [ + "../../OpenThread/OpenThreadUtils.cpp", + "ThreadStackManagerImpl.cpp", + "ThreadStackManagerImpl.h", + ] + + deps += [ "${chip_root}/third_party/openthread:openthread" ] + public_deps += [ "${chip_root}/third_party/openthread:openthread-platform" ] + + if (chip_mdns == "platform") { + sources += [ + "../../OpenThread/DnssdImpl.cpp", + "../../OpenThread/OpenThreadDnssdImpl.cpp", + "../../OpenThread/OpenThreadDnssdImpl.h", + ] + deps += [ "${chip_root}/src/lib/dnssd:platform_header" ] + } + + if (use_smu2_dynamic) { + sources += [ + "SMU2Manager.cpp", + "SMU2Manager.h", + ] + } + } + + deps += [ "${nxp_sdk_build_root}:nxp_sdk" ] + + public_deps += [ + "${chip_root}/examples/platform/nxp/${nxp_platform}/app/support:freertos_memory_utils", + "${chip_root}/src/crypto", + "${chip_root}/src/platform:syscalls_stub", + "${chip_root}/src/platform/logging:headers", + ] +} diff --git a/src/platform/nxp/k32w/k32w1/BlePlatformConfig.h b/src/platform/nxp/k32w1/BlePlatformConfig.h similarity index 100% rename from src/platform/nxp/k32w/k32w1/BlePlatformConfig.h rename to src/platform/nxp/k32w1/BlePlatformConfig.h diff --git a/src/platform/nxp/k32w/k32w1/CHIPCryptoPalK32W1.cpp b/src/platform/nxp/k32w1/CHIPCryptoPalK32W1.cpp similarity index 100% rename from src/platform/nxp/k32w/k32w1/CHIPCryptoPalK32W1.cpp rename to src/platform/nxp/k32w1/CHIPCryptoPalK32W1.cpp diff --git a/src/platform/nxp/k32w/k32w1/CHIPDevicePlatformConfig.h b/src/platform/nxp/k32w1/CHIPDevicePlatformConfig.h similarity index 94% rename from src/platform/nxp/k32w/k32w1/CHIPDevicePlatformConfig.h rename to src/platform/nxp/k32w1/CHIPDevicePlatformConfig.h index 52dec0809f..13dbd99290 100644 --- a/src/platform/nxp/k32w/k32w1/CHIPDevicePlatformConfig.h +++ b/src/platform/nxp/k32w1/CHIPDevicePlatformConfig.h @@ -61,6 +61,16 @@ // These are configuration options that are unique to the K32W platform. // These can be overridden by the application as needed. +/** + * @def CONFIG_CHIP_OTA_FACTORY_DATA_PROCESSOR + * + * Enables default OTA TLV factory data processor. + * Disabled by default. + */ +#ifndef CONFIG_CHIP_OTA_FACTORY_DATA_PROCESSOR +#define CONFIG_CHIP_OTA_FACTORY_DATA_PROCESSOR 0 +#endif // CONFIG_CHIP_OTA_FACTORY_DATA_PROCESSOR + /** * @def CHIP_DEVICE_LAYER_BLE_OBSERVER_PRIORITY * diff --git a/src/platform/nxp/k32w/k32w1/CHIPDevicePlatformEvent.h b/src/platform/nxp/k32w1/CHIPDevicePlatformEvent.h similarity index 100% rename from src/platform/nxp/k32w/k32w1/CHIPDevicePlatformEvent.h rename to src/platform/nxp/k32w1/CHIPDevicePlatformEvent.h diff --git a/src/platform/nxp/k32w/k32w1/CHIPPlatformConfig.h b/src/platform/nxp/k32w1/CHIPPlatformConfig.h similarity index 100% rename from src/platform/nxp/k32w/k32w1/CHIPPlatformConfig.h rename to src/platform/nxp/k32w1/CHIPPlatformConfig.h diff --git a/src/platform/nxp/k32w/k32w1/ConfigurationManagerImpl.cpp b/src/platform/nxp/k32w1/ConfigurationManagerImpl.cpp similarity index 80% rename from src/platform/nxp/k32w/k32w1/ConfigurationManagerImpl.cpp rename to src/platform/nxp/k32w1/ConfigurationManagerImpl.cpp index 68a1a4196e..fc6815d20f 100644 --- a/src/platform/nxp/k32w/k32w1/ConfigurationManagerImpl.cpp +++ b/src/platform/nxp/k32w1/ConfigurationManagerImpl.cpp @@ -29,9 +29,8 @@ #include #include #include -#include #if defined(USE_SMU2_DYNAMIC) -#include +#include #endif // #include @@ -56,7 +55,7 @@ CHIP_ERROR ConfigurationManagerImpl::Init() CHIP_ERROR err; uint32_t rebootCount = 0; - if (K32WConfig::ConfigValueExists(K32WConfig::kCounterKey_RebootCount)) + if (NXPConfig::ConfigValueExists(NXPConfig::kCounterKey_RebootCount)) { err = GetRebootCount(rebootCount); SuccessOrExit(err); @@ -71,20 +70,20 @@ CHIP_ERROR ConfigurationManagerImpl::Init() SuccessOrExit(err); } - if (!K32WConfig::ConfigValueExists(K32WConfig::kCounterKey_TotalOperationalHours)) + if (!NXPConfig::ConfigValueExists(NXPConfig::kCounterKey_TotalOperationalHours)) { err = StoreTotalOperationalHours(0); SuccessOrExit(err); } - if (!K32WConfig::ConfigValueExists(K32WConfig::kCounterKey_BootReason)) + if (!NXPConfig::ConfigValueExists(NXPConfig::kCounterKey_BootReason)) { err = StoreBootReason(to_underlying(BootReasonType::kUnspecified)); SuccessOrExit(err); } // Initialize the generic implementation base class. - err = Internal::GenericConfigurationManagerImpl::Init(); + err = Internal::GenericConfigurationManagerImpl::Init(); SuccessOrExit(err); // TODO: Initialize the global GroupKeyStore object here @@ -103,22 +102,22 @@ CHIP_ERROR ConfigurationManagerImpl::StoreSoftwareUpdateCompleted() CHIP_ERROR ConfigurationManagerImpl::GetRebootCount(uint32_t & rebootCount) { - return ReadConfigValue(K32WConfig::kCounterKey_RebootCount, rebootCount); + return ReadConfigValue(NXPConfig::kCounterKey_RebootCount, rebootCount); } CHIP_ERROR ConfigurationManagerImpl::StoreRebootCount(uint32_t rebootCount) { - return WriteConfigValue(K32WConfig::kCounterKey_RebootCount, rebootCount); + return WriteConfigValue(NXPConfig::kCounterKey_RebootCount, rebootCount); } CHIP_ERROR ConfigurationManagerImpl::GetTotalOperationalHours(uint32_t & totalOperationalHours) { - return ReadConfigValue(K32WConfig::kCounterKey_TotalOperationalHours, totalOperationalHours); + return ReadConfigValue(NXPConfig::kCounterKey_TotalOperationalHours, totalOperationalHours); } CHIP_ERROR ConfigurationManagerImpl::StoreTotalOperationalHours(uint32_t totalOperationalHours) { - return WriteConfigValue(K32WConfig::kCounterKey_TotalOperationalHours, totalOperationalHours); + return WriteConfigValue(NXPConfig::kCounterKey_TotalOperationalHours, totalOperationalHours); } CHIP_ERROR ConfigurationManagerImpl::GetBootReason(uint32_t & bootReason) @@ -149,7 +148,7 @@ CHIP_ERROR ConfigurationManagerImpl::GetBootReason(uint32_t & bootReason) CHIP_ERROR ConfigurationManagerImpl::StoreBootReason(uint32_t bootReason) { - return WriteConfigValue(K32WConfig::kCounterKey_BootReason, bootReason); + return WriteConfigValue(NXPConfig::kCounterKey_BootReason, bootReason); } bool ConfigurationManagerImpl::CanFactoryReset() @@ -168,7 +167,7 @@ CHIP_ERROR ConfigurationManagerImpl::ReadPersistedStorageValue(::chip::Platform: { CHIP_ERROR err; - err = K32WConfig::ReadConfigValueCounter(persistedStorageKey, value); + err = NXPConfig::ReadConfigValueCounter(persistedStorageKey, value); if (err == CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND) { err = CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND; @@ -186,7 +185,7 @@ CHIP_ERROR ConfigurationManagerImpl::WritePersistedStorageValue(::chip::Platform // (where persistedStorageKey represents an index to the counter). CHIP_ERROR err; - err = K32WConfig::WriteConfigValueCounter(persistedStorageKey, value); + err = NXPConfig::WriteConfigValueCounter(persistedStorageKey, value); if (err == CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND) { err = CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND; @@ -199,62 +198,62 @@ CHIP_ERROR ConfigurationManagerImpl::WritePersistedStorageValue(::chip::Platform CHIP_ERROR ConfigurationManagerImpl::ReadConfigValue(Key key, bool & val) { - return K32WConfig::ReadConfigValue(key, val); + return NXPConfig::ReadConfigValue(key, val); } CHIP_ERROR ConfigurationManagerImpl::ReadConfigValue(Key key, uint32_t & val) { - return K32WConfig::ReadConfigValue(key, val); + return NXPConfig::ReadConfigValue(key, val); } CHIP_ERROR ConfigurationManagerImpl::ReadConfigValue(Key key, uint64_t & val) { - return K32WConfig::ReadConfigValue(key, val); + return NXPConfig::ReadConfigValue(key, val); } CHIP_ERROR ConfigurationManagerImpl::ReadConfigValueStr(Key key, char * buf, size_t bufSize, size_t & outLen) { - return K32WConfig::ReadConfigValueStr(key, buf, bufSize, outLen); + return NXPConfig::ReadConfigValueStr(key, buf, bufSize, outLen); } CHIP_ERROR ConfigurationManagerImpl::ReadConfigValueBin(Key key, uint8_t * buf, size_t bufSize, size_t & outLen) { - return K32WConfig::ReadConfigValueBin(key, buf, bufSize, outLen); + return NXPConfig::ReadConfigValueBin(key, buf, bufSize, outLen); } CHIP_ERROR ConfigurationManagerImpl::WriteConfigValue(Key key, bool val) { - return K32WConfig::WriteConfigValue(key, val); + return NXPConfig::WriteConfigValue(key, val); } CHIP_ERROR ConfigurationManagerImpl::WriteConfigValue(Key key, uint32_t val) { - return K32WConfig::WriteConfigValue(key, val); + return NXPConfig::WriteConfigValue(key, val); } CHIP_ERROR ConfigurationManagerImpl::WriteConfigValue(Key key, uint64_t val) { - return K32WConfig::WriteConfigValue(key, val); + return NXPConfig::WriteConfigValue(key, val); } CHIP_ERROR ConfigurationManagerImpl::WriteConfigValueStr(Key key, const char * str) { - return K32WConfig::WriteConfigValueStr(key, str); + return NXPConfig::WriteConfigValueStr(key, str); } CHIP_ERROR ConfigurationManagerImpl::WriteConfigValueStr(Key key, const char * str, size_t strLen) { - return K32WConfig::WriteConfigValueStr(key, str, strLen); + return NXPConfig::WriteConfigValueStr(key, str, strLen); } CHIP_ERROR ConfigurationManagerImpl::WriteConfigValueBin(Key key, const uint8_t * data, size_t dataLen) { - return K32WConfig::WriteConfigValueBin(key, data, dataLen); + return NXPConfig::WriteConfigValueBin(key, data, dataLen); } void ConfigurationManagerImpl::RunConfigUnitTest(void) { - K32WConfig::RunConfigUnitTest(); + NXPConfig::RunConfigUnitTest(); } void ConfigurationManagerImpl::DoFactoryReset(intptr_t arg) @@ -263,7 +262,7 @@ void ConfigurationManagerImpl::DoFactoryReset(intptr_t arg) ChipLogProgress(DeviceLayer, "Performing factory reset"); - err = K32WConfig::FactoryResetConfig(); + err = NXPConfig::FactoryResetConfig(); if (err != CHIP_NO_ERROR) { ChipLogError(DeviceLayer, "FactoryResetConfig() failed: %s", ErrorStr(err)); diff --git a/src/platform/nxp/k32w/k32w1/ConfigurationManagerImpl.h b/src/platform/nxp/k32w1/ConfigurationManagerImpl.h similarity index 95% rename from src/platform/nxp/k32w/k32w1/ConfigurationManagerImpl.h rename to src/platform/nxp/k32w1/ConfigurationManagerImpl.h index 26201d85f5..ba6dd2e721 100644 --- a/src/platform/nxp/k32w/k32w1/ConfigurationManagerImpl.h +++ b/src/platform/nxp/k32w1/ConfigurationManagerImpl.h @@ -25,7 +25,11 @@ #pragma once -#include "K32W1Config.h" +#if (CHIP_PLAT_NVM_SUPPORT == 1) +#include +#else +#include +#endif #include namespace chip { @@ -34,7 +38,7 @@ namespace DeviceLayer { /** * Concrete implementation of the ConfigurationManager singleton object for the K32W platform. */ -class ConfigurationManagerImpl final : public Internal::GenericConfigurationManagerImpl +class ConfigurationManagerImpl final : public Internal::GenericConfigurationManagerImpl { public: // This returns an instance of this class. diff --git a/src/platform/nxp/k32w/k32w1/ConnectivityManagerImpl.cpp b/src/platform/nxp/k32w1/ConnectivityManagerImpl.cpp similarity index 100% rename from src/platform/nxp/k32w/k32w1/ConnectivityManagerImpl.cpp rename to src/platform/nxp/k32w1/ConnectivityManagerImpl.cpp diff --git a/src/platform/nxp/k32w/k32w1/ConnectivityManagerImpl.h b/src/platform/nxp/k32w1/ConnectivityManagerImpl.h similarity index 100% rename from src/platform/nxp/k32w/k32w1/ConnectivityManagerImpl.h rename to src/platform/nxp/k32w1/ConnectivityManagerImpl.h diff --git a/src/platform/nxp/k32w/k32w1/DiagnosticDataProviderImpl.cpp b/src/platform/nxp/k32w1/DiagnosticDataProviderImpl.cpp similarity index 99% rename from src/platform/nxp/k32w/k32w1/DiagnosticDataProviderImpl.cpp rename to src/platform/nxp/k32w1/DiagnosticDataProviderImpl.cpp index 3a3412eb03..090feb53ad 100644 --- a/src/platform/nxp/k32w/k32w1/DiagnosticDataProviderImpl.cpp +++ b/src/platform/nxp/k32w1/DiagnosticDataProviderImpl.cpp @@ -25,7 +25,7 @@ #include #include -#include +#include #if CHIP_SYSTEM_CONFIG_USE_LWIP #include diff --git a/src/platform/nxp/k32w/k32w1/DiagnosticDataProviderImpl.h b/src/platform/nxp/k32w1/DiagnosticDataProviderImpl.h similarity index 100% rename from src/platform/nxp/k32w/k32w1/DiagnosticDataProviderImpl.h rename to src/platform/nxp/k32w1/DiagnosticDataProviderImpl.h diff --git a/src/platform/nxp/k32w1/FactoryDataDriverImpl.cpp b/src/platform/nxp/k32w1/FactoryDataDriverImpl.cpp new file mode 100644 index 0000000000..ae50e2361b --- /dev/null +++ b/src/platform/nxp/k32w1/FactoryDataDriverImpl.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 +#include +#include + +using namespace chip::DeviceLayer::PersistedStorage; + +namespace chip { +namespace DeviceLayer { + +FactoryDataDriverImpl FactoryDataDriverImpl::sInstance; + +FactoryDataDriver & FactoryDataDrv() +{ + return FactoryDataDriverImpl::sInstance; +} + +FactoryDataDriverImpl & FactoryDataDrvImpl() +{ + return FactoryDataDriverImpl::sInstance; +} + +CHIP_ERROR FactoryDataDriverImpl::Init(void) +{ + mFactoryData = Nv_GetAppFactoryData(); + VerifyOrReturnError(mFactoryData != nullptr, CHIP_ERROR_INTERNAL); + + mSize = mFactoryData->extendedDataLength; + mMaxSize = FactoryDataProvider::kFactoryDataMaxSize; + + return CHIP_NO_ERROR; +} + +bool FactoryDataDriverImpl::DoesBackupExist(uint16_t * size) +{ + return false; +} + +CHIP_ERROR FactoryDataDriverImpl::DeleteBackup() +{ + CHIP_ERROR error = CHIP_NO_ERROR; + + error = KeyValueStoreMgr().Delete(FactoryDataDriverImpl::GetFactoryBackupKey().KeyName()); + ReturnErrorOnFailure(error); + + return CHIP_NO_ERROR; +} + +CHIP_ERROR FactoryDataDriverImpl::InitRamBackup(void) +{ + CHIP_ERROR error = CHIP_NO_ERROR; + + VerifyOrReturnError(mFactoryData != nullptr, CHIP_ERROR_INTERNAL); + VerifyOrReturnError(mFactoryDataRamBuff == nullptr, CHIP_ERROR_INTERNAL); + + mFactoryDataRamBuff = static_cast(chip::Platform::MemoryAlloc(mMaxSize)); + ReturnErrorCodeIf(mFactoryDataRamBuff == nullptr, CHIP_ERROR_INTERNAL); + + memset(mFactoryDataRamBuff, 0, mMaxSize); + memcpy(mFactoryDataRamBuff, (void *) &mFactoryData->app_factory_data[0], mSize); + + return CHIP_NO_ERROR; +} + +CHIP_ERROR FactoryDataDriverImpl::ClearRamBackup() +{ + VerifyOrReturnError(mFactoryDataRamBuff != nullptr, CHIP_ERROR_NO_MEMORY); + memset(mFactoryDataRamBuff, 0, mMaxSize); + chip::Platform::MemoryFree(mFactoryDataRamBuff); + + mFactoryDataRamBuff = nullptr; + + return CHIP_NO_ERROR; +} + +CHIP_ERROR FactoryDataDriverImpl::ReadBackupInRam() +{ + CHIP_ERROR error = CHIP_NO_ERROR; + size_t bytesRead = 0; + + if (mFactoryDataRamBuff == nullptr) + { + mFactoryDataRamBuff = static_cast(chip::Platform::MemoryAlloc(mMaxSize)); + ReturnErrorCodeIf(mFactoryDataRamBuff == nullptr, CHIP_ERROR_NO_MEMORY); + memset(mFactoryDataRamBuff, 0, mMaxSize); + } + + error = + KeyValueStoreMgr().Get(FactoryDataDriverImpl::GetFactoryBackupKey().KeyName(), mFactoryDataRamBuff, mMaxSize, &bytesRead); + ReturnErrorOnFailure(error); + + return CHIP_NO_ERROR; +} + +CHIP_ERROR FactoryDataDriverImpl::BackupFactoryData() +{ + CHIP_ERROR error = CHIP_NO_ERROR; + ReturnErrorCodeIf(mFactoryData == nullptr, CHIP_ERROR_INTERNAL); + + error = KeyValueStoreMgr().Put(FactoryDataDriverImpl::GetFactoryBackupKey().KeyName(), &mFactoryData->app_factory_data[0], + mMaxSize); + ReturnErrorOnFailure(error); + + return CHIP_NO_ERROR; +} + +CHIP_ERROR FactoryDataDriverImpl::UpdateFactoryData(void) +{ + FactoryDataProvider::Header * header; + extendedAppFactoryData_t * data; + VerifyOrReturnError(mFactoryDataRamBuff != nullptr, CHIP_ERROR_INTERNAL); + + header = (FactoryDataProvider::Header *) mFactoryDataRamBuff; + size_t size = offsetof(extendedAppFactoryData_t, app_factory_data) + sizeof(FactoryDataProvider::Header) + header->size; + data = static_cast(chip::Platform::MemoryAlloc(size)); + + memcpy(data->identificationWord, "APP_FACT_DATA: ", APP_FACTORY_DATA_ID_STRING_SZ); + + data->extendedDataLength = sizeof(FactoryDataProvider::Header) + header->size; + mSize = data->extendedDataLength; + memcpy(&data->app_factory_data[0], mFactoryDataRamBuff, mSize); + uint8_t status = Nv_WriteAppFactoryData(data, mSize); + VerifyOrReturnError(status == 0, CHIP_ERROR_INTERNAL); + + chip::Platform::MemoryFree(data); + + return CHIP_NO_ERROR; +} + +} // namespace DeviceLayer +} // namespace chip diff --git a/src/platform/nxp/k32w1/FactoryDataDriverImpl.h b/src/platform/nxp/k32w1/FactoryDataDriverImpl.h new file mode 100644 index 0000000000..8b3e77358c --- /dev/null +++ b/src/platform/nxp/k32w1/FactoryDataDriverImpl.h @@ -0,0 +1,59 @@ +/* + * + * Copyright (c) 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. + */ +#pragma once + +#include +#include +#include +#include + +extern "C" { +#include "HWParameter.h" +} + +namespace chip { +namespace DeviceLayer { + +/** + * This class implements the FactoryDataDriver with K32W1 specific functions + */ + +class FactoryDataDriverImpl : public FactoryDataDriver +{ +public: + static FactoryDataDriverImpl sInstance; + + FactoryDataDriverImpl() = default; + ~FactoryDataDriverImpl() = default; + + bool DoesBackupExist(uint16_t *) override; + CHIP_ERROR Init() override; + CHIP_ERROR DeleteBackup(void) override; + CHIP_ERROR InitRamBackup(void) override; + CHIP_ERROR ClearRamBackup(void) override; + CHIP_ERROR ReadBackupInRam(void) override; + CHIP_ERROR BackupFactoryData(void) override; + CHIP_ERROR UpdateFactoryData(void) override; + + static StorageKeyName GetFactoryBackupKey() { return StorageKeyName::FromConst("nxp/fact-bkp"); } + +private: + extendedAppFactoryData_t * mFactoryData = nullptr; +}; + +} // namespace DeviceLayer +} // namespace chip diff --git a/src/platform/nxp/k32w/k32w1/FactoryDataProviderImpl.cpp b/src/platform/nxp/k32w1/FactoryDataProviderImpl.cpp similarity index 70% rename from src/platform/nxp/k32w/k32w1/FactoryDataProviderImpl.cpp rename to src/platform/nxp/k32w1/FactoryDataProviderImpl.cpp index 764e3f6ac4..f3af97803b 100644 --- a/src/platform/nxp/k32w/k32w1/FactoryDataProviderImpl.cpp +++ b/src/platform/nxp/k32w1/FactoryDataProviderImpl.cpp @@ -14,9 +14,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#include +#include +#include #include "fsl_adapter_flash.h" -#include + +#if CONFIG_CHIP_OTA_FACTORY_DATA_PROCESSOR +extern "C" WEAK CHIP_ERROR FactoryDataDefaultRestoreMechanism(); +#endif + +using namespace chip::DeviceLayer::PersistedStorage; namespace chip { namespace DeviceLayer { @@ -27,6 +35,27 @@ static constexpr size_t kSssBlobMetadataLength = 24; static constexpr size_t kPrivateKeyBlobLength = Crypto::kP256_PrivateKey_Length + kSssBlobMetadataLength; #endif +uint32_t FactoryDataProvider::kFactoryDataMaxSize = 0x800; + +FactoryDataProviderImpl FactoryDataProviderImpl::sInstance; + +FactoryDataProvider & FactoryDataPrvd() +{ + return FactoryDataProviderImpl::sInstance; +} + +FactoryDataProviderImpl & FactoryDataPrvdImpl() +{ + return FactoryDataProviderImpl::sInstance; +} + +FactoryDataProviderImpl::FactoryDataProviderImpl() +{ +#if CONFIG_CHIP_OTA_FACTORY_DATA_PROCESSOR + RegisterRestoreMechanism(FactoryDataDefaultRestoreMechanism); +#endif +} + FactoryDataProviderImpl::~FactoryDataProviderImpl() { #if !CHIP_USE_PLAIN_DAC_KEY @@ -38,11 +67,27 @@ CHIP_ERROR FactoryDataProviderImpl::Init() { CHIP_ERROR error = CHIP_NO_ERROR; + mFactoryData = Nv_GetAppFactoryData(); + VerifyOrReturnError(mFactoryData != nullptr, CHIP_ERROR_INTERNAL); + + mConfig.start = (uint32_t) &mFactoryData->app_factory_data[0]; + mConfig.size = mFactoryData->extendedDataLength; + mConfig.payload = mConfig.start + sizeof(FactoryDataProvider::Header); + +#if CONFIG_CHIP_OTA_FACTORY_DATA_PROCESSOR + mFactoryDataDriver = &FactoryDataDrv(); + ReturnErrorOnFailure(PostResetCheck()); +#endif + #if CHIP_DEVICE_CONFIG_ENABLE_SSS_API_TEST && !CHIP_USE_PLAIN_DAC_KEY SSS_RunApiTest(); #endif +#if CONFIG_CHIP_OTA_FACTORY_DATA_PROCESSOR + error = ValidateWithRestore(); +#else error = Validate(); +#endif if (error != CHIP_NO_ERROR) { ChipLogError(DeviceLayer, "Factory data init failed with: %s", ErrorStr(error)); @@ -60,41 +105,7 @@ CHIP_ERROR FactoryDataProviderImpl::Init() #if CHIP_USE_PLAIN_DAC_KEY CHIP_ERROR FactoryDataProviderImpl::SignWithDacKey(const ByteSpan & messageToSign, MutableByteSpan & outSignBuffer) { - CHIP_ERROR error = CHIP_NO_ERROR; - Crypto::P256ECDSASignature signature; - Crypto::P256Keypair keypair; - Crypto::P256SerializedKeypair serializedKeypair; - uint8_t keyBuf[Crypto::kP256_PrivateKey_Length]; - MutableByteSpan dacPrivateKeySpan(keyBuf); - uint16_t keySize = 0; - - VerifyOrExit(!outSignBuffer.empty(), error = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(!messageToSign.empty(), error = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(outSignBuffer.size() >= signature.Capacity(), error = CHIP_ERROR_BUFFER_TOO_SMALL); - - /* Get private key of DAC certificate from reserved section */ - error = SearchForId(FactoryDataId::kDacPrivateKeyId, dacPrivateKeySpan.data(), dacPrivateKeySpan.size(), keySize); - SuccessOrExit(error); - dacPrivateKeySpan.reduce_size(keySize); - VerifyOrExit(keySize == Crypto::kP256_PrivateKey_Length, error = CHIP_ERROR_WRONG_KEY_TYPE); - - /* Only the private key is used when signing */ - error = serializedKeypair.SetLength(Crypto::kP256_PublicKey_Length + dacPrivateKeySpan.size()); - SuccessOrExit(error); - memcpy(serializedKeypair.Bytes() + Crypto::kP256_PublicKey_Length, dacPrivateKeySpan.data(), dacPrivateKeySpan.size()); - - error = keypair.Deserialize(serializedKeypair); - SuccessOrExit(error); - - error = keypair.ECDSA_sign_msg(messageToSign.data(), messageToSign.size(), signature); - SuccessOrExit(error); - - error = CopySpanToMutableSpan(ByteSpan{ signature.ConstBytes(), signature.Length() }, outSignBuffer); - -exit: - /* Sanitize temporary buffer */ - memset(keyBuf, 0, Crypto::kP256_PrivateKey_Length); - return error; + return FactoryDataProvider::SignWithDacKey(messageToSign, outSignBuffer); } #else @@ -164,11 +175,14 @@ CHIP_ERROR FactoryDataProviderImpl::SSS_ConvertDacKey() size_t blobSize = kPrivateKeyBlobLength; size_t newSize = sizeof(FactoryDataProvider::Header) + mHeader.size + kSssBlobMetadataLength; uint8_t blob[kPrivateKeyBlobLength] = { 0 }; - uint8_t * data = static_cast(chip::Platform::MemoryAlloc(newSize)); - uint32_t offset = 0; - bool convNeeded = true; + extendedAppFactoryData_t * data = static_cast( + chip::Platform::MemoryAlloc(offsetof(extendedAppFactoryData_t, app_factory_data) + newSize)); + uint32_t offset = 0; + bool convNeeded = true; + uint8_t status = 0; VerifyOrReturnError(data != nullptr, CHIP_ERROR_INTERNAL); + VerifyOrReturnError(mFactoryData != nullptr, CHIP_ERROR_INTERNAL); ReturnErrorOnFailure(SSS_ExportBlob(blob, &blobSize, offset, convNeeded)); if (!convNeeded) @@ -177,20 +191,17 @@ CHIP_ERROR FactoryDataProviderImpl::SSS_ConvertDacKey() chip::Platform::MemoryFree(data); return CHIP_NO_ERROR; } - ChipLogError(DeviceLayer, "SSS: extracted blob from DAC private key"); - hal_flash_status_t status = HAL_FlashRead(kFactoryDataStart, newSize - kSssBlobMetadataLength, data); - VerifyOrReturnError(status == kStatus_HAL_Flash_Success, CHIP_ERROR_INTERNAL); + memcpy(data, mFactoryData, offsetof(extendedAppFactoryData_t, app_factory_data) + mFactoryData->extendedDataLength); ChipLogError(DeviceLayer, "SSS: cached factory data in RAM"); - ReturnErrorOnFailure(ReplaceWithBlob(data, blob, blobSize, offset)); + ReturnErrorOnFailure(ReplaceWithBlob(&data->app_factory_data[0], blob, blobSize, offset)); ChipLogError(DeviceLayer, "SSS: replaced DAC private key with secured blob"); - status = HAL_FlashEraseSector(kFactoryDataStart, kFactoryDataSize); - VerifyOrReturnError(status == kStatus_HAL_Flash_Success, CHIP_ERROR_INTERNAL); - status = HAL_FlashProgramUnaligned(kFactoryDataStart, newSize, data); - VerifyOrReturnError(status == kStatus_HAL_Flash_Success, CHIP_ERROR_INTERNAL); + data->extendedDataLength = newSize; + status = Nv_WriteAppFactoryData(data, newSize); + VerifyOrReturnError(status == 0, CHIP_ERROR_INTERNAL); ChipLogError(DeviceLayer, "SSS: updated factory data"); memset(data, 0, newSize); @@ -255,6 +266,107 @@ CHIP_ERROR FactoryDataProviderImpl::ReplaceWithBlob(uint8_t * data, uint8_t * bl return CHIP_NO_ERROR; } +#if CONFIG_CHIP_OTA_FACTORY_DATA_PROCESSOR + +extern "C" WEAK CHIP_ERROR FactoryDataDefaultRestoreMechanism() +{ + CHIP_ERROR error = CHIP_NO_ERROR; + FactoryDataDriver * driver = &FactoryDataDrv(); + + ReturnErrorCodeIf(driver == nullptr, CHIP_ERROR_INTERNAL); + + // Check if key related to factory data backup exists. + // If it does, it means an external event (such as a power loss) + // interrupted the factory data update process and the section + // from internal flash is most likely erased and should be restored. + error = driver->ReadBackupInRam(); + + if (error == CHIP_NO_ERROR) + { + error = driver->UpdateFactoryData(); + if (error == CHIP_NO_ERROR) + { + ChipLogProgress(DeviceLayer, "Factory data was restored successfully"); + } + } + + ReturnErrorOnFailure(driver->ClearRamBackup()); + + if (error == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND) + return CHIP_NO_ERROR; + + return error; +} + +CHIP_ERROR FactoryDataProviderImpl::PreResetCheck() +{ + OTARequestorInterface * requestor = nullptr; + uint32_t targetVersion; + /* Check integrity of freshly copied data. If validation fails, OTA will be aborted + * and factory data will be restored to the previous version. Use device instance info + * provider getter to access the factory data provider instance. The instance is created + * by the application, so it's easier to access it this way.*/ + ReturnErrorOnFailure(Validate()); + + requestor = GetRequestorInstance(); + VerifyOrReturnError(requestor != nullptr, CHIP_ERROR_INVALID_ADDRESS); + + targetVersion = requestor->GetTargetVersion(); + ReturnErrorOnFailure(FactoryDataProviderImpl::SaveTargetVersion(targetVersion)); + + return CHIP_NO_ERROR; +} + +CHIP_ERROR FactoryDataProviderImpl::PostResetCheck() +{ + CHIP_ERROR err = CHIP_NO_ERROR; + uint32_t targetVersion, currentVersion; + + err = FactoryDataProviderImpl::GetTargetVersion(targetVersion); + if (err != CHIP_NO_ERROR) + ChipLogProgress(DeviceLayer, "Could not get target version"); + + err = DeviceLayer::ConfigurationMgr().GetSoftwareVersion(currentVersion); + if (err != CHIP_NO_ERROR) + ChipLogProgress(DeviceLayer, "Could not get current version"); + + if (targetVersion == currentVersion) + { + ChipLogProgress(DeviceLayer, "OTA successfully applied"); + // If this point is reached, it means the new image successfully booted. + // Delete the factory data backup to stop doing a restore. + // This ensures that both the factory data and app were updated, otherwise + // revert to the backed up factory data. + mFactoryDataDriver->DeleteBackup(); + } + + return CHIP_NO_ERROR; +} + +CHIP_ERROR FactoryDataProviderImpl::GetTargetVersion(uint32_t & version) +{ + CHIP_ERROR error = CHIP_NO_ERROR; + uint16_t len = sizeof(uint32_t); + size_t bytesRead = 0; + + error = KeyValueStoreMgr().Get(FactoryDataProviderImpl::GetTargetVersionKey().KeyName(), (uint8_t *) &version, len, &bytesRead); + ReturnErrorOnFailure(error); + + return CHIP_NO_ERROR; +} + +CHIP_ERROR FactoryDataProviderImpl::SaveTargetVersion(uint32_t & version) +{ + CHIP_ERROR error = CHIP_NO_ERROR; + + error = + KeyValueStoreMgr().Put(FactoryDataProviderImpl::GetTargetVersionKey().KeyName(), (uint8_t *) &version, sizeof(uint32_t)); + ReturnErrorOnFailure(error); + + return CHIP_NO_ERROR; +} +#endif // CONFIG_CHIP_OTA_FACTORY_DATA_PROCESSOR + #if CHIP_DEVICE_CONFIG_ENABLE_SSS_API_TEST #define _assert(condition) \ diff --git a/src/platform/nxp/k32w/k32w1/FactoryDataProviderImpl.h b/src/platform/nxp/k32w1/FactoryDataProviderImpl.h similarity index 81% rename from src/platform/nxp/k32w/k32w1/FactoryDataProviderImpl.h rename to src/platform/nxp/k32w1/FactoryDataProviderImpl.h index f81b5d1418..d7f15bba4e 100644 --- a/src/platform/nxp/k32w/k32w1/FactoryDataProviderImpl.h +++ b/src/platform/nxp/k32w1/FactoryDataProviderImpl.h @@ -17,12 +17,18 @@ #pragma once #include -#include +#include +#include +#include #if !CHIP_USE_PLAIN_DAC_KEY #include "sss_crypto.h" #endif +extern "C" { +#include "HWParameter.h" +} + /* This flag should be defined to run SSS_RunApiTest tests. */ #ifndef CHIP_DEVICE_CONFIG_ENABLE_SSS_API_TEST @@ -35,16 +41,31 @@ namespace DeviceLayer { /** * This class extends the default FactoryDataProvider functionality * by leveraging the secure subsystem for signing messages. + * CONFIG_CHIP_OTA_FACTORY_DATA_PROCESSOR - enables factory data OTA */ class FactoryDataProviderImpl : public FactoryDataProvider { public: + static FactoryDataProviderImpl sInstance; + + FactoryDataProviderImpl(); ~FactoryDataProviderImpl(); CHIP_ERROR Init() override; CHIP_ERROR SignWithDacKey(const ByteSpan & messageToSign, MutableByteSpan & outSignBuffer) override; +#if CONFIG_CHIP_OTA_FACTORY_DATA_PROCESSOR + + CHIP_ERROR PreResetCheck() override; + CHIP_ERROR PostResetCheck() override; + + static StorageKeyName GetTargetVersionKey() { return StorageKeyName::FromConst("nxp/tgt-sw-ver"); } + + static CHIP_ERROR GetTargetVersion(uint32_t & version); + static CHIP_ERROR SaveTargetVersion(uint32_t & version); +#endif + private: #if !CHIP_USE_PLAIN_DAC_KEY @@ -90,9 +111,13 @@ class FactoryDataProviderImpl : public FactoryDataProvider #if CHIP_DEVICE_CONFIG_ENABLE_SSS_API_TEST void SSS_RunApiTest(); #endif +#endif // CHIP_USE_PLAIN_DAC_KEY +private: + extendedAppFactoryData_t * mFactoryData = nullptr; +#if !CHIP_USE_PLAIN_DAC_KEY sss_sscp_object_t mContext; -#endif // CHIP_USE_PLAIN_DAC_KEY +#endif }; } // namespace DeviceLayer diff --git a/src/platform/nxp/k32w/k32w1/InetPlatformConfig.h b/src/platform/nxp/k32w1/InetPlatformConfig.h similarity index 100% rename from src/platform/nxp/k32w/k32w1/InetPlatformConfig.h rename to src/platform/nxp/k32w1/InetPlatformConfig.h diff --git a/src/platform/nxp/k32w/k32w1/K32W1Config.cpp b/src/platform/nxp/k32w1/K32W1Config.cpp similarity index 87% rename from src/platform/nxp/k32w/k32w1/K32W1Config.cpp rename to src/platform/nxp/k32w1/K32W1Config.cpp index 2019fce581..6f578f8ed0 100644 --- a/src/platform/nxp/k32w/k32w1/K32W1Config.cpp +++ b/src/platform/nxp/k32w1/K32W1Config.cpp @@ -25,7 +25,7 @@ /* this file behaves like a config.h, comes first */ #include -#include +#include #include #include @@ -110,7 +110,7 @@ static rsError AddToRamStorage(ramBufferDescriptor * pBuffer, uint16_t aKey, con return err; } -CHIP_ERROR K32WConfig::Init() +CHIP_ERROR NXPConfig::Init() { CHIP_ERROR err = CHIP_NO_ERROR; bool bLoadDataFromNvm = true; @@ -148,7 +148,7 @@ CHIP_ERROR K32WConfig::Init() return err; } -CHIP_ERROR K32WConfig::ReadConfigValue(Key key, bool & val) +CHIP_ERROR NXPConfig::ReadConfigValue(Key key, bool & val) { CHIP_ERROR err; bool tempVal; @@ -164,7 +164,7 @@ CHIP_ERROR K32WConfig::ReadConfigValue(Key key, bool & val) return err; } -CHIP_ERROR K32WConfig::ReadConfigValue(Key key, uint32_t & val) +CHIP_ERROR NXPConfig::ReadConfigValue(Key key, uint32_t & val) { CHIP_ERROR err; uint32_t tempVal; @@ -180,7 +180,7 @@ CHIP_ERROR K32WConfig::ReadConfigValue(Key key, uint32_t & val) return err; } -CHIP_ERROR K32WConfig::ReadConfigValue(Key key, uint64_t & val) +CHIP_ERROR NXPConfig::ReadConfigValue(Key key, uint64_t & val) { CHIP_ERROR err; uint32_t tempVal; @@ -196,7 +196,7 @@ CHIP_ERROR K32WConfig::ReadConfigValue(Key key, uint64_t & val) return err; } -CHIP_ERROR K32WConfig::ReadConfigValueStr(Key key, char * buf, size_t bufSize, size_t & outLen) +CHIP_ERROR NXPConfig::ReadConfigValueStr(Key key, char * buf, size_t bufSize, size_t & outLen) { CHIP_ERROR err; rsError status; @@ -213,18 +213,18 @@ CHIP_ERROR K32WConfig::ReadConfigValueStr(Key key, char * buf, size_t bufSize, s return err; } -CHIP_ERROR K32WConfig::ReadConfigValueBin(Key key, uint8_t * buf, size_t bufSize, size_t & outLen) +CHIP_ERROR NXPConfig::ReadConfigValueBin(Key key, uint8_t * buf, size_t bufSize, size_t & outLen) { return ReadConfigValueStr(key, (char *) buf, bufSize, outLen); } -CHIP_ERROR K32WConfig::ReadConfigValueCounter(uint8_t counterIdx, uint32_t & val) +CHIP_ERROR NXPConfig::ReadConfigValueCounter(uint8_t counterIdx, uint32_t & val) { Key key = kMinConfigKey_ChipCounter + counterIdx; return ReadConfigValue(key, val); } -CHIP_ERROR K32WConfig::WriteConfigValue(Key key, bool val) +CHIP_ERROR NXPConfig::WriteConfigValue(Key key, bool val) { CHIP_ERROR err; rsError status; @@ -242,7 +242,7 @@ CHIP_ERROR K32WConfig::WriteConfigValue(Key key, bool val) return err; } -CHIP_ERROR K32WConfig::WriteConfigValueSync(Key key, bool val) +CHIP_ERROR NXPConfig::WriteConfigValueSync(Key key, bool val) { CHIP_ERROR err; rsError status; @@ -260,7 +260,7 @@ CHIP_ERROR K32WConfig::WriteConfigValueSync(Key key, bool val) return err; } -CHIP_ERROR K32WConfig::WriteConfigValue(Key key, uint32_t val) +CHIP_ERROR NXPConfig::WriteConfigValue(Key key, uint32_t val) { CHIP_ERROR err; rsError status; @@ -278,7 +278,7 @@ CHIP_ERROR K32WConfig::WriteConfigValue(Key key, uint32_t val) return err; } -CHIP_ERROR K32WConfig::WriteConfigValue(Key key, uint64_t val) +CHIP_ERROR NXPConfig::WriteConfigValue(Key key, uint64_t val) { CHIP_ERROR err; rsError status; @@ -296,12 +296,12 @@ CHIP_ERROR K32WConfig::WriteConfigValue(Key key, uint64_t val) return err; } -CHIP_ERROR K32WConfig::WriteConfigValueStr(Key key, const char * str) +CHIP_ERROR NXPConfig::WriteConfigValueStr(Key key, const char * str) { return WriteConfigValueStr(key, str, (str != NULL) ? strlen(str) : 0); } -CHIP_ERROR K32WConfig::WriteConfigValueStr(Key key, const char * str, size_t strLen) +CHIP_ERROR NXPConfig::WriteConfigValueStr(Key key, const char * str, size_t strLen) { CHIP_ERROR err; rsError status; @@ -327,18 +327,18 @@ CHIP_ERROR K32WConfig::WriteConfigValueStr(Key key, const char * str, size_t str return err; } -CHIP_ERROR K32WConfig::WriteConfigValueBin(Key key, const uint8_t * data, size_t dataLen) +CHIP_ERROR NXPConfig::WriteConfigValueBin(Key key, const uint8_t * data, size_t dataLen) { return WriteConfigValueStr(key, (char *) data, dataLen); } -CHIP_ERROR K32WConfig::WriteConfigValueCounter(uint8_t counterIdx, uint32_t val) +CHIP_ERROR NXPConfig::WriteConfigValueCounter(uint8_t counterIdx, uint32_t val) { Key key = kMinConfigKey_ChipCounter + counterIdx; return WriteConfigValue(key, val); } -CHIP_ERROR K32WConfig::ClearConfigValue(Key key) +CHIP_ERROR NXPConfig::ClearConfigValue(Key key) { CHIP_ERROR err = CHIP_NO_ERROR; rsError status; @@ -355,7 +355,7 @@ CHIP_ERROR K32WConfig::ClearConfigValue(Key key) return err; } -bool K32WConfig::ConfigValueExists(Key key) +bool NXPConfig::ConfigValueExists(Key key) { rsError status; uint16_t sizeToRead; @@ -369,7 +369,7 @@ bool K32WConfig::ConfigValueExists(Key key) return found; } -CHIP_ERROR K32WConfig::FactoryResetConfig(void) +CHIP_ERROR NXPConfig::FactoryResetConfig(void) { CHIP_ERROR err = CHIP_NO_ERROR; @@ -386,7 +386,7 @@ CHIP_ERROR K32WConfig::FactoryResetConfig(void) return err; } -void K32WConfig::FactoryResetConfigInternal(Key firstKey, Key lastKey) +void NXPConfig::FactoryResetConfigInternal(Key firstKey, Key lastKey) { for (Key key = firstKey; key <= lastKey; key++) { @@ -394,7 +394,7 @@ void K32WConfig::FactoryResetConfigInternal(Key firstKey, Key lastKey) } } -CHIP_ERROR K32WConfig::MapRamStorageStatus(rsError rsStatus) +CHIP_ERROR NXPConfig::MapRamStorageStatus(rsError rsStatus) { CHIP_ERROR err; @@ -414,7 +414,7 @@ CHIP_ERROR K32WConfig::MapRamStorageStatus(rsError rsStatus) return err; } -bool K32WConfig::ValidConfigKey(Key key) +bool NXPConfig::ValidConfigKey(Key key) { // Returns true if the key is in the valid CHIP Config PDM key range. if ((key >= kMinConfigKey_ChipFactory) && (key <= kMaxConfigKey_KVSValue)) @@ -425,7 +425,7 @@ bool K32WConfig::ValidConfigKey(Key key) return false; } -void K32WConfig::RunConfigUnitTest() {} +void NXPConfig::RunConfigUnitTest() {} } // namespace Internal } // namespace DeviceLayer diff --git a/src/platform/nxp/k32w/k32w1/K32W1Config.h b/src/platform/nxp/k32w1/K32W1Config.h similarity index 99% rename from src/platform/nxp/k32w/k32w1/K32W1Config.h rename to src/platform/nxp/k32w1/K32W1Config.h index a14b4d5cd1..ceeae82a8d 100644 --- a/src/platform/nxp/k32w/k32w1/K32W1Config.h +++ b/src/platform/nxp/k32w1/K32W1Config.h @@ -49,7 +49,7 @@ constexpr inline uint16_t K32WConfigKey(uint8_t chipId, uint8_t nvmId) * naturally provides implementations for the delegated members referenced by * the template class (e.g. the ReadConfigValue() method). */ -class K32WConfig +class NXPConfig { public: // Category ids used by the CHIP Device Layer diff --git a/src/platform/nxp/k32w/k32w1/K32W1PersistentStorageOpKeystore.cpp b/src/platform/nxp/k32w1/K32W1PersistentStorageOpKeystore.cpp similarity index 100% rename from src/platform/nxp/k32w/k32w1/K32W1PersistentStorageOpKeystore.cpp rename to src/platform/nxp/k32w1/K32W1PersistentStorageOpKeystore.cpp diff --git a/src/platform/nxp/k32w/k32w1/K32W1PersistentStorageOpKeystore.h b/src/platform/nxp/k32w1/K32W1PersistentStorageOpKeystore.h similarity index 100% rename from src/platform/nxp/k32w/k32w1/K32W1PersistentStorageOpKeystore.h rename to src/platform/nxp/k32w1/K32W1PersistentStorageOpKeystore.h diff --git a/src/platform/nxp/k32w/k32w1/KeyValueStoreManagerImpl.cpp b/src/platform/nxp/k32w1/KeyValueStoreManagerImpl.cpp similarity index 85% rename from src/platform/nxp/k32w/k32w1/KeyValueStoreManagerImpl.cpp rename to src/platform/nxp/k32w1/KeyValueStoreManagerImpl.cpp index 6af22df678..f70c6abb6c 100644 --- a/src/platform/nxp/k32w/k32w1/KeyValueStoreManagerImpl.cpp +++ b/src/platform/nxp/k32w1/KeyValueStoreManagerImpl.cpp @@ -25,7 +25,7 @@ #include #include -#include +#include #include #include @@ -45,7 +45,7 @@ uint16_t GetStringKeyId(const char * key, uint16_t * freeId) { CHIP_ERROR err = CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND; uint8_t keyId = 0; - uint8_t nvmIdKvsKey = chip::DeviceLayer::Internal::K32WConfig::kFileId_KVSKey; + uint8_t nvmIdKvsKey = chip::DeviceLayer::Internal::NXPConfig::kFileId_KVSKey; bool bFreeIdxFound = false; char keyString[kMaxKeyValueBytes] = { 0 }; size_t keyStringSize = 0; @@ -55,7 +55,7 @@ uint16_t GetStringKeyId(const char * key, uint16_t * freeId) { nvmInternalId = chip::DeviceLayer::Internal::K32WConfigKey(nvmIdKvsKey, keyId); err = - chip::DeviceLayer::Internal::K32WConfig::ReadConfigValueStr(nvmInternalId, keyString, kMaxKeyValueBytes, keyStringSize); + chip::DeviceLayer::Internal::NXPConfig::ReadConfigValueStr(nvmInternalId, keyString, kMaxKeyValueBytes, keyStringSize); if (err == CHIP_NO_ERROR) { @@ -78,7 +78,7 @@ CHIP_ERROR KeyValueStoreManagerImpl::_Get(const char * key, void * value, size_t size_t offset_bytes) { CHIP_ERROR err = CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND; - uint8_t nvmIdKvsValue = chip::DeviceLayer::Internal::K32WConfig::kFileId_KVSValue; + uint8_t nvmIdKvsValue = chip::DeviceLayer::Internal::NXPConfig::kFileId_KVSValue; size_t read_bytes = 0; uint8_t keyId = 0; uint16_t nvmInternalId = 0; @@ -92,7 +92,7 @@ CHIP_ERROR KeyValueStoreManagerImpl::_Get(const char * key, void * value, size_t // This is the ID of the actual data nvmInternalId = chip::DeviceLayer::Internal::K32WConfigKey(nvmIdKvsValue, keyId); ChipLogProgress(DeviceLayer, "KVS, get the value of Matter key [%s] with NVM id: %i", key, nvmInternalId); - err = chip::DeviceLayer::Internal::K32WConfig::ReadConfigValueBin(nvmInternalId, (uint8_t *) value, value_size, read_bytes); + err = chip::DeviceLayer::Internal::NXPConfig::ReadConfigValueBin(nvmInternalId, (uint8_t *) value, value_size, read_bytes); // According to Get api read_bytes_size can be null if (read_bytes_size) @@ -115,8 +115,8 @@ CHIP_ERROR KeyValueStoreManagerImpl::_Put(const char * key, const void * value, { CHIP_ERROR err = CHIP_ERROR_INVALID_ARGUMENT; bool_t putKey = false; - uint8_t nvmIdKvsKey = chip::DeviceLayer::Internal::K32WConfig::kFileId_KVSKey; - uint8_t nvmIdKvsValue = chip::DeviceLayer::Internal::K32WConfig::kFileId_KVSValue; + uint8_t nvmIdKvsKey = chip::DeviceLayer::Internal::NXPConfig::kFileId_KVSKey; + uint8_t nvmIdKvsValue = chip::DeviceLayer::Internal::NXPConfig::kFileId_KVSValue; uint16_t nvmInternalId = 0; uint16_t freeKeyId; uint8_t keyId; @@ -135,7 +135,7 @@ CHIP_ERROR KeyValueStoreManagerImpl::_Put(const char * key, const void * value, nvmInternalId = chip::DeviceLayer::Internal::K32WConfigKey(nvmIdKvsValue, keyId); ChipLogProgress(DeviceLayer, "KVS, save in flash the value of the Matter key [%s] with NVM id: %i", key, nvmInternalId); - err = chip::DeviceLayer::Internal::K32WConfig::WriteConfigValueBin(nvmInternalId, (uint8_t *) value, value_size); + err = chip::DeviceLayer::Internal::NXPConfig::WriteConfigValueBin(nvmInternalId, (uint8_t *) value, value_size); /* save the 'key' in flash such that it can be retrieved later on */ if (err == CHIP_NO_ERROR) @@ -145,7 +145,7 @@ CHIP_ERROR KeyValueStoreManagerImpl::_Put(const char * key, const void * value, nvmInternalId = chip::DeviceLayer::Internal::K32WConfigKey(nvmIdKvsKey, keyId); ChipLogProgress(DeviceLayer, "KVS, save in flash the Matter key [%s] with NVM id: %i", key, nvmInternalId); - err = chip::DeviceLayer::Internal::K32WConfig::WriteConfigValueStr(nvmInternalId, key, strlen(key) + 1); + err = chip::DeviceLayer::Internal::NXPConfig::WriteConfigValueStr(nvmInternalId, key, strlen(key) + 1); if (err != CHIP_NO_ERROR) { @@ -168,8 +168,8 @@ CHIP_ERROR KeyValueStoreManagerImpl::_Put(const char * key, const void * value, CHIP_ERROR KeyValueStoreManagerImpl::_Delete(const char * key) { CHIP_ERROR err = CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND; - uint8_t nvmIdKvsKey = chip::DeviceLayer::Internal::K32WConfig::kFileId_KVSKey; - uint8_t nvmIdKvsValue = chip::DeviceLayer::Internal::K32WConfig::kFileId_KVSValue; + uint8_t nvmIdKvsKey = chip::DeviceLayer::Internal::NXPConfig::kFileId_KVSKey; + uint8_t nvmIdKvsValue = chip::DeviceLayer::Internal::NXPConfig::kFileId_KVSValue; uint8_t keyId = 0; uint16_t nvmInternalId = 0; @@ -183,7 +183,7 @@ CHIP_ERROR KeyValueStoreManagerImpl::_Delete(const char * key) nvmInternalId = chip::DeviceLayer::Internal::K32WConfigKey(nvmIdKvsKey, keyId); ChipLogProgress(DeviceLayer, "KVS, delete from flash the Matter key [%s] with NVM id: %i", key, nvmInternalId); - err = chip::DeviceLayer::Internal::K32WConfig::ClearConfigValue(nvmInternalId); + err = chip::DeviceLayer::Internal::NXPConfig::ClearConfigValue(nvmInternalId); /* also delete the 'key string' from flash */ if (err == CHIP_NO_ERROR) @@ -192,7 +192,7 @@ CHIP_ERROR KeyValueStoreManagerImpl::_Delete(const char * key) ChipLogProgress(DeviceLayer, "KVS, delete from flash the value of the Matter key [%s] with NVM id: %i", key, nvmInternalId); - err = chip::DeviceLayer::Internal::K32WConfig::ClearConfigValue(nvmInternalId); + err = chip::DeviceLayer::Internal::NXPConfig::ClearConfigValue(nvmInternalId); if (err != CHIP_NO_ERROR) { diff --git a/src/platform/nxp/k32w/k32w1/KeyValueStoreManagerImpl.h b/src/platform/nxp/k32w1/KeyValueStoreManagerImpl.h similarity index 100% rename from src/platform/nxp/k32w/k32w1/KeyValueStoreManagerImpl.h rename to src/platform/nxp/k32w1/KeyValueStoreManagerImpl.h diff --git a/src/platform/nxp/k32w/k32w1/Logging.cpp b/src/platform/nxp/k32w1/Logging.cpp similarity index 98% rename from src/platform/nxp/k32w/k32w1/Logging.cpp rename to src/platform/nxp/k32w1/Logging.cpp index 8f8aedd667..8efa4539fd 100644 --- a/src/platform/nxp/k32w/k32w1/Logging.cpp +++ b/src/platform/nxp/k32w1/Logging.cpp @@ -12,7 +12,7 @@ #include "fsl_debug_console.h" #include -#ifdef PW_RPC_ENABLED +#ifdef CONFIG_ENABLE_PW_RPC #include #endif @@ -113,7 +113,7 @@ void ENFORCE_FORMAT(1, 0) GenericLog(const char * format, va_list arg, const cha if (!isLogInitialized) { isLogInitialized = true; -#ifndef PW_RPC_ENABLED +#ifndef CONFIG_ENABLE_PW_RPC otPlatUartEnable(); #endif } @@ -127,7 +127,7 @@ void ENFORCE_FORMAT(1, 0) GenericLog(const char * format, va_list arg, const cha VerifyOrDie(writtenLen > 0); memcpy(formattedMsg + prefixLen + writtenLen, EOL_CHARS, EOL_CHARS_LEN); -#ifndef PW_RPC_ENABLED +#ifndef CONFIG_ENABLE_PW_RPC otPlatUartSendBlocking((const uint8_t *) formattedMsg, strlen(formattedMsg)); #else PigweedLogger::PutString((const char *) formattedMsg, strlen(formattedMsg)); diff --git a/src/platform/nxp/k32w/k32w1/LowPowerHooks.cpp b/src/platform/nxp/k32w1/LowPowerHooks.cpp similarity index 100% rename from src/platform/nxp/k32w/k32w1/LowPowerHooks.cpp rename to src/platform/nxp/k32w1/LowPowerHooks.cpp diff --git a/src/platform/nxp/k32w/k32w1/OTAFirmwareProcessor.cpp b/src/platform/nxp/k32w1/OTAFirmwareProcessor.cpp similarity index 96% rename from src/platform/nxp/k32w/k32w1/OTAFirmwareProcessor.cpp rename to src/platform/nxp/k32w1/OTAFirmwareProcessor.cpp index ee3ff9b655..33eed513ba 100644 --- a/src/platform/nxp/k32w/k32w1/OTAFirmwareProcessor.cpp +++ b/src/platform/nxp/k32w1/OTAFirmwareProcessor.cpp @@ -17,8 +17,8 @@ */ #include -#include -#include +#include +#include #include "OtaSupport.h" diff --git a/src/platform/nxp/k32w/k32w1/OTAFirmwareProcessor.h b/src/platform/nxp/k32w1/OTAFirmwareProcessor.h similarity index 96% rename from src/platform/nxp/k32w/k32w1/OTAFirmwareProcessor.h rename to src/platform/nxp/k32w1/OTAFirmwareProcessor.h index c06a2342ba..b8bb3abd00 100644 --- a/src/platform/nxp/k32w/k32w1/OTAFirmwareProcessor.h +++ b/src/platform/nxp/k32w1/OTAFirmwareProcessor.h @@ -20,7 +20,7 @@ #include "OtaPrivate.h" #include -#include +#include /* Posted Operations Size Info */ #define NB_PENDING_TRANSACTIONS 12 diff --git a/src/platform/nxp/k32w/k32w1/OTAHooks.cpp b/src/platform/nxp/k32w1/OTAHooks.cpp similarity index 82% rename from src/platform/nxp/k32w/k32w1/OTAHooks.cpp rename to src/platform/nxp/k32w1/OTAHooks.cpp index c045a11161..3bbabaa274 100644 --- a/src/platform/nxp/k32w/k32w1/OTAHooks.cpp +++ b/src/platform/nxp/k32w1/OTAHooks.cpp @@ -16,12 +16,16 @@ * limitations under the License. */ -#include +#include #include #include -#include +#include +#if CONFIG_CHIP_OTA_FACTORY_DATA_PROCESSOR +#include +#include +#endif // CONFIG_CHIP_OTA_FACTORY_DATA_PROCESSOR #include "OtaSupport.h" @@ -34,6 +38,7 @@ #endif #define APPLICATION_PROCESSOR_TAG 1 +#define FACTORY_DATA_PROCESSOR_TAG 3 extern "C" void HAL_ResetMCU(void); @@ -60,10 +65,17 @@ extern "C" WEAK CHIP_ERROR OtaHookInit() static chip::OTAFirmwareProcessor processors[8]; #endif +#if CONFIG_CHIP_OTA_FACTORY_DATA_PROCESSOR + static chip::OTAFactoryDataProcessor sFactoryDataProcessor; +#endif // CONFIG_CHIP_OTA_FACTORY_DATA_PROCESSOR + gApplicationProcessor.RegisterDescriptorCallback(ProcessDescriptor); auto & imageProcessor = chip::OTAImageProcessorImpl::GetDefaultInstance(); ReturnErrorOnFailure(imageProcessor.RegisterProcessor(APPLICATION_PROCESSOR_TAG, &gApplicationProcessor)); +#if CONFIG_CHIP_OTA_FACTORY_DATA_PROCESSOR + ReturnErrorOnFailure(imageProcessor.RegisterProcessor(FACTORY_DATA_PROCESSOR_TAG, &sFactoryDataProcessor)); +#endif // CONFIG_CHIP_OTA_FACTORY_DATA_PROCESSOR #if CONFIG_CHIP_K32W1_MAX_ENTRIES_TEST for (auto i = 0; i < 8; i++) @@ -78,8 +90,11 @@ extern "C" WEAK CHIP_ERROR OtaHookInit() extern "C" WEAK void OtaHookReset() { +#if (CHIP_PLAT_NVM_SUPPORT == 1) // Process all idle saves NvShutdown(); +#endif + // Set the bootloader flags OTA_SetNewImageFlag(); ResetMCU(); diff --git a/src/platform/nxp/k32w/k32w1/PlatformManagerImpl.cpp b/src/platform/nxp/k32w1/PlatformManagerImpl.cpp similarity index 80% rename from src/platform/nxp/k32w/k32w1/PlatformManagerImpl.cpp rename to src/platform/nxp/k32w1/PlatformManagerImpl.cpp index 40d747fc8a..964884e775 100644 --- a/src/platform/nxp/k32w/k32w1/PlatformManagerImpl.cpp +++ b/src/platform/nxp/k32w1/PlatformManagerImpl.cpp @@ -26,11 +26,17 @@ #include #include +#include #include #include #include -#include -#include +#ifdef EXTERNAL_CONFIGURATIONMANAGERIMPL_HEADER +#include EXTERNAL_CONFIGURATIONMANAGERIMPL_HEADER +#else +#include +#endif +#include +#include #if CHIP_SYSTEM_CONFIG_USE_LWIP #include @@ -40,7 +46,10 @@ #include "fwk_platform.h" #include +#include + extern "C" void HAL_ResetMCU(void); +extern "C" void freertos_mbedtls_mutex_init(void); extern uint8_t __data_end__[], m_data0_end[]; memAreaCfg_t data0Heap = { .start_address = (void *) __data_end__, .end_address = (void *) m_data0_end }; @@ -60,7 +69,19 @@ namespace DeviceLayer { PlatformManagerImpl PlatformManagerImpl::sInstance; -CHIP_ERROR PlatformManagerImpl::InitBoardFwk(void) +void PlatformManagerImpl::HardwareInit(void) +{ + mbedtls_platform_set_calloc_free(CHIPPlatformMemoryCalloc, CHIPPlatformMemoryFree); + + /* Used for HW initializations */ + otSysInit(0, NULL); + + /* Mbedtls Threading support is needed because both + * Thread and Matter tasks are using it */ + freertos_mbedtls_mutex_init(); +} + +CHIP_ERROR PlatformManagerImpl::ServiceInit(void) { mem_status_t memSt = kStatus_MemSuccess; @@ -71,11 +92,12 @@ CHIP_ERROR PlatformManagerImpl::InitBoardFwk(void) return CHIP_NO_ERROR; } + void PlatformManagerImpl::CleanReset() { StopEventLoopTask(); Shutdown(); -#if CHIP_PLAT_NVM_SUPPORT +#if (CHIP_PLAT_NVM_SUPPORT == 1) NvCompletePendingOperations(); #endif HAL_ResetMCU(); @@ -99,7 +121,10 @@ CHIP_ERROR PlatformManagerImpl::_InitChipStack(void) CHIP_ERROR err = CHIP_NO_ERROR; // Initialize the configuration system. - err = Internal::K32WConfig::Init(); + err = Internal::NXPConfig::Init(); + SuccessOrExit(err); + + err = ServiceInit(); SuccessOrExit(err); SetConfigurationMgr(&ConfigurationManagerImpl::GetDefaultInstance()); @@ -119,6 +144,10 @@ CHIP_ERROR PlatformManagerImpl::_InitChipStack(void) err = Internal::GenericPlatformManagerImpl_FreeRTOS::_InitChipStack(); SuccessOrExit(err); +#if USE_SMU2_DYNAMIC + ReturnErrorOnFailure(SMU2::Init()); +#endif + exit: return err; } diff --git a/src/platform/nxp/k32w/k32w1/PlatformManagerImpl.h b/src/platform/nxp/k32w1/PlatformManagerImpl.h similarity index 96% rename from src/platform/nxp/k32w/k32w1/PlatformManagerImpl.h rename to src/platform/nxp/k32w1/PlatformManagerImpl.h index 6798cb911e..ae1ef0ad3e 100644 --- a/src/platform/nxp/k32w/k32w1/PlatformManagerImpl.h +++ b/src/platform/nxp/k32w1/PlatformManagerImpl.h @@ -49,8 +49,10 @@ class PlatformManagerImpl final : public PlatformManager, public Internal::Gener // ===== Platform-specific members that may be accessed directly by the application. System::Clock::Timestamp GetStartTime() { return mStartTime; } - CHIP_ERROR InitBoardFwk(void); + void HardwareInit(void); + CHIP_ERROR ServiceInit(void); void CleanReset(); + void StopBLEConnectivity() {} private: // ===== Methods that implement the PlatformManager abstract interface. diff --git a/src/platform/nxp/k32w/k32w1/SMU2Manager.cpp b/src/platform/nxp/k32w1/SMU2Manager.cpp similarity index 99% rename from src/platform/nxp/k32w/k32w1/SMU2Manager.cpp rename to src/platform/nxp/k32w1/SMU2Manager.cpp index f7c54ea7c7..6f941b3f10 100644 --- a/src/platform/nxp/k32w/k32w1/SMU2Manager.cpp +++ b/src/platform/nxp/k32w1/SMU2Manager.cpp @@ -123,6 +123,7 @@ CHIP_ERROR Init() if (mUseAllocator) { + ResetBLEController(); RegisterArea(); } diff --git a/src/platform/nxp/k32w/k32w1/SMU2Manager.h b/src/platform/nxp/k32w1/SMU2Manager.h similarity index 100% rename from src/platform/nxp/k32w/k32w1/SMU2Manager.h rename to src/platform/nxp/k32w1/SMU2Manager.h diff --git a/src/platform/nxp/k32w/k32w1/SystemPlatformConfig.h b/src/platform/nxp/k32w1/SystemPlatformConfig.h similarity index 100% rename from src/platform/nxp/k32w/k32w1/SystemPlatformConfig.h rename to src/platform/nxp/k32w1/SystemPlatformConfig.h diff --git a/src/platform/nxp/k32w/k32w1/SystemTimeSupport.cpp b/src/platform/nxp/k32w1/SystemTimeSupport.cpp similarity index 100% rename from src/platform/nxp/k32w/k32w1/SystemTimeSupport.cpp rename to src/platform/nxp/k32w1/SystemTimeSupport.cpp diff --git a/src/platform/nxp/k32w/k32w1/ThreadStackManagerImpl.cpp b/src/platform/nxp/k32w1/ThreadStackManagerImpl.cpp similarity index 90% rename from src/platform/nxp/k32w/k32w1/ThreadStackManagerImpl.cpp rename to src/platform/nxp/k32w1/ThreadStackManagerImpl.cpp index 89c63694fe..c7b16ffd3e 100644 --- a/src/platform/nxp/k32w/k32w1/ThreadStackManagerImpl.cpp +++ b/src/platform/nxp/k32w1/ThreadStackManagerImpl.cpp @@ -35,7 +35,7 @@ #include #if defined(USE_SMU2_DYNAMIC) -#include +#include #endif #include @@ -89,6 +89,18 @@ bool ThreadStackManagerImpl::IsInitialized() using namespace ::chip; using namespace ::chip::DeviceLayer; +/** + * Glue function called directly by the OpenThread stack + * when system event processing work is pending. + */ +extern "C" void otSysEventSignalPending(void) +{ + { + BaseType_t yieldRequired = chip::DeviceLayer::ThreadStackMgrImpl().SignalThreadActivityPendingFromISR(); + portYIELD_FROM_ISR(yieldRequired); + } +} + /** * Glue function called directly by the OpenThread stack when tasklet processing work * is pending. diff --git a/src/platform/nxp/k32w/k32w1/ThreadStackManagerImpl.h b/src/platform/nxp/k32w1/ThreadStackManagerImpl.h similarity index 100% rename from src/platform/nxp/k32w/k32w1/ThreadStackManagerImpl.h rename to src/platform/nxp/k32w1/ThreadStackManagerImpl.h diff --git a/src/platform/nxp/k32w/k32w1/args.gni b/src/platform/nxp/k32w1/args.gni similarity index 72% rename from src/platform/nxp/k32w/k32w1/args.gni rename to src/platform/nxp/k32w1/args.gni index 8b90982be9..1c984c386e 100644 --- a/src/platform/nxp/k32w/k32w1/args.gni +++ b/src/platform/nxp/k32w1/args.gni @@ -19,15 +19,28 @@ import("//build_overrides/openthread.gni") declare_args() { chip_with_ot_cli = 0 chip_with_low_power = 0 - sdk_release = 1 + sdk_release = false + k32w1_sdk_root = "" + + # 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 + + k32w1_sdk_root = "${nxp_sdk_matter_support_root}/github_sdk/common_sdk/repo" +} + +if (sdk_release || getenv("NXP_SDK_ROOT") != "") { + k32w1_sdk_root = getenv("NXP_SDK_ROOT") } -nxp_platform = "k32w/k32w1" +openthread_root = + "//third_party/connectedhomeip/third_party/openthread/ot-nxp/openthread" +nxp_platform = "k32w1" nxp_sdk_name = "k32w1_sdk" nxp_device_layer = "nxp/${nxp_platform}" nxp_use_lwip = false -nxp_use_mbedtls_port = false # ARM architecture flags will be set based on NXP board. arm_platform_config = "${nxp_sdk_build_root}/${nxp_sdk_name}/nxp_arm.gni" @@ -39,8 +52,6 @@ chip_project_config_include = "" chip_inet_project_config_include = "" chip_system_project_config_include = "" chip_ble_project_config_include = "" -chip_project_config_include_dirs = - [ "${chip_root}/examples/platform/${nxp_platform}/app/project_include" ] chip_enable_openthread = true @@ -57,12 +68,12 @@ chip_mdns = "platform" chip_system_config_use_open_thread_inet_endpoints = true chip_with_lwip = false -mbedtls_target = "${nxp_sdk_build_root}/${nxp_sdk_name}:mbedtls" +mbedtls_target = "${nxp_sdk_build_root}:nxp_mbedtls" openthread_external_mbedtls = mbedtls_target openthread_project_core_config_file = "OpenThreadConfig.h" openthread_core_config_platform_check_file = "openthread-core-k32w1-config-check.h" -openthread_core_config_deps = [ "${chip_root}/examples/platform/nxp/k32w/k32w1:openthread_core_config_k32w1_chip_examples" ] +openthread_core_config_deps = [ "${chip_root}/third_party/openthread/platforms/nxp/${nxp_platform}:openthread_core_config_k32w1" ] -openthread_external_platform = "${chip_root}/third_party/openthread/platforms/nxp/k32w/k32w1:libopenthread-k32w1" +openthread_external_platform = "${chip_root}/third_party/openthread/platforms/nxp/${nxp_platform}:libopenthread-k32w1" diff --git a/src/platform/nxp/k32w/k32w1/ble_function_mux.c b/src/platform/nxp/k32w1/ble_function_mux.c similarity index 100% rename from src/platform/nxp/k32w/k32w1/ble_function_mux.c rename to src/platform/nxp/k32w1/ble_function_mux.c diff --git a/src/platform/nxp/k32w/k32w1/ble_function_mux.h b/src/platform/nxp/k32w1/ble_function_mux.h similarity index 100% rename from src/platform/nxp/k32w/k32w1/ble_function_mux.h rename to src/platform/nxp/k32w1/ble_function_mux.h diff --git a/src/platform/nxp/k32w/k32w1/gatt_db.h b/src/platform/nxp/k32w1/gatt_db.h similarity index 100% rename from src/platform/nxp/k32w/k32w1/gatt_db.h rename to src/platform/nxp/k32w1/gatt_db.h diff --git a/src/platform/nxp/k32w/k32w1/gatt_uuid128.h b/src/platform/nxp/k32w1/gatt_uuid128.h similarity index 100% rename from src/platform/nxp/k32w/k32w1/gatt_uuid128.h rename to src/platform/nxp/k32w1/gatt_uuid128.h diff --git a/src/platform/nxp/k32w/k32w1/k32w1-chip-mbedtls-config.h b/src/platform/nxp/k32w1/k32w1-chip-mbedtls-config.h similarity index 100% rename from src/platform/nxp/k32w/k32w1/k32w1-chip-mbedtls-config.h rename to src/platform/nxp/k32w1/k32w1-chip-mbedtls-config.h diff --git a/src/platform/nxp/k32w/k32w1/ram_storage.c b/src/platform/nxp/k32w1/ram_storage.c similarity index 100% rename from src/platform/nxp/k32w/k32w1/ram_storage.c rename to src/platform/nxp/k32w1/ram_storage.c diff --git a/src/platform/nxp/k32w/k32w1/ram_storage.h b/src/platform/nxp/k32w1/ram_storage.h similarity index 100% rename from src/platform/nxp/k32w/k32w1/ram_storage.h rename to src/platform/nxp/k32w1/ram_storage.h diff --git a/src/platform/nxp/rt/rw61x/BUILD.gn b/src/platform/nxp/rt/rw61x/BUILD.gn index 7337f896c8..1793b50884 100644 --- a/src/platform/nxp/rt/rw61x/BUILD.gn +++ b/src/platform/nxp/rt/rw61x/BUILD.gn @@ -22,6 +22,11 @@ import("${nxp_sdk_build_root}/nxp_sdk.gni") assert(chip_device_platform == "nxp") +source_set("nxp_factory_data") { +} +source_set("nxp_ota") { +} + config("nxp_platform_config") { defines = [ "EXTERNAL_BLEMANAGERIMPL_HEADER=\"platform/nxp/common/ble_zephyr/BLEManagerImpl.h\"" ] include_dirs = [ diff --git a/third_party/nxp/nxp_matter_support b/third_party/nxp/nxp_matter_support index e6deaf5600..2aad923994 160000 --- a/third_party/nxp/nxp_matter_support +++ b/third_party/nxp/nxp_matter_support @@ -1 +1 @@ -Subproject commit e6deaf5600138763ea68418e34bc62a02d1aef0d +Subproject commit 2aad9239944047012e525caf52119a5c84b704d3 diff --git a/third_party/openthread/platforms/nxp/k32w/k32w1/BUILD.gn b/third_party/openthread/platforms/nxp/k32w1/BUILD.gn similarity index 73% rename from third_party/openthread/platforms/nxp/k32w/k32w1/BUILD.gn rename to third_party/openthread/platforms/nxp/k32w1/BUILD.gn index b004389a09..38a2f231cb 100644 --- a/third_party/openthread/platforms/nxp/k32w/k32w1/BUILD.gn +++ b/third_party/openthread/platforms/nxp/k32w1/BUILD.gn @@ -24,7 +24,6 @@ openthread_nxp_root = "${chip_root}/third_party/openthread/ot-nxp" config("openthread_k32w1_config") { include_dirs = [ "${openthread_nxp_root}/src/k32w1/k32w1" ] - include_dirs += [ "${chip_root}/examples/platform/nxp/k32w/k32w1" ] defines = [ "OPENTHREAD_CONFIG_HEAP_EXTERNAL_ENABLE=1", @@ -34,12 +33,27 @@ config("openthread_k32w1_config") { "MBEDTLS_THREADING_ALT=1", ] + if (chip_mdns == "platform") { + defines += [ + "OPENTHREAD_CONFIG_SRP_CLIENT_ENABLE=1", + "OPENTHREAD_CONFIG_ECDSA_ENABLE=1", + "OPENTHREAD_CONFIG_DNS_CLIENT_SERVICE_DISCOVERY_ENABLE=1", + "OPENTHREAD_CONFIG_DNS_CLIENT_ENABLE=1", + ] + } + if (use_smu2_dynamic) { defines += [ "OPENTHREAD_CONFIG_MESSAGE_USE_HEAP_ENABLE=1", "OPENTHREAD_CONFIG_ENABLE_BUILTIN_MBEDTLS_MANAGEMENT=0", ] } + + if (chip_key_storage == "littlefs") { + defines += [ "OT_PLAT_SAVE_NVM_DATA_ON_IDLE=0" ] + } else if (chip_key_storage == "nvs") { + defines += [ "CONFIG_SETTINGS_RUNTIME=1" ] + } } source_set("openthread_core_config_k32w1") { @@ -49,16 +63,12 @@ source_set("openthread_core_config_k32w1") { ] public_configs = [ ":openthread_k32w1_config" ] -} - -source_set("openthread_mbedtls_config_k32w1") { - sources = [ "${openthread_nxp_root}/src/k32w1/k32w1/k32w1-mbedtls-config.h" ] + public_deps = [ nxp_sdk_target ] } source_set("libopenthread-k32w1") { sources = [ "${openthread_nxp_root}/src/common/crypto.c", - "${openthread_nxp_root}/src/common/flash_nvm.c", "${openthread_nxp_root}/src/k32w1/k32w1/alarm.c", "${openthread_nxp_root}/src/k32w1/k32w1/diag.c", "${openthread_nxp_root}/src/k32w1/k32w1/entropy.c", @@ -79,6 +89,14 @@ source_set("libopenthread-k32w1") { if (use_hw_aes) { sources += [ "${openthread_nxp_root}/src/k32w1/k32w1/aes_sss.cpp" ] } + + if (chip_key_storage == "fwk_nvm") { + sources += [ "${openthread_nxp_root}/src/common/flash_nvm.c" ] + } else if (chip_key_storage == "littlefs") { + sources += [ "${openthread_nxp_root}/src/common/flash_fsa.c" ] + } else if (chip_key_storage == "nvs") { + sources += [ "${openthread_nxp_root}/src/common/flash_nvs.c" ] + } } if (chip_with_ot_cli == 1) { @@ -86,10 +104,9 @@ source_set("libopenthread-k32w1") { } public_deps = [ - ":openthread_core_config_k32w1", - "${nxp_sdk_build_root}:nxp_sdk", - "${openthread_root}/src/core:libopenthread_core_headers", - "../../..:libopenthread-platform", - "../../..:libopenthread-platform-utils", + "${nxp_sdk_build_root}:nxp_mbedtls", + "../..:libopenthread-platform", + "../..:libopenthread-platform-utils", + nxp_sdk_target, ] } From d95acb48a5debaaa78f75537119d2dc0f2dff5bc Mon Sep 17 00:00:00 2001 From: Yufeng Wang Date: Thu, 15 Aug 2024 07:58:59 -0700 Subject: [PATCH 053/165] [Fabric-Sync] Simplify and update the fabric sync guide (#34993) * [Fabric-Sync] Symplify and update the fabric sync guide * Restyled by prettier-markdown * Update docs/guides/fabric_synchronization_guide.md Co-authored-by: Terence Hampson * Update docs/guides/fabric_synchronization_guide.md Co-authored-by: saurabhst * Address review comments --------- Co-authored-by: Restyled.io Co-authored-by: Terence Hampson Co-authored-by: saurabhst --- docs/guides/fabric_synchronization_guide.md | 108 ++++++++++++------ .../fabric-sync/FabricSyncCommand.cpp | 2 + .../device_manager/DeviceManager.cpp | 3 +- .../fabric-admin/scripts/run_fabric_sink.sh | 78 ------------- ...un_fabric_source.sh => run_fabric_sync.sh} | 14 +-- ...p_fabric_source.sh => stop_fabric_sync.sh} | 0 6 files changed, 84 insertions(+), 121 deletions(-) delete mode 100755 examples/fabric-admin/scripts/run_fabric_sink.sh rename examples/fabric-admin/scripts/{run_fabric_source.sh => run_fabric_sync.sh} (85%) rename examples/fabric-admin/scripts/{stop_fabric_source.sh => stop_fabric_sync.sh} (100%) diff --git a/docs/guides/fabric_synchronization_guide.md b/docs/guides/fabric_synchronization_guide.md index 1b545ce36e..b2cfd26d9f 100644 --- a/docs/guides/fabric_synchronization_guide.md +++ b/docs/guides/fabric_synchronization_guide.md @@ -2,7 +2,9 @@ - [Fabric Synchronization Guide](#fabric-synchronization-guide) - [Fabric Sync Example Applications](#fabric-sync-example-applications) - - [Run Fabric Sync Demo on RP4](#run-fabric-sync-demo-on-rp4) + - [Bootstrap Fabric Sync Demo on Linux](#bootstrap-fabric-sync-demo-on-linux) + - [Bootstrap Fabric Sync Demo on RP4](#bootstrap-fabric-sync-demo-on-rp4) + - [Run Fabric Sync Demo](#run-fabric-sync-demo) ## Fabric Sync Example Applications @@ -38,27 +40,29 @@ enables a seamless and efficient synchronization process. [Fabric-Bridge](https://github.com/project-chip/connectedhomeip/tree/master/examples/fabric-bridge-app/linux/README.md) -## Run Fabric Sync Demo on RP4 +## Bootstrap Fabric Sync Demo on Linux -### Setup Fabric Source +### Start Fabric Synchronization on Ecosystem 1 -Connect to the Fabric Source server: +Run the Fabric Synchronization script: ``` -ssh ubuntu@xxx.xxx.xxx.xxx +./examples/fabric-admin/scripts/run_fabric_sync.sh ``` -Password: +### Start Fabric Synchronization on Ecosystem 2 -Run the Fabric Source script: +Run the Fabric Synchronization script: ``` -./run_fabric_source.sh +./examples/fabric-admin/scripts/run_fabric_sync.sh ``` -### Setup Fabric Sink +## Bootstrap Fabric Sync Demo on RP4 -Connect to the Fabric Sink server: +### Start Fabric Synchronization on Ecosystem 1 + +Connect to the Ecosystem 1 server: ``` ssh ubuntu@xxx.xxx.xxx.xxx @@ -66,29 +70,41 @@ ssh ubuntu@xxx.xxx.xxx.xxx Password: -Run the Fabric Sink script: +Run the Fabric Synchronization script: ``` -./run_fabric_sink.sh +./run_fabric_sync.sh ``` -### Fabric Sync Setup +### Start Fabric Synchronization on Ecosystem 2 + +Connect to the Ecosystem 2 server: + +``` +ssh ubuntu@xxx.xxx.xxx.xxx +``` -Enable Fabric Auto Sync: +Password: -In Fabric-Sync console: +Run the Fabric Synchronization script: ``` -fabricsync enable-auto-sync 1 +./run_fabric_sync.sh ``` -Pair the Fabric-Source bridge to Fabric-Sync with node ID 1: +## Run Fabric Sync Demo + +### Fabric Sync Setup + +In Ecosystem 1 Fabric-Admin console: + +Pair the Ecosystem 2 bridge to Ecosystem 1 with node ID 2: ``` -fabricsync add-bridge 1 +fabricsync add-bridge 2 ``` -### Pair Light Example to Fabric-Source +### Pair Light Example to Ecosystem 2 Since Fabric-Bridge also functions as a Matter server, running it alongside the Light Example app on the same machine would cause conflicts. Therefore, you need @@ -114,26 +130,47 @@ Pair the Light Example with node ID 3 using its payload number: pairing already-discovered 3 20202021 5540 ``` -After the Light Example is successfully paired in Fabric-Source, it will be -synced to Fabric-Sink with a new assigned node ID. +After the device is successfully added, you will observe the following on +Ecosystem 2 with the newly assigned Node ID: + +``` +>>> New device with Node ID: 0x3 has been successfully added. +``` + +Additionally, you should also get notified when a new device is added to +Ecosystem 2 from the Ecosystem 1: + +``` +>>> A new device is added on Endpoint 3. +``` + +### Synchronize Light Example to Ecosystem 1 + +After the Light Example is successfully paired in Ecosystem 2, we can start to +synchronize the light device to Ecosystem 1 using the new assigned dynamic +endpointid on Ecosystem 2. + +``` +fabricsync sync-device +``` Toggle the Light Example: -From Fabric-Source: +From Ecosystem 1: ``` onoff on 1 onoff off 1 ``` -From Fabric-Sink: (Use the node ID assigned) +From Ecosystem 2: (Use the node ID assigned) ``` onoff on x 1 onoff off x 1 ``` -### Remove Light Example from Fabric-Source +### Remove Light Example from Ecosystem Unpair the Light Example: @@ -141,9 +178,6 @@ Unpair the Light Example: pairing unpair ``` -After the Light Example is successfully unpaired from Fabric-Source, it will -also be removed from the Fabric-Sink. - ### Pair Commercial Switch to Fabric-Source Pair the switch using its payload number: @@ -154,32 +188,36 @@ In Fabric-Source console: pairing code-wifi ``` -After the switch is successfully paired in Fabric-Source, it will be synced to -Fabric-Sink with a new assigned node ID. +### Synchronize Switch to Ecosystem 1 + +After the switch is successfully paired in Ecosystem 2, we can start to +synchronize it to Ecosystem 1 using the new assigned dynamic endpointid on +Ecosystem 2.. + +``` +fabricsync sync-device +``` Toggle the switch: -From Fabric-Source: +From Ecosystem 1: ``` onoff on 1 onoff off 1 ``` -From Fabric-Sink: (Use the node ID assigned) +From Ecosystem 2: (Use the node ID assigned) ``` onoff on 1 onoff off 1 ``` -### Remove Switch from Fabric-Source +### Remove Switch from Ecosystem Unpair the switch: ``` pairing unpair ``` - -After the switch is successfully unpaired from Fabric-Source, it will also be -removed from the Fabric-Sink. diff --git a/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.cpp b/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.cpp index dade5932fb..f62d85ce5a 100644 --- a/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.cpp +++ b/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.cpp @@ -252,6 +252,8 @@ CHIP_ERROR FabricAutoSyncCommand::RunCommand(bool enableAutoSync) // print to console fprintf(stderr, "Auto Fabric Sync is %s.\n", enableAutoSync ? "enabled" : "disabled"); + fprintf(stderr, + "WARNING: The auto-sync command is currently under development and may contain bugs. Use it at your own risk.\n"); return CHIP_NO_ERROR; } diff --git a/examples/fabric-admin/device_manager/DeviceManager.cpp b/examples/fabric-admin/device_manager/DeviceManager.cpp index 4207378670..7204e153d2 100644 --- a/examples/fabric-admin/device_manager/DeviceManager.cpp +++ b/examples/fabric-admin/device_manager/DeviceManager.cpp @@ -331,7 +331,8 @@ void DeviceManager::HandleAttributeData(const app::ConcreteDataAttributePath & p // Process added endpoints for (const auto & endpoint : addedEndpoints) { - ChipLogProgress(NotSpecified, "Endpoint added: %u", endpoint); + // print to console + fprintf(stderr, "A new devie is added on Endpoint: %u\n", endpoint); if (mAutoSyncEnabled) { diff --git a/examples/fabric-admin/scripts/run_fabric_sink.sh b/examples/fabric-admin/scripts/run_fabric_sink.sh deleted file mode 100755 index 3013965479..0000000000 --- a/examples/fabric-admin/scripts/run_fabric_sink.sh +++ /dev/null @@ -1,78 +0,0 @@ -#!/bin/bash - -# Default paths -DEFAULT_CHOICES=( - "./fabric-admin" - "out/debug/standalone/fabric-admin" - "out/linux-x64-fabric-admin/fabric-admin" - "out/darwin-arm64-fabric-admin/fabric-admin" -) -FABRIC_ADMIN_LOG="/tmp/fabric_admin.log" -FABRIC_ADMIN_PATH="" - -# Function to find fabric-admin binary -find_fabric_admin() { - local choices=("$@") - for path in "${choices[@]}"; do - if [[ -e "$path" ]]; then - echo "$path" - return 0 - fi - done - return 1 -} - -# Parse arguments -VERBOSE=false -SPECIFIED_PATH="" - -for arg in "$@"; do - case $arg in - --verbose) - VERBOSE=true - ;; - --path=*) - SPECIFIED_PATH="${arg#*=}" - ;; - esac -done - -# Use specified path if provided -if [[ -n "$SPECIFIED_PATH" ]]; then - if [[ -e "$SPECIFIED_PATH" ]]; then - FABRIC_ADMIN_PATH="$SPECIFIED_PATH" - else - echo >&2 "Specified path does not exist: $SPECIFIED_PATH" - exit 1 - fi -else - FABRIC_ADMIN_PATH=$(find_fabric_admin "${DEFAULT_CHOICES[@]}") - if [[ $? -ne 0 ]]; then - echo >&2 "Could not find the fabric-admin binary" - exit 1 - fi -fi - -echo "PATH IS: $FABRIC_ADMIN_PATH" - -# Kill fabric-admin if it is running -echo "Checking for running fabric-admin process..." -fabric_admin_pid=$(pgrep -f "$FABRIC_ADMIN_PATH") -if [[ -n "$fabric_admin_pid" ]]; then - echo "Found fabric-admin with PID $fabric_admin_pid, attempting to kill..." - kill -9 "$fabric_admin_pid" - echo "Killed fabric-admin with PID $fabric_admin_pid" -fi - -# Remove /tmp/chip_* files and directories -echo "Removing /tmp/chip_* files and directories..." -sudo rm -rf /tmp/chip_* -echo "Removed /tmp/chip_* files and directories" - -# Start fabric-admin with or without log file path based on --verbose option -echo "Starting fabric-admin..." -if [ "$VERBOSE" = true ]; then - "$FABRIC_ADMIN_PATH" -else - "$FABRIC_ADMIN_PATH" --log-file-path "$FABRIC_ADMIN_LOG" -fi diff --git a/examples/fabric-admin/scripts/run_fabric_source.sh b/examples/fabric-admin/scripts/run_fabric_sync.sh similarity index 85% rename from examples/fabric-admin/scripts/run_fabric_source.sh rename to examples/fabric-admin/scripts/run_fabric_sync.sh index 95df7a135b..8c820d111c 100755 --- a/examples/fabric-admin/scripts/run_fabric_source.sh +++ b/examples/fabric-admin/scripts/run_fabric_sync.sh @@ -86,19 +86,19 @@ fi echo "Admin path: $FABRIC_ADMIN_PATH" echo "Bridge path: $FABRIC_BRIDGE_APP_PATH" -# Determine the path to stop_fabric_source.sh based on the location of run_fabric_source.sh -RUN_FABRIC_SOURCE_PATH=$(find_binary "$SCRIPT_DIR/run_fabric_source.sh") +# Determine the path to stop_fabric_sync.sh based on the location of run_fabric_sync.sh +RUN_FABRIC_SOURCE_PATH=$(find_binary "$SCRIPT_DIR/run_fabric_sync.sh") if [[ $? -ne 0 ]]; then - echo >&2 "Could not find the run_fabric_source.sh script" + echo >&2 "Could not find the run_fabric_sync.sh script" exit 1 fi -STOP_FABRIC_SOURCE_PATH="${RUN_FABRIC_SOURCE_PATH/run_fabric_source/stop_fabric_source}" +STOP_FABRIC_SYNC_PATH="${RUN_FABRIC_SOURCE_PATH/run_fabric_sync/stop_fabric_sync}" # Stop any running instances and clean up -if [[ -e "$STOP_FABRIC_SOURCE_PATH" ]]; then - "$STOP_FABRIC_SOURCE_PATH" +if [[ -e "$STOP_FABRIC_SYNC_PATH" ]]; then + "$STOP_FABRIC_SYNC_PATH" else - echo >&2 "Could not find the stop_fabric_source.sh script" + echo >&2 "Could not find the stop_fabric_sync.sh script" exit 1 fi diff --git a/examples/fabric-admin/scripts/stop_fabric_source.sh b/examples/fabric-admin/scripts/stop_fabric_sync.sh similarity index 100% rename from examples/fabric-admin/scripts/stop_fabric_source.sh rename to examples/fabric-admin/scripts/stop_fabric_sync.sh From 78ce5b0ad922ffb12b9c91cca282eb1a6613f88d Mon Sep 17 00:00:00 2001 From: Kiel Oleson Date: Thu, 15 Aug 2024 08:04:12 -0700 Subject: [PATCH 054/165] [Darwin] Duplicate / begin raising `MTRDeviceController` (#34832) * Keep MTRDeviceController.mm * Copy MTRDeviceController.mm into MTRDeviceController_Concrete.mm * Set back MTRDeviceController.mm file * Keep MTRDeviceController.h * Copy MTRDeviceController.h into MTRDeviceController_Concrete.h * Set back MTRDeviceController.h file * add `MTRDeviceController_Concrete` files * WIP: bring up `MTRDeviceController_Concrete` * temporary init implementation * only vend `MTRDeviceController` pointers not concrete class (`instancetype`) pointers * add `storedFabricIndex` (currently broken) * reduce access of internal properties * move C++-style fabric index and keypairs to protected ivars * return base class pointer from constructors rather than `instancetype` * clean up property synthesis/ivars in concrete * update merged code * WIP: get us building again, plus plan comments * remove superfluous comments * Update src/darwin/Framework/CHIP/MTRDeviceControllerFactory.h * Restyled by clang-format * move MTRDeviceController protected ivars to standard `MTRDeviceController.h` header * `MTRDeviceController_Concrete` isn't public API thus no `MTR_AVAILABLE` * remove commented code * move ivar extension back to internal header * Fixing TAPI * Restyled by whitespace * Restyled by clang-format --------- Co-authored-by: Justin Wood Co-authored-by: Restyled.io --- .../Framework/CHIP/MTRDeviceController.h | 4 +- .../Framework/CHIP/MTRDeviceController.mm | 30 +- .../CHIP/MTRDeviceControllerFactory.h | 2 +- .../CHIP/MTRDeviceControllerFactory.mm | 6 +- .../CHIP/MTRDeviceController_Concrete.h | 17 +- .../CHIP/MTRDeviceController_Concrete.mm | 292 +++++++----------- .../CHIP/MTRDeviceController_Internal.h | 38 +++ .../Matter.xcodeproj/project.pbxproj | 8 + 8 files changed, 176 insertions(+), 221 deletions(-) diff --git a/src/darwin/Framework/CHIP/MTRDeviceController.h b/src/darwin/Framework/CHIP/MTRDeviceController.h index eaae1fcf7d..9e2c833f6e 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController.h +++ b/src/darwin/Framework/CHIP/MTRDeviceController.h @@ -57,8 +57,8 @@ MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) * Once this returns non-nil, it's the caller's responsibility to call shutdown * on the controller to avoid leaking it. */ -- (nullable instancetype)initWithParameters:(MTRDeviceControllerAbstractParameters *)parameters - error:(NSError * __autoreleasing *)error MTR_AVAILABLE(ios(17.6), macos(14.6), watchos(10.6), tvos(17.6)); +- (nullable MTRDeviceController *)initWithParameters:(MTRDeviceControllerAbstractParameters *)parameters + error:(NSError * __autoreleasing *)error MTR_AVAILABLE(ios(17.6), macos(14.6), watchos(10.6), tvos(17.6)); /** * If true, the controller has not been shut down yet. diff --git a/src/darwin/Framework/CHIP/MTRDeviceController.mm b/src/darwin/Framework/CHIP/MTRDeviceController.mm index 25a0e7d4dc..ee8cc2b754 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController.mm +++ b/src/darwin/Framework/CHIP/MTRDeviceController.mm @@ -108,10 +108,6 @@ using namespace chip::Tracing::DarwinFramework; @implementation MTRDeviceController { - // Atomic because they can be touched from multiple threads. - std::atomic _storedFabricIndex; - std::atomic> _storedCompressedFabricID; - // queue used to serialize all work performed by the MTRDeviceController dispatch_queue_t _chipWorkQueue; @@ -120,8 +116,6 @@ @implementation MTRDeviceController { chip::Credentials::DefaultDACVerifier * _defaultDACVerifier; MTRDeviceControllerDelegateBridge * _deviceControllerDelegateBridge; MTROperationalCredentialsDelegate * _operationalCredentialsDelegate; - MTRP256KeypairBridge _signingKeypairBridge; - MTRP256KeypairBridge _operationalKeypairBridge; MTRDeviceAttestationDelegateBridge * _deviceAttestationDelegateBridge; MTRDeviceControllerFactory * _factory; NSMapTable * _nodeIDToDeviceMap; @@ -133,9 +127,22 @@ @implementation MTRDeviceController { NSMutableArray * _serverEndpoints; MTRDeviceStorageBehaviorConfiguration * _storageBehaviorConfiguration; + std::atomic _storedFabricIndex; + std::atomic> _storedCompressedFabricID; + MTRP256KeypairBridge _signingKeypairBridge; + MTRP256KeypairBridge _operationalKeypairBridge; +} + +- (instancetype)initForSubclasses +{ + if (self = [super init]) { + // nothing, as superclass of MTRDeviceController is NSObject + } + + return self; } -- (nullable instancetype)initWithParameters:(MTRDeviceControllerAbstractParameters *)parameters error:(NSError * __autoreleasing *)error +- (nullable MTRDeviceController *)initWithParameters:(MTRDeviceControllerAbstractParameters *)parameters error:(NSError * __autoreleasing *)error { if (![parameters isKindOfClass:MTRDeviceControllerParameters.class]) { MTR_LOG_ERROR("Unsupported type of MTRDeviceControllerAbstractParameters: %@", parameters); @@ -1575,15 +1582,6 @@ + (void)forceLocalhostAdvertisingOnly @end -/** - * Shim to allow us to treat an MTRDevicePairingDelegate as an - * MTRDeviceControllerDelegate. - */ -@interface MTRDevicePairingDelegateShim : NSObject -@property (nonatomic, readonly) id delegate; -- (instancetype)initWithDelegate:(id)delegate; -@end - @implementation MTRDevicePairingDelegateShim - (instancetype)initWithDelegate:(id)delegate { diff --git a/src/darwin/Framework/CHIP/MTRDeviceControllerFactory.h b/src/darwin/Framework/CHIP/MTRDeviceControllerFactory.h index 0f9de90363..5d1fc4c180 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceControllerFactory.h +++ b/src/darwin/Framework/CHIP/MTRDeviceControllerFactory.h @@ -23,6 +23,7 @@ #import #import #import +#import NS_ASSUME_NONNULL_BEGIN @@ -31,7 +32,6 @@ NS_ASSUME_NONNULL_BEGIN @protocol MTROTAProviderDelegate; @protocol MTRKeypair; -@class MTRDeviceController; @class MTRDeviceControllerStartupParams; @class MTRFabricInfo; diff --git a/src/darwin/Framework/CHIP/MTRDeviceControllerFactory.mm b/src/darwin/Framework/CHIP/MTRDeviceControllerFactory.mm index 1812824937..5b089b3920 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceControllerFactory.mm +++ b/src/darwin/Framework/CHIP/MTRDeviceControllerFactory.mm @@ -1133,9 +1133,9 @@ - (void)operationalInstanceAdded:(chip::PeerId &)operationalID } } -- (MTRDeviceController * _Nullable)initializeController:(MTRDeviceController *)controller - withParameters:(MTRDeviceControllerParameters *)parameters - error:(NSError * __autoreleasing *)error +- (nullable MTRDeviceController *)initializeController:(MTRDeviceController *)controller + withParameters:(MTRDeviceControllerParameters *)parameters + error:(NSError * __autoreleasing *)error { [self _assertCurrentQueueIsNotMatterQueue]; diff --git a/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.h b/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.h index eaae1fcf7d..c9587e910d 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.h +++ b/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.h @@ -19,6 +19,7 @@ #import #import +#import #import @class MTRBaseDevice; @@ -37,15 +38,7 @@ typedef void (^MTRDeviceConnectionCallback)(MTRBaseDevice * _Nullable device, NS @protocol MTRDevicePairingDelegate; @protocol MTRDeviceControllerDelegate; -MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) -@interface MTRDeviceController : NSObject - -/** - * Controllers are created via the MTRDeviceControllerFactory object or - * initialized via initWithParameters:error:. - */ -- (instancetype)init NS_UNAVAILABLE; -+ (instancetype)new NS_UNAVAILABLE; +@interface MTRDeviceController_Concrete : MTRDeviceController /** * Initialize a device controller with the provided parameters. This will: @@ -57,8 +50,8 @@ MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) * Once this returns non-nil, it's the caller's responsibility to call shutdown * on the controller to avoid leaking it. */ -- (nullable instancetype)initWithParameters:(MTRDeviceControllerAbstractParameters *)parameters - error:(NSError * __autoreleasing *)error MTR_AVAILABLE(ios(17.6), macos(14.6), watchos(10.6), tvos(17.6)); +- (nullable MTRDeviceController *)initWithParameters:(MTRDeviceControllerAbstractParameters *)parameters + error:(NSError * __autoreleasing *)error MTR_AVAILABLE(ios(17.6), macos(14.6), watchos(10.6), tvos(17.6)); /** * If true, the controller has not been shut down yet. @@ -262,7 +255,7 @@ MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) @end -@interface MTRDeviceController (Deprecated) +@interface MTRDeviceController_Concrete (Deprecated) @property (readonly, nonatomic, nullable) NSNumber * controllerNodeId MTR_DEPRECATED( "Please use controllerNodeID", ios(16.1, 16.4), macos(13.0, 13.3), watchos(9.1, 9.4), tvos(16.1, 16.4)); diff --git a/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.mm b/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.mm index 6c312d510a..c7ccab25e1 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.mm +++ b/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.mm @@ -26,11 +26,13 @@ #import "MTRCommissionableBrowserResult_Internal.h" #import "MTRCommissioningParameters.h" #import "MTRConversion.h" +#import "MTRDeviceController.h" #import "MTRDeviceControllerDelegateBridge.h" #import "MTRDeviceControllerFactory_Internal.h" #import "MTRDeviceControllerLocalTestStorage.h" #import "MTRDeviceControllerStartupParams.h" #import "MTRDeviceControllerStartupParams_Internal.h" +#import "MTRDeviceController_Concrete.h" #import "MTRDevice_Concrete.h" #import "MTRDevice_Internal.h" #import "MTRError_Internal.h" @@ -79,61 +81,81 @@ #import -static NSString * const kErrorCommissionerInit = @"Init failure while initializing a commissioner"; -static NSString * const kErrorIPKInit = @"Init failure while initializing IPK"; -static NSString * const kErrorSigningKeypairInit = @"Init failure while creating signing keypair bridge"; -static NSString * const kErrorOperationalCredentialsInit = @"Init failure while creating operational credentials delegate"; -static NSString * const kErrorOperationalKeypairInit = @"Init failure while creating operational keypair bridge"; -static NSString * const kErrorPairingInit = @"Init failure while creating a pairing delegate"; -static NSString * const kErrorPartialDacVerifierInit = @"Init failure while creating a partial DAC verifier"; -static NSString * const kErrorPairDevice = @"Failure while pairing the device"; -static NSString * const kErrorStopPairing = @"Failure while trying to stop the pairing process"; -static NSString * const kErrorOpenPairingWindow = @"Open Pairing Window failed"; -static NSString * const kErrorNotRunning = @"Controller is not running. Call startup first."; -static NSString * const kErrorSetupCodeGen = @"Generating Manual Pairing Code failed"; -static NSString * const kErrorGenerateNOC = @"Generating operational certificate failed"; -static NSString * const kErrorKeyAllocation = @"Generating new operational key failed"; -static NSString * const kErrorCSRValidation = @"Extracting public key from CSR failed"; -static NSString * const kErrorGetCommissionee = @"Failure obtaining device being commissioned"; -static NSString * const kErrorGetAttestationChallenge = @"Failure getting attestation challenge"; -static NSString * const kErrorSpake2pVerifierGenerationFailed = @"PASE verifier generation failed"; -static NSString * const kErrorSpake2pVerifierSerializationFailed = @"PASE verifier serialization failed"; -static NSString * const kErrorCDCertStoreInit = @"Init failure while initializing Certificate Declaration Signing Keys store"; - typedef void (^SyncWorkQueueBlock)(void); typedef id (^SyncWorkQueueBlockWithReturnValue)(void); typedef BOOL (^SyncWorkQueueBlockWithBoolReturnValue)(void); using namespace chip::Tracing::DarwinFramework; -@implementation MTRDeviceController { - // Atomic because it can be touched from multiple threads. - std::atomic _storedFabricIndex; +@interface MTRDeviceController_Concrete () - // queue used to serialize all work performed by the MTRDeviceController - dispatch_queue_t _chipWorkQueue; +// MTRDeviceController ivar internal access + +@property (nonatomic, readonly) chip::Controller::DeviceCommissioner * cppCommissioner; +@property (nonatomic, readonly) chip::Credentials::PartialDACVerifier * partialDACVerifier; +@property (nonatomic, readonly) chip::Credentials::DefaultDACVerifier * defaultDACVerifier; +@property (nonatomic, readonly) MTRDeviceControllerDelegateBridge * deviceControllerDelegateBridge; +@property (nonatomic, readonly) MTROperationalCredentialsDelegate * operationalCredentialsDelegate; +@property (nonatomic, readonly) MTRDeviceAttestationDelegateBridge * deviceAttestationDelegateBridge; +@property (nonatomic, readwrite) NSUUID * uniqueIdentifier; +@property (nonatomic, readonly) dispatch_queue_t chipWorkQueue; +@property (nonatomic, readonly, nullable) MTRDeviceControllerFactory * factory; +@property (nonatomic, readonly, nullable) NSMapTable * nodeIDToDeviceMap; +@property (nonatomic, readonly) os_unfair_lock deviceMapLock; +@property (nonatomic, readonly, nullable) id otaProviderDelegate; +@property (nonatomic, readonly, nullable) dispatch_queue_t otaProviderDelegateQueue; +@property (nonatomic, readonly, nullable) MTRCommissionableBrowser * commissionableBrowser; +@property (nonatomic, readonly, nullable) MTRAttestationTrustStoreBridge * attestationTrustStoreBridge; +@property (nonatomic, readonly, nullable) NSMutableArray * serverEndpoints; + +@property (nonatomic, readonly) MTRAsyncWorkQueue * concurrentSubscriptionPool; - chip::Controller::DeviceCommissioner * _cppCommissioner; - chip::Credentials::PartialDACVerifier * _partialDACVerifier; - chip::Credentials::DefaultDACVerifier * _defaultDACVerifier; - MTRDeviceControllerDelegateBridge * _deviceControllerDelegateBridge; - MTROperationalCredentialsDelegate * _operationalCredentialsDelegate; +@property (nonatomic, readonly) MTRDeviceStorageBehaviorConfiguration * storageBehaviorConfiguration; + +@end + +@implementation MTRDeviceController_Concrete { + // queue used to serialize all work performed by the MTRDeviceController + std::atomic _storedFabricIndex; + std::atomic> _storedCompressedFabricID; MTRP256KeypairBridge _signingKeypairBridge; MTRP256KeypairBridge _operationalKeypairBridge; - MTRDeviceAttestationDelegateBridge * _deviceAttestationDelegateBridge; - MTRDeviceControllerFactory * _factory; - NSMapTable * _nodeIDToDeviceMap; - os_unfair_lock _deviceMapLock; // protects nodeIDToDeviceMap - MTRCommissionableBrowser * _commissionableBrowser; - MTRAttestationTrustStoreBridge * _attestationTrustStoreBridge; +} - // _serverEndpoints is only touched on the Matter queue. - NSMutableArray * _serverEndpoints; +// MTRDeviceController ivar internal access +@synthesize uniqueIdentifier = _uniqueIdentifier; +@synthesize chipWorkQueue = _chipWorkQueue; +@synthesize controllerDataStore = _controllerDataStore; +@synthesize factory = _factory; +@synthesize deviceMapLock = _deviceMapLock; +@synthesize otaProviderDelegate = _otaProviderDelegate; +@synthesize otaProviderDelegateQueue = _otaProviderDelegateQueue; +@synthesize commissionableBrowser = _commissionableBrowser; +@synthesize concurrentSubscriptionPool = _concurrentSubscriptionPool; +@synthesize storageBehaviorConfiguration = _storageBehaviorConfiguration; + +- (nullable MTRDeviceController_Concrete *)initWithParameters:(MTRDeviceControllerAbstractParameters *)parameters + error:(NSError * __autoreleasing *)error +{ + if (![parameters isKindOfClass:MTRDeviceControllerParameters.class]) { + MTR_LOG_ERROR("Unsupported type of MTRDeviceControllerAbstractParameters: %@", parameters); + if (error) { + *error = [MTRError errorForCHIPErrorCode:CHIP_ERROR_INVALID_ARGUMENT]; + } + return nil; + } + auto * controllerParameters = static_cast(parameters); - MTRDeviceStorageBehaviorConfiguration * _storageBehaviorConfiguration; + // or, if necessary, MTRDeviceControllerFactory will auto-start in per-controller-storage mode if necessary + MTRDeviceControllerFactory * factory = MTRDeviceControllerFactory.sharedInstance; + id controller = [factory initializeController:self + withParameters:controllerParameters + error:error]; + return controller; } -- (nullable instancetype)initWithParameters:(MTRDeviceControllerAbstractParameters *)parameters error:(NSError * __autoreleasing *)error +- (nullable MTRDeviceController *)bogusWithParameters:(MTRDeviceControllerAbstractParameters *)parameters + error:(NSError * __autoreleasing *)error { if (![parameters isKindOfClass:MTRDeviceControllerParameters.class]) { MTR_LOG_ERROR("Unsupported type of MTRDeviceControllerAbstractParameters: %@", parameters); @@ -145,7 +167,11 @@ - (nullable instancetype)initWithParameters:(MTRDeviceControllerAbstractParamete auto * controllerParameters = static_cast(parameters); // MTRDeviceControllerFactory will auto-start in per-controller-storage mode if necessary - return [MTRDeviceControllerFactory.sharedInstance initializeController:self withParameters:controllerParameters error:error]; + MTRDeviceControllerFactory * factory = MTRDeviceControllerFactory.sharedInstance; + MTRDeviceController * controller = [factory initializeController:self + withParameters:controllerParameters + error:error]; + return controller; } - (instancetype)initWithFactory:(MTRDeviceControllerFactory *)factory @@ -158,7 +184,7 @@ - (instancetype)initWithFactory:(MTRDeviceControllerFactory *)factory concurrentSubscriptionPoolSize:(NSUInteger)concurrentSubscriptionPoolSize storageBehaviorConfiguration:(MTRDeviceStorageBehaviorConfiguration *)storageBehaviorConfiguration { - if (self = [super init]) { + if (self = [super initForSubclasses]) { // Make sure our storage is all set up to work as early as possible, // before we start doing anything else with the controller. _uniqueIdentifier = uniqueIdentifier; @@ -242,17 +268,17 @@ - (instancetype)initWithFactory:(MTRDeviceControllerFactory *)factory _commissionableBrowser = nil; _deviceControllerDelegateBridge = new MTRDeviceControllerDelegateBridge(); - if ([self checkForInitError:(_deviceControllerDelegateBridge != nullptr) logMsg:kErrorPairingInit]) { + if ([self checkForInitError:(_deviceControllerDelegateBridge != nullptr) logMsg:kDeviceControllerErrorPairingInit]) { return nil; } _partialDACVerifier = new chip::Credentials::PartialDACVerifier(); - if ([self checkForInitError:(_partialDACVerifier != nullptr) logMsg:kErrorPartialDacVerifierInit]) { + if ([self checkForInitError:(_partialDACVerifier != nullptr) logMsg:kDeviceControllerErrorPartialDacVerifierInit]) { return nil; } _operationalCredentialsDelegate = new MTROperationalCredentialsDelegate(self); - if ([self checkForInitError:(_operationalCredentialsDelegate != nullptr) logMsg:kErrorOperationalCredentialsInit]) { + if ([self checkForInitError:(_operationalCredentialsDelegate != nullptr) logMsg:kDeviceControllerErrorOperationalCredentialsInit]) { return nil; } @@ -438,14 +464,14 @@ - (BOOL)startup:(MTRDeviceControllerStartupParamsInternal *)startupParams chip::Crypto::P256Keypair * signingKeypair = nullptr; if (startupParams.nocSigner) { errorCode = _signingKeypairBridge.Init(startupParams.nocSigner); - if ([self checkForStartError:errorCode logMsg:kErrorSigningKeypairInit]) { + if ([self checkForStartError:errorCode logMsg:kDeviceControllerErrorSigningKeypairInit]) { return; } signingKeypair = &_signingKeypairBridge; } errorCode = _operationalCredentialsDelegate->Init( signingKeypair, startupParams.ipk, startupParams.rootCertificate, startupParams.intermediateCertificate); - if ([self checkForStartError:errorCode logMsg:kErrorOperationalCredentialsInit]) { + if ([self checkForStartError:errorCode logMsg:kDeviceControllerErrorOperationalCredentialsInit]) { return; } @@ -469,7 +495,7 @@ - (BOOL)startup:(MTRDeviceControllerStartupParamsInternal *)startupParams if (startupParams.operationalKeypair != nil) { errorCode = _operationalKeypairBridge.Init(startupParams.operationalKeypair); - if ([self checkForStartError:errorCode logMsg:kErrorOperationalKeypairInit]) { + if ([self checkForStartError:errorCode logMsg:kDeviceControllerErrorOperationalKeypairInit]) { return; } commissionerParams.operationalKeypair = &_operationalKeypairBridge; @@ -494,7 +520,7 @@ - (BOOL)startup:(MTRDeviceControllerStartupParamsInternal *)startupParams errorCode = _operationalCredentialsDelegate->GenerateNOC(startupParams.nodeID.unsignedLongLongValue, startupParams.fabricID.unsignedLongLongValue, cats, commissionerParams.operationalKeypair->Pubkey(), noc); - if ([self checkForStartError:errorCode logMsg:kErrorGenerateNOC]) { + if ([self checkForStartError:errorCode logMsg:kDeviceControllerErrorGenerateNOC]) { return; } } else { @@ -502,20 +528,20 @@ - (BOOL)startup:(MTRDeviceControllerStartupParamsInternal *)startupParams uint8_t csrBuffer[chip::Crypto::kMIN_CSR_Buffer_Size]; chip::MutableByteSpan csr(csrBuffer); errorCode = startupParams.fabricTable->AllocatePendingOperationalKey(startupParams.fabricIndex, csr); - if ([self checkForStartError:errorCode logMsg:kErrorKeyAllocation]) { + if ([self checkForStartError:errorCode logMsg:kDeviceControllerErrorKeyAllocation]) { return; } chip::Crypto::P256PublicKey pubKey; errorCode = VerifyCertificateSigningRequest(csr.data(), csr.size(), pubKey); - if ([self checkForStartError:errorCode logMsg:kErrorCSRValidation]) { + if ([self checkForStartError:errorCode logMsg:kDeviceControllerErrorCSRValidation]) { return; } errorCode = _operationalCredentialsDelegate->GenerateNOC( startupParams.nodeID.unsignedLongLongValue, startupParams.fabricID.unsignedLongLongValue, cats, pubKey, noc); - if ([self checkForStartError:errorCode logMsg:kErrorGenerateNOC]) { + if ([self checkForStartError:errorCode logMsg:kDeviceControllerErrorGenerateNOC]) { return; } } @@ -553,13 +579,13 @@ - (BOOL)startup:(MTRDeviceControllerStartupParamsInternal *)startupParams if (cdTrustStore == nullptr) { errorCode = CHIP_ERROR_INCORRECT_STATE; } - if ([self checkForStartError:errorCode logMsg:kErrorCDCertStoreInit]) { + if ([self checkForStartError:errorCode logMsg:kDeviceControllerErrorCDCertStoreInit]) { return; } for (NSData * cdSigningCert in startupParams.certificationDeclarationCertificates) { errorCode = cdTrustStore->AddTrustedKey(AsByteSpan(cdSigningCert)); - if ([self checkForStartError:errorCode logMsg:kErrorCDCertStoreInit]) { + if ([self checkForStartError:errorCode logMsg:kDeviceControllerErrorCDCertStoreInit]) { return; } } @@ -570,7 +596,7 @@ - (BOOL)startup:(MTRDeviceControllerStartupParamsInternal *)startupParams auto & factory = chip::Controller::DeviceControllerFactory::GetInstance(); errorCode = factory.SetupCommissioner(commissionerParams, *_cppCommissioner); - if ([self checkForStartError:errorCode logMsg:kErrorCommissionerInit]) { + if ([self checkForStartError:errorCode logMsg:kDeviceControllerErrorCommissionerInit]) { return; } @@ -579,13 +605,13 @@ - (BOOL)startup:(MTRDeviceControllerStartupParamsInternal *)startupParams uint8_t compressedIdBuffer[sizeof(uint64_t)]; chip::MutableByteSpan compressedId(compressedIdBuffer); errorCode = _cppCommissioner->GetCompressedFabricIdBytes(compressedId); - if ([self checkForStartError:errorCode logMsg:kErrorIPKInit]) { + if ([self checkForStartError:errorCode logMsg:kDeviceControllerErrorIPKInit]) { return; } errorCode = chip::Credentials::SetSingleIpkEpochKey( _factory.groupDataProvider, fabricIdx, _operationalCredentialsDelegate->GetIPK(), compressedId); - if ([self checkForStartError:errorCode logMsg:kErrorIPKInit]) { + if ([self checkForStartError:errorCode logMsg:kDeviceControllerErrorIPKInit]) { return; } @@ -688,7 +714,7 @@ - (BOOL)setupCommissioningSessionWithPayload:(MTRSetupPayload *)payload } if (pairingCode == nil) { errorCode = CHIP_ERROR_INVALID_ARGUMENT; - return ![MTRDeviceController checkForError:errorCode logMsg:kErrorSetupCodeGen error:error]; + return ![MTRDeviceController_Concrete checkForError:errorCode logMsg:kDeviceControllerErrorSetupCodeGen error:error]; } chip::NodeId nodeId = [newNodeID unsignedLongLongValue]; @@ -702,7 +728,7 @@ - (BOOL)setupCommissioningSessionWithPayload:(MTRSetupPayload *)payload MATTER_LOG_METRIC_END(kMetricSetupPASESession, errorCode); } - return ![MTRDeviceController checkForError:errorCode logMsg:kErrorPairDevice error:error]; + return ![MTRDeviceController_Concrete checkForError:errorCode logMsg:kDeviceControllerErrorPairDevice error:error]; }; auto success = [self syncRunOnWorkQueueWithBoolReturnValue:block error:error]; @@ -758,7 +784,7 @@ - (BOOL)setupCommissioningSessionWithDiscoveredDevice:(MTRCommissionableBrowserR } if (pairingCode == nil) { errorCode = CHIP_ERROR_INVALID_ARGUMENT; - return ![MTRDeviceController checkForError:errorCode logMsg:kErrorSetupCodeGen error:error]; + return ![MTRDeviceController_Concrete checkForError:errorCode logMsg:kDeviceControllerErrorSetupCodeGen error:error]; } for (id key in discoveredDevice.interfaces) { @@ -779,7 +805,7 @@ - (BOOL)setupCommissioningSessionWithDiscoveredDevice:(MTRCommissionableBrowserR } } - return ![MTRDeviceController checkForError:errorCode logMsg:kErrorPairDevice error:error]; + return ![MTRDeviceController_Concrete checkForError:errorCode logMsg:kDeviceControllerErrorPairDevice error:error]; }; auto success = [self syncRunOnWorkQueueWithBoolReturnValue:block error:error]; @@ -886,7 +912,7 @@ - (BOOL)commissionNodeWithID:(NSNumber *)nodeID self->_operationalCredentialsDelegate->SetDeviceID(deviceId); auto errorCode = self->_cppCommissioner->Commission(deviceId, params); MATTER_LOG_METRIC(kMetricCommissionNode, errorCode); - return ![MTRDeviceController checkForError:errorCode logMsg:kErrorPairDevice error:error]; + return ![MTRDeviceController_Concrete checkForError:errorCode logMsg:kDeviceControllerErrorPairDevice error:error]; }; return [self syncRunOnWorkQueueWithBoolReturnValue:block error:error]; @@ -906,7 +932,7 @@ - (BOOL)continueCommissioningDevice:(void *)device ignoreAttestationFailure ? chip::Credentials::AttestationVerificationResult::kSuccess : lastAttestationResult); // Emit metric on stage after continuing post attestation MATTER_LOG_METRIC(kMetricContinueCommissioningAfterAttestation, errorCode); - return ![MTRDeviceController checkForError:errorCode logMsg:kErrorPairDevice error:error]; + return ![MTRDeviceController_Concrete checkForError:errorCode logMsg:kDeviceControllerErrorPairDevice error:error]; }; return [self syncRunOnWorkQueueWithBoolReturnValue:block error:error]; @@ -919,7 +945,7 @@ - (BOOL)cancelCommissioningForNodeID:(NSNumber *)nodeID error:(NSError * __autor auto errorCode = self->_cppCommissioner->StopPairing([nodeID unsignedLongLongValue]); // Emit metric on status of cancel MATTER_LOG_METRIC(kMetricCancelCommissioning, errorCode); - return ![MTRDeviceController checkForError:errorCode logMsg:kErrorStopPairing error:error]; + return ![MTRDeviceController_Concrete checkForError:errorCode logMsg:kDeviceControllerErrorStopPairing error:error]; }; return [self syncRunOnWorkQueueWithBoolReturnValue:block error:error]; @@ -969,7 +995,7 @@ - (MTRBaseDevice *)deviceBeingCommissionedWithNodeID:(NSNumber *)nodeID error:(N auto errorCode = self->_cppCommissioner->GetDeviceBeingCommissioned(nodeID.unsignedLongLongValue, &deviceProxy); MATTER_LOG_METRIC(kMetricDeviceBeingCommissioned, errorCode); - VerifyOrReturnValue(![MTRDeviceController checkForError:errorCode logMsg:kErrorGetCommissionee error:error], nil); + VerifyOrReturnValue(![MTRDeviceController_Concrete checkForError:errorCode logMsg:kDeviceControllerErrorGetCommissionee error:error], nil); return [[MTRBaseDevice alloc] initWithPASEDevice:deviceProxy controller:self]; }; @@ -989,7 +1015,7 @@ - (MTRDevice *)_setupDeviceForNodeID:(NSNumber *)nodeID prefetchedClusterData:(N { os_unfair_lock_assert_owner(&_deviceMapLock); - MTRDevice * deviceToReturn = [[MTRDevice_Concrete alloc] initWithNodeID:nodeID controller:self]; + MTRDevice * deviceToReturn = [[MTRDevice alloc] initWithNodeID:nodeID controller:self]; // If we're not running, don't add the device to our map. That would // create a cycle that nothing would break. Just return the device, // which will be in exactly the state it would be in if it were created @@ -1105,14 +1131,14 @@ + (nullable NSData *)computePASEVerifierForSetupPasscode:(NSNumber *)setupPassco MATTER_LOG_METRIC_SCOPE(kMetricPASEVerifierForSetupCode, err); - if ([MTRDeviceController checkForError:err logMsg:kErrorSpake2pVerifierGenerationFailed error:error]) { + if ([MTRDeviceController_Concrete checkForError:err logMsg:kDeviceControllerErrorSpake2pVerifierGenerationFailed error:error]) { return nil; } uint8_t serializedBuffer[chip::Crypto::kSpake2p_VerifierSerialized_Length]; chip::MutableByteSpan serializedBytes(serializedBuffer); err = verifier.Serialize(serializedBytes); - if ([MTRDeviceController checkForError:err logMsg:kErrorSpake2pVerifierSerializationFailed error:error]) { + if ([MTRDeviceController_Concrete checkForError:err logMsg:kDeviceControllerErrorSpake2pVerifierSerializationFailed error:error]) { return nil; } @@ -1129,13 +1155,13 @@ - (NSData * _Nullable)attestationChallengeForDeviceID:(NSNumber *)deviceID MATTER_LOG_METRIC_SCOPE(kMetricAttestationChallengeForDevice, errorCode); errorCode = self->_cppCommissioner->GetDeviceBeingCommissioned([deviceID unsignedLongLongValue], &deviceProxy); - VerifyOrReturnValue(![MTRDeviceController checkForError:errorCode logMsg:kErrorGetCommissionee error:nil], nil); + VerifyOrReturnValue(![MTRDeviceController_Concrete checkForError:errorCode logMsg:kDeviceControllerErrorGetCommissionee error:nil], nil); uint8_t challengeBuffer[chip::Crypto::kAES_CCM128_Key_Length]; chip::ByteSpan challenge(challengeBuffer); errorCode = deviceProxy->GetAttestationChallenge(challenge); - VerifyOrReturnValue(![MTRDeviceController checkForError:errorCode logMsg:kErrorGetAttestationChallenge error:nil], nil); + VerifyOrReturnValue(![MTRDeviceController_Concrete checkForError:errorCode logMsg:kDeviceControllerErrorGetAttestationChallenge error:nil], nil); return AsData(challenge); }; @@ -1272,7 +1298,7 @@ - (BOOL)checkIsRunning:(NSError * __autoreleasing *)error return YES; } - MTR_LOG_ERROR("MTRDeviceController: %@ Error: %s", self, [kErrorNotRunning UTF8String]); + MTR_LOG_ERROR("MTRDeviceController: %@ Error: %s", self, [kDeviceControllerErrorNotRunning UTF8String]); if (error) { *error = [MTRError errorForCHIPErrorCode:CHIP_ERROR_INCORRECT_STATE]; } @@ -1582,63 +1608,6 @@ + (void)forceLocalhostAdvertisingOnly @end -/** - * Shim to allow us to treat an MTRDevicePairingDelegate as an - * MTRDeviceControllerDelegate. - */ -@interface MTRDevicePairingDelegateShim : NSObject -@property (nonatomic, readonly) id delegate; -- (instancetype)initWithDelegate:(id)delegate; -@end - -@implementation MTRDevicePairingDelegateShim -- (instancetype)initWithDelegate:(id)delegate -{ - if (self = [super init]) { - _delegate = delegate; - } - return self; -} - -- (BOOL)respondsToSelector:(SEL)selector -{ - if (selector == @selector(controller:statusUpdate:)) { - return [self.delegate respondsToSelector:@selector(onStatusUpdate:)]; - } - - if (selector == @selector(controller:commissioningSessionEstablishmentDone:)) { - return [self.delegate respondsToSelector:@selector(onPairingComplete:)]; - } - - if (selector == @selector(controller:commissioningComplete:)) { - return [self.delegate respondsToSelector:@selector(onCommissioningComplete:)]; - } - - return [super respondsToSelector:selector]; -} - -- (void)controller:(MTRDeviceController *)controller statusUpdate:(MTRCommissioningStatus)status -{ - [self.delegate onStatusUpdate:static_cast(status)]; -} - -- (void)controller:(MTRDeviceController *)controller commissioningSessionEstablishmentDone:(NSError * _Nullable)error -{ - [self.delegate onPairingComplete:error]; -} - -- (void)controller:(MTRDeviceController *)controller commissioningComplete:(NSError * _Nullable)error -{ - [self.delegate onCommissioningComplete:error]; -} - -- (void)onPairingDeleted:(NSError * _Nullable)error -{ - [self.delegate onPairingDeleted:error]; -} - -@end - /** * Shim to allow us to treat an MTRNOCChainIssuer as an * MTROperationalCertificateIssuer. @@ -1649,58 +1618,7 @@ @interface MTROperationalCertificateChainIssuerShim : NSObject )nocChainIssuer; @end -@implementation MTROperationalCertificateChainIssuerShim -- (instancetype)initWithIssuer:(id)nocChainIssuer -{ - if (self = [super init]) { - _nocChainIssuer = nocChainIssuer; - _shouldSkipAttestationCertificateValidation = YES; - } - return self; -} - -- (void)issueOperationalCertificateForRequest:(MTROperationalCSRInfo *)csrInfo - attestationInfo:(MTRDeviceAttestationInfo *)attestationInfo - controller:(MTRDeviceController *)controller - completion:(void (^)(MTROperationalCertificateChain * _Nullable info, - NSError * _Nullable error))completion -{ - CSRInfo * oldCSRInfo = [[CSRInfo alloc] initWithNonce:csrInfo.csrNonce - elements:csrInfo.csrElementsTLV - elementsSignature:csrInfo.attestationSignature - csr:csrInfo.csr]; - NSData * _Nullable firmwareInfo = attestationInfo.firmwareInfo; - if (firmwareInfo == nil) { - firmwareInfo = [NSData data]; - } - AttestationInfo * oldAttestationInfo = - [[AttestationInfo alloc] initWithChallenge:attestationInfo.challenge - nonce:attestationInfo.nonce - elements:attestationInfo.elementsTLV - elementsSignature:attestationInfo.elementsSignature - dac:attestationInfo.deviceAttestationCertificate - pai:attestationInfo.productAttestationIntermediateCertificate - certificationDeclaration:attestationInfo.certificationDeclaration - firmwareInfo:firmwareInfo]; - [self.nocChainIssuer - onNOCChainGenerationNeeded:oldCSRInfo - attestationInfo:oldAttestationInfo - onNOCChainGenerationComplete:^(NSData * operationalCertificate, NSData * intermediateCertificate, NSData * rootCertificate, - NSData * _Nullable ipk, NSNumber * _Nullable adminSubject, NSError * __autoreleasing * error) { - auto * chain = [[MTROperationalCertificateChain alloc] initWithOperationalCertificate:operationalCertificate - intermediateCertificate:intermediateCertificate - rootCertificate:rootCertificate - adminSubject:adminSubject]; - completion(chain, nil); - if (error != nil) { - *error = nil; - } - }]; -} - -@end - -@implementation MTRDeviceController (Deprecated) +@implementation MTRDeviceController_Concrete (Deprecated) - (NSNumber *)controllerNodeId { @@ -1768,7 +1686,7 @@ - (BOOL)pairDevice:(uint64_t)deviceID payload.setUpPINCode = setupPINCode; errorCode = chip::ManualSetupPayloadGenerator(payload).payloadDecimalStringRepresentation(manualPairingCode); - VerifyOrReturnValue(![MTRDeviceController checkForError:errorCode logMsg:kErrorSetupCodeGen error:error], NO); + VerifyOrReturnValue(![MTRDeviceController_Concrete checkForError:errorCode logMsg:kDeviceControllerErrorSetupCodeGen error:error], NO); self->_operationalCredentialsDelegate->SetDeviceID(deviceID); @@ -1780,7 +1698,7 @@ - (BOOL)pairDevice:(uint64_t)deviceID MATTER_LOG_METRIC_END(kMetricSetupPASESession, errorCode); } - return ![MTRDeviceController checkForError:errorCode logMsg:kErrorPairDevice error:error]; + return ![MTRDeviceController_Concrete checkForError:errorCode logMsg:kDeviceControllerErrorPairDevice error:error]; }; auto success = [self syncRunOnWorkQueueWithBoolReturnValue:block error:error]; @@ -1825,7 +1743,7 @@ - (BOOL)pairDevice:(uint64_t)deviceID MATTER_LOG_METRIC_END(kMetricSetupPASESession, errorCode); } - return ![MTRDeviceController checkForError:errorCode logMsg:kErrorPairDevice error:error]; + return ![MTRDeviceController_Concrete checkForError:errorCode logMsg:kDeviceControllerErrorPairDevice error:error]; }; auto success = [self syncRunOnWorkQueueWithBoolReturnValue:block error:error]; @@ -1861,7 +1779,7 @@ - (BOOL)pairDevice:(uint64_t)deviceID onboardingPayload:(NSString *)onboardingPa MATTER_LOG_METRIC_END(kMetricSetupPASESession, errorCode); } - return ![MTRDeviceController checkForError:errorCode logMsg:kErrorPairDevice error:error]; + return ![MTRDeviceController_Concrete checkForError:errorCode logMsg:kDeviceControllerErrorPairDevice error:error]; }; auto success = [self syncRunOnWorkQueueWithBoolReturnValue:block error:error]; @@ -1904,7 +1822,7 @@ - (BOOL)openPairingWindow:(uint64_t)deviceID duration:(NSUInteger)duration error errorCode = chip::Controller::AutoCommissioningWindowOpener::OpenBasicCommissioningWindow( self->_cppCommissioner, deviceID, chip::System::Clock::Seconds16(static_cast(duration))); - return ![MTRDeviceController checkForError:errorCode logMsg:kErrorOpenPairingWindow error:error]; + return ![MTRDeviceController_Concrete checkForError:errorCode logMsg:kDeviceControllerErrorOpenPairingWindow error:error]; }; return [self syncRunOnWorkQueueWithBoolReturnValue:block error:error]; @@ -1952,7 +1870,7 @@ - (NSString *)openPairingWindowWithPIN:(uint64_t)deviceID static_cast(discriminator), chip::MakeOptional(static_cast(setupPIN)), chip::NullOptional, setupPayload); - VerifyOrReturnValue(![MTRDeviceController checkForError:errorCode logMsg:kErrorOpenPairingWindow error:error], nil); + VerifyOrReturnValue(![MTRDeviceController_Concrete checkForError:errorCode logMsg:kDeviceControllerErrorOpenPairingWindow error:error], nil); chip::ManualSetupPayloadGenerator generator(setupPayload); std::string outCode; diff --git a/src/darwin/Framework/CHIP/MTRDeviceController_Internal.h b/src/darwin/Framework/CHIP/MTRDeviceController_Internal.h index 479dd8518d..d943775d43 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController_Internal.h +++ b/src/darwin/Framework/CHIP/MTRDeviceController_Internal.h @@ -32,8 +32,11 @@ #import "MTRBaseDevice.h" #import "MTRDeviceController.h" #import "MTRDeviceControllerDataStore.h" +#import "MTRDeviceControllerDelegate.h" #import "MTRDeviceStorageBehaviorConfiguration.h" +#import + #import #import #import @@ -44,6 +47,9 @@ @class MTRDeviceControllerFactory; @class MTRDevice; @class MTRAsyncWorkQueue; +@protocol MTRDevicePairingDelegate; +@protocol MTRDeviceControllerDelegate; +@class MTRDevice_Concrete; namespace chip { class FabricTable; @@ -57,6 +63,8 @@ NS_ASSUME_NONNULL_BEGIN @interface MTRDeviceController () +- (instancetype)initForSubclasses; + #pragma mark - MTRDeviceControllerFactory methods /** @@ -273,4 +281,34 @@ NS_ASSUME_NONNULL_BEGIN @end +/** + * Shim to allow us to treat an MTRDevicePairingDelegate as an + * MTRDeviceControllerDelegate. + */ +@interface MTRDevicePairingDelegateShim : NSObject +@property (nonatomic, readonly) id delegate; +- (instancetype)initWithDelegate:(id)delegate; +@end + +static NSString * const kDeviceControllerErrorCommissionerInit = @"Init failure while initializing a commissioner"; +static NSString * const kDeviceControllerErrorIPKInit = @"Init failure while initializing IPK"; +static NSString * const kDeviceControllerErrorSigningKeypairInit = @"Init failure while creating signing keypair bridge"; +static NSString * const kDeviceControllerErrorOperationalCredentialsInit = @"Init failure while creating operational credentials delegate"; +static NSString * const kDeviceControllerErrorOperationalKeypairInit = @"Init failure while creating operational keypair bridge"; +static NSString * const kDeviceControllerErrorPairingInit = @"Init failure while creating a pairing delegate"; +static NSString * const kDeviceControllerErrorPartialDacVerifierInit = @"Init failure while creating a partial DAC verifier"; +static NSString * const kDeviceControllerErrorPairDevice = @"Failure while pairing the device"; +static NSString * const kDeviceControllerErrorStopPairing = @"Failure while trying to stop the pairing process"; +static NSString * const kDeviceControllerErrorOpenPairingWindow = @"Open Pairing Window failed"; +static NSString * const kDeviceControllerErrorNotRunning = @"Controller is not running. Call startup first."; +static NSString * const kDeviceControllerErrorSetupCodeGen = @"Generating Manual Pairing Code failed"; +static NSString * const kDeviceControllerErrorGenerateNOC = @"Generating operational certificate failed"; +static NSString * const kDeviceControllerErrorKeyAllocation = @"Generating new operational key failed"; +static NSString * const kDeviceControllerErrorCSRValidation = @"Extracting public key from CSR failed"; +static NSString * const kDeviceControllerErrorGetCommissionee = @"Failure obtaining device being commissioned"; +static NSString * const kDeviceControllerErrorGetAttestationChallenge = @"Failure getting attestation challenge"; +static NSString * const kDeviceControllerErrorSpake2pVerifierGenerationFailed = @"PASE verifier generation failed"; +static NSString * const kDeviceControllerErrorSpake2pVerifierSerializationFailed = @"PASE verifier serialization failed"; +static NSString * const kDeviceControllerErrorCDCertStoreInit = @"Init failure while initializing Certificate Declaration Signing Keys store"; + NS_ASSUME_NONNULL_END diff --git a/src/darwin/Framework/Matter.xcodeproj/project.pbxproj b/src/darwin/Framework/Matter.xcodeproj/project.pbxproj index bb5a8ce180..2dc7bd266a 100644 --- a/src/darwin/Framework/Matter.xcodeproj/project.pbxproj +++ b/src/darwin/Framework/Matter.xcodeproj/project.pbxproj @@ -302,6 +302,8 @@ 99AECC802798A57F00B6355B /* MTRCommissioningParameters.mm in Sources */ = {isa = PBXBuildFile; fileRef = 99AECC7F2798A57E00B6355B /* MTRCommissioningParameters.mm */; }; 99C65E10267282F1003402F6 /* MTRControllerTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 99C65E0F267282F1003402F6 /* MTRControllerTests.m */; }; 99D466E12798936D0089A18F /* MTRCommissioningParameters.h in Headers */ = {isa = PBXBuildFile; fileRef = 99D466E02798936D0089A18F /* MTRCommissioningParameters.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 9B231B042C62EF650030EB37 /* MTRDeviceController_Concrete.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B231B022C62EF650030EB37 /* MTRDeviceController_Concrete.h */; }; + 9B231B052C62EF650030EB37 /* MTRDeviceController_Concrete.mm in Sources */ = {isa = PBXBuildFile; fileRef = 9B231B032C62EF650030EB37 /* MTRDeviceController_Concrete.mm */; }; 9BDA2A062C5D9AF800A32BDD /* MTRDevice_Concrete.mm in Sources */ = {isa = PBXBuildFile; fileRef = 9BDA2A052C5D9AF800A32BDD /* MTRDevice_Concrete.mm */; }; 9BDA2A082C5D9AFB00A32BDD /* MTRDevice_Concrete.h in Headers */ = {isa = PBXBuildFile; fileRef = 9BDA2A072C5D9AFB00A32BDD /* MTRDevice_Concrete.h */; }; AF1CB86E2874B03B00865A96 /* MTROTAProviderDelegate.h in Headers */ = {isa = PBXBuildFile; fileRef = AF1CB86D2874B03B00865A96 /* MTROTAProviderDelegate.h */; settings = {ATTRIBUTES = (Public, ); }; }; @@ -731,6 +733,8 @@ 99AECC7F2798A57E00B6355B /* MTRCommissioningParameters.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = MTRCommissioningParameters.mm; sourceTree = ""; }; 99C65E0F267282F1003402F6 /* MTRControllerTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = MTRControllerTests.m; sourceTree = ""; }; 99D466E02798936D0089A18F /* MTRCommissioningParameters.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MTRCommissioningParameters.h; sourceTree = ""; }; + 9B231B022C62EF650030EB37 /* MTRDeviceController_Concrete.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MTRDeviceController_Concrete.h; sourceTree = ""; }; + 9B231B032C62EF650030EB37 /* MTRDeviceController_Concrete.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = MTRDeviceController_Concrete.mm; sourceTree = ""; }; 9BDA2A052C5D9AF800A32BDD /* MTRDevice_Concrete.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = MTRDevice_Concrete.mm; sourceTree = ""; }; 9BDA2A072C5D9AFB00A32BDD /* MTRDevice_Concrete.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MTRDevice_Concrete.h; sourceTree = ""; }; AF1CB86D2874B03B00865A96 /* MTROTAProviderDelegate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MTROTAProviderDelegate.h; sourceTree = ""; }; @@ -1242,6 +1246,8 @@ B202528F2459E34F00F97062 /* CHIP */ = { isa = PBXGroup; children = ( + 9B231B022C62EF650030EB37 /* MTRDeviceController_Concrete.h */, + 9B231B032C62EF650030EB37 /* MTRDeviceController_Concrete.mm */, 88E07D602B9A89A4005FD53E /* MTRMetricKeys.h */, 88FA798B2B7B257100CD4B6F /* MTRMetricsCollector.h */, 88FA798C2B7B257100CD4B6F /* MTRMetricsCollector.mm */, @@ -1676,6 +1682,7 @@ 51E51FC0282AD37A00FC978D /* MTRDeviceControllerStartupParams_Internal.h in Headers */, 3DECCB702934AECD00585AEC /* MTRLogging.h in Headers */, 1E4D654E29C208DD00BC3478 /* MTRCommissionableBrowserResult.h in Headers */, + 9B231B042C62EF650030EB37 /* MTRDeviceController_Concrete.h in Headers */, 515BE4ED2B72C0C5000BC1FD /* MTRUnfairLock.h in Headers */, 998F286F26D55EC5001846C6 /* MTRP256KeypairBridge.h in Headers */, 2C222ADF255C811800E446B9 /* MTRBaseDevice_Internal.h in Headers */, @@ -1986,6 +1993,7 @@ 511913FB28C100EF009235E9 /* MTRBaseSubscriptionCallback.mm in Sources */, 510470FB2A2F7DF60053EA7E /* MTRBackwardsCompatShims.mm in Sources */, 5173A47629C0E2ED00F67F48 /* MTRFabricInfo.mm in Sources */, + 9B231B052C62EF650030EB37 /* MTRDeviceController_Concrete.mm in Sources */, 5ACDDD7D27CD16D200EFD68A /* MTRClusterStateCacheContainer.mm in Sources */, 75B3269E2BCDB9EA00E17C4E /* MTRDeviceConnectivityMonitor.mm in Sources */, 513DDB8A2761F6F900DAA01A /* MTRAttributeTLVValueDecoder.mm in Sources */, From 05671a16871800eb0b0338b583759d6aff7a65d8 Mon Sep 17 00:00:00 2001 From: mkardous-silabs <84793247+mkardous-silabs@users.noreply.github.com> Date: Thu, 15 Aug 2024 14:51:44 -0400 Subject: [PATCH 055/165] Update silabs docker image (#35011) Co-authored-by: Andrei Litvin --- integrations/docker/images/base/chip-build/version | 2 +- .../images/stage-2/chip-build-efr32/Dockerfile | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/integrations/docker/images/base/chip-build/version b/integrations/docker/images/base/chip-build/version index dfc4231a8e..0ca6f37e4e 100644 --- a/integrations/docker/images/base/chip-build/version +++ b/integrations/docker/images/base/chip-build/version @@ -1 +1 @@ -73 : [Telink] Update Docker image (Zephyr update) +74 : Update Silabs docker SiSDK 2024.06.1 WiseConnect 3.3.1 Wiseconnect Wifi bt sdk 2.10.0 diff --git a/integrations/docker/images/stage-2/chip-build-efr32/Dockerfile b/integrations/docker/images/stage-2/chip-build-efr32/Dockerfile index 7927c5ef1e..4de8beb62a 100644 --- a/integrations/docker/images/stage-2/chip-build-efr32/Dockerfile +++ b/integrations/docker/images/stage-2/chip-build-efr32/Dockerfile @@ -13,8 +13,8 @@ RUN set -x \ && : # last line -# Download Simplicity SDK v2024.6.0 (a1a37fa) -RUN wget https://github.com/SiliconLabs/simplicity_sdk/releases/download/v2024.6.0/sisdk-sdk.zip -O /tmp/simplicity_sdk.zip \ +# Download Simplicity SDK v2024.6.1 (a1a37fa) +RUN wget https://github.com/SiliconLabs/simplicity_sdk/releases/download/v2024.6.1-0/sisdk-sdk.zip -O /tmp/simplicity_sdk.zip \ && unzip /tmp/simplicity_sdk.zip -d /tmp/simplicity_sdk \ && rm -rf /tmp/simplicity_sdk.zip \ # Deleting files that are not needed to save space @@ -23,14 +23,14 @@ RUN wget https://github.com/SiliconLabs/simplicity_sdk/releases/download/v2024.6 && find /tmp/simplicity_sdk/protocol/openthread -name "*efr32mg21*" -delete \ && : # last line -# Clone WiSeConnect Wi-Fi and Bluetooth Software 2.8.2 (4fa5c5f) -RUN git clone --depth=1 --single-branch --branch=2.8.2 https://github.com/SiliconLabs/wiseconnect-wifi-bt-sdk.git /tmp/wiseconnect-wifi-bt-sdk && \ +# Clone WiSeConnect Wi-Fi and Bluetooth Software 2.10.0 (f94b83d) +RUN git clone --depth=1 --single-branch --branch=2.10.0 https://github.com/SiliconLabs/wiseconnect-wifi-bt-sdk.git /tmp/wiseconnect-wifi-bt-sdk && \ cd /tmp/wiseconnect-wifi-bt-sdk && \ rm -rf .git \ && : # last line -# Clone WiSeConnect SDK v3.3.0 (e97a0ed) -RUN git clone --depth=1 --single-branch --branch=v3.3.0 https://github.com/SiliconLabs/wiseconnect.git /tmp/wifi_sdk && \ +# Clone WiSeConnect SDK v3.3.1 (841ea3f) +RUN git clone --depth=1 --single-branch --branch=v3.3.1 https://github.com/SiliconLabs/wiseconnect.git /tmp/wifi_sdk && \ cd /tmp/wifi_sdk && \ rm -rf .git \ && : # last line From ede44b33a4b1153c4c31410321d7b6097bae26aa Mon Sep 17 00:00:00 2001 From: Andrei Litvin Date: Thu, 15 Aug 2024 15:22:34 -0400 Subject: [PATCH 056/165] Make BRBINFO_4_1 require commissioning (#35017) * Make BRVINFO_4_1 require commissioning * Also add icd registration --------- Co-authored-by: Andrei Litvin --- src/python_testing/TC_BRBINFO_4_1.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/python_testing/TC_BRBINFO_4_1.py b/src/python_testing/TC_BRBINFO_4_1.py index 18e478c872..922a6cb555 100644 --- a/src/python_testing/TC_BRBINFO_4_1.py +++ b/src/python_testing/TC_BRBINFO_4_1.py @@ -57,7 +57,8 @@ def desc_TC_BRBINFO_4_1(self) -> str: def steps_TC_BRBINFO_4_1(self) -> list[TestStep]: steps = [ - TestStep("0", "Preconditions"), + TestStep("0", "DUT commissioned", is_commissioning=True), + TestStep("0a", "Preconditions"), TestStep("1a", "TH reads from the ICD the A_IDLE_MODE_DURATION, A_ACTIVE_MODE_DURATION, and ACTIVE_MODE_THRESHOLD attributes"), TestStep("1b", "Simple KeepActive command w/ subscription. ActiveChanged event received by TH contains PromisedActiveDuration"), TestStep("2", "Sends 3x KeepActive commands w/ subscription. ActiveChanged event received ONCE and contains PromisedActiveDuration"), @@ -73,7 +74,7 @@ def _ask_for_vendor_commissioniong_ux_operation(self, discriminator, setupPinCod f"- setupQRCode: {setupQRCode}\n" f"- setupManualcode: {setupManualCode}\n" f"If using FabricSync Admin test app, you may type:\n" - f">>> pairing onnetwork 111 {setupPinCode}") + f">>> pairing onnetwork 111 {setupPinCode} --icd-registration true") async def _send_keep_active_command(self, duration, endpoint_id) -> int: logging.info("Sending keep active command") @@ -164,9 +165,11 @@ async def test_TC_BRBINFO_4_1(self): dynamic_endpoint_id = await self._get_dynamic_endpoint() logging.info(f"Dynamic endpoint is {dynamic_endpoint_id}") - # Preconditions self.step("0") + # Preconditions + self.step("0a") + logging.info("Ensuring DUT is commissioned to TH") # Confirms commissioning of DUT on TH as it reads its fature map From 50ede86c4947543d2f990bd41904ab4ab4932b79 Mon Sep 17 00:00:00 2001 From: Andrei Litvin Date: Thu, 15 Aug 2024 15:31:20 -0400 Subject: [PATCH 057/165] Disable TI builds from CI (#35024) Co-authored-by: Andrei Litvin --- .github/workflows/examples-cc13xx_26xx.yaml | 14 +++++++++----- .github/workflows/examples-cc32xx.yaml | 14 +++++++++----- 2 files changed, 18 insertions(+), 10 deletions(-) diff --git a/.github/workflows/examples-cc13xx_26xx.yaml b/.github/workflows/examples-cc13xx_26xx.yaml index d462d9f272..9d1ba6aa6c 100644 --- a/.github/workflows/examples-cc13xx_26xx.yaml +++ b/.github/workflows/examples-cc13xx_26xx.yaml @@ -15,11 +15,15 @@ name: Build example - TI CC13XX_26XX on: - push: - branches-ignore: - - "dependabot/**" - pull_request: - merge_group: + workflow_dispatch: + # Temporarely disabled: + # - TI CI runs out of disk space + # - Image should be updated to an Ubuntu 24.04 or higher based one (move from :54 version) + # push: + # branches-ignore: + # - 'dependabot/**' + # pull_request: + # merge_group: concurrency: group: diff --git a/.github/workflows/examples-cc32xx.yaml b/.github/workflows/examples-cc32xx.yaml index 564cd34ddd..dedf9e9c79 100644 --- a/.github/workflows/examples-cc32xx.yaml +++ b/.github/workflows/examples-cc32xx.yaml @@ -15,11 +15,15 @@ name: Build example - TI CC32XX on: - push: - branches-ignore: - - 'dependabot/**' - pull_request: - merge_group: + workflow_dispatch: + # Temporarely disabled: + # - TI CI runs out of disk space + # - Image should be updated to an Ubuntu 24.04 or higher based one (move from :54 version) + # push: + # branches-ignore: + # - 'dependabot/**' + # pull_request: + # merge_group: concurrency: group: ${{ github.ref }}-${{ github.workflow }}-${{ (github.event_name == 'pull_request' && github.event.number) || (github.event_name == 'workflow_dispatch' && github.run_number) || github.sha }} From 6cdd2747904e631c10bd2f52102d83bd2638e02c Mon Sep 17 00:00:00 2001 From: Andrei Litvin Date: Thu, 15 Aug 2024 15:56:03 -0400 Subject: [PATCH 058/165] Fix header usage in rvc (#35025) Co-authored-by: Andrei Litvin --- examples/rvc-app/rvc-common/include/rvc-service-area-delegate.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/rvc-app/rvc-common/include/rvc-service-area-delegate.h b/examples/rvc-app/rvc-common/include/rvc-service-area-delegate.h index 4c13fcd493..fdad4f83f0 100644 --- a/examples/rvc-app/rvc-common/include/rvc-service-area-delegate.h +++ b/examples/rvc-app/rvc-common/include/rvc-service-area-delegate.h @@ -21,7 +21,7 @@ #include #include #include -#include +#include namespace chip { namespace app { From e8e9fc5a21d825b1b5b718dc328a11e486e2f6fa Mon Sep 17 00:00:00 2001 From: Yufeng Wang Date: Thu, 15 Aug 2024 14:25:38 -0700 Subject: [PATCH 059/165] [Fabric-Admin] Add API to commission local bridge within its own fabric (#35020) * Add local bridge handle API * Update examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.cpp Co-authored-by: saurabhst * Update examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.cpp Co-authored-by: saurabhst * Use VerifyOrDie to check pairingCommand --------- Co-authored-by: saurabhst --- .../commands/fabric-sync/Commands.h | 2 + .../fabric-sync/FabricSyncCommand.cpp | 121 ++++++++++++++++-- .../commands/fabric-sync/FabricSyncCommand.h | 47 ++++++- .../device_manager/DeviceManager.cpp | 25 +++- .../device_manager/DeviceManager.h | 30 ++++- 5 files changed, 210 insertions(+), 15 deletions(-) diff --git a/examples/fabric-admin/commands/fabric-sync/Commands.h b/examples/fabric-admin/commands/fabric-sync/Commands.h index 94de1d31d8..a6bf1c258f 100644 --- a/examples/fabric-admin/commands/fabric-sync/Commands.h +++ b/examples/fabric-admin/commands/fabric-sync/Commands.h @@ -28,6 +28,8 @@ void registerCommandsFabricSync(Commands & commands, CredentialIssuerCommands * commands_list clusterCommands = { make_unique(credsIssuerConfig), make_unique(credsIssuerConfig), + make_unique(credsIssuerConfig), + make_unique(credsIssuerConfig), make_unique(credsIssuerConfig), make_unique(credsIssuerConfig), }; diff --git a/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.cpp b/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.cpp index f62d85ce5a..704996d189 100644 --- a/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.cpp +++ b/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.cpp @@ -32,10 +32,6 @@ using namespace ::chip; namespace { -// Constants -constexpr uint32_t kCommissionPrepareTimeMs = 500; -constexpr uint16_t kMaxManaulCodeLength = 21; - void CheckFabricBridgeSynchronizationSupport(intptr_t ignored) { DeviceMgr().ReadSupportedDeviceCategories(); @@ -43,7 +39,7 @@ void CheckFabricBridgeSynchronizationSupport(intptr_t ignored) } // namespace -void FabricSyncAddBridgeCommand::OnCommissioningComplete(chip::NodeId deviceId, CHIP_ERROR err) +void FabricSyncAddBridgeCommand::OnCommissioningComplete(NodeId deviceId, CHIP_ERROR err) { if (mBridgeNodeId != deviceId) { @@ -90,7 +86,7 @@ CHIP_ERROR FabricSyncAddBridgeCommand::RunCommand(NodeId remoteId) if (DeviceMgr().IsFabricSyncReady()) { // print to console - fprintf(stderr, "Remote Fabric Bridge has been alread configured."); + fprintf(stderr, "Remote Fabric Bridge has already been configured."); return CHIP_NO_ERROR; } @@ -98,7 +94,7 @@ CHIP_ERROR FabricSyncAddBridgeCommand::RunCommand(NodeId remoteId) if (pairingCommand == nullptr) { - ChipLogError(NotSpecified, "Pairing onnetwork command is not available"); + ChipLogError(NotSpecified, "Pairing already-discovered command is not available"); return CHIP_ERROR_NOT_IMPLEMENTED; } @@ -110,7 +106,7 @@ CHIP_ERROR FabricSyncAddBridgeCommand::RunCommand(NodeId remoteId) return CHIP_NO_ERROR; } -void FabricSyncRemoveBridgeCommand::OnDeviceRemoved(chip::NodeId deviceId, CHIP_ERROR err) +void FabricSyncRemoveBridgeCommand::OnDeviceRemoved(NodeId deviceId, CHIP_ERROR err) { if (mBridgeNodeId != deviceId) { @@ -150,7 +146,7 @@ CHIP_ERROR FabricSyncRemoveBridgeCommand::RunCommand() if (pairingCommand == nullptr) { - ChipLogError(NotSpecified, "Pairing code command is not available"); + ChipLogError(NotSpecified, "Pairing unpair command is not available"); return CHIP_ERROR_NOT_IMPLEMENTED; } @@ -161,13 +157,116 @@ CHIP_ERROR FabricSyncRemoveBridgeCommand::RunCommand() return CHIP_NO_ERROR; } +void FabricSyncAddLocalBridgeCommand::OnCommissioningComplete(NodeId deviceId, CHIP_ERROR err) +{ + if (mLocalBridgeNodeId != 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().SetLocalBridgeNodeId(mLocalBridgeNodeId); + ChipLogProgress(NotSpecified, "Successfully paired local bridge device: NodeId: " ChipLogFormatX64, + ChipLogValueX64(mLocalBridgeNodeId)); + } + else + { + ChipLogError(NotSpecified, "Failed to pair local bridge device (0x:" ChipLogFormatX64 ") with error: %" CHIP_ERROR_FORMAT, + ChipLogValueX64(deviceId), err.Format()); + } + + mLocalBridgeNodeId = kUndefinedNodeId; +} + +CHIP_ERROR FabricSyncAddLocalBridgeCommand::RunCommand(NodeId deviceId) +{ + if (DeviceMgr().IsLocalBridgeReady()) + { + // print to console + fprintf(stderr, "Local Fabric Bridge has already been configured."); + return CHIP_NO_ERROR; + } + + PairingCommand * pairingCommand = static_cast(CommandMgr().GetCommandByName("pairing", "already-discovered")); + VerifyOrDie(pairingCommand != nullptr); + + pairingCommand->RegisterCommissioningDelegate(this); + mLocalBridgeNodeId = deviceId; + + DeviceMgr().PairLocalFabricBridge(deviceId); + + return CHIP_NO_ERROR; +} + +void FabricSyncRemoveLocalBridgeCommand::OnDeviceRemoved(NodeId deviceId, CHIP_ERROR err) +{ + if (mLocalBridgeNodeId != deviceId) + { + ChipLogProgress(NotSpecified, "A non-bridge device: NodeId: " ChipLogFormatX64 " is removed.", ChipLogValueX64(deviceId)); + return; + } + + if (err == CHIP_NO_ERROR) + { + DeviceMgr().SetLocalBridgeNodeId(kUndefinedNodeId); + ChipLogProgress(NotSpecified, "Successfully removed local bridge device: NodeId: " ChipLogFormatX64, + ChipLogValueX64(mLocalBridgeNodeId)); + } + else + { + ChipLogError(NotSpecified, "Failed to remove local bridge device (0x:" ChipLogFormatX64 ") with error: %" CHIP_ERROR_FORMAT, + ChipLogValueX64(deviceId), err.Format()); + } + + mLocalBridgeNodeId = kUndefinedNodeId; +} + +CHIP_ERROR FabricSyncRemoveLocalBridgeCommand::RunCommand() +{ + NodeId bridgeNodeId = DeviceMgr().GetLocalBridgeNodeId(); + + if (bridgeNodeId == kUndefinedNodeId) + { + // print to console + fprintf(stderr, "Local Fabric Bridge is not configured yet, nothing to remove."); + return CHIP_NO_ERROR; + } + + mLocalBridgeNodeId = bridgeNodeId; + + PairingCommand * pairingCommand = static_cast(CommandMgr().GetCommandByName("pairing", "unpair")); + + if (pairingCommand == nullptr) + { + ChipLogError(NotSpecified, "Pairing unpair command is not available"); + return CHIP_ERROR_NOT_IMPLEMENTED; + } + + pairingCommand->RegisterPairingDelegate(this); + + DeviceMgr().UnpairLocalFabricBridge(); + + return CHIP_NO_ERROR; +} + void FabricSyncDeviceCommand::OnCommissioningWindowOpened(NodeId deviceId, CHIP_ERROR err, chip::SetupPayload payload) { ChipLogProgress(NotSpecified, "FabricSyncDeviceCommand::OnCommissioningWindowOpened"); if (err == CHIP_NO_ERROR) { - char payloadBuffer[kMaxManaulCodeLength + 1]; + char payloadBuffer[kMaxManualCodeLength + 1]; MutableCharSpan manualCode(payloadBuffer); CHIP_ERROR error = ManualSetupPayloadGenerator(payload).payloadDecimalStringRepresentation(manualCode); if (error == CHIP_NO_ERROR) @@ -202,7 +301,7 @@ void FabricSyncDeviceCommand::OnCommissioningWindowOpened(NodeId deviceId, CHIP_ } } -void FabricSyncDeviceCommand::OnCommissioningComplete(chip::NodeId deviceId, CHIP_ERROR err) +void FabricSyncDeviceCommand::OnCommissioningComplete(NodeId deviceId, CHIP_ERROR err) { if (mAssignedNodeId != deviceId) { diff --git a/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.h b/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.h index ca1b105207..1bbd22d293 100644 --- a/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.h +++ b/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.h @@ -22,6 +22,10 @@ #include #include +// Constants +constexpr uint32_t kCommissionPrepareTimeMs = 500; +constexpr uint16_t kMaxManualCodeLength = 21; + class FabricSyncAddBridgeCommand : public CHIPCommand, public CommissioningDelegate { public: @@ -31,7 +35,7 @@ class FabricSyncAddBridgeCommand : public CHIPCommand, public CommissioningDeleg AddArgument("device-remote-ip", &mRemoteAddr); } - void OnCommissioningComplete(NodeId deviceId, CHIP_ERROR err) override; + void OnCommissioningComplete(chip::NodeId deviceId, CHIP_ERROR err) override; /////////// CHIPCommand Interface ///////// CHIP_ERROR RunCommand() override { return RunCommand(mNodeId); } @@ -63,6 +67,47 @@ class FabricSyncRemoveBridgeCommand : public CHIPCommand, public PairingDelegate chip::NodeId mBridgeNodeId; }; +class FabricSyncAddLocalBridgeCommand : public CHIPCommand, public CommissioningDelegate +{ +public: + FabricSyncAddLocalBridgeCommand(CredentialIssuerCommands * credIssuerCommands) : + CHIPCommand("add-local-bridge", credIssuerCommands) + { + AddArgument("nodeid", 0, UINT64_MAX, &mNodeId); + } + + void OnCommissioningComplete(NodeId deviceId, CHIP_ERROR err) override; + + /////////// CHIPCommand Interface ///////// + CHIP_ERROR RunCommand() override { return RunCommand(mNodeId); } + + chip::System::Clock::Timeout GetWaitDuration() const override { return chip::System::Clock::Seconds16(1); } + +private: + chip::NodeId mNodeId; + chip::NodeId mLocalBridgeNodeId; + + CHIP_ERROR RunCommand(chip::NodeId deviceId); +}; + +class FabricSyncRemoveLocalBridgeCommand : public CHIPCommand, public PairingDelegate +{ +public: + FabricSyncRemoveLocalBridgeCommand(CredentialIssuerCommands * credIssuerCommands) : + CHIPCommand("remove-local-bridge", credIssuerCommands) + {} + + void OnDeviceRemoved(chip::NodeId deviceId, CHIP_ERROR err) override; + + /////////// CHIPCommand Interface ///////// + CHIP_ERROR RunCommand() override; + + chip::System::Clock::Timeout GetWaitDuration() const override { return chip::System::Clock::Seconds16(1); } + +private: + chip::NodeId mLocalBridgeNodeId; +}; + class FabricSyncDeviceCommand : public CHIPCommand, public CommissioningWindowDelegate, public CommissioningDelegate { public: diff --git a/examples/fabric-admin/device_manager/DeviceManager.cpp b/examples/fabric-admin/device_manager/DeviceManager.cpp index 7204e153d2..17adcc2427 100644 --- a/examples/fabric-admin/device_manager/DeviceManager.cpp +++ b/examples/fabric-admin/device_manager/DeviceManager.cpp @@ -33,6 +33,7 @@ namespace { // Constants constexpr uint32_t kSetupPinCode = 20202021; constexpr uint16_t kRemoteBridgePort = 5540; +constexpr uint16_t kLocalBridgePort = 5540; constexpr uint16_t kWindowTimeout = 300; constexpr uint16_t kIteration = 1000; constexpr uint16_t kSubscribeMinInterval = 0; @@ -117,6 +118,8 @@ void DeviceManager::RemoveSyncedDevice(NodeId nodeId) void DeviceManager::OpenDeviceCommissioningWindow(NodeId nodeId, uint32_t commissioningTimeout, uint32_t iterations, uint32_t discriminator, const char * saltHex, const char * verifierHex) { + ChipLogProgress(NotSpecified, "Open the commissioning window of device with NodeId:" ChipLogFormatX64, ChipLogValueX64(nodeId)); + // Open the commissioning window of a device within its own fabric. StringBuilder commandBuilder; @@ -132,7 +135,7 @@ void DeviceManager::OpenRemoteDeviceCommissioningWindow(EndpointId remoteEndpoin // Open the commissioning window of a device from another fabric via its fabric bridge. // This method constructs and sends a command to open the commissioning window for a device // that is part of a different fabric, accessed through a fabric bridge. - StringBuilder<512> commandBuilder; + StringBuilder commandBuilder; // Use random discriminator to have less chance of collission. uint16_t discriminator = @@ -166,6 +169,16 @@ void DeviceManager::PairRemoteDevice(chip::NodeId nodeId, const char * payload) PushCommand(commandBuilder.c_str()); } +void DeviceManager::PairLocalFabricBridge(NodeId nodeId) +{ + StringBuilder commandBuilder; + + commandBuilder.Add("pairing already-discovered "); + commandBuilder.AddFormat("%lu %d ::1 %d", nodeId, kSetupPinCode, kLocalBridgePort); + + PushCommand(commandBuilder.c_str()); +} + void DeviceManager::UnpairRemoteFabricBridge() { StringBuilder commandBuilder; @@ -176,6 +189,16 @@ void DeviceManager::UnpairRemoteFabricBridge() PushCommand(commandBuilder.c_str()); } +void DeviceManager::UnpairLocalFabricBridge() +{ + StringBuilder commandBuilder; + + commandBuilder.Add("pairing unpair "); + commandBuilder.AddFormat("%lu", mLocalBridgeNodeId); + + PushCommand(commandBuilder.c_str()); +} + void DeviceManager::SubscribeRemoteFabricBridge() { // Listen to the state changes of the remote fabric bridge. diff --git a/examples/fabric-admin/device_manager/DeviceManager.h b/examples/fabric-admin/device_manager/DeviceManager.h index cad573a931..454986bd7a 100644 --- a/examples/fabric-admin/device_manager/DeviceManager.h +++ b/examples/fabric-admin/device_manager/DeviceManager.h @@ -55,14 +55,20 @@ class DeviceManager : public PairingDelegate chip::NodeId GetRemoteBridgeNodeId() const { return mRemoteBridgeNodeId; } + chip::NodeId GetLocalBridgeNodeId() const { return mLocalBridgeNodeId; } + void UpdateLastUsedNodeId(chip::NodeId nodeId); - void SetRemoteBridgeNodeId(chip::NodeId remoteBridgeNodeId) { mRemoteBridgeNodeId = remoteBridgeNodeId; } + void SetRemoteBridgeNodeId(chip::NodeId nodeId) { mRemoteBridgeNodeId = nodeId; } + + void SetLocalBridgeNodeId(chip::NodeId nodeId) { mLocalBridgeNodeId = nodeId; } bool IsAutoSyncEnabled() const { return mAutoSyncEnabled; } bool IsFabricSyncReady() const { return mRemoteBridgeNodeId != chip::kUndefinedNodeId; } + bool IsLocalBridgeReady() const { return mLocalBridgeNodeId != chip::kUndefinedNodeId; } + void EnableAutoSync(bool state) { mAutoSyncEnabled = state; } void AddSyncedDevice(const Device & device); @@ -126,8 +132,20 @@ class DeviceManager : public PairingDelegate */ void PairRemoteDevice(chip::NodeId nodeId, const char * payload); + /** + * @brief Pair a local fabric bridge with a given node ID. + * + * This function initiates the pairing process for the local 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. + */ + void PairLocalFabricBridge(chip::NodeId nodeId); + void UnpairRemoteFabricBridge(); + void UnpairLocalFabricBridge(); + void SubscribeRemoteFabricBridge(); void StartReverseCommissioning(); @@ -147,8 +165,16 @@ class DeviceManager : public PairingDelegate static DeviceManager sInstance; - chip::NodeId mLastUsedNodeId = 0; + 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; + + // The Node ID of the local bridge used for Fabric-Sync + // This represents the bridge within its own ecosystem. + chip::NodeId mLocalBridgeNodeId = chip::kUndefinedNodeId; + std::set mSyncedDevices; bool mAutoSyncEnabled = false; bool mInitialized = false; From 2dc166f86130a635ea46fde4e78ab353a926f663 Mon Sep 17 00:00:00 2001 From: joonhaengHeo <85541460+joonhaengHeo@users.noreply.github.com> Date: Fri, 16 Aug 2024 10:25:07 +0900 Subject: [PATCH 060/165] [Android] Fix mDNS discover ANR issue (#34968) * Fix mDNS discover ANR issue * Restyled by google-java-format --------- Co-authored-by: Restyled.io --- .../platform/NsdManagerServiceBrowser.java | 6 ++- .../platform/NsdManagerServiceResolver.java | 40 ++++++++++--------- 2 files changed, 27 insertions(+), 19 deletions(-) diff --git a/src/platform/android/java/chip/platform/NsdManagerServiceBrowser.java b/src/platform/android/java/chip/platform/NsdManagerServiceBrowser.java index e4ac8a673b..1df91c6830 100644 --- a/src/platform/android/java/chip/platform/NsdManagerServiceBrowser.java +++ b/src/platform/android/java/chip/platform/NsdManagerServiceBrowser.java @@ -161,7 +161,11 @@ public void onServiceFound(NsdServiceInfo serviceInfo) { @Override public void onServiceLost(NsdServiceInfo serviceInfo) { - Log.i(TAG, "Lost service '" + serviceType + "'"); + Log.i( + TAG, + "Lost service '" + (serviceInfo != null ? serviceInfo.getServiceName() : "null") + "'"); + boolean ret = serviceNameList.remove(serviceInfo.getServiceName()); + Log.i(TAG, "Remove List: " + ret); } @Override diff --git a/src/platform/android/java/chip/platform/NsdManagerServiceResolver.java b/src/platform/android/java/chip/platform/NsdManagerServiceResolver.java index 11b53537bf..40595263cb 100644 --- a/src/platform/android/java/chip/platform/NsdManagerServiceResolver.java +++ b/src/platform/android/java/chip/platform/NsdManagerServiceResolver.java @@ -98,10 +98,6 @@ public void resolve( + serviceType + "'"); - if (nsdManagerResolverAvailState != null) { - nsdManagerResolverAvailState.acquireResolver(); - } - Runnable timeoutRunnable = new Runnable() { @Override @@ -120,21 +116,29 @@ public void run() { } }; - ScheduledFuture resolveTimeoutExecutor = - Executors.newSingleThreadScheduledExecutor() - .schedule(timeoutRunnable, timeout, TimeUnit.MILLISECONDS); + new Thread( + () -> { + if (nsdManagerResolverAvailState != null) { + nsdManagerResolverAvailState.acquireResolver(); + } + + ScheduledFuture resolveTimeoutExecutor = + Executors.newSingleThreadScheduledExecutor() + .schedule(timeoutRunnable, timeout, TimeUnit.MILLISECONDS); - NsdServiceFinderAndResolver serviceFinderResolver = - new NsdServiceFinderAndResolver( - this.nsdManager, - serviceInfo, - callbackHandle, - contextHandle, - chipMdnsCallback, - multicastLock, - resolveTimeoutExecutor, - nsdManagerResolverAvailState); - serviceFinderResolver.start(); + NsdServiceFinderAndResolver serviceFinderResolver = + new NsdServiceFinderAndResolver( + this.nsdManager, + serviceInfo, + callbackHandle, + contextHandle, + chipMdnsCallback, + multicastLock, + resolveTimeoutExecutor, + nsdManagerResolverAvailState); + serviceFinderResolver.start(); + }) + .start(); } @Override From 3ecfb6c9dd07a2b98472e99543e0856a5f2310bc Mon Sep 17 00:00:00 2001 From: joonhaengHeo <85541460+joonhaengHeo@users.noreply.github.com> Date: Fri, 16 Aug 2024 10:25:43 +0900 Subject: [PATCH 061/165] [Android] Implement Establish PASE Connection for SetupCode (#34971) * Implement Establish PASE Connection for SetupCode * Restyled by google-java-format * Restyled by clang-format --------- Co-authored-by: Restyled.io --- .../java/CHIPDeviceController-JNI.cpp | 25 +++++++++++++++++++ .../ChipDeviceController.java | 18 +++++++++++++ 2 files changed, 43 insertions(+) diff --git a/src/controller/java/CHIPDeviceController-JNI.cpp b/src/controller/java/CHIPDeviceController-JNI.cpp index 93ab5ccd0a..a0482b41db 100644 --- a/src/controller/java/CHIPDeviceController-JNI.cpp +++ b/src/controller/java/CHIPDeviceController-JNI.cpp @@ -852,6 +852,31 @@ JNI_METHOD(void, establishPaseConnectionByAddress) } } +JNI_METHOD(void, establishPaseConnectionByCode) +(JNIEnv * env, jobject self, jlong handle, jlong deviceId, jstring setUpCode, jboolean useOnlyOnNetworkDiscovery) +{ + chip::DeviceLayer::StackLock lock; + CHIP_ERROR err = CHIP_NO_ERROR; + AndroidDeviceControllerWrapper * wrapper = AndroidDeviceControllerWrapper::FromJNIHandle(handle); + + auto discoveryType = DiscoveryType::kAll; + if (useOnlyOnNetworkDiscovery) + { + discoveryType = DiscoveryType::kDiscoveryNetworkOnly; + } + + JniUtfString setUpCodeJniString(env, setUpCode); + + err = wrapper->Controller()->EstablishPASEConnection(static_cast(deviceId), setUpCodeJniString.c_str(), + discoveryType); + + if (err != CHIP_NO_ERROR) + { + ChipLogError(Controller, "Failed to establish PASE connection."); + JniReferences::GetInstance().ThrowError(env, sChipDeviceControllerExceptionCls, err); + } +} + JNI_METHOD(void, continueCommissioning) (JNIEnv * env, jobject self, jlong handle, jlong devicePtr, jboolean ignoreAttestationFailure) { diff --git a/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java b/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java index 37e9e7093a..4a59b178f8 100644 --- a/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java +++ b/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java @@ -470,6 +470,21 @@ public void establishPaseConnection(long deviceId, String address, int port, lon establishPaseConnectionByAddress(deviceControllerPtr, deviceId, address, port, setupPincode); } + /** + * Establish a secure PASE connection using the scanned QR code or manual entry code. + * + * @param deviceId the ID of the node to connect to + * @param setupCode the scanned QR code or manual entry code + * @param useOnlyOnNetworkDiscovery the flag to indicate the commissionable device is available on + * the network + */ + public void establishPaseConnection( + long deviceId, String setupCode, boolean useOnlyOnNetworkDiscovery) { + Log.d(TAG, "Establishing PASE connection using Code: " + setupCode); + establishPaseConnectionByCode( + deviceControllerPtr, deviceId, setupCode, useOnlyOnNetworkDiscovery); + } + /** * Initiates the automatic commissioning flow using the specified network credentials. It is * expected that a secure session has already been established via {@link @@ -1624,6 +1639,9 @@ private native void establishPaseConnection( private native void establishPaseConnectionByAddress( long deviceControllerPtr, long deviceId, String address, int port, long setupPincode); + private native void establishPaseConnectionByCode( + long deviceControllerPtr, long deviceId, String setupCode, boolean useOnlyOnNetworkDiscovery); + private native void commissionDevice( long deviceControllerPtr, long deviceId, From 6adca647bed45109f9a0bbf96214f57efa22d187 Mon Sep 17 00:00:00 2001 From: Justin Wood Date: Thu, 15 Aug 2024 20:18:22 -0700 Subject: [PATCH 062/165] Adding XPC protocols for darwin (#35029) * Initial checkin * Cleaning up protocol * Restyled by whitespace * Restyled by clang-format * Adding nodeID and controllerID for simple routing * Moving to implied Non-null * Removing these --------- Co-authored-by: Restyled.io --- src/darwin/Framework/CHIP/Matter.h | 3 + .../CHIP/XPC Protocol/MTRXPCClientProtocol.h | 39 ++++++++++ .../CHIP/XPC Protocol/MTRXPCServerProtocol.h | 76 +++++++++++++++++++ .../Matter.xcodeproj/project.pbxproj | 16 ++++ 4 files changed, 134 insertions(+) create mode 100644 src/darwin/Framework/CHIP/XPC Protocol/MTRXPCClientProtocol.h create mode 100644 src/darwin/Framework/CHIP/XPC Protocol/MTRXPCServerProtocol.h diff --git a/src/darwin/Framework/CHIP/Matter.h b/src/darwin/Framework/CHIP/Matter.h index 3c0ec41443..109f4a20a9 100644 --- a/src/darwin/Framework/CHIP/Matter.h +++ b/src/darwin/Framework/CHIP/Matter.h @@ -69,4 +69,7 @@ #import #import +#import +#import + #undef MTR_INCLUDED_FROM_UMBRELLA_HEADER diff --git a/src/darwin/Framework/CHIP/XPC Protocol/MTRXPCClientProtocol.h b/src/darwin/Framework/CHIP/XPC Protocol/MTRXPCClientProtocol.h new file mode 100644 index 0000000000..0d518f525f --- /dev/null +++ b/src/darwin/Framework/CHIP/XPC Protocol/MTRXPCClientProtocol.h @@ -0,0 +1,39 @@ +// +/** + * Copyright (c) 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. + */ +NS_ASSUME_NONNULL_BEGIN + +@protocol MTRXPCClientProtocol_MTRDevice +- (oneway void)device:(NSNumber *)nodeID stateChanged:(MTRDeviceState)state; +- (oneway void)device:(NSNumber *)nodeID receivedAttributeReport:(NSArray *> *)attributeReport; +- (oneway void)device:(NSNumber *)nodeID receivedEventReport:(NSArray *> *)eventReport; +- (oneway void)deviceBecameActive:(NSNumber *)nodeID; +- (oneway void)deviceCachePrimed:(NSNumber *)nodeID; +- (oneway void)deviceConfigurationChanged:(NSNumber *)nodeID; +@end + +@protocol MTRXPCClientProtocol_MTRDeviceController +// Not Supported via XPC +//- (oneway void)controller:(NSUUID *)controller statusUpdate:(MTRCommissioningStatus)status; +//- (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; +@end + +@protocol MTRXPCClientProtocol +@end + +NS_ASSUME_NONNULL_END diff --git a/src/darwin/Framework/CHIP/XPC Protocol/MTRXPCServerProtocol.h b/src/darwin/Framework/CHIP/XPC Protocol/MTRXPCServerProtocol.h new file mode 100644 index 0000000000..56077897a9 --- /dev/null +++ b/src/darwin/Framework/CHIP/XPC Protocol/MTRXPCServerProtocol.h @@ -0,0 +1,76 @@ +// +/** + * Copyright (c) 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. + */ + +NS_ASSUME_NONNULL_BEGIN + +@protocol MTRXPCServerProtocol_MTRDevice + +- (oneway void)deviceController:(NSUUID *)controller nodeID:(NSNumber *)nodeID getStateWithReply:(void (^)(MTRDeviceState state))reply; +- (oneway void)deviceController:(NSUUID *)controller nodeID:(NSNumber *)nodeID getDeviceCachePrimedWithReply:(void (^)(BOOL primed))reply; +- (oneway void)deviceController:(NSUUID *)controller nodeID:(NSNumber *)nodeID getEstimatedStartTimeWithReply:(void (^)(NSDate * _Nullable estimatedStartTime))reply; +- (oneway void)deviceController:(NSUUID *)controller nodeID:(NSNumber *)nodeID getEstimatedSubscriptionLatencyWithReply:(void (^)(NSNumber * _Nullable estimatedSubscriptionLatency))reply; + +- (oneway void)deviceController:(NSUUID *)controller nodeID:(NSNumber *)nodeID readAttributeWithEndpointID:(NSNumber *)endpointID clusterID:(NSNumber *)clusterID attributeID:(NSNumber *)attributeID params:(MTRReadParams * _Nullable)params withReply:(void (^)(NSDictionary * _Nullable))reply; +- (oneway void)deviceController:(NSUUID *)controller nodeID:(NSNumber *)nodeID writeAttributeWithEndpointID:(NSNumber *)endpointID clusterID:(NSNumber *)clusterID attributeID:(NSNumber *)attributeID value:(id _Nullable)value expectedValueInterval:(NSNumber * _Nullable)expectedValueInterval timedWriteTimeout:(NSNumber * _Nullable)timeout; + +- (oneway void)deviceController:(NSUUID *)controller nodeID:(NSNumber *)nodeID invokeCommandWithEndpointID:(NSNumber *)endpointID clusterID:(NSNumber *)clusterID commandID:(NSNumber *)commandID commandFields:(id)commandFields expectedValues:(NSArray *> * _Nullable)expectedValues expectedValueInterval:(NSNumber * _Nullable)expectedValueInterval timedInvokeTimeout:(NSNumber * _Nullable)timeout completion:(MTRDeviceResponseHandler)completion; + +// Not Supported via XPC +//- (oneway void)deviceController:(NSUUID *)controller nodeID:(NSNumber *)nodeID openCommissioningWindowWithSetupPasscode:(NSNumber *)setupPasscode discriminator:(NSNumber *)discriminator duration:(NSNumber *)duration completion:(MTRDeviceOpenCommissioningWindowHandler)completion; + +- (oneway void)deviceController:(NSUUID *)controller nodeID:(NSNumber *)nodeID getClientDataKeysWithReply:(void (^)(NSArray * _Nullable))reply; +- (oneway void)deviceController:(NSUUID *)controller nodeID:(NSNumber *)nodeID clientDataForKey:(NSString *)key withReply:(void (^)(id _Nullable))reply; +- (oneway void)deviceController:(NSUUID *)controller nodeID:(NSNumber *)nodeID setClientDataForKey:(NSString *)key value:(id)value; +- (oneway void)deviceController:(NSUUID *)controller nodeID:(NSNumber *)nodeID removeClientDataForKey:(NSString *)key; +- (oneway void)deviceController:(NSUUID *)controller nodeID:(NSNumber *)nodeID clientDataKeysForEndpointID:(NSNumber *)endpointID withReply:(void (^)(NSArray * _Nullable))reply; +- (oneway void)deviceController:(NSUUID *)controller nodeID:(NSNumber *)nodeID clientDataForKey:(NSString *)key endpointID:(NSNumber *)endpointID withReply:(void (^)(id _Nullable))reply; +- (oneway void)deviceController:(NSUUID *)controller nodeID:(NSNumber *)nodeID setClientDataForKey:(NSString *)key endpointID:(NSNumber *)endpointID value:(id _Nullable)value; +- (oneway void)deviceController:(NSUUID *)controller nodeID:(NSNumber *)nodeID removeClientDataForKey:(NSString *)key endpointID:(NSNumber *)endpointID; + +// Not Supported via XPC +// - (oneway void)downloadLogOfType:(MTRDiagnosticLogType)type nodeID:(NSNumber *)nodeID timeout:(NSTimeInterval)timeout completion:(void (^)(NSURL * _Nullable url, NSError * _Nullable error))completion; +@end + +@protocol MTRXPCServerProtocol_MTRDeviceController + +- (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; + +// 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; +// - (oneway void)deviceController:(NSUUID *)controller commissionNodeWithID:(NSNumber *)nodeID commissioningParams:(MTRCommissioningParameters *)commissioningParams withReply:(void(^)(BOOL success, NSError * _Nullable error))reply; +// - (oneway void)deviceController:(NSUUID *)controller continueCommissioningDevice:(void *)opaqueDeviceHandle ignoreAttestationFailure:(BOOL)ignoreAttestationFailure withReply:(void(^)(BOOL success, NSError * _Nullable error))reply; +// - (oneway void)deviceController:(NSUUID *)controller cancelCommissioningForNodeID:(NSNumber *)nodeID withReply:(void(^)(BOOL success, NSError * _Nullable error))reply; +// - (nullable MTRBaseDevice *)deviceController:(NSUUID *)controller deviceBeingCommissionedWithNodeID:(NSNumber *)nodeID error:(NSError * __autoreleasing *)error; +// - (oneway void)deviceController:(NSUUID *)controller startBrowseForCommissionables:(id)delegate withReply:(void(^)(BOOL success))reply; +// - (oneway void)deviceController:(NSUUID *)controller stopBrowseForCommissionablesWithReply:(void(^)(BOOL success))reply; +// - (oneway void)deviceController:(NSUUID *)controller attestationChallengeForDeviceID:(NSNumber *)deviceID withReply:(void(^)(NSData * _Nullable))reply; + +//- (oneway void)deviceController:(NSUUID *)controller addServerEndpoint:(MTRServerEndpoint *)endpoint withReply:(void(^)(BOOL success))reply; +//- (oneway void)deviceController:(NSUUID *)controller removeServerEndpoint:(MTRServerEndpoint *)endpoint; + +- (oneway void)shutdownDeviceController:(NSUUID *)controller; + +@end + +@protocol MTRXPCServerProtocol +- (oneway void)deviceController:(NSUUID *)controller checkInWithContext:(NSDictionary *)context; +@end + +NS_ASSUME_NONNULL_END diff --git a/src/darwin/Framework/Matter.xcodeproj/project.pbxproj b/src/darwin/Framework/Matter.xcodeproj/project.pbxproj index 2dc7bd266a..69ef3bdc71 100644 --- a/src/darwin/Framework/Matter.xcodeproj/project.pbxproj +++ b/src/darwin/Framework/Matter.xcodeproj/project.pbxproj @@ -371,6 +371,8 @@ B4FCD5722B603A6300832859 /* DownloadLogCommand.mm in Sources */ = {isa = PBXBuildFile; fileRef = B4FCD56F2B603A6300832859 /* DownloadLogCommand.mm */; }; B4FCD5732B611EB300832859 /* MTRDiagnosticLogsDownloader.h in Headers */ = {isa = PBXBuildFile; fileRef = B4C8E6B32B3453AD00FCD54D /* MTRDiagnosticLogsDownloader.h */; }; BA09EB43247477BA00605257 /* libCHIP.a in Frameworks */ = {isa = PBXBuildFile; fileRef = BA09EB3F2474762900605257 /* libCHIP.a */; }; + D444F9A72C6E8F9D007761E5 /* MTRXPCServerProtocol.h in Headers */ = {isa = PBXBuildFile; fileRef = D444F9A62C6E8F9D007761E5 /* MTRXPCServerProtocol.h */; settings = {ATTRIBUTES = (Public, ); }; }; + D444F9AA2C6E9A08007761E5 /* MTRXPCClientProtocol.h in Headers */ = {isa = PBXBuildFile; fileRef = D444F9A82C6E99CA007761E5 /* MTRXPCClientProtocol.h */; settings = {ATTRIBUTES = (Public, ); }; }; D4772A46285AE98400383630 /* MTRClusterConstants.h in Headers */ = {isa = PBXBuildFile; fileRef = D4772A45285AE98300383630 /* MTRClusterConstants.h */; settings = {ATTRIBUTES = (Public, ); }; }; E04AC67D2BEEA17F00BA409B /* ember-io-storage.cpp in Sources */ = {isa = PBXBuildFile; fileRef = E04AC67B2BEEA17F00BA409B /* ember-io-storage.cpp */; }; E04AC67E2BEEA17F00BA409B /* ember-io-storage.cpp in Sources */ = {isa = PBXBuildFile; fileRef = E04AC67B2BEEA17F00BA409B /* ember-io-storage.cpp */; }; @@ -809,6 +811,8 @@ D437613E285BDC0D0051FEA2 /* MTRErrorTestUtils.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MTRErrorTestUtils.h; sourceTree = ""; }; D437613F285BDC0D0051FEA2 /* MTRTestKeys.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MTRTestKeys.h; sourceTree = ""; }; D4376140285BDC0D0051FEA2 /* MTRTestStorage.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MTRTestStorage.h; sourceTree = ""; }; + D444F9A62C6E8F9D007761E5 /* MTRXPCServerProtocol.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MTRXPCServerProtocol.h; sourceTree = ""; }; + D444F9A82C6E99CA007761E5 /* MTRXPCClientProtocol.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MTRXPCClientProtocol.h; sourceTree = ""; }; D4772A45285AE98300383630 /* MTRClusterConstants.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MTRClusterConstants.h; sourceTree = ""; }; E04AC67B2BEEA17F00BA409B /* ember-io-storage.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = "ember-io-storage.cpp"; path = "util/ember-io-storage.cpp"; sourceTree = ""; }; E04AC67C2BEEA17F00BA409B /* ember-global-attribute-access-interface.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = "ember-global-attribute-access-interface.cpp"; path = "util/ember-global-attribute-access-interface.cpp"; sourceTree = ""; }; @@ -1246,6 +1250,7 @@ B202528F2459E34F00F97062 /* CHIP */ = { isa = PBXGroup; children = ( + D444F9A12C6E8058007761E5 /* XPC Protocol */, 9B231B022C62EF650030EB37 /* MTRDeviceController_Concrete.h */, 9B231B032C62EF650030EB37 /* MTRDeviceController_Concrete.mm */, 88E07D602B9A89A4005FD53E /* MTRMetricKeys.h */, @@ -1539,6 +1544,15 @@ name = Frameworks; sourceTree = ""; }; + D444F9A12C6E8058007761E5 /* XPC Protocol */ = { + isa = PBXGroup; + children = ( + D444F9A82C6E99CA007761E5 /* MTRXPCClientProtocol.h */, + D444F9A62C6E8F9D007761E5 /* MTRXPCServerProtocol.h */, + ); + path = "XPC Protocol"; + sourceTree = ""; + }; /* End PBXGroup section */ /* Begin PBXHeadersBuildPhase section */ @@ -1609,6 +1623,7 @@ 75B765C12A1D71BC0014719B /* MTRAttributeSpecifiedCheck.h in Headers */, 5ACDDD7A27CD129700EFD68A /* MTRClusterStateCacheContainer.h in Headers */, 5A6FEC9227B5669C00F25F42 /* MTRDeviceControllerOverXPC.h in Headers */, + D444F9AA2C6E9A08007761E5 /* MTRXPCClientProtocol.h in Headers */, 5117DD3929A931AE00FFA1AA /* MTROperationalBrowser.h in Headers */, 2C1B027B2641DB4E00780EF1 /* MTROperationalCredentialsDelegate.h in Headers */, 5173A47529C0E2ED00F67F48 /* MTRFabricInfo_Internal.h in Headers */, @@ -1698,6 +1713,7 @@ 5A7947E527C0129F00434CF2 /* MTRDeviceController+XPC.h in Headers */, 51E95DFB2A78443C00A434F0 /* MTRSessionResumptionStorageBridge.h in Headers */, B2E0D7B4245B0B5C003C5B48 /* MTRError_Internal.h in Headers */, + D444F9A72C6E8F9D007761E5 /* MTRXPCServerProtocol.h in Headers */, 51F5226A2AE70761000C4050 /* MTRDeviceTypeMetadata.h in Headers */, 5146544B2A72F9F500904E61 /* MTRDemuxingStorage.h in Headers */, 1EDCE545289049A100E41EC9 /* MTROTAHeader.h in Headers */, From 7ae51991a95f615e7aff306b257fefc69c062312 Mon Sep 17 00:00:00 2001 From: Andrei Litvin Date: Thu, 15 Aug 2024 23:49:28 -0400 Subject: [PATCH 063/165] Set FabricFiltered to True when reading Fabrics. (#35023) Otherwise we get a fabric view on the list of fabrics which does not change over time. Co-authored-by: Andrei Litvin --- src/python_testing/TC_CCTRL_2_2.py | 6 +++--- src/python_testing/TC_MCORE_FS_1_1.py | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/python_testing/TC_CCTRL_2_2.py b/src/python_testing/TC_CCTRL_2_2.py index 5204352b8b..53c196113d 100644 --- a/src/python_testing/TC_CCTRL_2_2.py +++ b/src/python_testing/TC_CCTRL_2_2.py @@ -123,7 +123,7 @@ async def test_TC_CCTRL_2_2(self): self.is_ci = self.check_pics('PICS_SDK_CI_ONLY') self.step(1) - th_server_fabrics = await self.read_single_attribute_check_success(cluster=Clusters.OperationalCredentials, attribute=Clusters.OperationalCredentials.Attributes.Fabrics, dev_ctrl=self.TH_server_controller, node_id=self.server_nodeid, endpoint=0) + th_server_fabrics = await self.read_single_attribute_check_success(cluster=Clusters.OperationalCredentials, attribute=Clusters.OperationalCredentials.Attributes.Fabrics, dev_ctrl=self.TH_server_controller, node_id=self.server_nodeid, endpoint=0, fabric_filtered=False) self.step(2) th_server_vid = await self.read_single_attribute_check_success(cluster=Clusters.BasicInformation, attribute=Clusters.BasicInformation.Attributes.VendorID, dev_ctrl=self.TH_server_controller, node_id=self.server_nodeid, endpoint=0) self.step(3) @@ -248,7 +248,7 @@ async def test_TC_CCTRL_2_2(self): self.step(20) print(f'server node id {self.server_nodeid}') - th_server_fabrics_new = await self.read_single_attribute_check_success(cluster=Clusters.OperationalCredentials, attribute=Clusters.OperationalCredentials.Attributes.Fabrics, dev_ctrl=self.TH_server_controller, node_id=self.server_nodeid, endpoint=0) + th_server_fabrics_new = await self.read_single_attribute_check_success(cluster=Clusters.OperationalCredentials, attribute=Clusters.OperationalCredentials.Attributes.Fabrics, dev_ctrl=self.TH_server_controller, node_id=self.server_nodeid, endpoint=0, fabric_filtered=False) asserts.assert_equal(len(th_server_fabrics), len(th_server_fabrics_new), "Unexpected number of fabrics on TH_SERVER") self.step(21) @@ -294,7 +294,7 @@ async def test_TC_CCTRL_2_2(self): time.sleep(30) self.step(28) - th_server_fabrics_new = await self.read_single_attribute_check_success(cluster=Clusters.OperationalCredentials, attribute=Clusters.OperationalCredentials.Attributes.Fabrics, dev_ctrl=self.TH_server_controller, node_id=self.server_nodeid, endpoint=0) + th_server_fabrics_new = await self.read_single_attribute_check_success(cluster=Clusters.OperationalCredentials, attribute=Clusters.OperationalCredentials.Attributes.Fabrics, dev_ctrl=self.TH_server_controller, node_id=self.server_nodeid, endpoint=0, fabric_filtered=False) # TODO: this should be mocked too. if not self.is_ci: asserts.assert_equal(len(th_server_fabrics) + 1, len(th_server_fabrics_new), diff --git a/src/python_testing/TC_MCORE_FS_1_1.py b/src/python_testing/TC_MCORE_FS_1_1.py index 0680210bab..6753db81a3 100755 --- a/src/python_testing/TC_MCORE_FS_1_1.py +++ b/src/python_testing/TC_MCORE_FS_1_1.py @@ -93,7 +93,7 @@ async def test_TC_MCORE_FS_1_1(self): self.step(1) self.step(2) self.step(3) - th_fsa_server_fabrics = await self.read_single_attribute_check_success(cluster=Clusters.OperationalCredentials, attribute=Clusters.OperationalCredentials.Attributes.Fabrics, dev_ctrl=self.TH_server_controller, node_id=self.server_nodeid, endpoint=0) + th_fsa_server_fabrics = await self.read_single_attribute_check_success(cluster=Clusters.OperationalCredentials, attribute=Clusters.OperationalCredentials.Attributes.Fabrics, dev_ctrl=self.TH_server_controller, node_id=self.server_nodeid, endpoint=0, fabric_filtered=False) th_fsa_server_vid = await self.read_single_attribute_check_success(cluster=Clusters.BasicInformation, attribute=Clusters.BasicInformation.Attributes.VendorID, dev_ctrl=self.TH_server_controller, node_id=self.server_nodeid, endpoint=0) th_fsa_server_pid = await self.read_single_attribute_check_success(cluster=Clusters.BasicInformation, attribute=Clusters.BasicInformation.Attributes.ProductID, dev_ctrl=self.TH_server_controller, node_id=self.server_nodeid, endpoint=0) @@ -138,7 +138,7 @@ async def test_TC_MCORE_FS_1_1(self): if not self.is_ci: time.sleep(30) - th_fsa_server_fabrics_new = await self.read_single_attribute_check_success(cluster=Clusters.OperationalCredentials, attribute=Clusters.OperationalCredentials.Attributes.Fabrics, dev_ctrl=self.TH_server_controller, node_id=self.server_nodeid, endpoint=0) + th_fsa_server_fabrics_new = await self.read_single_attribute_check_success(cluster=Clusters.OperationalCredentials, attribute=Clusters.OperationalCredentials.Attributes.Fabrics, dev_ctrl=self.TH_server_controller, node_id=self.server_nodeid, endpoint=0, fabric_filtered=False) # TODO: this should be mocked too. if not self.is_ci: asserts.assert_equal(len(th_fsa_server_fabrics) + 1, len(th_fsa_server_fabrics_new), From e9f1f1eb2e7df8ea1e080341d4855b6305616eea Mon Sep 17 00:00:00 2001 From: Terence Hampson Date: Fri, 16 Aug 2024 10:34:40 -0400 Subject: [PATCH 064/165] Fix BRBINFO_4_1 to run further (#35026) * Fix BRBINFO_4_1 to run further * Restyled by autopep8 --------- Co-authored-by: Restyled.io --- src/python_testing/TC_BRBINFO_4_1.py | 71 +++++++++++++++------------- 1 file changed, 38 insertions(+), 33 deletions(-) diff --git a/src/python_testing/TC_BRBINFO_4_1.py b/src/python_testing/TC_BRBINFO_4_1.py index 922a6cb555..8e920d8bc6 100644 --- a/src/python_testing/TC_BRBINFO_4_1.py +++ b/src/python_testing/TC_BRBINFO_4_1.py @@ -81,11 +81,12 @@ async def _send_keep_active_command(self, duration, endpoint_id) -> int: keep_active = await self.default_controller.SendCommand(nodeid=self.dut_node_id, endpoint=endpoint_id, payload=Clusters.Objects.BridgedDeviceBasicInformation.Commands.KeepActive(stayActiveDuration=duration)) return keep_active - async def _wait_for_active_changed_event(self, timeout) -> int: + async def _wait_for_active_changed_event(self, timeout_s) -> int: try: - promised_active_duration = self.q.get(block=True, timeout=timeout) - logging.info(f"PromisedActiveDuration: {promised_active_duration}") - return promised_active_duration + promised_active_duration_event = self.q.get(block=True, timeout=timeout_s) + logging.info(f"PromisedActiveDurationEvent: {promised_active_duration_event}") + promised_active_duration_ms = promised_active_duration_event.Data.promisedActiveDuration + return promised_active_duration_ms except queue.Empty: asserts.fail("Timeout on event ActiveChanged") @@ -192,21 +193,21 @@ async def test_TC_BRBINFO_4_1(self): self.step("1a") - idle_mode_duration = await self._read_attribute_expect_success( + idle_mode_duration_s = await self._read_attribute_expect_success( _ROOT_ENDPOINT_ID, icdm_cluster, icdm_attributes.IdleModeDuration, self.icd_nodeid ) - logging.info(f"IdleModeDuration: {idle_mode_duration}") + logging.info(f"IdleModeDurationS: {idle_mode_duration_s}") - active_mode_duration = await self._read_attribute_expect_success( + active_mode_duration_ms = await self._read_attribute_expect_success( _ROOT_ENDPOINT_ID, icdm_cluster, icdm_attributes.ActiveModeDuration, self.icd_nodeid ) - logging.info(f"ActiveModeDuration: {active_mode_duration}") + logging.info(f"ActiveModeDurationMs: {active_mode_duration_ms}") self.step("1b") @@ -218,49 +219,53 @@ async def test_TC_BRBINFO_4_1(self): subscription = await self.default_controller.ReadEvent(nodeid=self.dut_node_id, events=[(dynamic_endpoint_id, event, urgent)], reportInterval=[1, 3]) subscription.SetEventUpdateCallback(callback=cb) - stay_active_duration = 1000 - logging.info(f"Sending KeepActiveCommand({stay_active_duration}ms)") - self._send_keep_active_command(stay_active_duration, dynamic_endpoint_id) + stay_active_duration_ms = 1000 + logging.info(f"Sending KeepActiveCommand({stay_active_duration_ms}ms)") + await self._send_keep_active_command(stay_active_duration_ms, dynamic_endpoint_id) logging.info("Waiting for ActiveChanged from DUT...") - promised_active_duration = await self._wait_for_active_changed_event((idle_mode_duration + max(active_mode_duration, stay_active_duration))/1000) + timeout_s = idle_mode_duration_s + max(active_mode_duration_ms, stay_active_duration_ms)/1000 + promised_active_duration_ms = await self._wait_for_active_changed_event(timeout_s) - asserts.assert_greater_equal(promised_active_duration, stay_active_duration, "PromisedActiveDuration < StayActiveDuration") + asserts.assert_greater_equal(promised_active_duration_ms, stay_active_duration_ms, + "PromisedActiveDuration < StayActiveDuration") self.step("2") - stay_active_duration = 1500 - logging.info(f"Sending KeepActiveCommand({stay_active_duration}ms)") - self._send_keep_active_command(stay_active_duration) + stay_active_duration_ms = 1500 + logging.info(f"Sending KeepActiveCommand({stay_active_duration_ms}ms)") + await self._send_keep_active_command(stay_active_duration_ms, dynamic_endpoint_id) logging.info("Waiting for ActiveChanged from DUT...") - promised_active_duration = await self._wait_for_active_changed_event((idle_mode_duration + max(active_mode_duration, stay_active_duration))/1000) + timeout_s = idle_mode_duration_s + max(active_mode_duration_ms, stay_active_duration_ms)/1000 + promised_active_duration_ms = await self._wait_for_active_changed_event(timeout_s) # wait for active time duration - time.sleep(max(stay_active_duration/1000, promised_active_duration)) + sleep_time_s = max(stay_active_duration_ms, promised_active_duration_ms)/1000 + time.sleep(sleep_time_s) # ICD now should be in idle mode # sends 3x keep active commands - logging.info(f"Sending KeepActiveCommand({stay_active_duration})") - self._send_keep_active_command(stay_active_duration, dynamic_endpoint_id) - time.sleep(100) - logging.info(f"Sending KeepActiveCommand({stay_active_duration})") - self._send_keep_active_command(stay_active_duration, dynamic_endpoint_id) - time.sleep(100) - logging.info(f"Sending KeepActiveCommand({stay_active_duration})") - self._send_keep_active_command(stay_active_duration, dynamic_endpoint_id) - time.sleep(100) + logging.info(f"Step3 Sending first KeepActiveCommand({stay_active_duration_ms})") + await self._send_keep_active_command(stay_active_duration_ms, dynamic_endpoint_id) + time.sleep(0.1) + logging.info(f"Step3 Sending second KeepActiveCommand({stay_active_duration_ms})") + await self._send_keep_active_command(stay_active_duration_ms, dynamic_endpoint_id) + time.sleep(0.1) + logging.info(f"Step3 Sending third KeepActiveCommand({stay_active_duration_ms})") + await self._send_keep_active_command(stay_active_duration_ms, dynamic_endpoint_id) + time.sleep(0.1) logging.info("Waiting for ActiveChanged from DUT...") - promised_active_duration = await self._wait_for_active_changed_event((idle_mode_duration + max(active_mode_duration, stay_active_duration))/1000) + promised_active_duration_ms = await self._wait_for_active_changed_event((idle_mode_duration_s + max(active_mode_duration_ms, stay_active_duration_ms))/1000) asserts.assert_equal(self.q.qSize(), 0, "More than one event received from DUT") self.step("3") - stay_active_duration = 10000 - logging.info(f"Sending KeepActiveCommand({stay_active_duration})") - self._send_keep_active_command(stay_active_duration, dynamic_endpoint_id) + stay_active_duration_ms = 10000 + logging.info(f"Sending KeepActiveCommand({stay_active_duration_ms})") + await self._send_keep_active_command(stay_active_duration_ms, dynamic_endpoint_id) # stops (halts) the ICD server process by sending a SIGTOP signal self.app_process.send_signal(signal.SIGSTOP.value) @@ -274,9 +279,9 @@ async def test_TC_BRBINFO_4_1(self): self.app_process.send_signal(signal.SIGCONT.value) # wait for active changed event, expect no event will be sent - event_timeout = (idle_mode_duration + max(active_mode_duration, stay_active_duration))/1000 + event_timeout = (idle_mode_duration_s + max(active_mode_duration_ms, stay_active_duration_ms))/1000 try: - promised_active_duration = self.q.get(block=True, timeout=event_timeout) + promised_active_duration_ms = self.q.get(block=True, timeout=event_timeout) finally: asserts.assert_true(queue.Empty(), "ActiveChanged event received when not expected") From ab5fbebee03553029491637a9d1b33c987d2e18b Mon Sep 17 00:00:00 2001 From: doru91 Date: Fri, 16 Aug 2024 17:35:48 +0300 Subject: [PATCH 065/165] fabric sync guide: fix device-remote-port (#35035) Signed-off-by: Doru Gucea --- docs/guides/fabric_synchronization_guide.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/guides/fabric_synchronization_guide.md b/docs/guides/fabric_synchronization_guide.md index b2cfd26d9f..5944105512 100644 --- a/docs/guides/fabric_synchronization_guide.md +++ b/docs/guides/fabric_synchronization_guide.md @@ -127,7 +127,7 @@ KVS Pair the Light Example with node ID 3 using its payload number: ``` -pairing already-discovered 3 20202021 5540 +pairing already-discovered 3 20202021 5543 ``` After the device is successfully added, you will observe the following on From 5a1949c705c0e82b5ae89c33f67ca6e2886fbe13 Mon Sep 17 00:00:00 2001 From: adabreuti <76965454+adabreuti@users.noreply.github.com> Date: Fri, 16 Aug 2024 09:35:55 -0500 Subject: [PATCH 066/165] [TI] Update TI BLE Manager Task priority (#34852) * Update TI BLE Manager task priority for initialization sequence * Restyled by clang-format --------- Co-authored-by: Restyled.io --- src/platform/cc13xx_26xx/BLEManagerImpl.cpp | 4 +- src/platform/cc13xx_26xx/icall_FreeRTOS.c | 3926 +++++++++++++++++ .../ti_simplelink_sdk/ti_simplelink_sdk.gni | 4 +- 3 files changed, 3931 insertions(+), 3 deletions(-) create mode 100644 src/platform/cc13xx_26xx/icall_FreeRTOS.c diff --git a/src/platform/cc13xx_26xx/BLEManagerImpl.cpp b/src/platform/cc13xx_26xx/BLEManagerImpl.cpp index fc0a6af0be..f1d179c4b3 100644 --- a/src/platform/cc13xx_26xx/BLEManagerImpl.cpp +++ b/src/platform/cc13xx_26xx/BLEManagerImpl.cpp @@ -521,7 +521,7 @@ void BLEManagerImpl::EventHandler_init(void) /* set the stacks in default states */ DMMPolicy_updateStackState(DMMPolicy_StackRole_BlePeripheral, DMMPOLICY_BLE_IDLE); - vTaskPrioritySet(xTaskGetCurrentTaskHandle(), 3); + vTaskPrioritySet(xTaskGetCurrentTaskHandle(), BLE_MANAGER_TASK_PRIORITY); // ****************************************************************** // N0 STACK API CALLS CAN OCCUR BEFORE THIS CALL TO ICall_registerApp @@ -634,7 +634,7 @@ CHIP_ERROR BLEManagerImpl::CreateEventHandler(void) "ble_hndlr", /* Text name for the task. */ BLEMANAGER_EVENT_HANDLER_STACK_SIZE, /* Stack size in words, not bytes. */ this, /* Parameter passed into the task. */ - ICALL_TASK_PRIORITIES, /* Keep priority the same as ICALL until init is complete */ + BLE_STACK_TASK_PRIORITY, /* Keep priority the same as ICALL until init is complete */ NULL); /* Used to pass out the created task's handle. */ if (xReturned == errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY) diff --git a/src/platform/cc13xx_26xx/icall_FreeRTOS.c b/src/platform/cc13xx_26xx/icall_FreeRTOS.c new file mode 100644 index 0000000000..469ef9b3e0 --- /dev/null +++ b/src/platform/cc13xx_26xx/icall_FreeRTOS.c @@ -0,0 +1,3926 @@ +/****************************************************************************** + @file icall_FreeRTOS.c + + @brief Indirect function Call dispatcher implementation on top of OS. + + This implementation uses heapmgr.h to implement a simple heap with low + memory overhead but large processing overhead.
+ The size of the heap is determined with HEAPMGR_SIZE macro, which can + be overridden with a compile option. + Note: The ICall layer (e.g. this file) is using TI internal implementation of POSIX. + For now, the ICall layer is not supports using outer POSIX on the application layer. + + Group: WCS, LPC, BTS + Target Device: cc13xx_cc26xx + + ****************************************************************************** + + Copyright (c) 2013-2024, Texas Instruments Incorporated + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + * Neither the name of Texas Instruments Incorporated nor the names of + its contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, + EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + ****************************************************************************** + + + *****************************************************************************/ + +#ifdef FREERTOS +#include "bget.h" +#include +#include +#endif + +#ifdef FREERTOS +#include +#include +#include +#endif + +#include +#include +#define Hwi_disable HwiP_disable +#define Hwi_restore HwiP_restore +#define Hwi_disableinterrupt HwiP_disableInterrupt +#define Hwi_enableinterrupt HwiP_enableInterrupt +#define Swi_restore SwiP_restore +#define Swi_disable SwiP_disable +#define BIOS_WAIT_FOREVER (~(0U)) +#define BIOS_NO_WAIT (0U) + +#include "icall.h" +#include "icall_platform.h" +#include "osal.h" +#include +#include + +#ifndef ICALL_FEATURE_SEPARATE_IMGINFO +#include +#endif /* ICALL_FEATURE_SEPARATE_IMGINFO */ + +#ifndef Task_self +#define Task_self ICall_taskSelf +#endif + +#ifndef ICALL_MAX_NUM_ENTITIES +/** + * Maximum number of entities that use ICall, including service entities + * and application entities. + * The value may be overridden by a compile option. + * Note that there are at least, + * Primitive service, Stack services along with potentially generic + * framework service for the stack thread. + */ +#define ICALL_MAX_NUM_ENTITIES 6 +#endif + +#ifndef ICALL_MAX_NUM_TASKS +/** + * Maximum number of threads which include entities. + * The value may be overridden by a compile option. + */ +#define ICALL_MAX_NUM_TASKS 2 +#endif + +/** + * @internal + * Service class value used to indicate an invalid (unused) entry + */ +#define ICALL_SERVICE_CLASS_INVALID_ENTRY 0x0000 + +/** + * @internal + * Service class value used to indicate an entry for an application entity + */ +#define ICALL_SERVICE_CLASS_APPLICATION ICALL_SERVICE_CLASS_MASK + +/** + * @internal + * Primitive service entity ID + */ +#define ICALL_PRIMITIVE_ENTITY_ID 0 + +/** + * @internal + * Accessor macro to get a header field (next) from a message pointer + */ +#define ICALL_MSG_NEXT(_p) (((ICall_MsgHdr *) (_p) -1)->next) + +/** + * @internal + * Accessor macro to get a header field (dest_id) from a message pointer + */ +#define ICALL_MSG_DEST_ID(_p) (((ICall_MsgHdr *) (_p) -1)->dest_id) + +#ifndef ICALL_TIMER_TASK_STACK_SIZE +/** + * @internal + * Timer thread stack size + */ +#define ICALL_TIMER_TASK_STACK_SIZE (512) +#endif // ICALL_TIMER_TASK_STACK_SIZE + +/** + * @internal + * Creation of the synchronous object between application and service + */ + +#ifdef ICALL_EVENTS +#define ICALL_SYNC_HANDLE_CREATE() (Event_create(NULL, NULL)) +#else /* ICALL_EVENTS */ +#define ICALL_SYNC_HANDLE_CREATE() (Semaphore_create(0, NULL, NULL)) +#endif /* ICALL_EVENTS */ + +/** + * @internal + * post the synchronous object between application and service + */ +#ifdef ICALL_EVENTS +#define ICALL_SYNC_HANDLE_POST(x) (Event_post(x, ICALL_MSG_EVENT_ID)) +#define ICALL_SYNC_HANDLE_POST_WM(x) (Event_post(x, ICALL_WAITMATCH_EVENT_ID)) +#else /* ICALL_EVENTS */ +#define ICALL_SYNC_HANDLE_POST(x) (Semaphore_post(x)) +#define ICALL_SYNC_HANDLE_POST_WM(x) (Semaphore_post(x)) /* Semaphore does not have event ID */ +#endif /* ICALL_EVENTS */ + +/** + * @internal + * pend for the synchronous object between application and service + */ +#ifdef ICALL_EVENTS +#define ICALL_SYNC_HANDLE_PEND(x, t) (Event_pend(x, 0, ICALL_MSG_EVENT_ID, t)) +#define ICALL_SYNC_HANDLE_PEND_WM(x, t) (Event_pend(x, 0, ICALL_WAITMATCH_EVENT_ID, t)) +#else /* ICALL_EVENTS */ +#define ICALL_SYNC_HANDLE_PEND(x, t) (Semaphore_pend(x, t)) +#define ICALL_SYNC_HANDLE_PEND_WM(x, t) (Semaphore_pend(x, t)) /* Semaphore does not have event ID */ +#endif /* ICALL_EVENTS */ + +/** + * @internal + * ticks + */ +#define CLOCK_TICKS_PERIOD (10) + +/** + * @internal + * Data structure used to access critical section + * state variable. + * Without this data structure, C code will violate + * C89 or C99 strict aliasing rule. + */ +typedef union _icall_cs_state_union_t +{ + /** critical section variable as declared in the interface */ + ICall_CSState state; + /** @internal field used to access internal data */ + struct _icall_cs_state_aggr_t + { + /** field to store Swi_disable() return value */ + uint_least16_t swikey; + /** field to store Hwi_disable() return value */ + uint_least16_t hwikey; + } each; +} ICall_CSStateUnion; + +/** + * @internal Primitive service handler function type + */ +typedef ICall_Errno (*ICall_PrimSvcFunc)(ICall_FuncArgsHdr *); + +#ifdef ICALL_FEATURE_SEPARATE_IMGINFO +/* Image information shall be in separate module */ + +/** + * Array of entry function addresses of external images. + * + * Note that function address must be odd number for Thumb mode functions. + */ +extern const ICall_RemoteTaskEntry ICall_imgEntries[]; +/** + * Array of task priorities of external images. + * One task is created per image to start off the image entry function. + * Each element of this array correspond to the task priority of + * each entry function defined in @ref ICall_imgEntries. + */ +extern const int ICall_imgTaskPriorities[]; + +/** + * Array of task stack sizes of external images. + * One task is created per image to start off the image entry function. + * Each element of this array correspond to the task stack size of + * each entry function defined in @ref ICall_imgEntries. + */ +extern const size_t ICall_imgTaskStackSizes[]; + +/** + * Array of custom initialization parameters (pointers). + * Each initialization parameter (pointer) is passed to each corresponding + * image entry function defined in @ref ICall_imgEntries; + */ +extern const void * ICall_imgInitParams[]; + +/** + * Number of external images. + */ +extern const uint_least8_t ICall_numImages; + +#define icall_threadEntries ICall_imgEntries +#define ICall_threadPriorities ICall_imgTaskPriorities +#define ICall_threadStackSizes ICall_imgTaskStackSizes +#define ICall_getInitParams(_i) (ICall_imgInitParams[i]) +#define ICALL_REMOTE_THREAD_COUNT ICall_numImages +#else /* ICALL_FEATURE_SEPARATE_IMGINFO */ +/** + * @internal + * Array of entry function of external images. + */ +static const ICall_RemoteTaskEntry icall_threadEntries[] = ICALL_ADDR_MAPS; + +/** @internal external image count */ +#define ICALL_REMOTE_THREAD_COUNT (sizeof(icall_threadEntries) / sizeof(icall_threadEntries[0])) + +/** @internal thread priorities to be assigned to each remote thread */ +#ifndef BLE_STACK_TASK_PRIORITY +static const int ICall_threadPriorities[] = { ICALL_TASK_PRIORITIES }; +#else +static const int ICall_threadPriorities[] = { BLE_STACK_TASK_PRIORITY }; +#endif + +/** @internal thread stack max depth for each remote thread */ +static const size_t ICall_threadStackSizes[] = ICALL_TASK_STACK_SIZES; + +/** @internal initialization parameter (pointer) for each remote thread */ +#ifdef ICALL_CUSTOM_INIT_PARAMS +static const void * ICall_initParams[] = ICALL_CUSTOM_INIT_PARAMS; +#define ICall_getInitParams(_i) (ICall_initParams[i]) +#else /* ICALL_CUSTOM_INIT_PARAMS */ +#define ICall_getInitParams(_i) NULL +#endif /* ICALL_CUSTOM_INIT_PARAMS */ + +#endif /* ICALL_FEATURE_SEPARATE_IMGINFO */ + +/** @internal message queue */ +typedef void * ICall_MsgQueue; + +/** @internal data structure about a task using ICall module */ +typedef struct _icall_task_entry_t +{ + TaskHandle_t task; + ICall_SyncHandle syncHandle; + ICall_MsgQueue queue; +} ICall_TaskEntry; + +/** @internal data structure about an entity using ICall module */ +typedef struct _icall_entity_entry_t +{ + ICall_ServiceEnum service; + ICall_TaskEntry * task; + ICall_ServiceFunc fn; +} ICall_entityEntry; + +/** @internal storage to track all tasks using ICall module */ +static ICall_TaskEntry ICall_tasks[ICALL_MAX_NUM_TASKS]; + +/** @internal storage to track all entities using ICall module */ +static ICall_entityEntry ICall_entities[ICALL_MAX_NUM_ENTITIES]; + +#ifndef FREERTOS +extern mqd_t g_EventsQueueID; +#endif +/** + * @internal + * Wakeup schedule data structure definition + */ + +#ifdef FREERTOS +void ICALL_Task_restore(UBaseType_t * OriginalParam); +void ICALL_Task_disable(UBaseType_t * OriginalParam); +#else + +void ICALL_Task_restore(struct sched_param * OriginalParam); +void ICALL_Task_disable(struct sched_param * OriginalParam); +#endif +typedef struct _icall_schedule_t +{ + ClockP_Handle clockP; + ICall_TimerCback cback; + void * arg; +} ICall_ScheduleEntry; + +/* For now critical sections completely disable hardware interrupts + * because they are used from ISRs in MAC layer implementation. + * If MAC layer implementation changes, critical section + * implementation may change to reduce overall interrupt latency. + */ +/* Enter critical section implementation. See header file for comment. */ +ICall_CSState ICall_enterCSImpl(void) +{ + + ICall_CSStateUnion cu; + cu.each.swikey = (uint_least16_t) Swi_disable(); + cu.each.hwikey = (uint_least16_t) Hwi_disable(); + return cu.state; +} +#ifdef FREERTOS +TaskHandle_t ICall_taskSelf(void) +#else +Task_Handle ICall_taskSelf(void) +#endif +{ + + TaskHandle_t task = NULL; +#ifdef FREERTOS + task = (TaskHandle_t) xTaskGetCurrentTaskHandle(); +#else + task = ; +#endif // FREERTOS + return (task); +} + +/* See header file for comment */ +ICall_EnterCS ICall_enterCriticalSection = ICall_enterCSImpl; + +/* leave critical section implementation. See header file for comment */ +void ICall_leaveCSImpl(ICall_CSState key) +{ + ICall_CSStateUnion * cu = (ICall_CSStateUnion *) &key; + Hwi_restore((uint32_t) cu->each.hwikey); + Swi_restore((uint32_t) cu->each.swikey); +} + +/* See header file for comment */ +ICall_LeaveCS ICall_leaveCriticalSection = ICall_leaveCSImpl; + +/* Implementing a simple heap using heapmgr.h template. + * This simple heap depends on critical section implementation + * and hence the template is used after critical section definition. */ +void * ICall_heapMalloc(uint32_t size); +void * ICall_heapRealloc(void * blk, uint32_t size); +void ICall_heapFree(void * blk); + +#define HEAPMGR_INIT ICall_heapInit +#define HEAPMGR_MALLOC ICall_heapMalloc +#define HEAPMGR_FREE ICall_heapFree +#define HEAPMGR_REALLOC ICall_heapRealloc +#define HEAPMGR_GETSTATS ICall_heapGetStats +#define HEAPMGR_MALLOC_LIMITED ICall_heapMallocLimited + +void ICall_heapMgrGetMetrics(uint32_t * pBlkMax, uint32_t * pBlkCnt, uint32_t * pBlkFree, uint32_t * pMemAlo, uint32_t * pMemMax, + uint32_t * pMemUB); +#ifdef HEAPMGR_METRICS +#define HEAPMGR_GETMETRICS ICall_heapMgrGetMetrics +#endif + +#define HEAPMGR_LOCK() \ + do \ + { \ + ICall_heapCSState = ICall_enterCSImpl(); \ + } while (0) +#define HEAPMGR_UNLOCK() \ + do \ + { \ + ICall_leaveCSImpl(ICall_heapCSState); \ + } while (0) +#define HEAPMGR_IMPL_INIT() +/* Note that a static variable can be used to contain critical section + * state since heapmgr.h template ensures that there is no nested + * lock call. */ + +#if defined(HEAPMGR_CONFIG) && ((HEAPMGR_CONFIG == 0) || (HEAPMGR_CONFIG == 0x80)) +#include +#elif defined(HEAPMGR_CONFIG) && ((HEAPMGR_CONFIG == 1) || (HEAPMGR_CONFIG == 0x81)) +#include +#elif defined(HEAPMGR_CONFIG) && ((HEAPMGR_CONFIG == 2) || (HEAPMGR_CONFIG == 0x82)) +#include +#elif defined(FREERTOS) +#include "TI_heap_wrapper.h" +#else +static ICall_CSState ICall_heapCSState; +#include +#endif + +/** + * @internal Searches for a task entry within @ref ICall_tasks. + * @param taskhandle OS task handle + * @return Pointer to task entry when found, or NULL. + */ +static ICall_TaskEntry * ICall_searchTask(TaskHandle_t taskhandle) +{ + size_t i; + ICall_CSState key; + + key = ICall_enterCSImpl(); + for (i = 0; i < ICALL_MAX_NUM_TASKS; i++) + { + if (!ICall_tasks[i].task) + { + /* Empty slot */ + break; + } + if ((TaskHandle_t) taskhandle == (TaskHandle_t) ICall_tasks[i].task) + { + ICall_leaveCSImpl(key); + return &ICall_tasks[i]; + } + } + ICall_leaveCSImpl(key); + return NULL; +} + +/** + * @internal Searches for a task entry within @ref ICall_tasks or + * build an entry if the entry table is empty. + * @param taskhandle OS task handle + * @return Pointer to task entry when found, or NULL. + */ + +static ICall_TaskEntry * ICall_newTask(TaskHandle_t taskhandle) +{ + size_t i; + ICall_CSState key; + + key = ICall_enterCSImpl(); + for (i = 0; i < ICALL_MAX_NUM_TASKS; i++) + { + if (!ICall_tasks[i].task) + { + /* Empty slot */ + ICall_TaskEntry * taskentry = &ICall_tasks[i]; + taskentry->task = taskhandle; + taskentry->queue = NULL; + +#ifdef FREERTOS + taskentry->syncHandle = xQueueCreate(20, sizeof(uint32_t)); +#endif + + if (taskentry->syncHandle == 0) + { + /* abort */ + ICALL_HOOK_ABORT_FUNC(); + } + + ICall_leaveCSImpl(key); + return taskentry; + } + if (taskhandle == (TaskHandle_t) ICall_tasks[i].task) + { + ICall_leaveCSImpl(key); + return &ICall_tasks[i]; + } + } + ICall_leaveCSImpl(key); + return NULL; +} + +/* See header file for comments. */ +ICall_EntityID ICall_searchServiceEntity(ICall_ServiceEnum service) +{ + size_t i; + ICall_CSState key; + + key = ICall_enterCSImpl(); + for (i = 0; i < ICALL_MAX_NUM_ENTITIES; i++) + { + if (ICall_entities[i].service == ICALL_SERVICE_CLASS_INVALID_ENTRY) + { + /* Empty slot */ + break; + } + if (service == ICall_entities[i].service) + { + ICall_leaveCSImpl(key); + return (ICall_EntityID) i; + } + } + ICall_leaveCSImpl(key); + return ICALL_INVALID_ENTITY_ID; +} + +/** + * @internal Searches for a service entity entry. + * @param service service id + * @return Pointer to entity entry of the service or + * NULL when none found. + */ +static ICall_entityEntry * ICall_searchService(ICall_ServiceEnum service) +{ + ICall_EntityID entity = ICall_searchServiceEntity(service); + if (entity == ICALL_INVALID_ENTITY_ID) + { + return NULL; + } + return &ICall_entities[entity]; +} + +/* Dispatcher implementation. See ICall_dispatcher declaration + * for comment. */ +static ICall_Errno ICall_dispatch(ICall_FuncArgsHdr * args) +{ + ICall_entityEntry * entity; + + entity = ICall_searchService(args->service); + if (!entity) + { + return ICALL_ERRNO_INVALID_SERVICE; + } + if (!entity->fn) + { + return ICALL_ERRNO_INVALID_FUNCTION; + } + + return entity->fn(args); +} + +/* See header file for comments */ +ICall_Dispatcher ICall_dispatcher = ICall_dispatch; + +/* Static instance of ICall_RemoteTaskArg to pass to + * remote task entry function. + * See header file for comments */ +static const ICall_RemoteTaskArg ICall_taskEntryFuncs = { ICall_dispatch, ICall_enterCSImpl, ICall_leaveCSImpl }; + +/** + * @internal Thread entry function wrapper that complies with + * OS. + * @param arg0 actual entry function + * @param arg1 ignored + */ +TaskHandle_t RemoteTask = NULL; + +// pthread_t RemoteTask; + +struct argsForPosixTaskStart +{ + void * arg0; + void * arg1; +}; +struct argsForPosixTaskStart POSIX_args; + +typedef void (*TaskFunction_t)(void *); + +static void ICall_taskEntry(void * arg) + +{ + void * arg0 = ((struct argsForPosixTaskStart *) (arg))->arg0; + void * arg1 = ((struct argsForPosixTaskStart *) (arg))->arg1; + + ICall_CSState key; + key = ICall_enterCSImpl(); + if (ICall_newTask(ICall_taskSelf()) == NULL) + { + /* abort */ + ICALL_HOOK_ABORT_FUNC(); + } + ICall_leaveCSImpl(key); + + /* Attempt to yield prior to running task */ + taskYIELD(); + + ICall_RemoteTaskEntry entryfn = (ICall_RemoteTaskEntry) arg0; + + entryfn(&ICall_taskEntryFuncs, (void *) arg1); + + // return NULL; +} + +#ifndef ICALL_JT +/* forward reference */ +static void ICall_initPrim(void); +#endif /* ICALL_JT */ + +/* See header file for comments. */ +void ICall_init(void) +{ + size_t i; + + for (i = 0; i < ICALL_MAX_NUM_TASKS; i++) + { + ICall_tasks[i].task = NULL; + ICall_tasks[i].queue = NULL; + } + for (i = 0; i < ICALL_MAX_NUM_ENTITIES; i++) + { + ICall_entities[i].service = ICALL_SERVICE_CLASS_INVALID_ENTRY; + } + +#ifndef ICALL_JT + /* Initialize primitive service */ + ICall_initPrim(); +#else + /* Initialize heap */ +#ifndef FREERTOS + ICall_heapInit(); +#endif // FREERTOS +#endif +} + +/* See header file for comments */ +void ICall_createRemoteTasksAtRuntime(ICall_RemoteTask_t * remoteTaskTable, uint8_t nbElems) +{ + size_t i; + /* ICALL_Task_disable is a cheap locking mechanism to lock tasks + * which may attempt to access the service call dispatcher + * till all services are registered. + */ + UBaseType_t OriginalParam; + ICALL_Task_disable(&OriginalParam); + for (i = 0; i < nbElems; i++) + { +#ifdef FREERTOS + BaseType_t xReturned; + + /* Pass the args via external sturct (POSIX use only single arg) */ + POSIX_args.arg0 = (void *) remoteTaskTable[i].startupEntry; + POSIX_args.arg1 = (void *) remoteTaskTable[i].ICall_imgInitParam; + + xReturned = xTaskCreate(ICall_taskEntry, /* Function that implements the task. */ + "x", /* Text name for the task. */ + remoteTaskTable[i].imgTaskStackSize / sizeof(uint32_t), /* Stack size in words, not bytes. */ + (void *) &POSIX_args, /* Parameter passed into the task. */ + remoteTaskTable[i].imgTaskPriority, /* Priority at which the task is created. */ + &RemoteTask); /* Used to pass out the created task's handle. */ + + if (xReturned == errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY) + { + /* Creation of FreeRTOS task failed */ + while (1) + ; + } + } + ICALL_Task_restore(&OriginalParam); +#endif +} + +/* See header file for comments */ +void ICall_createRemoteTasks(void) +{ + size_t i; + ICall_RemoteTask_t remoteTaskTable[ICALL_REMOTE_THREAD_COUNT]; + + for (i = 0; i < ICALL_REMOTE_THREAD_COUNT; i++) + { + remoteTaskTable[i].imgTaskPriority = ICall_threadPriorities[i]; + remoteTaskTable[i].imgTaskStackSize = ICall_threadStackSizes[i]; + remoteTaskTable[i].startupEntry = icall_threadEntries[i]; + remoteTaskTable[i].ICall_imgInitParam = (void *) ICall_getInitParams(i); + } + ICall_createRemoteTasksAtRuntime(remoteTaskTable, ICALL_REMOTE_THREAD_COUNT); +} + +#ifdef FREERTOS +void ICALL_Task_disable(UBaseType_t * OriginalParam) + +#else + void ICALL_Task_disable(struct sched_param * OriginalParam) +#endif +{ + +#ifdef FREERTOS + TaskStatus_t pxTaskStatus; + vTaskGetInfo(ICall_taskSelf(), &pxTaskStatus, pdFALSE, eInvalid); + *OriginalParam = pxTaskStatus.uxCurrentPriority; + + vTaskPrioritySet(ICall_taskSelf(), configMAX_PRIORITIES - 1); +#endif +} +#ifdef FREERTOS +void ICALL_Task_restore(UBaseType_t * OriginalParam) +#else + void ICALL_Task_restore(struct sched_param * OriginalParam) +#endif +{ + +#ifdef FREERTOS + vTaskPrioritySet(ICall_taskSelf(), *OriginalParam); + +#else + pthread_t pthreadID = pthread_self(); + pthread_setschedparam(pthreadID, 0, OriginalParam); +#endif +} + +/* See header file for comments */ +ICall_TaskHandle ICall_getRemoteTaskHandle(uint8 index) +{ + TaskHandle_t * task = NULL; + + UBaseType_t OriginalParam; + ICALL_Task_disable(&OriginalParam); + + if (index < ICALL_MAX_NUM_TASKS) + { + task = &ICall_tasks[index].task; + } + + ICALL_Task_restore(&OriginalParam); + + return ((ICall_TaskHandle) task); +} + +/* Primitive service implementation follows */ + +#ifndef ICALL_JT +/** + * @internal Enrolls a service + * @param args arguments + * @return @ref ICALL_ERRNO_SUCCESS when successful.
+ * @ref ICALL_ERRNO_INVALID_PARAMETER when service id is already + * registered by another entity.
+ * @ref ICALL_ERRNO_NO_RESOURCE when maximum number of services + * are already registered. + */ +static ICall_Errno ICall_primEnroll(ICall_EnrollServiceArgs * args) +{ + size_t i; + ICall_TaskEntry * taskentry = ICall_newTask(Task_self()); + ICall_CSState key; + + /* Note that certain service does not handle a message + * and hence, taskentry might be NULL. + */ + if (taskentry == NULL) + { + return ICALL_ERRNO_INVALID_PARAMETER; + } + + key = ICall_enterCSImpl(); + for (i = 0; i < ICALL_MAX_NUM_ENTITIES; i++) + { + if (ICall_entities[i].service == ICALL_SERVICE_CLASS_INVALID_ENTRY) + { + /* Use this entry */ + ICall_entities[i].service = args->service; + ICall_entities[i].task = taskentry; + ICall_entities[i].fn = args->fn; + args->entity = (ICall_EntityID) i; + args->msgSyncHdl = taskentry->syncHandle; + ICall_leaveCSImpl(key); + return ICALL_ERRNO_SUCCESS; + } + else if (args->service == ICall_entities[i].service) + { + /* Duplicate service enrollment */ + ICall_leaveCSImpl(key); + return ICALL_ERRNO_INVALID_PARAMETER; + } + } + /* abort */ + ICALL_HOOK_ABORT_FUNC(); + ICall_leaveCSImpl(key); + return ICALL_ERRNO_NO_RESOURCE; +} + +/** + * @internal Registers an application + * @param args arguments + * @return @ref ICALL_ERRNO_SUCCESS when successful.
+ * @ref ICALL_ERRNO_NO_RESOURCE when ran out of resource. + */ +static ICall_Errno ICall_primRegisterApp(ICall_RegisterAppArgs * args) +{ + size_t i; + ICall_TaskEntry * taskentry = ICall_newTask(Task_self()); + ICall_CSState key; + + if (!taskentry) + { + /* abort */ + ICALL_HOOK_ABORT_FUNC(); + return ICALL_ERRNO_NO_RESOURCE; + } + + key = ICall_enterCSImpl(); + for (i = 0; i < ICALL_MAX_NUM_ENTITIES; i++) + { + if (ICall_entities[i].service == ICALL_SERVICE_CLASS_INVALID_ENTRY) + { + /* Use this entry */ + ICall_entities[i].service = ICALL_SERVICE_CLASS_APPLICATION; + ICall_entities[i].task = taskentry; + ICall_entities[i].fn = NULL; + args->entity = (ICall_EntityID) i; + args->msgSyncHdl = taskentry->syncHandle; + ICall_leaveCSImpl(key); + return ICALL_ERRNO_SUCCESS; + } + } + /* abort */ + ICALL_HOOK_ABORT_FUNC(); + ICall_leaveCSImpl(key); + return ICALL_ERRNO_NO_RESOURCE; +} + +/** + * @internal Allocates memory block for a message. + * @param args arguments + */ +static ICall_Errno ICall_primAllocMsg(ICall_AllocArgs * args) +{ + ICall_MsgHdr * hdr = (ICall_MsgHdr *) ICall_heapMalloc(sizeof(ICall_MsgHdr) + args->size); + + if (!hdr) + { + return ICALL_ERRNO_NO_RESOURCE; + } + hdr->len = args->size; + hdr->next = NULL; + hdr->dest_id = ICALL_UNDEF_DEST_ID; + args->ptr = (void *) (hdr + 1); + return ICALL_ERRNO_SUCCESS; +} + +/** + * @internal Frees the memory block allocated for a message. + * @param args arguments + * @return @ref ICALL_ERRNO_SUCCESS + */ +static ICall_Errno ICall_primFreeMsg(ICall_FreeArgs * args) +{ + ICall_MsgHdr * hdr = (ICall_MsgHdr *) args->ptr - 1; + ICall_heapFree(hdr); + return ICALL_ERRNO_SUCCESS; +} + +/** + * Allocates a memory block. + * Note that this function is for use by ICall implementation. + * + * @param size size in bytes + * @return pointer to the allocated memory block or NULL + */ +void * ICall_mallocImpl(uint_fast16_t size) +{ + return ICall_heapMalloc(size); +} + +/** + * Frees a memory block. + * Note that this function is for use by ICall implementation. + * + * @param ptr pointer to the memory block + */ +void ICall_freeImpl(void * ptr) +{ + ICall_heapFree(ptr); +} + +/** + * @internal Allocates a memory block + * @param args arguments + * @return @ref ICALL_ERRNO_SUCCESS when successful.
+ * @ref ICALL_ERRNO_NO_RESOURCE when memory block cannot + * be allocated. + */ +static ICall_Errno ICall_primMalloc(ICall_AllocArgs * args) +{ + args->ptr = ICall_heapMalloc(args->size); + if (args->ptr == NULL) + { + return ICALL_ERRNO_NO_RESOURCE; + } + return ICALL_ERRNO_SUCCESS; +} + +/** + * @internal Frees a memory block + * @param args arguments + * @return @ref ICALL_ERRNO_SUCCESS + */ +static ICall_Errno ICall_primFree(ICall_FreeArgs * args) +{ + ICall_heapFree(args->ptr); + return ICALL_ERRNO_SUCCESS; +} +#endif /* ICALL_JT */ + +/** + * @internal Queues a message to a message queue. + * @param q_ptr message queue + * @param msg_ptr message pointer + */ +static void ICall_msgEnqueue(ICall_MsgQueue * q_ptr, void * msg_ptr) +{ + void * list; + ICall_CSState key; + + // Hold off interrupts + key = ICall_enterCSImpl(); + + ICALL_MSG_NEXT(msg_ptr) = NULL; + // If first message in queue + if (*q_ptr == NULL) + { + *q_ptr = msg_ptr; + } + else + { + // Find end of queue + for (list = *q_ptr; ICALL_MSG_NEXT(list) != NULL; list = ICALL_MSG_NEXT(list)) + ; + + // Add message to end of queue + ICALL_MSG_NEXT(list) = msg_ptr; + } + + // Re-enable interrupts + ICall_leaveCSImpl(key); +} + +/** + * @internal Dequeues a message from a message queue + * @param q_ptr message queue pointer + * @return Dequeued message pointer or NULL if none. + */ +static void * ICall_msgDequeue(ICall_MsgQueue * q_ptr) +{ + void * msg_ptr = NULL; + ICall_CSState key; + + // Hold off interrupts + key = ICall_enterCSImpl(); + + if (*q_ptr != NULL) + { + // Dequeue message + msg_ptr = *q_ptr; + *q_ptr = ICALL_MSG_NEXT(msg_ptr); + ICALL_MSG_NEXT(msg_ptr) = NULL; + ICALL_MSG_DEST_ID(msg_ptr) = ICALL_UNDEF_DEST_ID; + } + + // Re-enable interrupts + ICall_leaveCSImpl(key); + + return msg_ptr; +} + +/** + * @internal Prepends a list of messages to a message queue + * @param q_ptr message queue pointer + * @param head message list to prepend + */ +static void ICall_msgPrepend(ICall_MsgQueue * q_ptr, ICall_MsgQueue head) +{ + void * msg_ptr = NULL; + ICall_CSState key; + + // Hold off interrupts + key = ICall_enterCSImpl(); + + if (head != NULL) + { + /* Find the end of the queue */ + msg_ptr = head; + while (ICALL_MSG_NEXT(msg_ptr) != NULL) + { + msg_ptr = ICALL_MSG_NEXT(msg_ptr); + } + ICALL_MSG_NEXT(msg_ptr) = *q_ptr; + *q_ptr = head; + } + + // Re-enable interrupts + ICall_leaveCSImpl(key); +} + +#ifndef ICALL_JT +/** + * @internal Sends a message to an entity. + * @param args arguments + * @return @ref ICALL_ERRNO_SUCCESS when successful.
+ * @ref ICALL_ERRNO_INVALID_PARAMETER when either src + * or dest is not a valid entity id or when + * dest is an entity id of an entity that does + * not receive a message + * (e.g., ICall primitive service entity). + */ +static ICall_Errno ICall_primSend(ICall_SendArgs * args) +{ + ICall_CSState key; + ICall_MsgHdr * hdr = (ICall_MsgHdr *) args->msg - 1; + + if (args->dest.entityId >= ICALL_MAX_NUM_ENTITIES || args->src >= ICALL_MAX_NUM_ENTITIES) + { + return ICALL_ERRNO_INVALID_PARAMETER; + } + key = ICall_enterCSImpl(); + if (!ICall_entities[args->dest.entityId].task) + { + ICall_leaveCSImpl(key); + return ICALL_ERRNO_INVALID_PARAMETER; + } + + ICall_leaveCSImpl(key); + /* Note that once the entry is valid, + * the value does not change and hence it is OK + * to leave the critical section. + */ + + hdr->srcentity = args->src; + hdr->dstentity = args->dest.entityId; + hdr->format = args->format; + ICall_msgEnqueue(&ICall_entities[args->dest.entityId].task->queue, args->msg); + ICALL_SYNC_HANDLE_POST(ICall_entities[args->dest.entityId].task->syncHandle); + + return ICALL_ERRNO_SUCCESS; +} + +/** + * @internal Retrieves a message, queued to receive queue of the calling thread. + * + * @param args arguments + * @return @ref ICALL_ERRNO_SUCCESS when a message was successfully + * retrieved.
+ * @ref ICALL_ERRNO_NOMSG when no message was queued to + * the receive queue at the moment.
+ * @ref ICALL_ERRNO_UNKNOWN_THREAD when the calling thread + * does not have a received queue associated with it. + * This happens when neither ICall_enrollService() nor + * ICall_registerApp() was ever called from the calling + * thread. + */ +static ICall_Errno ICall_primFetchMsg(ICall_FetchMsgArgs * args) +{ + Task_Handle taskhandle = Task_self(); + ICall_TaskEntry * taskentry = ICall_searchTask(taskhandle); + ICall_MsgHdr * hdr; + + if (!taskentry) + { + return ICALL_ERRNO_UNKNOWN_THREAD; + } + /* Successful */ + args->msg = ICall_msgDequeue(&taskentry->queue); + + if (args->msg == NULL) + { + return ICALL_ERRNO_NOMSG; + } + hdr = (ICall_MsgHdr *) args->msg - 1; + args->src.entityId = hdr->srcentity; + args->dest = hdr->dstentity; + return ICALL_ERRNO_SUCCESS; +} +#endif /* ICALL_JT */ + +/** + * @internal + * Transforms and entityId into a serviceId. + * @param entityId entity id + * @param servId pointer to a variable to store + * the resultant service id + * @return @ICALL_ERRNO_SUCCESS if the transformation was successful. + * @ICALL_ERRNO_INVALID_SERVICE if no matching service + * is found for the entity id. + */ +static ICall_Errno ICall_primEntityId2ServiceId(ICall_EntityID entityId, ICall_ServiceEnum * servId) +{ + if (entityId >= ICALL_MAX_NUM_ENTITIES || ICall_entities[entityId].service == ICALL_SERVICE_CLASS_INVALID_ENTRY || + ICall_entities[entityId].service == ICALL_SERVICE_CLASS_APPLICATION) + { + return ICALL_ERRNO_INVALID_SERVICE; + } + *servId = ICall_entities[entityId].service; + return ICALL_ERRNO_SUCCESS; +} + +#ifndef ICALL_JT +/** + * @internal Transforms and entityId into a serviceId. + * @param args arguments + * @return return values corresponding to those of ICall_entityId2ServiceId() + */ +static ICall_Errno ICall_primE2S(ICall_EntityId2ServiceIdArgs * args) +{ + return ICall_primEntityId2ServiceId(args->entityId, &args->servId); +} + +/** + * @internal Sends a message to a registered server. + * @param args arguments corresponding to those of ICall_sendServiceMsg(). + * @return @ref ICALL_ERRNO_SUCCESS when successful.
+ * @ref ICALL_ERRNO_INVALID_SERVICE when the 'dest' + * is unregistered service.
+ * @ref ICALL_ERRNO_INVALID_PARAMETER when the 'src' + * is not a valid entity id or when 'dest' is + * is a service that does not receive a message + * (such as ICall primitive service). + */ +static ICall_Errno ICall_primSendServiceMsg(ICall_SendArgs * args) +{ + ICall_EntityID dstentity = ICall_searchServiceEntity(args->dest.servId); + + if (dstentity == ICALL_INVALID_ENTITY_ID) + { + return ICALL_ERRNO_INVALID_SERVICE; + } + args->dest.entityId = dstentity; + return ICall_primSend(args); +} + +/** + * @internal Retrieves a message received at the message queue + * associated with the calling thread. + * + * Note that this function should be used by an application + * which does not expect any message from non-server entity. + * + * @param args arguments corresponding to those of ICall_fetchServiceMsg() + * @return @ref ICALL_ERRNO_SUCCESS when the operation was successful + * and a message was retrieved.
+ * @ref ICALL_ERRNO_NOMSG when there is no queued message + * at the moment.
+ * @ref ICALL_ERRNO_CORRUPT_MSG when a message queued in + * front of the thread's receive queue was not sent by + * a server. Note that in this case, the message is + * not retrieved but thrown away.
+ * @ref ICALL_ERRNO_UNKNOWN_THREAD when this function is + * called from a thread which has not registered + * an entity, either through ICall_enrollService() + * or through ICall_registerApp(). + */ +static ICall_Errno ICall_primFetchServiceMsg(ICall_FetchMsgArgs * args) +{ + ICall_ServiceEnum servId; + ICall_Errno errno = ICall_primFetchMsg(args); + if (errno == ICALL_ERRNO_SUCCESS) + { + if (ICall_primEntityId2ServiceId(args->src.entityId, &servId) != ICALL_ERRNO_SUCCESS) + { + /* Source entity ID cannot be translated to service id */ + ICall_freeMsg(args->msg); + return ICALL_ERRNO_CORRUPT_MSG; + } + args->src.servId = servId; + +#ifdef ICALL_EVENTS + /* + * Because Events are binary flags, the task's queue must be checked for + * any remaining messages. If there are the ICall event flag must be + * re-posted due to it being cleared on the last pend. + */ + ICall_primRepostSync(); +#endif // ICALL_EVENTS + } + return errno; +} +#endif /* ICALL_JT */ +/** + * @internal + * Converts milliseconds to number of ticks. + * @param msecs milliseconds + * @param ticks pointer to a variable to store the resultant number of ticks + * @return @ref ICALL_ERRNO_SUCCESS when successful
+ * @ref ICALL_ERRNO_INVALID_PARAMETER when conversion failed + * as the input goes out of range for the output data type. + */ +static ICall_Errno ICall_msecs2Ticks(uint_fast32_t msecs, uint32_t * ticks) +{ + uint_fast64_t intermediate = msecs; + + /*convert to microSec*/ + intermediate *= 1000; + /*divide with the ticks perios*/ + intermediate /= ICall_getTickPeriod(); + if (intermediate >= ((uint_fast64_t) 1 << (sizeof(uint32_t) * 8 - 1))) + { + /* Out of range. + * Note that we use only half of the range so that client can + * determine whether the time has passed or time has yet to come. + */ + return ICALL_ERRNO_INVALID_PARAMETER; + } + *ticks = (uint32_t) intermediate; + return ICALL_ERRNO_SUCCESS; +} + +#ifndef ICALL_JT +/** + * @internal + * Waits for a signal to the synchronization object associated with the calling + * thread. + * + * Note that the synchronization object associated with a thread is signaled + * when a message is queued to the message receive queue of the thread + * or when ICall_signal() function is called onto the synchronization object. + * + * @param args arguments corresponding to those of ICall_wait(). + * @return @ref ICALL_ERRNO_SUCCESS when the synchronization object is + * signaled.
+ * @ref ICALL_ERRNO_TIMEOUT when designated timeout period + * has passed since the call of the function without + * the synchronization object being signaled.
+ * @ref ICALL_ERRNO_INVALID_PARAMETER when the milliseconds + * is greater than the value of ICall_getMaxMSecs(). + */ +static ICall_Errno ICall_primWait(ICall_WaitArgs * args) +{ + Task_Handle taskhandle = Task_self(); + ICall_TaskEntry * taskentry = ICall_searchTask(taskhandle); + uint32_t timeout; + + { + BIOS_ThreadType threadtype = BIOS_getThreadType(); + + if (threadtype == BIOS_ThreadType_Hwi || threadtype == BIOS_ThreadType_Swi) + { + /* Blocking call is not allowed from Hwi or Swi. + * Note that though theoretically, Swi or lower priority Hwi may block + * on an event to be generated by a higher priority Hwi, it is not a + * safe practice and hence it is disabled. + */ + return ICALL_ERRNO_UNKNOWN_THREAD; + } + } + + if (!taskentry) + { + return ICALL_ERRNO_UNKNOWN_THREAD; + } + /* Successful */ + if (args->milliseconds == 0) + { + timeout = BIOS_NO_WAIT; + } + else if (args->milliseconds == ICALL_TIMEOUT_FOREVER) + { + timeout = BIOS_WAIT_FOREVER; + } + else + { + /* Convert milliseconds to number of ticks */ + ICall_Errno errno = ICall_msecs2Ticks(args->milliseconds, &timeout); + if (errno != ICALL_ERRNO_SUCCESS) + { + return errno; + } + } + + if (ICALL_SYNC_HANDLE_PEND(taskentry->syncHandle, timeout)) + { + return ICALL_ERRNO_SUCCESS; + } + + return ICALL_ERRNO_TIMEOUT; +} + +/** + * @internal signals a synchronziation object. + * @param args arguments corresponding to those of ICall_signal() + * @return return value corresponding to those of ICall_signal() + */ +static ICall_Errno ICall_primSignal(ICall_SignalArgs * args) +{ + ICALL_SYNC_HANDLE_POST(args->syncHandle); + return ICALL_ERRNO_SUCCESS; +} + +/** + * @internal aborts program + * @param args arguments corresponding to those of ICall_abort() + * @return return value corresponding to those of ICall_abort() + */ +static ICall_Errno ICall_primAbort(ICall_FuncArgsHdr * args) +{ + ICALL_HOOK_ABORT_FUNC(); + return ICALL_ERRNO_SUCCESS; +} + +/** + * @internal Enables an interrupt. + * @param args arguments corresponding to those of ICall_enableint() + * @return return values corresponding to those of ICall_enableint() + */ +static ICall_Errno ICall_primEnableint(ICall_intNumArgs * args) +{ + Hwi_enableinterrupt(args->intnum); + return ICALL_ERRNO_SUCCESS; +} + +/** + * @internal Disables an interrupt. + * @param args arguments corresponding to those of ICall_disableint() + * @return return values corresponding to those of ICall_disableint() + */ +static ICall_Errno ICall_primDisableint(ICall_intNumArgs * args) +{ + Hwi_disableinterrupt(args->intnum); + return ICALL_ERRNO_SUCCESS; +} + +/** + * @internal Enables master interrupt and context switching. + * @param args arguments corresponding to those of ICall_enableMint() + * @return return values corresponding to those of ICall_enableMint() + */ +static ICall_Errno ICall_primEnableMint(ICall_FuncArgsHdr * args) +{ + Hwi_enable(); + Swi_enable(); + return ICALL_ERRNO_SUCCESS; +} + +/** + * @internal Disables master interrupt and context switching. + * @param args arguments corresponding to those of ICall_disableMint() + * @return return values corresponding to those of ICall_disableMint() + */ +static ICall_Errno ICall_primDisableMint(ICall_FuncArgsHdr * args) +{ + Swi_disable(); + Hwi_disable(); + return ICALL_ERRNO_SUCCESS; +} + +/** + * @internal registers an interrupt service routine + * @param args arguments corresponding to those of ICall_registerISR() + * @return return values corresponding to those of ICall_registerISR() + */ +static ICall_Errno ICall_primRegisterISR(ICall_RegisterISRArgs * args) +{ + Hwi_Params hwiParams; + + Hwi_Params_init(&hwiParams); + hwiParams.priority = 0xE0; // default all registered ints to lowest priority + + if (Hwi_create(args->intnum, (void (*)((void *) )) args->isrfunc, &hwiParams, NULL) == NULL) + { + ICALL_HOOK_ABORT_FUNC(); + return ICALL_ERRNO_NO_RESOURCE; + } + return ICALL_ERRNO_SUCCESS; +} + +/** + * @internal registers an interrupt service routine + * @param args arguments corresponding to those of ICall_registerISR_Ext() + * @return return values corresponding to those of ICall_registerISR_ext() + */ +static ICall_Errno ICall_primRegisterISR_Ext(ICall_RegisterISRArgs_Ext * args) +{ + Hwi_Params hwiParams; + + Hwi_Params_init(&hwiParams); + hwiParams.priority = args->intPriority; + + if (Hwi_create(args->intnum, (void (*)((void *) )) args->isrfunc, &hwiParams, NULL) == NULL) + { + ICALL_HOOK_ABORT_FUNC(); + return ICALL_ERRNO_NO_RESOURCE; + } + return ICALL_ERRNO_SUCCESS; +} + +/** + * @internal Gets tick counter value + * @param args arguments corresponding to those of ICall_getTicks() + * @return return values corresponding to those of ICall_getTicks() + */ +static ICall_Errno ICall_primGetTicks(ICall_Getuint32_tArgs * args) +{ + args->value = Clock_getTicks(); + return ICALL_ERRNO_SUCCESS; +} +#endif /* ICALL_JT */ + +/** + * @internal + * Clock event handler function. + * This function is used to implement the wakeup scheduler. + * + * @param arg an @ref ICall_ScheduleEntry + */ + +static void ICall_clockFunc(uintptr_t arg) +{ + ICall_ScheduleEntry * entry = (ICall_ScheduleEntry *) arg; + + entry->cback(entry->arg); +} + +#ifndef ICALL_JT +/** + * @internal + * Set up or restart a timer. + * + * @param args arguments corresponding to those of ICall_setTimer() + * @return @ref ICALL_ERRNO_SUCCESS when successful;
+ * @ref ICALL_ERRNO_INVALID_PARAMETER if timer designated by the + * timer ID value was not set up before. + * @ref ICALL_ERRNO_NO_RESOURCE when ran out of resource. + * Check ICall heap size and OS heap size if this happens. + */ +static ICall_Errno ICall_primSetTimer(ICall_SetTimerArgs * args) +{ + ICall_ScheduleEntry * entry; + + if (args->timerid == ICALL_INVALID_TIMER_ID) + { + Clock_Params params; + + /* Create a new timer */ + entry = ICall_heapMalloc(sizeof(ICall_ScheduleEntry)); + if (entry == NULL) + { + /* allocation failed */ + return ICALL_ERRNO_NO_RESOURCE; + } + Clock_Params_init(¶ms); + params.startFlag = FALSE; + params.period = 0; + params.arg = ((void *) ) entry; + entry->clock = Clock_create(ICall_clockFunc, args->timeout, ¶ms, NULL); + if (!entry->clock) + { + /* abort */ + ICall_abort(); + ICall_heapFree(entry); + return ICALL_ERRNO_NO_RESOURCE; + } + entry->cback = args->cback; + entry->arg = args->arg; + args->timerid = (ICall_TimerID) entry; + } + else + { + ICall_CSState key; + + entry = (ICall_ScheduleEntry *) args->timerid; + + /* Critical section is entered to disable interrupts that might cause call + * to callback due to race condition */ + key = ICall_enterCriticalSection(); + Clock_stop(entry->clock); + entry->arg = args->arg; + ICall_leaveCriticalSection(key); + } + + Clock_setTimeout(entry->clock, args->timeout); + Clock_start(entry->clock); + + return ICALL_ERRNO_SUCCESS; +} + +/** + * @internal + * Set up or restart a timer. + * + * @param args arguments corresponding to those of ICall_setTimerMSecs() + * @return @ref ICALL_ERRNO_SUCCESS when successful;
+ * @ref ICALL_ERRNO_INVALID_PARAMETER when msecs is greater than + * maximum value supported. + * @ref ICALL_ERRNO_NO_RESOURCE when ran out of resource. + * Check ICall heap size and OS heap size if this happens. + */ +static ICall_Errno ICall_primSetTimerMSecs(ICall_SetTimerArgs * args) +{ + uint32_t ticks; + /* Convert to tick time */ + ICall_Errno errno = ICall_msecs2Ticks(args->timeout, &ticks); + + if (errno != ICALL_ERRNO_SUCCESS) + { + return errno; + } + args->timeout = ticks; + return ICall_primSetTimer(args); +} + +/** + * @internal + * Stops a timer. + * + * @param args arguments corresponding to those of ICall_stopTimer() + * + * @return @ref ICALL_ERRNO_SUCCESS when successful;
+ * @ref ICALL_ERRNO_INVALID_PARAMETER + * if id is @ref ICALL_INVALID_TIMER_ID. + */ +static ICall_Errno ICall_primStopTimer(ICall_StopTimerArgs * args) +{ + ICall_ScheduleEntry * entry = (ICall_ScheduleEntry *) args->timerid; + + if (args->timerid == ICALL_INVALID_TIMER_ID) + { + return ICALL_ERRNO_INVALID_PARAMETER; + } + + Clock_stop(entry->clock); + return ICALL_ERRNO_SUCCESS; +} + +/** + * @internal Gets tick period + * @param args arguments corresponding to those of ICall_getTickPeriod() + * @return return values corresponding to those of ICall_getTickPeriod() + */ +static ICall_Errno ICall_primGetTickPeriod(ICall_Getuint32_tArgs * args) +{ + args->value = Clock_tickPeriod; + return ICALL_ERRNO_SUCCESS; +} + +/** + * @internal Gets maximum period supported + * @param args arguments corresponding to those of ICall_getMaxMSecs() + * @return return values corresponding to those of ICall_getMaxMSecs() + */ +static ICall_Errno ICall_primGetMaxMSecs(ICall_Getuint32_tArgs * args) +{ + uint_fast64_t tmp = ((uint_fast64_t) 0x7ffffffful) * Clock_tickPeriod; + tmp /= 1000; + if (tmp >= 0x80000000ul) + { + tmp = 0x7ffffffful; + } + args->value = (uint_least32_t) tmp; + return ICALL_ERRNO_SUCCESS; +} + +/** + * @internal + * Waits for a message that matches comparison + * + * @param args arguments corresponding to those of ICall_waitMatch(). + * @return @ref ICALL_ERRNO_SUCCESS when the synchronization object is + * signaled.
+ * @ref ICALL_ERRNO_TIMEOUT when designated timeout period + * has passed since the call of the function without + * the semaphore being signaled.
+ * @ref ICALL_ERRNO_INVALID_PARAMETER when the milliseconds + * is greater than the value of ICall_getMaxMSecs(). + */ +static ICall_Errno ICall_primWaitMatch(ICall_WaitMatchArgs * args) +{ + Task_Handle taskhandle = Task_self(); + ICall_TaskEntry * taskentry = ICall_searchTask(taskhandle); + ICall_MsgQueue prependQueue = NULL; +#ifndef ICALL_EVENTS + uint_fast16_t consumedCount = 0; +#endif + uint32_t timeout; + uint_fast32_t timeoutStamp; + ICall_Errno errno; + + { + BIOS_ThreadType threadtype = BIOS_getThreadType(); + + if (threadtype == BIOS_ThreadType_Hwi || threadtype == BIOS_ThreadType_Swi) + { + /* Blocking call is not allowed from Hwi or Swi. + * Note that though theoretically, Swi or lower priority Hwi may block + * on an event to be generated by a higher priority Hwi, it is not a + * safe practice and hence it is disabled. + */ + return ICALL_ERRNO_UNKNOWN_THREAD; + } + } + + if (!taskentry) + { + return ICALL_ERRNO_UNKNOWN_THREAD; + } + /* Successful */ + if (args->milliseconds == 0) + { + timeout = BIOS_NO_WAIT; + } + else if (args->milliseconds == ICALL_TIMEOUT_FOREVER) + { + timeout = BIOS_WAIT_FOREVER; + } + else + { + /* Convert milliseconds to number of ticks */ + errno = ICall_msecs2Ticks(args->milliseconds, &timeout); + if (errno != ICALL_ERRNO_SUCCESS) + { + return errno; + } + } + + errno = ICALL_ERRNO_TIMEOUT; + timeoutStamp = Clock_getTicks() + timeout; + while (ICALL_SYNC_HANDLE_PEND(taskentry->syncHandle, timeout)) + { + ICall_FetchMsgArgs fetchArgs; + ICall_ServiceEnum servId; + errno = ICall_primFetchMsg(&fetchArgs); + if (errno == ICALL_ERRNO_SUCCESS) + { + if (ICall_primEntityId2ServiceId(fetchArgs.src.entityId, &servId) == ICALL_ERRNO_SUCCESS) + { + if (args->matchFn(servId, fetchArgs.dest, fetchArgs.msg)) + { + /* Matching message found*/ + args->servId = servId; + args->dest = fetchArgs.dest; + args->msg = fetchArgs.msg; + errno = ICALL_ERRNO_SUCCESS; + break; + } + } + /* Message was received but it wasn't expected one. + * Add to the prepend queue */ + ICall_msgEnqueue(&prependQueue, fetchArgs.msg); +#ifdef ICALL_EVENTS + /* Event are binary semaphore, so if several messsages are posted while + * we are processing one, it's possible that some of them are 'missed' and + * not processed. Sending a event to ourself force this loop to run until + * all the messages in the queue are processed. + */ + ICALL_SYNC_HANDLE_POST(taskentry->syncHandle); +#endif + } + + /* Prepare for timeout exit */ + errno = ICALL_ERRNO_TIMEOUT; + +#ifndef ICALL_EVENTS + /* Keep the decremented semaphore count */ + consumedCount++; +#endif /* ICALL_EVENTS */ + if (timeout != BIOS_WAIT_FOREVER && timeout != BIOS_NO_WAIT) + { + /* Readjust timeout */ + uint32_t newTimeout = timeoutStamp - Clock_getTicks(); + if (newTimeout == 0 || newTimeout > timeout) + { + break; + } + timeout = newTimeout; + } + } + +#ifdef ICALL_EVENTS + /* + * Because Events are binary semaphores, the task's queue must be checked for + * any remaining messages. If there are, the ICall event flag must be + * re-posted due to it being cleared on the last pend. + */ + ICall_primRepostSync(); +#endif // ICALL_EVENTS + + /* Prepend retrieved irrelevant messages */ + ICall_msgPrepend(&taskentry->queue, prependQueue); +#ifndef ICALL_EVENTS + /* Re-increment the consumed semaphores */ + for (; consumedCount > 0; consumedCount--) + { + Semaphore_post(taskentry->syncHandle); + } +#endif /* ICALL_EVENTS */ + return errno; +} + +/** + * @internal + * Retrieves an entity ID of an entity associated with the calling thread. + * + * @param args arguments corresponding to those of ICall_getEntityId(). + * @return @ref ICALL_ERRNO_SUCCESS when successful.
+ * @ref ICALL_ERRNO_UNKNOWN_THREAD when no entity was associated + * with the calling thread. + */ +static ICall_Errno ICall_primGetEntityId(ICall_GetEntityIdArgs * args) +{ + Task_Handle taskhandle = Task_self(); + ICall_CSState key; + size_t i; + + { + BIOS_ThreadType threadtype = BIOS_getThreadType(); + + if (threadtype == BIOS_ThreadType_Hwi || threadtype == BIOS_ThreadType_Swi) + { + return ICALL_ERRNO_UNKNOWN_THREAD; + } + } + + key = ICall_enterCSImpl(); + for (i = 0; i < ICALL_MAX_NUM_ENTITIES; i++) + { + if (ICall_entities[i].service == ICALL_SERVICE_CLASS_INVALID_ENTRY) + { + /* Not found */ + break; + } + if (ICall_entities[i].task->task == taskhandle) + { + /* Found */ + args->entity = i; + ICall_leaveCSImpl(key); + return ICALL_ERRNO_SUCCESS; + } + } + ICall_leaveCSImpl(key); + return ICALL_ERRNO_UNKNOWN_THREAD; +} + +/** + * @internal + * Checks whether the calling thread provides the designated service. + * + * @param args arguments corresponding to those of ICall_threadServes(). + * @return @ref ICALL_ERRNO_SUCCESS when successful.
+ * @ref ICALL_ERRNO_UNKNOWN_THREAD when the calling thread is + * unrecognized. + * @ref ICALL_ERRNO_INVALID_SERVICE if the service id is not enrolled + * by any thread. + */ +static ICall_Errno ICall_primThreadServes(ICall_ThreadServesArgs * args) +{ + Task_Handle taskhandle; + ICall_CSState key; + size_t i; + + { + BIOS_ThreadType threadtype = BIOS_getThreadType(); + + if (threadtype == BIOS_ThreadType_Hwi || threadtype == BIOS_ThreadType_Swi) + { + return ICALL_ERRNO_UNKNOWN_THREAD; + } + } + + taskhandle = Task_self(); + + key = ICall_enterCSImpl(); + for (i = 0; i < ICALL_MAX_NUM_ENTITIES; i++) + { + if (ICall_entities[i].service == ICALL_SERVICE_CLASS_INVALID_ENTRY) + { + /* Not found */ + break; + } + else if (ICall_entities[i].service == args->servId) + { + args->result = (uint_fast8_t) (ICall_entities[i].task->task == taskhandle); + ICall_leaveCSImpl(key); + return ICALL_ERRNO_SUCCESS; + } + } + ICall_leaveCSImpl(key); + return ICALL_ERRNO_INVALID_SERVICE; +} + +/** + * @internal + * Creates an RTOS task. + * + * @param args arguments corresponding to those of ICall_createTask(). + * @return @ref ICALL_ERRNO_SUCCESS when successful.
+ * @ref ICALL_ERRNO_NO_RESOURCE when task creation failed. + */ +static ICall_Errno ICall_primCreateTask(ICall_CreateTaskArgs * args) +{ + /* Task_Params is a huge structure. + * To reduce stack usage, heap is used instead. + * This implies that ICall_createTask() must be called before heap + * space may be exhausted. + */ + Task_Params * params = (Task_Params *) ICall_heapMalloc(sizeof(Task_Params)); + Task_Handle task; + + if (params == NULL) + { + return ICALL_ERRNO_NO_RESOURCE; + } + + Task_Params_init(params); + params->priority = args->priority; + params->stackSize = args->stacksize; + params->arg0 = args->arg; + + task = Task_create((Task_FuncPtr) args->entryfn, params, NULL); + ICall_heapFree(params); + + if (task == NULL) + { + return ICALL_ERRNO_NO_RESOURCE; + } + return ICALL_ERRNO_SUCCESS; +} +#endif /* ICALL_JT */ + +#ifdef ICALL_RTOS_EVENT_API +/** + * @internal + * Creates an event. + * + * @param args arguments corresponding to those of ICall_createEvent(). + * @return @ref ICALL_ERRNO_SUCCESS when successful.
+ * @ref ICALL_ERRNO_NO_RESOURCE when task creation failed. + */ +static ICall_Errno ICall_primCreateEvent(ICall_CreateEventArgs * args) +{ + args->event = Event_create(NULL, NULL); + + if (args->event == NULL) + { + return ICALL_ERRNO_NO_RESOURCE; + } + return ICALL_ERRNO_SUCCESS; +} +#endif /* ICALL_RTOS_EVENT_API */ +#ifdef ICALL_RTOS_SEMAPHORE_API +/** + * @internal + * Creates a semaphore. + * + * @param args arguments corresponding to those of ICall_createSemaphore(). + * @return @ref ICALL_ERRNO_SUCCESS when successful.
+ * @ref ICALL_ERRNO_NO_RESOURCE when task creation failed. + */ +static ICall_Errno ICall_primCreateSemaphore(ICall_CreateSemaphoreArgs * args) +{ + /* Semaphore_Params is a huge structure. + * To reduce stack usage, heap is used instead. + * This implies that ICall_createSemaphore() must be called before heap + * space may be exhausted. + */ + Semaphore_Params * semParams = (Semaphore_Params *) ICall_heapMalloc(sizeof(Semaphore_Params)); + + if (semParams == NULL) + { + return ICALL_ERRNO_NO_RESOURCE; + } + + Semaphore_Params_init(semParams); + if (args->mode == ICALL_SEMAPHORE_MODE_BINARY) + { + semParams->mode = Semaphore_Mode_BINARY; + } + + args->sem = Semaphore_create(args->initcount, semParams, NULL); + ICall_heapFree(semParams); + + if (args->sem == NULL) + { + return ICALL_ERRNO_NO_RESOURCE; + } + return ICALL_ERRNO_SUCCESS; +} +#endif /* ICALL_RTOS_SEMAPHORE_API */ +#ifdef ICALL_RTOS_EVENT_API +/** + * @internal + * Waits on a ICALL_MSG_EVENT_ID. + * + * @param args arguments corresponding to those of ICall_waitEvent(). + * @return @ref ICALL_ERRNO_SUCCESS when successful.
+ * @ref ICALL_ERRNO_TIMEOUT when timeout occurred. + */ +static ICall_Errno ICall_primWaitEvent(ICall_WaitEventArgs * args) +{ + uint32_t timeout; + + if (args->milliseconds == 0) + { + timeout = BIOS_NO_WAIT; + } + else if (args->milliseconds == ICALL_TIMEOUT_FOREVER) + { + timeout = BIOS_WAIT_FOREVER; + } + else + { + ICall_Errno errno = ICall_msecs2Ticks(args->milliseconds, &timeout); + if (errno != ICALL_ERRNO_SUCCESS) + { + return errno; + } + } + + if (Event_pend(args->event, 0, ICALL_MSG_EVENT_ID, timeout)) + { + return ICALL_ERRNO_SUCCESS; + } + return ICALL_ERRNO_TIMEOUT; +} +#endif /* ICALL_RTOS_EVENT_API */ + +#ifdef ICALL_RTOS_SEMAPHORE_API +/** + * @internal + * Waits on a semaphore. + * + * @param args arguments corresponding to those of ICall_waitSemaphore(). + * @return @ref ICALL_ERRNO_SUCCESS when successful.
+ * @ref ICALL_ERRNO_TIMEOUT when timeout occurred. + */ +static ICall_Errno ICall_primWaitSemaphore(ICall_WaitSemaphoreArgs * args) +{ + uint32_t timeout; + + if (args->milliseconds == 0) + { + timeout = BIOS_NO_WAIT; + } + else if (args->milliseconds == ICALL_TIMEOUT_FOREVER) + { + timeout = BIOS_WAIT_FOREVER; + } + else + { + ICall_Errno errno = ICall_msecs2Ticks(args->milliseconds, &timeout); + if (errno != ICALL_ERRNO_SUCCESS) + { + return errno; + } + } + if (Semaphore_pend(args->sem, timeout)) + { + return ICALL_ERRNO_SUCCESS; + } + return ICALL_ERRNO_TIMEOUT; +} +#endif /* ICALL_RTOS_SEMAPHORE_API */ + +#ifdef ICALL_RTOS_SEMAPHORE_API +/** + * @internal signals a semaphore + * @param args arguments corresponding to those of ICall_signal() + * @return return value corresponding to those of ICall_signal() + */ +static ICall_Errno ICall_primPostSemaphore(ICall_SignalArgs * args) +{ + Semaphore_post(args->syncHandle); + return ICALL_ERRNO_SUCCESS; +} +#endif /* ICALL_RTOS_EVENT_API */ +#ifdef ICALL_RTOS_EVENT_API +/** + * @internal signals an event + * @param args arguments corresponding to those of ICall_signal() + * @return return value corresponding to those of ICall_signal() + */ +static ICall_Errno ICall_primPostEvent(ICall_SignalEventsArgs * args) +{ + Event_post(args->syncHandle, args->events); + return ICALL_ERRNO_SUCCESS; +} +#endif /* ICALL_RTOS_EVENT_API */ +/** + * @internal Primitive service function ID to handler function map + */ +#ifndef ICALL_JT +static const struct _icall_primsvcfunc_map_entry_t +{ +#ifdef COVERAGE_TEST + size_t id; +#endif /* COVERAGE_TEST */ + ICall_PrimSvcFunc func; +} ICall_primSvcFuncs[] = { + { +#ifdef COVERAGE_TEST + ICALL_PRIMITIVE_FUNC_ENROLL, +#endif /* COVERAGE_TEST */ + (ICall_PrimSvcFunc) ICall_primEnroll }, + + { +#ifdef COVERAGE_TEST + ICALL_PRIMITIVE_FUNC_REGISTER_APP, +#endif /* COVERAGE_TEST */ + (ICall_PrimSvcFunc) ICall_primRegisterApp }, + + { +#ifdef COVERAGE_TEST + ICALL_PRIMITIVE_FUNC_MSG_ALLOC, +#endif /* COVERAGE_TEST */ + (ICall_PrimSvcFunc) ICall_primAllocMsg }, + + { +#ifdef COVERAGE_TEST + ICALL_PRIMITIVE_FUNC_MSG_FREE, +#endif /* COVERAGE_TEST */ + (ICall_PrimSvcFunc) ICall_primFreeMsg }, + + { +#ifdef COVERAGE_TEST + ICALL_PRIMITIVE_FUNC_MALLOC, +#endif /* COVERAGE_TEST */ + (ICall_PrimSvcFunc) ICall_primMalloc }, + + { +#ifdef COVERAGE_TEST + ICALL_PRIMITIVE_FUNC_FREE, +#endif /* COVERAGE_TEST */ + (ICall_PrimSvcFunc) ICall_primFree }, + + { +#ifdef COVERAGE_TEST + ICALL_PRIMITIVE_FUNC_SEND_MSG, +#endif /* COVERAGE_TEST */ + (ICall_PrimSvcFunc) ICall_primSend }, + + { +#ifdef COVERAGE_TEST + ICALL_PRIMITIVE_FUNC_FETCH_MSG, +#endif /* COVERAGE_TEST */ + (ICall_PrimSvcFunc) ICall_primFetchMsg }, + + { +#ifdef COVERAGE_TEST + ICALL_PRIMITIVE_FUNC_SEND_SERV_MSG, +#endif /* COVERAGE_TEST */ + (ICall_PrimSvcFunc) ICall_primSendServiceMsg }, + + { +#ifdef COVERAGE_TEST + ICALL_PRIMITIVE_FUNC_FETCH_SERV_MSG, +#endif /* COVERAGE_TEST */ + (ICall_PrimSvcFunc) ICall_primFetchServiceMsg }, + + { +#ifdef COVERAGE_TEST + ICALL_PRIMITIVE_FUNC_WAIT, +#endif /* COVERAGE_TEST */ + (ICall_PrimSvcFunc) ICall_primWait }, + + { +#ifdef COVERAGE_TEST + ICALL_PRIMITIVE_FUNC_SIGNAL, +#endif /* COVERAGE_TEST */ + (ICall_PrimSvcFunc) ICall_primSignal }, + + { +#ifdef COVERAGE_TEST + ICALL_PRIMITIVE_FUNC_ABORT, +#endif /* COVERAGE_TEST */ + (ICall_PrimSvcFunc) ICall_primAbort }, + + { +#ifdef COVERAGE_TEST + ICALL_PRIMITIVE_FUNC_ENABLE_int, +#endif /* COVERAGE_TEST */ + (ICall_PrimSvcFunc) ICall_primEnableint }, + + { +#ifdef COVERAGE_TEST + ICALL_PRIMITIVE_FUNC_DISABLE_int, +#endif /* COVERAGE_TEST */ + (ICall_PrimSvcFunc) ICall_primDisableint }, + + { +#ifdef COVERAGE_TEST + ICALL_PRIMITIVE_FUNC_ENABLE_Mint, +#endif /* COVERAGE_TEST */ + (ICall_PrimSvcFunc) ICall_primEnableMint }, + + { +#ifdef COVERAGE_TEST + ICALL_PRIMITIVE_FUNC_DISABLE_Mint, +#endif /* COVERAGE_TEST */ + (ICall_PrimSvcFunc) ICall_primDisableMint }, + + { +#ifdef COVERAGE_TEST + ICALL_PRIMITIVE_FUNC_REGISTER_ISR, +#endif /* COVERAGE_TEST */ + (ICall_PrimSvcFunc) ICall_primRegisterISR }, + + { +#ifdef COVERAGE_TEST + ICALL_PRIMITIVE_FUNC_GET_TICKS, +#endif /* COVERAGE_TEST */ + (ICall_PrimSvcFunc) ICall_primGetTicks }, + + { +#ifdef COVERAGE_TEST + ICALL_PRIMITIVE_FUNC_SET_TIMER_MSECS, +#endif /* COVERAGE_TEST */ + (ICall_PrimSvcFunc) ICall_primSetTimerMSecs }, + + { +#ifdef COVERAGE_TEST + ICALL_PRIMITIVE_FUNC_GET_TICK_PERIOD, +#endif /* COVERAGE_TEST */ + (ICall_PrimSvcFunc) ICall_primGetTickPeriod }, + + { +#ifdef COVERAGE_TEST + ICALL_PRIMITIVE_FUNC_GET_MAX_MILLISECONDS, +#endif /* COVERAGE_TEST */ + (ICall_PrimSvcFunc) ICall_primGetMaxMSecs }, + + { +#ifdef COVERAGE_TEST + ICALL_PRIMITIVE_FUNC_ENTITY2SERVICE, +#endif /* COVERAGE_TEST */ + (ICall_PrimSvcFunc) ICall_primE2S }, + + { +#ifdef COVERAGE_TEST + ICALL_PRIMITIVE_FUNC_PWR_UPD_ACTIVITY_COUNTER, +#endif /* COVERAGE_TEST */ + (ICall_PrimSvcFunc) ICallPlatform_pwrUpdActivityCounter }, + + { +#ifdef COVERAGE_TEST + ICALL_PRIMITIVE_FUNC_PWR_REGISTER_NOTIFY, +#endif /* COVERAGE_TEST */ + (ICall_PrimSvcFunc) ICallPlatform_pwrRegisterNotify }, + + { +#ifdef COVERAGE_TEST + ICALL_PRIMITIVE_FUNC_WAIT_MATCH, +#endif /* COVERAGE_TEST */ + (ICall_PrimSvcFunc) ICall_primWaitMatch }, + + { +#ifdef COVERAGE_TEST + ICALL_PRIMITIVE_FUNC_GET_ENTITY_ID, +#endif /* COVERAGE_TEST */ + (ICall_PrimSvcFunc) ICall_primGetEntityId }, + + { +#ifdef COVERAGE_TEST + ICALL_PRIMITIVE_FUNC_SET_TIMER, +#endif /* COVERAGE_TEST */ + (ICall_PrimSvcFunc) ICall_primSetTimer }, + + { +#ifdef COVERAGE_TEST + ICALL_PRIMITIVE_FUNC_STOP_TIMER, +#endif /* COVERAGE_TEST */ + (ICall_PrimSvcFunc) ICall_primStopTimer }, + + { +#ifdef COVERAGE_TEST + ICALL_PRIMITIVE_FUNC_PWR_CONFIG_AC_ACTION, +#endif /* COVERAGE_TEST */ + (ICall_PrimSvcFunc) ICallPlatform_pwrConfigACAction }, + + { +#ifdef COVERAGE_TEST + ICALL_PRIMITIVE_FUNC_PWR_REQUIRE, +#endif /* COVERAGE_TEST */ + (ICall_PrimSvcFunc) ICallPlatform_pwrRequire }, + + { +#ifdef COVERAGE_TEST + ICALL_PRIMITIVE_FUNC_PWR_DISPENSE, +#endif /* COVERAGE_TEST */ + (ICall_PrimSvcFunc) ICallPlatform_pwrDispense }, + + { +#ifdef COVERAGE_TEST + ICALL_PRIMITIVE_FUNC_THREAD_SERVES, +#endif /* COVERAGE_TEST */ + (ICall_PrimSvcFunc) ICall_primThreadServes }, + + { +#ifdef COVERAGE_TEST + ICALL_PRIMITIVE_FUNC_PWR_IS_STABLE_XOSC_HF, +#endif /* COVERAGE_TEST */ + (ICall_PrimSvcFunc) ICallPlatform_pwrIsStableXOSCHF }, + + { +#ifdef COVERAGE_TEST + ICALL_PRIMITIVE_FUNC_PWR_GET_TRANSITION_STATE, +#endif /* COVERAGE_TEST */ + (ICall_PrimSvcFunc) ICallPlatform_pwrGetTransitionState }, + + { +#ifdef COVERAGE_TEST + ICALL_PRIMITIVE_FUNC_CREATE_TASK, +#endif /* COVERAGE_TEST */ + (ICall_PrimSvcFunc) ICall_primCreateTask }, + +#ifdef ICALL_RTOS_SEMAPHORE_API + { +#ifdef COVERAGE_TEST + ICALL_PRIMITIVE_FUNC_CREATE_SEMAPHORE, +#endif /* COVERAGE_TEST */ + (ICall_PrimSvcFunc) ICall_primCreateSemaphore }, + + { +#ifdef COVERAGE_TEST + ICALL_PRIMITIVE_FUNC_WAIT_SEMAPHORE, +#endif /* COVERAGE_TEST */ + (ICall_PrimSvcFunc) ICall_primWaitSemaphore }, + +#else /* ICALL_RTOS_SEMAPHORE_API */ + + { +#ifdef COVERAGE_TEST + ICALL_PRIMITIVE_FUNC_WAIT_SEMAPHORE, +#endif /* COVERAGE_TEST */ + NULL }, + + { +#ifdef COVERAGE_TEST + ICALL_PRIMITIVE_FUNC_WAIT_SEMAPHORE, +#endif /* COVERAGE_TEST */ + NULL }, +#endif /* ICALL_RTOS_SEMAPHORE_API */ + + { +#ifdef COVERAGE_TEST + ICALL_PRIMITIVE_FUNC_SWITCH_XOSC_HF, +#endif /* COVERAGE_TEST */ + (ICall_PrimSvcFunc) ICallPlatform_pwrSwitchXOSCHF }, + + { +#ifdef COVERAGE_TEST + ICALL_PRIMITIVE_FUNC_PWR_GET_XOSC_STARTUP_TIME, +#endif /* COVERAGE_TEST */ + (ICall_PrimSvcFunc) ICallPlatform_pwrGetXOSCStartupTime }, + + { +#ifdef COVERAGE_TEST + ICALL_PRIMITIVE_FUNC_REGISTER_ISR_EXT, +#endif /* COVERAGE_TEST */ + (ICall_PrimSvcFunc) ICall_primRegisterISR_Ext }, + +#ifdef ICALL_RTOS_SEMAPHORE_API + { +#ifdef COVERAGE_TEST + ICALL_PRIMITIVE_FUNC_POST_SEMAPHORE, +#endif /* COVERAGE_TEST */ + (ICall_PrimSvcFunc) ICall_primPostSemaphore }, +#else /*ICALL_RTOS_SEMAPHORE_API */ + { +#ifdef COVERAGE_TEST + ICALL_PRIMITIVE_FUNC_POST_SEMAPHORE, +#endif /* COVERAGE_TEST */ + NULL }, /* ICALL_RTOS_SEMAPHORE_API */ +#endif + +#ifdef ICALL_RTOS_EVENT_API + { +#ifdef COVERAGE_TEST + ICALL_PRIMITIVE_FUNC_CREATE_EVENT, +#endif /* COVERAGE_TEST */ + (ICall_PrimSvcFunc) ICall_primCreateEvent }, + + { +#ifdef COVERAGE_TEST + ICALL_PRIMITIVE_FUNC_WAIT_EVENT, +#endif /* COVERAGE_TEST */ + (ICall_PrimSvcFunc) ICall_primWaitEvent }, + + { +#ifdef COVERAGE_TEST + ICALL_PRIMITIVE_FUNC_POST_EVENT, +#endif /* COVERAGE_TEST */ + (ICall_PrimSvcFunc) ICall_primPostEvent }, +#else /*ICALL_RTOS_EVENT_API */ + { +#ifdef COVERAGE_TEST + ICALL_PRIMITIVE_FUNC_CREATE_EVENT, +#endif /* COVERAGE_TEST */ + NULL }, + { +#ifdef COVERAGE_TEST + ICALL_PRIMITIVE_FUNC_WAIT_EVENT, +#endif /* COVERAGE_TEST */ + NULL }, /* ICALL_RTOS_EVENT_API */ + { +#ifdef COVERAGE_TEST + ICALL_PRIMITIVE_FUNC_POST_EVENT, +#endif /* COVERAGE_TEST */ + NULL }, /* ICALL_RTOS_EVENT_API */ +#endif /* ICALL_RTOS_EVENT_API */ +}; +/** + * @internal + * Primitive service registered handler function + * @param args arguments + * @return error code + */ +static ICall_Errno ICall_primService(ICall_FuncArgsHdr * args) +{ + if (args->func >= sizeof(ICall_primSvcFuncs) / sizeof(ICall_primSvcFuncs[0])) + { + return ICALL_ERRNO_INVALID_FUNCTION; + } + return ICall_primSvcFuncs[args->func].func(args); +} + +/** + * @internal Enrolls primitive service + */ +static void ICall_initPrim(void) +{ + ICall_entities[0].service = ICALL_SERVICE_CLASS_PRIMITIVE; + ICall_entities[0].fn = ICall_primService; + + /* Initialize heap */ + ICall_heapInit(); + + /* TODO: Think about freezing permanently allocated memory blocks + * for optimization. + * Now that multiple stack images may share the same heap. + * kick cannot be triggered by a single stack image. + * Hence, maybe there should be an alternative API to + * permanently allocate memory blocks, such as + * by allocating the blocks at the end of the heap space. */ +} +#endif /* ICALL_JT */ + +#ifdef COVERAGE_TEST +/** + * @internal + * Verification function for ICall implementation + */ +void ICall_verify(void) +{ + size_t i; + for (i = 0; i < sizeof(ICall_primSvcFuncs) / sizeof(ICall_primSvcFuncs[0]); i++) + { + if (i != ICall_primSvcFuncs[i].id) + { + ICall_abort(); + } + } +} +#endif /* COVERAGE_TEST */ + +#ifdef ICALL_JT +/** + * Registers an application. + * Note that this function must be called from the thread + * from which ICall_wait() function will be called. + * + * @param entity pointer to a variable to store entity id assigned + * to the application. + * @param msgsem pointer to a variable to store the synchronous object handle + * associated with the calling thread. + * @return @ref ICALL_ERRNO_SUCCESS when successful.
+ * @ref ICALL_ERRNO_NO_RESOURCE when ran out of resource. + */ +ICall_Errno ICall_registerApp(ICall_EntityID * entity, ICall_SyncHandle * msgSyncHdl) +{ + + size_t i; + ICall_TaskEntry * taskentry = ICall_newTask(Task_self()); + ICall_CSState key; + + if (!taskentry) + { + /* abort */ + ICALL_HOOK_ABORT_FUNC(); + return ICALL_ERRNO_NO_RESOURCE; + } + + key = ICall_enterCSImpl(); + for (i = 0; i < ICALL_MAX_NUM_ENTITIES; i++) + { + if (ICall_entities[i].service == ICALL_SERVICE_CLASS_INVALID_ENTRY) + { + /* Use this entry */ + ICall_entities[i].service = ICALL_SERVICE_CLASS_APPLICATION; + ICall_entities[i].task = taskentry; + ICall_entities[i].fn = NULL; + *entity = (ICall_EntityID) i; + *msgSyncHdl = taskentry->syncHandle; + ICall_leaveCSImpl(key); + return ICALL_ERRNO_SUCCESS; + } + } + /* abort */ + ICALL_HOOK_ABORT_FUNC(); + ICall_leaveCSImpl(key); + return (ICALL_ERRNO_NO_RESOURCE); +} + +/** + * Allocates memory block for a message. + * @param size size of the message body in bytes. + * @return pointer to the start of the message body of the newly + * allocated memory block, or NULL if the allocation + * failed. + */ +void * ICall_allocMsg(size_t size) +{ + ICall_MsgHdr * hdr = (ICall_MsgHdr *) ICall_heapMalloc(sizeof(ICall_MsgHdr) + size); + + if (!hdr) + { + return NULL; + } + hdr->len = size; + hdr->next = NULL; + hdr->dest_id = ICALL_UNDEF_DEST_ID; + return ((void *) (hdr + 1)); +} + +/** + * Frees the memory block allocated for a message. + * @param msg pointer to the start of the message body + * which was returned from ICall_allocMsg(). + */ +void ICall_freeMsg(void * msg) +{ + ICall_MsgHdr * hdr = (ICall_MsgHdr *) msg - 1; + ICall_heapFree(hdr); +} + +/** + * Sends a message to a registered server. + * @param src Entity id of the sender of the message + * @param dest Service id + * @param format Message format: + * @ref ICALL_MSG_FORMAT_KEEP, + * @ref ICALL_MSG_FORMAT_1ST_CHAR_TASK_ID or + * @ref ICALL_MSG_FORMAT_3RD_CHAR_TASK_ID. + * Message format indicates whether and which + * field of the message must be transformed + * into a implementation specific sender + * identity for an external image.
+ * When a service message interface is defined, + * it may contain a field that is not understood + * by the client but only understood by + * the system on the server's side. + * The format provides an information to the + * messaging system on such a server + * so that it can generically tag necessary + * information to the message. + * @param msg pointer to the message body to send.
+ * Note that if message is successfully sent, + * the caller should not reference the message any + * longer.
+ * However, if the function fails, the caller + * still owns the reference to the message. + * That is, caller may attempt another send, + * or may free the memory block, etc. + * @return @ref ICALL_ERRNO_SUCCESS when successful.
+ * @ref ICALL_ERRNO_INVALID_SERVICE when the 'dest' + * is unregistered service.
+ * @ref ICALL_ERRNO_INVALID_PARAMETER when the 'src' + * is an out of range entity id or when 'dest' is + * is a service that does not receive a message + * (such as ICall primitive service).
+ * Note that as far as 'src' is within the range, + * this function won't notice the 'src' entity id + * as invalid. + */ + +ICall_Errno ICall_sendServiceMsg(ICall_EntityID src, ICall_ServiceEnum dest, ICall_MSGFormat format, void * msg) +{ + ICall_EntityID dstentity = ICall_searchServiceEntity(dest); + + if (dstentity == ICALL_INVALID_ENTITY_ID) + { + return ICALL_ERRNO_INVALID_SERVICE; + } + return (ICall_send(src, dstentity, format, msg)); +} + +/** + * Retrieves a message received at the message queue + * associated with the calling thread. + * + * Note that this function should be used by an application + * which does not expect any message from non-server entity. + * + * @param src pointer to a variable to store the service id + * of the registered server which sent the retrieved + * message + * @param dest pointer to a variable to store the entity id + * of the destination of the message. + * @param msg pointer to a pointer variable to store the + * starting address of the message body being + * retrieved. + * @return @ref ICALL_ERRNO_SUCCESS when the operation was successful + * and a message was retrieved.
+ * @ref ICALL_ERRNO_NOMSG when there is no queued message + * at the moment.
+ * @ref ICALL_ERRNO_CORRUPT_MSG when a message queued in + * front of the thread's receive queue was not sent by + * a server. Note that in this case, the message is + * not retrieved but thrown away.
+ * @ref ICALL_ERRNO_UNKNOWN_THREAD when this function is + * called from a thread which has not registered + * an entity, either through ICall_enrollService() + * or through ICall_registerApp(). + */ +ICall_Errno ICall_fetchServiceMsg(ICall_ServiceEnum * src, ICall_EntityID * dest, void ** msg) +{ + ICall_ServiceEnum servId; + ICall_Errno errno = ICall_fetchMsg((ICall_EntityID *) src, dest, msg); + + if (errno == ICALL_ERRNO_SUCCESS) + { + if (ICall_primEntityId2ServiceId(*src, &servId) != ICALL_ERRNO_SUCCESS) + { + /* Source entity ID cannot be translated to service id */ + ICall_freeMsg(*msg); + return ICALL_ERRNO_CORRUPT_MSG; + } + *src = servId; + } + return (errno); +} +#if 0 +void convertMilliToTimepec(struct timespec *timeoutPosix,uint32_t timeout) +{ + timeoutPosix->tv_sec = (timeout / 1000); + timeout = timeout % 1000; + + /* 1 millisecond = 1 000 000 nanoseconds */ + timeoutPosix->tv_nsec = timeout * 1000000; +} +#endif + +/** + * Waits for a signal to the semaphore associated with the calling thread. + * + * Note that the semaphore associated with a thread is signaled + * when a message is queued to the message receive queue of the thread + * or when ICall_signal() function is called onto the semaphore. + * + * @param milliseconds timeout period in milliseconds. + * @return @ref ICALL_ERRNO_SUCCESS when the semaphore is signaled.
+ * @ref ICALL_ERRNO_TIMEOUT when designated timeout period + * has passed since the call of the function without + * the semaphore being signaled. + */ +ICall_Errno ICall_wait(uint_fast32_t milliseconds) +{ + TaskHandle_t taskhandle = Task_self(); + ICall_TaskEntry * taskentry = ICall_searchTask(taskhandle); + uint32_t timeout; + uint32_t event; + + int16_t retVal = 0; + + if (!taskentry) + { + return (ICALL_ERRNO_UNKNOWN_THREAD); + } + /* Successful */ + if (milliseconds == 0) + { + timeout = BIOS_NO_WAIT; + } + else if (milliseconds == ICALL_TIMEOUT_FOREVER) + { + timeout = BIOS_WAIT_FOREVER; + } + else + { + /* Convert milliseconds to number of ticks */ + ICall_Errno errno = ICall_msecs2Ticks(milliseconds, &timeout); + if (errno != ICALL_ERRNO_SUCCESS) + { + return (errno); + } + } + +#ifdef FREERTOS + if (HwiP_inISR()) + { + xQueueReceiveFromISR(taskentry->syncHandle, (char *) &event, NULL); + } + else + { + xQueueReceive(taskentry->syncHandle, (char *) &event, milliseconds * 100); + } +#endif + if (retVal != (-1)) + { + return (ICALL_ERRNO_SUCCESS); + } + + return (ICALL_ERRNO_TIMEOUT); +} + +/** + * Signals a semaphore. + * @param msgsem handle of a synchronous object to signal + * @return @ref ICALL_ERRNO_SUCCESS + */ +ICall_Errno ICall_signal(ICall_SyncHandle msgSyncHdl) +{ + /* 0x80000000 is an internal Event_ID */ + uint32_t msg_ptr = 0x80000000; + ICall_Errno status = ICALL_ERRNO_NO_RESOURCE; + +#ifdef FREERTOS + uint8_t statusQ; + if (HwiP_inISR()) + { + statusQ = xQueueSendFromISR(msgSyncHdl, (char *) &msg_ptr, NULL); + } + else + { + statusQ = xQueueSend(msgSyncHdl, (char *) &msg_ptr, 0); + } + + if (statusQ == pdTRUE) + { + status = ICALL_ERRNO_SUCCESS; + } +#endif + return (status); +} + +/** + * Registers a service entity + * @param service service id of the enrolling service + * @param fn handler function which handles function + * calls to the service. + * @param entity pointer to a variable to store the assigned entity id + * @param msgsem pointer to a variable to store the synchronous object handle + * associated with the calling thread. + * @return @ref ICALL_ERRNO_SUCCESS when successful.
+ * @ref ICALL_ERRNO_INVALID_PARAMETER when service id is already + * registered by another entity.
+ * @ref ICALL_ERRNO_NO_RESOURCE when maximum number of services + * are already registered. + */ +ICall_Errno ICall_enrollService(ICall_ServiceEnum service, ICall_ServiceFunc fn, ICall_EntityID * entity, + ICall_SyncHandle * msgSyncHdl) +{ + size_t i; + ICall_TaskEntry * taskentry = ICall_newTask(Task_self()); + ICall_CSState key; + + /* Note that certain service does not handle a message + * and hence, taskentry might be NULL. + */ + if (taskentry == NULL) + { + return (ICALL_ERRNO_INVALID_PARAMETER); + } + + key = ICall_enterCSImpl(); + for (i = 0; i < ICALL_MAX_NUM_ENTITIES; i++) + { + if (ICall_entities[i].service == ICALL_SERVICE_CLASS_INVALID_ENTRY) + { + /* Use this entry */ + ICall_entities[i].service = service; + ICall_entities[i].task = taskentry; + ICall_entities[i].fn = fn; + *entity = (ICall_EntityID) i; + *msgSyncHdl = taskentry->syncHandle; + + ICall_leaveCSImpl(key); + return (ICALL_ERRNO_SUCCESS); + } + else if (service == ICall_entities[i].service) + { + /* Duplicate service enrollment */ + ICall_leaveCSImpl(key); + return (ICALL_ERRNO_INVALID_PARAMETER); + } + } + /* abort */ + ICALL_HOOK_ABORT_FUNC(); + ICall_leaveCSImpl(key); + return (ICALL_ERRNO_NO_RESOURCE); +} +#ifdef FREERTOS + +/** + * Allocates a memory block. + * @param size size of the block in bytes. + * @return address of the allocated memory block or NULL + * if allocation fails. + */ + +void * ICall_heapMalloc(uint32_t size) +{ + void * ret = NULL; + ret = malloc(size); + return ret; +} + +/** + * Frees an allocated memory block. + * @param msg pointer to a memory block to free. + */ +void ICall_heapFree(void * msg) +{ + free(msg); +} + +/** + * Allocates a memory block, but check if enough memory will be left after the allocation. + * @param size size of the block in bytes. + * @return address of the allocated memory block or NULL + * if allocation fails. + */ + +void * ICall_heapMallocLimited(uint_least16_t size) +{ + return malloc(size); +} + +/** + * Get Statistic on Heap. + * @param stats pointer to a heapStats_t structure. + */ + +/* Statistics currently are not supported via ICall apis. + * Please consider to use bget statistics (or any of your internal heap statistics) */ +void ICall_heapGetStats(ICall_heapStats_t * pStats) {} + +#endif // FREERTOS +/** + * Allocates a memory block. + * @param size size of the block in bytes. + * @return address of the allocated memory block or NULL + * if allocation fails. + */ +void * ICall_malloc(uint_least16_t size) +{ + return (ICall_heapMalloc(size)); +} + +/** + * Frees an allocated memory block. + * @param msg pointer to a memory block to free. + */ +void ICall_free(void * msg) +{ + ICall_heapFree(msg); +} + +/** + * Allocates a memory block, but check if enough memory will be left after the allocation. + * @param size size of the block in bytes. + * @return address of the allocated memory block or NULL + * if allocation fails. + */ + +void * ICall_mallocLimited(uint_least16_t size) +{ + return (ICall_heapMallocLimited(size)); +} + +/** + * Get Statistic on Heap. + * @param stats pointer to a heapStats_t structure. + */ +void ICall_getHeapStats(ICall_heapStats_t * pStats) +{ + ICall_heapGetStats(pStats); +} + +#ifdef HEAPMGR_METRICS +/** + * @brief obtain heap usage metrics + * @param pBlkMax pointer to a variable to store max cnt of all blocks ever seen at once + * @param pBlkCnt pointer to a variable to store current cnt of all blocks + * @param pBlkFree pointer to a variable to store current cnt of free blocks + * @param pMemAlo pointer to a variable to store current total memory allocated + * @param pMemMax pointer to a variable to store max total memory ever allocated at once + * @param pMemUB pointer to a variable to store the upper bound of memory usage + */ +void ICall_getHeapMgrGetMetrics(uint32_t * pBlkMax, uint32_t * pBlkCnt, uint32_t * pBlkFree, uint32_t * pMemAlo, uint32_t * pMemMax, + uint32_t * pMemUB) +{ + ICall_heapMgrGetMetrics(pBlkMax, pBlkCnt, pBlkFree, pMemAlo, pMemMax, pMemUB); +} + +#endif +/** + * Sends a message to an entity. + * @param src entity id of the sender + * @param dest entity id of the destination of the message. + * @param format message format. See ICall_sendServiceMsg(). + * @param msg pointer to the message body. + * @return @ref ICALL_ERRNO_SUCCESS when successful.
+ * @ref ICALL_ERRNO_INVALID_PARAMETER when either src + * or dest is not a valid entity id or when + * dest is an entity id of an entity that does + * not receive a message + * (e.g., ICall primitive service entity). + */ +ICall_Errno ICall_send(ICall_EntityID src, ICall_EntityID dest, ICall_MSGFormat format, void * msg) +{ + ICall_CSState key; + ICall_MsgHdr * hdr = (ICall_MsgHdr *) msg - 1; + + if (dest >= ICALL_MAX_NUM_ENTITIES || src >= ICALL_MAX_NUM_ENTITIES) + { + return (ICALL_ERRNO_INVALID_PARAMETER); + } + key = ICall_enterCSImpl(); + if (!ICall_entities[dest].task) + { + ICall_leaveCSImpl(key); + return (ICALL_ERRNO_INVALID_PARAMETER); + } + + ICall_leaveCSImpl(key); + /* Note that once the entry is valid, + * the value does not change and hence it is OK + * to leave the critical section. + */ + + hdr->srcentity = src; + hdr->dstentity = dest; + hdr->format = format; + + ICall_msgEnqueue(&ICall_entities[dest].task->queue, msg); + /* 0x80000000 is an internal event number */ + uint32_t msg_ptr = 0x80000000; +#ifdef FREERTOS + uint8_t status; + + if (HwiP_inISR()) + { + status = xQueueSendFromISR(ICall_entities[dest].task->syncHandle, (char *) &msg_ptr, NULL); + } + else + { + status = xQueueSend(ICall_entities[dest].task->syncHandle, (char *) &msg_ptr, 0); + } + + if (status != pdPASS) + { + return status; + } +#endif + return (ICALL_ERRNO_SUCCESS); +} + +/** + * Retrieves a message, queued to receive queue of the calling thread. + * + * @param src pointer to a variable to store the sender entity id + * of the received message. + * @param dest pointer to a variable to store the destination entity id + * of the received message. + * @param msg pointer to a pointer variable to store the starting + * address of a received message body. + * @return @ref ICALL_ERRNO_SUCCESS when a message was successfully + * retrieved.
+ * @ref ICALL_ERRNO_NOMSG when no message was queued to + * the receive queue at the moment.
+ * @ref ICALL_ERRNO_UNKNOWN_THREAD when the calling thread + * does not have a received queue associated with it. + * This happens when neither ICall_enrollService() nor + * ICall_registerApp() was ever called from the calling + * thread. + */ +ICall_Errno ICall_fetchMsg(ICall_EntityID * src, ICall_EntityID * dest, void ** msg) +{ + void * msgTemp; + TaskHandle_t taskhandle = Task_self(); + ICall_TaskEntry * taskentry = ICall_searchTask(taskhandle); + ICall_MsgHdr * hdr; + + if (!taskentry) + { + return (ICALL_ERRNO_UNKNOWN_THREAD); + } + /* Successful */ + msgTemp = ICall_msgDequeue(&taskentry->queue); + + if (msgTemp == NULL) + { + return (ICALL_ERRNO_NOMSG); + } + hdr = (ICall_MsgHdr *) msgTemp - 1; + *src = hdr->srcentity; + *dest = hdr->dstentity; + *msg = msgTemp; + return (ICALL_ERRNO_SUCCESS); +} + +/** + * Transforms and entityId into a serviceId. + * Note that this function is useful in case an application + * waits for messages from both a server and another application, + * in which case, the application can only use ICall_fetchMsg(), + * not ICall_fetchServiceMsg() because the latter will return + * @ref ICALL_ERRNO_CORRUPT_MSG when a message sent by the other + * application is about to be fetched.
+ * This function, then, is useful to retrieve service id + * matching the source entity id in case the source entity + * id is not that of the other application. + * + * @param entityId entity id + * @param servId pointer to a variable to store + * the resultant service id + * @return @ref ICALL_ERRNO_SUCCESS if the transformation was successful.
+ * @ref ICALL_ERRNO_INVALID_SERVICE if no matching service + * is found for the entity id. + */ +ICall_Errno ICall_entityId2ServiceId(ICall_EntityID entityId, ICall_ServiceEnum * servId) +{ + return ICall_primEntityId2ServiceId(entityId, servId); +} + +/** + * Aborts. + * + * This is preferred over C runtime abort() function, + * in an external image since the C runtime abort() is only + * guaranteed in a root image which contains the C runtime + * entry function that is executed upon startup. + */ +ICall_Errno ICall_abort(void) +{ +#ifdef HALNODEBUG +#elif defined(EXT_HAL_ASSERT) + HAL_ASSERT(HAL_ASSERT_CAUSE_ICALL_ABORT); +#else + { + volatile uint8_t j = 1; + while (j) + ; + } +#endif /* EXT_HAL_ASSERT */ + ICALL_HOOK_ABORT_FUNC(); + return (ICALL_ERRNO_SUCCESS); +} + +/** + * Enables interrupt. + * @param intnum interrupt number + * @return @ref ICALL_ERRNO_SUCCESS. + */ +ICall_Errno ICall_enableint(int intnum) +{ + Hwi_enableinterrupt(intnum); + return (ICALL_ERRNO_SUCCESS); +} + +/** + * Disables interrupt + * @param intnum interrupt number + * @return @ref ICALL_ERRNO_SUCCESS + */ +ICall_Errno ICall_disableint(int intnum) +{ + Hwi_disableinterrupt(intnum); + return (ICALL_ERRNO_SUCCESS); +} + +/** + * Gets the current tick counter value. + * @return current tick counter value + */ +uint_fast32_t ICall_getTicks(void) +{ + return (ClockP_getSystemTicks()); +} + +/** + * Gets the tick period. + * @return tick period in microseconds. + */ +uint_fast32_t ICall_getTickPeriod(void) +{ + return CLOCK_TICKS_PERIOD; +} + +/** + * Gets the maximum timeout period supported by + * ICall_setTimerMSecs() function. + * + * @return maximum timeout period in milliseconds + */ +uint_fast32_t ICall_getMaxMSecs(void) +{ + + uint_fast64_t tmp = ((uint_fast64_t) 0x7ffffffful) * (ICall_getTickPeriod()); + tmp /= 1000; + if (tmp >= 0x80000000ul) + { + tmp = 0x7ffffffful; + } + return ((uint_least32_t) tmp); +} + +/** + * Set up or restart a timer. + * Note that the timer setup initially by this function may be restarted + * using ICall_setTimer() function as well. + * + * @param msecs timeout period in milliseconds after which callback function + * shall be called. + * @param cback callback function pointer + * @param arg argument to pass to the callback function + * @param id pointer to the timer ID. + * If a new timer must be set up, the value of the timer ID + * must be set to @ref ICALL_INVALID_TIMER_ID when making this + * call and when the function returns successfully, the variable + * will be assigned a new timer ID value. + * The value other than @ref ICALL_INVALID_TIMER_ID shall be + * regarded as a request to restart the earlier set timer. + * @return @ref ICALL_ERRNO_SUCCESS when successful;
+ * @ref ICALL_ERRNO_INVALID_PARAMETER when msecs is greater than + * maximum value supported;
+ * @ref ICALL_ERRNO_NO_RESOURCE when ran out of resource. + * Check ICall heap size and OS heap size if this happens. + * + * @see ICall_getMaxMSecs() + */ +ICall_Errno ICall_setTimerMSecs(uint_fast32_t msecs, ICall_TimerCback cback, void * arg, ICall_TimerID * id) +{ + uint32_t ticks; + uint32_t timeout; + /* Convert to tick time */ + ICall_Errno errno = ICall_msecs2Ticks(msecs, &ticks); + + if (errno != ICALL_ERRNO_SUCCESS) + { + return (errno); + } + timeout = ticks; + ICall_setTimer(timeout, cback, arg, id); + + return (errno); +} + +/** + * Set up or restart a timer. + * Note that the timer setup initially by this function may be restarted + * using ICall_setTimerMSecs() function as well. + * + * @param ticks timeout period in ticks after which the callback function + * shall be called. + * @param cback callback function pointer + * @param arg argument to pass to the callback function + * @param id pointer to the timer ID. + * If a new timer must be set up, the value of the timer ID + * must be set to @ref ICALL_INVALID_TIMER_ID when making this + * call and when the function returns successfully, the variable + * will be assigned a new timer ID value. + * The value other than @ref ICALL_INVALID_TIMER_ID shall be + * regarded as a request to restart the earlier set timer. + * @return @ref ICALL_ERRNO_SUCCESS when successful;
+ * @ref ICALL_ERRNO_NO_RESOURCE when ran out of resource. + * Check ICall heap size and OS heap size if this happens. + * + * @see ICall_getTickPeriod() + */ + +ICall_Errno ICall_setTimer(uint32_t ticks, ICall_TimerCback cback, void * arg, ICall_TimerID * id) +{ + + ICall_ScheduleEntry * entry; + + if (*id == ICALL_INVALID_TIMER_ID) + { + ClockP_Params params; + + /* Create a new timer */ + entry = ICall_heapMalloc(sizeof(ICall_ScheduleEntry)); + if (entry == NULL) + { + /* allocation failed */ + return (ICALL_ERRNO_NO_RESOURCE); + } + ClockP_Params_init(¶ms); + params.startFlag = FALSE; + params.period = 0; + params.arg = (uintptr_t) entry; + + entry->clockP = ClockP_create(ICall_clockFunc, ticks, ¶ms); + if (!entry->clockP) + { + /* abort */ + ICall_abort(); + ICall_heapFree(entry); + return (ICALL_ERRNO_NO_RESOURCE); + } + entry->cback = cback; + entry->arg = arg; + *id = (ICall_TimerID) entry; + } + else + { + ICall_CSState key; + + entry = (ICall_ScheduleEntry *) *id; + + /* Critical section is entered to disable interrupts that might cause call + * to callback due to race condition */ + key = ICall_enterCriticalSection(); + ClockP_stop(entry->clockP); + entry->arg = arg; + ICall_leaveCriticalSection(key); + } + ClockP_setTimeout(entry->clockP, ticks); + + ClockP_start(entry->clockP); + + return (ICALL_ERRNO_SUCCESS); +} + +/** + * Stops a timer. + * + * @param id timer ID. + */ +void ICall_stopTimer(ICall_TimerID id) +{ + ICall_ScheduleEntry * entry = (ICall_ScheduleEntry *) id; + + if (id == ICALL_INVALID_TIMER_ID) + { + return; + } + + ClockP_stop(entry->clockP); +} + +/** + * Increments or decrements power activity counter. + * + * When power activity counter is greater than zero, + * the device shall stay in the active power state. + * The caller has to make sure that it decrements the counter + * as many times as it has incremented the counter + * when there is no activity that requires the active power state. + * It is recommended that each client increments the counter by just one, + * but it is not mandated to be so. + * + * @param incFlag TRUE to indicate incrementing the counter.
+ * FALSE to indicate decrementing the counter. + * @return @ref TRUE if power is required.
+ * @ref FALSE if power is not required.
+ */ +bool ICall_pwrUpdActivityCounter(bool incFlag) +{ + ICall_PwrUpdActivityCounterArgs args; + args.incFlag = incFlag; + ICallPlatform_pwrUpdActivityCounter(&args); + return (args.pwrRequired); +} + +/** + * Configures power constraint/dependency set/release actions upon + * activity counter change. + * + * When activity counter value drops to zero, all constraints and + * dependencies configured by this function shall be released.
+ * When activity counter value increments to one, all constraints + * and dependencies configured by this function shall be set. + * + * @param bitmap a bitmap of constraint or dependency flags.
+ * The flag definition is specific to each platform. + * For instance, see ICallCC26xxDefs.h. + * + * @return @ref ICALL_ERRNO_SUCCESS when successful
+ * @ref ICALL_ERRNO_INVALID_PARAMETER when an invalid + * flag in the bitmap is detected.
+ */ +ICall_Errno ICall_pwrConfigACAction(ICall_PwrBitmap_t bitmap) +{ + ICall_PwrBitmapArgs args; + args.bitmap = bitmap; + return (ICallPlatform_pwrConfigACAction(&args)); +} + +/** + * Sets power constraints and dependencies. + * + * @param bitmap a bitmap of constraint or dependency flags.
+ * The flag definition is specific to each platform. + * For instance, see ICallCC26xxDefs.h. + * + * @return @ref ICALL_ERRNO_SUCCESS when successful
+ * @ref ICALL_ERRNO_INVALID_PARAMETER when an invalid + * flag in the bitmap is detected.
+ */ +ICall_Errno ICall_pwrRequire(ICall_PwrBitmap_t bitmap) +{ + ICall_PwrBitmapArgs args; + args.bitmap = bitmap; + return (ICallPlatform_pwrRequire(&args)); +} + +/** + * Releases power constraints and dependencies. + * + * @param bitmap a bitmap of constraint or dependency flags.
+ * The flag definition is specific to each platform. + * For instance, see ICallCC26xxDefs.h. + * + * @return @ref ICALL_ERRNO_SUCCESS when successful
+ * @ref ICALL_ERRNO_INVALID_PARAMETER when an invalid + * flag in the bitmap is detected.
+ */ +ICall_Errno ICall_pwrDispense(ICall_PwrBitmap_t bitmap) +{ + ICall_PwrBitmapArgs args; + args.bitmap = bitmap; + return (ICallPlatform_pwrDispense(&args)); +} + +/** + * Checks whether HF XOSC is stable. + * This function must be called after HF XOSC is turned on + * (through power dependency). + * + * @return TRUE when HF XOSC is stable.
+ * FALSE when HF XOSC is not stable.
+ */ +bool ICall_pwrIsStableXOSCHF(void) +{ + ICall_GetBoolArgs args; + (void) ICallPlatform_pwrIsStableXOSCHF(&args); + return (args.value); +} + +/** + * Switch clock source to HF XOSC. + * This function must be called after HF XOSC is stable. + * + * @return @ref ICALL_ERRNO_SUCCESS + */ +ICall_Errno ICall_pwrSwitchXOSCHF(void) +{ + ICall_FuncArgsHdr args; + return (ICallPlatform_pwrSwitchXOSCHF(&args)); +} + +/** + * Gets the estimated crystal oscillator startup time. + * + * @return estimated crystal oscillator startup time + */ +uint32_t ICall_pwrGetXOSCStartupTime(uint_fast32_t timeUntilWakeupInMs) +{ + ICall_PwrGetXOSCStartupTimeArgs args; + args.timeUntilWakeupInMs = timeUntilWakeupInMs; + (void) ICallPlatform_pwrGetXOSCStartupTime(&args); + return (args.value); +} + +/** + * Registers a power state transition notify function. + * + * The registered notify function shall be called when the power state + * changes. + * + * @param fn notify function pointer + * @param obj pointer to data object to be passed to notify function.
+ * This pointer must not be NULL and can point to an aggregate type + * containing the @ref ICall_PwrNotifyData. + * The object must not be released. + * @return @ref ICALL_ERRNO_SUCCESS when successful
+ * @ref ICALL_ERRNO_NO_RESOURCE when registration failed
+ */ +ICall_Errno ICall_pwrRegisterNotify(ICall_PwrNotifyFn fn, ICall_PwrNotifyData * obj) +{ + ICall_PwrRegisterNotifyArgs args; + args.hdr.service = ICALL_SERVICE_CLASS_PRIMITIVE; + args.hdr.func = ICALL_PRIMITIVE_FUNC_PWR_REGISTER_NOTIFY; + args.fn = fn; + args.obj = obj; + return (ICallPlatform_pwrRegisterNotify(&args)); +} + +/** + * Retrieves power transition state. + * + * @return Implementation specific transition state when successful
+ * Zero when the function is not implemented.
+ */ +uint_fast8_t ICall_pwrGetTransitionState(void) +{ + ICall_PwrGetTransitionStateArgs args; + ICall_Errno errno; + + errno = ICallPlatform_pwrGetTransitionState(&args); + + if (errno == ICALL_ERRNO_SUCCESS) + { + return (args.state); + } + return (0); +} + +/** + * Creates a new RTOS task. + * + * @param entryfn task entry function. + * @param priority task priority as understood by the underlying RTOS + * @param stacksize stack size as understood by the underlying RTOS + * @param arg argument to pass to the task entry function + * + * @return @ref ICALL_ERRNO_SUCCESS when successful
+ * @ref ICALL_ERRNO_NO_RESOURCE when creation failed
+ */ + +#ifdef ICALL_RTOS_SEMAPHORE_API +/** + * Creates a semaphore. + * + * @param mode Semaphore mode
+ * @ref ICALL_SEMAPHORE_MODE_COUNTING, or
+ * @ref ICALL_SEMAPHORE_MODE_BINARY + * @param initcount initial count value + * @return created semaphore when successful
+ * NULL when creation failed
+ */ +ICall_Semaphore ICall_createSemaphore(uint_fast8_t mode, int initcount) +{ + /* Semaphore_Params is a huge structure. + * To reduce stack usage, heap is used instead. + * This implies that ICall_createSemaphore() must be called before heap + * space may be exhausted. + */ + ICall_Semaphore sem; + Semaphore_Params * semParams = (Semaphore_Params *) ICall_heapMalloc(sizeof(Semaphore_Params)); + + if (semParams == NULL) + { + return (NULL); + } + + Semaphore_Params_init(semParams); + if (mode == ICALL_SEMAPHORE_MODE_BINARY) + { + semParams->mode = Semaphore_Mode_BINARY; + } + + sem = Semaphore_create(args->initcount, semParams, NULL); + ICall_heapFree(semParams); + + return (sem); +} +#endif + +#ifdef ICALL_RTOS_SEMAPHORE_API +/** + * Post on a semaphore + * + * @param sem semaphore. + * + * @return @ref ICALL_ERRNO_SUCCESS when the operation was successful + */ +ICall_Errno ICall_postSemaphore(ICall_Semaphore sem) +{ + Semaphore_post(sem); + return (ICALL_ERRNO_SUCCESS); +} +#endif /* ICALL_RTOS_SEMAPHORE_API */ + +#ifdef ICALL_RTOS_EVENTS_API +/** + * Creates a event. + * + * @return created event when successful
+ * NULL when creation failed
+ */ +ICall_Event ICall_createEvent(void) +{ + ICall_Event event = Event_create(NULL, NULL); + return (event); + + ICall_CreateEventArgs args; + ICall_Errno errno; + + args.hdr.service = ICALL_SERVICE_CLASS_PRIMITIVE; + args.hdr.func = ICALL_PRIMITIVE_FUNC_CREATE_EVENT; + errno = ICall_dispatcher(&args.hdr); + if (errno == ICALL_ERRNO_SUCCESS) + { + return (args.event); + } + return (NULL); +} + +/** + * Post on an event + * + * @param event event. + * + * @return @ref ICALL_ERRNO_SUCCESS when the operation was successful + */ +ICall_Errno ICall_postEvent(ICall_Event event, uint32_t events) +{ + Event_post(event, events); + return (ICALL_ERRNO_SUCCESS); +} +/** + * Waits on a event for ICALL_MSG_EVENT_ID + * + * @param event event. + * @param milliseconds timeout in milliseconds + * or @ref ICALL_TIMEOUT_FOREVER to wait forever + * + * @return @ref ICALL_ERRNO_SUCCESS when the operation was successful + * and event was received.
+ * @ref ICALL_ERRNO_TIMEOUT when designated timeout period + * has passed since the call of the function without + * the event being signaled. + */ +ICall_Errno ICall_waitEvent(ICall_Event event, uint_fast32_t milliseconds) +{ + uint32_t timeout; + + if (milliseconds == 0) + { + timeout = BIOS_NO_WAIT; + } + else if (milliseconds == ICALL_TIMEOUT_FOREVER) + { + timeout = BIOS_WAIT_FOREVER; + } + else + { + ICall_Errno errno = ICall_msecs2Ticks(milliseconds, &timeout); + if (errno != ICALL_ERRNO_SUCCESS) + { + return (errno); + } + } + + if (Event_pend(event, 0, ICALL_MSG_EVENT_ID, timeout)) + { + return (ICALL_ERRNO_SUCCESS); + } + return (ICALL_ERRNO_TIMEOUT); +} +#endif /* ICALL_RTOS_EVENTS_API */ + +#ifdef ICALL_RTOS_SEMAPHORE_API +/** + * Waits on a semaphore + * + * @param sem semaphore. + * @param milliseconds timeout in milliseconds + * or @ref ICALL_TIMEOUT_FOREVER to wait forever + * + * @return @ref ICALL_ERRNO_SUCCESS when the operation was successful + * and semaphore was acquired.
+ * @ref ICALL_ERRNO_TIMEOUT when designated timeout period + * has passed since the call of the function without + * the semaphore being signaled. + */ +ICall_Errno ICall_waitSemaphore(ICall_Semaphore sem, uint_fast32_t milliseconds) +{ + uint32_t timeout; + + if (milliseconds == 0) + { + timeout = BIOS_NO_WAIT; + } + else if (milliseconds == ICALL_TIMEOUT_FOREVER) + { + timeout = BIOS_WAIT_FOREVER; + } + else + { + ICall_Errno errno = ICall_msecs2Ticks(milliseconds, &timeout); + if (errno != ICALL_ERRNO_SUCCESS) + { + return (errno); + } + } + if (Semaphore_pend(sem, timeout)) + { + return (ICALL_ERRNO_SUCCESS); + } + return (ICALL_ERRNO_TIMEOUT); +} +#endif /* ICALL_RTOS_SEMAPHORE_API */ + +#if 0 +/* Util function that take time in ticks and convert it into ms - relate to system clock (returns system clock + converted ms) */ +static void AbsoluteTimeInMilliPlusTimer(uint_least32_t timeout,struct timespec *tsTimer) +{ + + clock_gettime(CLOCK_REALTIME, tsTimer); + + tsTimer->tv_sec += (timeout / 1000); + tsTimer->tv_nsec += (timeout % 1000) * 1000000; +} +#endif + +/** + * Waits for and retrieves a message received at the message queue + * associated with the calling thread, which matches a certain condition. + * + * @param milliseconds timeout period in milliseconds. + * @param matchFn pointer to a function that would return TRUE when + * the message matches its condition. + * @param src pointer to a variable to store the service id + * of the registered server which sent the retrieved + * message, or NULL if not interested in storing service id. + * @param dest pointer to a variable to store the entity id + * of the destination of the message, + * of NULL if not interested in storing the destination entity id. + * @param msg pointer to a pointer variable to store the + * starting address of the message body being + * retrieved. The pointer must not be NULL. + * @return @ref ICALL_ERRNO_SUCCESS when the operation was successful + * and a message was retrieved.
+ * @ref ICALL_ERRNO_TIMEOUT when designated timeout period + * has passed since the call of the function without + * the semaphore being signaled. + * @ref ICALL_ERRNO_UNKNOWN_THREAD when this function is + * called from a thread which has not registered + * an entity, either through ICall_enrollService() + * or through ICall_registerApp(). + */ +ICall_Errno ICall_waitMatch(uint_least32_t milliseconds, ICall_MsgMatchFn matchFn, ICall_ServiceEnum * src, ICall_EntityID * dest, + void ** msg) +{ + TaskHandle_t taskhandle = Task_self(); + ICall_TaskEntry * taskentry = ICall_searchTask(taskhandle); + ICall_MsgQueue prependQueue = NULL; +#ifndef ICALL_EVENTS + uint_fast16_t consumedCount = 0; +#endif + uint32_t timeout; + uint_fast32_t timeoutStamp; + ICall_Errno errno; + + if (!taskentry) + { + return (ICALL_ERRNO_UNKNOWN_THREAD); + } + /* Successful */ + if (milliseconds == 0) + { + timeout = BIOS_NO_WAIT; + } + else if (milliseconds == ICALL_TIMEOUT_FOREVER) + { + timeout = BIOS_WAIT_FOREVER; + } + else + { + /* Convert milliseconds to number of ticks */ + errno = ICall_msecs2Ticks(milliseconds, &timeout); + if (errno != ICALL_ERRNO_SUCCESS) + { + return (errno); + } + } + + errno = ICALL_ERRNO_TIMEOUT; + + timeoutStamp = ICall_getTicks() + timeout; + +#ifdef ICALL_LITE + + uint32_t events; + +#ifdef FREERTOS + // TODO: Investigate ICALL Wait tick period (Last parameter) + while (xQueueReceive(taskentry->syncHandle, (char *) &events, milliseconds * 1000) == pdPASS) +#endif +#else /* !ICALL_LITE */ + while (ICALL_SYNC_HANDLE_PEND(taskentry->syncHandle, timeout)) +#endif /* ICALL_LITE */ + { + ICall_EntityID fetchSrc; + ICall_EntityID fetchDst; + ICall_ServiceEnum servId; + void * fetchMsg; + errno = ICall_fetchMsg(&fetchSrc, &fetchDst, &fetchMsg); + if (errno == ICALL_ERRNO_SUCCESS) + { + if (ICall_primEntityId2ServiceId(fetchSrc, &servId) == ICALL_ERRNO_SUCCESS) + { + if (matchFn(servId, fetchDst, fetchMsg)) + { + /* Matching message found*/ + if (src != NULL) + { + *src = servId; + } + if (dest != NULL) + { + *dest = fetchDst; + } + *msg = fetchMsg; + errno = ICALL_ERRNO_SUCCESS; + break; + } + } + /* Message was received but it wasn't expected one. + * Add to the prepend queue */ + ICall_msgEnqueue(&prependQueue, fetchMsg); +#ifdef ICALL_EVENTS + /* Event are binary semaphore, so if several messsages are posted while + * we are processing one, it's possible that some of them are 'missed' and + * not processed. Sending a event to ourself force this loop to run until + * all the messages in the queue are processed. + */ +#ifdef ICALL_LITE + /* 0x20000000 is an internal Event_ID */ + uint32_t msg_ptr = (0x20000000); // Event_Id_29; + +#ifdef FREERTOS + + uint8_t status; + if (HwiP_inISR()) + { + status = xQueueSendFromISR(taskentry->syncHandle, (char *) &msg_ptr, NULL); + } + else + { + status = xQueueSend(taskentry->syncHandle, (char *) &msg_ptr, 0); + } + + if (status != pdTRUE) + { + return status; + } +#endif + +#else /* !ICALL_LITE */ + ICALL_SYNC_HANDLE_POST(taskentry->syncHandle); +#endif /* ICALL_LITE*/ +#endif /* ICALL_EVENTS */ + } + + /* Prepare for timeout exit */ + errno = ICALL_ERRNO_TIMEOUT; + +#ifndef ICALL_EVENTS + /* Keep the decremented semaphore count */ + consumedCount++; +#endif /* ICALL_EVENTS */ + if (timeout != BIOS_WAIT_FOREVER && timeout != BIOS_NO_WAIT) + { + /* Readjust timeout */ + uint32_t newTimeout = timeoutStamp - ICall_getTicks(); + + if (newTimeout == 0 || newTimeout > timeout) + { + break; + } + timeout = newTimeout; + } + } + + /* Prepend retrieved irrelevant messages */ + ICall_msgPrepend(&taskentry->queue, prependQueue); +#ifndef ICALL_EVENTS + /* Re-increment the consumed semaphores */ + for (; consumedCount > 0; consumedCount--) + { + Semaphore_post(taskentry->syncHandle); + } +#endif /* ICALL_EVENTS */ + return (errno); +} + +/** + * Retrieves an entity ID of (arbitrary) one of the entities registered + * from the calling thread. + * + * Note that, if multiple entities were registered from the same thread, + * this function shall arbitrarily pick one of the entities. + * + * @return A valid entity ID or @ref ICALL_INVALID_ENTITY_ID + * when no entity was registered from the calling thread. + */ +ICall_EntityID ICall_getEntityId(void) +{ + ICall_EntityID id; + TaskHandle_t taskhandle = Task_self(); + ICall_CSState key; + size_t i; + key = ICall_enterCSImpl(); + for (i = 0; i < ICALL_MAX_NUM_ENTITIES; i++) + { + if (ICall_entities[i].service == ICALL_SERVICE_CLASS_INVALID_ENTRY) + { + /* Not found */ + break; + } + if (ICall_entities[i].task->task == (TaskHandle_t) taskhandle) + { + /* Found */ + id = i; + ICall_leaveCSImpl(key); + return (id); + } + } + ICall_leaveCSImpl(key); + return ICALL_INVALID_ENTITY_ID; +} + +/** + * Checks whether the calling thread provides the designated service. + * + * @param service Service enumeration value for the service. + * + * @return Non-zero if the current thread provides the designated service. + * Zero, otherwise. + */ +uint_fast8_t ICall_threadServes(ICall_ServiceEnum service) +{ + uint_fast8_t res = 0; + TaskHandle_t taskhandle; + ICall_CSState key; + size_t i; + taskhandle = Task_self(); + + key = ICall_enterCSImpl(); + for (i = 0; i < ICALL_MAX_NUM_ENTITIES; i++) + { + if (ICall_entities[i].service == ICALL_SERVICE_CLASS_INVALID_ENTRY) + { + /* Not found */ + break; + } + else if (ICall_entities[i].service == service) + { + res = (uint_fast8_t) (ICall_entities[i].task->task == taskhandle); + } + } + ICall_leaveCSImpl(key); + return (res); +} + +/** + * Retrieves an internal ID understood only by a service entity, + * corresponding to an ICall entity ID. + * + * This function is used when a message body includes a field indicating a + * software entity and the destination of the message has its own internal + * message routing mechanism with its own entity enumeration system. + * + * @param service Service enumeration value for the service. + * Currently @ref ICALL_SERVICE_CLASS_BLE_MSG is supported. + * @param entity ICall entity ID. + * + * @return Stack specific 8 bit ID or 0xFF when failed. + */ +uint_fast8_t ICall_getLocalMsgEntityId(ICall_ServiceEnum service, ICall_EntityID entity) +{ + ICall_GetLocalMsgEntityIdArgs args; + ICall_Errno errno; + args.hdr.service = service; + args.hdr.func = ICALL_MSG_FUNC_GET_LOCAL_MSG_ENTITY_ID; + args.entity = entity; + errno = ICall_dispatcher(&args.hdr); + if (errno == ICALL_ERRNO_SUCCESS) + { + return (args.localId); + } + return (0xFF); +} + +#endif /* ICALL_JT */ + +#ifdef ICALL_LITE +/******************************************************************************* + * @fn matchLiteCS + */ +static bool matchLiteCS(ICall_ServiceEnum src, ICall_EntityID dest, const void * msg) +{ + (void) src; + (void) dest; + ICall_LiteCmdStatus * pMsg = (ICall_LiteCmdStatus *) msg; + return (pMsg->cmdId == ICALL_LITE_DIRECT_API_DONE_CMD_ID); +} +/******************************************************************************* + * @fn icall_directAPI + * see headers for details. + */ +uint32_t icall_directAPI(uint8_t service, icall_lite_id_t id, ...) +{ + va_list argp; + uint32_t res; + icallLiteMsg_t liteMsg; + + // The following will push all parameter in the runtime stack. + // This need to be call before any other local declaration of variable.... + va_start(argp, id); + + // Todo - add string for every icall API function, instead of printing function address + BLE_LOG_INT_INT(0, BLE_LOG_MODULE_APP, "APP : icall_directAPI to BLE func=0x%x, status=%d\n", id, 0); + // Create the message that will be send to the requested service.. + liteMsg.hdr.len = sizeof(icallLiteMsg_t); + liteMsg.hdr.next = NULL; + liteMsg.hdr.dest_id = ICALL_UNDEF_DEST_ID; + liteMsg.msg.directAPI = id; + liteMsg.msg.pointerStack = (uint32_t *) (*((uint32_t *) (&argp))); + ICall_sendServiceMsg(ICall_getEntityId(), service, ICALL_MSG_FORMAT_DIRECT_API_ID, &(liteMsg.msg)); + + // Since stack needs to always have a higher priority than the thread calling + // the API, when we reach this point the API has been executed by the stack. + // This implies the following: + // - API are not called in critical section or in section where task + // switching is disabled + // It is possible that the stack is blocking on this API, in this case a + // sync object needs to be used in order for this call to resume only when + // the API has been process in full. + { + ICall_Errno errno; + void * pCmdStatus = NULL; + + errno = ICall_waitMatch(ICALL_TIMEOUT_PREDEFINE, matchLiteCS, NULL, NULL, (void **) &pCmdStatus); + if (errno == ICALL_ERRNO_TIMEOUT) + { +#ifdef HALNODEBUG +#elif defined(EXT_HAL_ASSERT) + HAL_ASSERT(HAL_ASSERT_CAUSE_ICALL_TIMEOUT); +#else /* !EXT_HAL_ASSERT */ + ICall_abort(); +#endif /* EXT_HAL_ASSERT */ + } + else if (errno == ICALL_ERRNO_SUCCESS) + { + if (pCmdStatus) + { + ICall_freeMsg(pCmdStatus); + } + } + else + { +#ifdef HALNODEBUG +#else /* ! HALNODEBUG */ + ICall_abort(); +#endif /* HALNODEBUG */ + } + } + + // The return parameter is set in the runtime stack, at the location of the + // first parameter. + res = liteMsg.msg.pointerStack[0]; + + va_end(argp); + + return (res); +} + +/******************************************************************************* + * @fn ICall_sendServiceComplete + * see headers for details. + */ +ICall_Errno ICall_sendServiceComplete(ICall_EntityID src, ICall_EntityID dest, ICall_MSGFormat format, void * msg) +{ + ICall_CSState key; + ICall_MsgHdr * hdr = (ICall_MsgHdr *) msg - 1; + + if (dest >= ICALL_MAX_NUM_ENTITIES || src >= ICALL_MAX_NUM_ENTITIES) + { + return (ICALL_ERRNO_INVALID_PARAMETER); + } + key = ICall_enterCSImpl(); + if (!ICall_entities[dest].task) + { + ICall_leaveCSImpl(key); + return (ICALL_ERRNO_INVALID_PARAMETER); + } + + ICall_leaveCSImpl(key); + /* Note that once the entry is valid, + * the value does not change and hence it is OK + * to leave the critical section. + */ + + hdr->srcentity = src; + hdr->dstentity = dest; + hdr->format = format; + ICall_msgEnqueue(&ICall_entities[dest].task->queue, msg); + + /* 0x20000000 is an internal Event_ID */ + uint32_t msg_ptr = (0x20000000); // Event_Id_29; +#ifdef FREERTOS + uint8_t status; + if (HwiP_inISR()) + { + status = xQueueSendFromISR(ICall_entities[dest].task->syncHandle, (char *) &msg_ptr, NULL); + } + else + { + status = xQueueSend(ICall_entities[dest].task->syncHandle, (char *) &msg_ptr, 0); + } + + if (status != pdTRUE) + { + return status; + } +#endif + return (ICALL_ERRNO_SUCCESS); +} +#endif /* ICALL_LITE*/ diff --git a/third_party/ti_simplelink_sdk/ti_simplelink_sdk.gni b/third_party/ti_simplelink_sdk/ti_simplelink_sdk.gni index b3aae392cf..2bae18ab2a 100644 --- a/third_party/ti_simplelink_sdk/ti_simplelink_sdk.gni +++ b/third_party/ti_simplelink_sdk/ti_simplelink_sdk.gni @@ -360,6 +360,8 @@ template("ti_simplelink_sdk") { libs = [] defines = [ + "BLE_MANAGER_TASK_PRIORITY=5", + "BLE_STACK_TASK_PRIORITY=6", "INCLUDE_BGET_STATS", "USE_DMM", "NVOCMP_FREERTOS_MUTEX=1", @@ -523,10 +525,10 @@ template("ti_simplelink_sdk") { sources = [ "${chip_root}/src/platform/cc13xx_26xx/TI_heap_wrapper.c", "${chip_root}/src/platform/cc13xx_26xx/chipOBleProfile.c", + "${chip_root}/src/platform/cc13xx_26xx/icall_FreeRTOS.c", "${ti_simplelink_sdk_root}/source/ti/ble5stack/common/cc26xx/freertos/bget.c", "${ti_simplelink_sdk_root}/source/ti/ble5stack/common/cc26xx/rcosc/rcosc_calibration.c", "${ti_simplelink_sdk_root}/source/ti/dmm/apps/common/ble_remote_display/stack/osal_icall_ble.c", - "${ti_simplelink_sdk_root}/source/ti/dmm/apps/common/freertos/icall_FreeRTOS.c", "${ti_simplelink_sdk_root}/source/ti/dmm/apps/common/freertos/util.c", "${ti_simplelink_sdk_root}/source/ti/dmm/apps/common/thread/source/activity/dmm_thread_activity.c", "${ti_simplelink_sdk_root}/source/ti/dmm/dmm_priority_ble_thread.c", From d055e38c15e8bd0083e7b568641608993a2e8e3b Mon Sep 17 00:00:00 2001 From: cdj <45139296+DejinChen@users.noreply.github.com> Date: Fri, 16 Aug 2024 22:36:09 +0800 Subject: [PATCH 067/165] Use RootEndponId for reading SupportsConcurrentConnection in CNET_1_4 (#34972) --- src/python_testing/TC_CNET_1_4.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/python_testing/TC_CNET_1_4.py b/src/python_testing/TC_CNET_1_4.py index d7560c4fd0..58f885c9d5 100644 --- a/src/python_testing/TC_CNET_1_4.py +++ b/src/python_testing/TC_CNET_1_4.py @@ -98,7 +98,8 @@ async def test_TC_CNET_1_4(self): self.step(6) concurrent_connection = await self.read_single_attribute_check_success(cluster=Clusters.GeneralCommissioning, - attribute=Clusters.GeneralCommissioning.Attributes.SupportsConcurrentConnection) + attribute=Clusters.GeneralCommissioning.Attributes.SupportsConcurrentConnection, + endpoint=kRootEndpointId) asserts.assert_true(concurrent_connection, "The device does not support concurrent connection commissioning") From 7b32747d52c73ef5ab5ceae8f6bc76eabe416edf Mon Sep 17 00:00:00 2001 From: Alex Tsitsiura Date: Fri, 16 Aug 2024 18:02:22 +0300 Subject: [PATCH 068/165] [Telink] Disable Wi-Fi LPM during the OTA (#35006) * [Telink] Add OTAImageProcessorImplWiFi.h * [Telink] remove IPv4 temporarry debug configs --- config/telink/chip-module/Kconfig.defaults | 3 - src/platform/telink/BUILD.gn | 1 + .../telink/OTAImageProcessorImplWiFi.h | 63 +++++++++++++++++++ 3 files changed, 64 insertions(+), 3 deletions(-) create mode 100644 src/platform/telink/OTAImageProcessorImplWiFi.h diff --git a/config/telink/chip-module/Kconfig.defaults b/config/telink/chip-module/Kconfig.defaults index 9c27fe1059..45c8894722 100644 --- a/config/telink/chip-module/Kconfig.defaults +++ b/config/telink/chip-module/Kconfig.defaults @@ -304,9 +304,6 @@ config CHIP_WIFI select NET_IPV6_ND # enable Neighbor Discovery to handle Router Advertisements select NET_IPV6_NBR_CACHE select NET_STATISTICS_USER_API -# select NET_IPV4 # TODO: remove IPv4 when IPv6 will be ready (see CHIP_IPV4) -# select NET_CONFIG_NEED_IPV4 -# select NET_DHCPV4 if CHIP_WIFI diff --git a/src/platform/telink/BUILD.gn b/src/platform/telink/BUILD.gn index 4857c048af..93f6aaef5e 100644 --- a/src/platform/telink/BUILD.gn +++ b/src/platform/telink/BUILD.gn @@ -93,6 +93,7 @@ static_library("telink") { if (chip_enable_wifi) { sources += [ + "OTAImageProcessorImplWiFi.h", "wifi/ConnectivityManagerImplWiFi.cpp", "wifi/ConnectivityManagerImplWiFi.h", "wifi/TelinkWiFiDriver.cpp", diff --git a/src/platform/telink/OTAImageProcessorImplWiFi.h b/src/platform/telink/OTAImageProcessorImplWiFi.h new file mode 100644 index 0000000000..29f1db87f6 --- /dev/null +++ b/src/platform/telink/OTAImageProcessorImplWiFi.h @@ -0,0 +1,63 @@ +/* + * 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 "OTAImageProcessorImpl.h" +#include "wifi/WiFiManager.h" + +namespace chip { + +namespace DeviceLayer { + +class OTAImageProcessorImplWiFi : public OTAImageProcessorImpl +{ +public: + explicit OTAImageProcessorImplWiFi(ExternalFlashManager * flashHandler = nullptr) : OTAImageProcessorImpl(flashHandler) {} + + CHIP_ERROR PrepareDownload() override + { + CHIP_ERROR err = WiFiManager::Instance().SetLowPowerMode(false); + if (err == CHIP_NO_ERROR) + { + return OTAImageProcessorImpl::PrepareDownload(); + } + return err; + }; + + CHIP_ERROR Abort() override + { + CHIP_ERROR err = OTAImageProcessorImpl::Abort(); + if (err == CHIP_NO_ERROR) + { + return WiFiManager::Instance().SetLowPowerMode(true); + } + return err; + }; + + CHIP_ERROR Apply() override + { + CHIP_ERROR err = OTAImageProcessorImpl::Apply(); + if (err == CHIP_NO_ERROR) + { + return WiFiManager::Instance().SetLowPowerMode(true); + } + return err; + }; +}; + +} // namespace DeviceLayer +} // namespace chip From 2b0b1d8de1fd701115d75d60a7779dfd0fae1bfc Mon Sep 17 00:00:00 2001 From: Alex Tsitsiura Date: Fri, 16 Aug 2024 18:02:57 +0300 Subject: [PATCH 069/165] [Telink] w91 remove not connected PWM channels (#35005) * telink: w91 remowe PWM channels Signed-off-by: Dmytro Kashkarov * Restyled by whitespace --------- Signed-off-by: Dmytro Kashkarov Co-authored-by: Dmytro Kashkarov Co-authored-by: Restyled.io --- examples/platform/telink/common/src/AppTaskCommon.cpp | 5 +++-- src/platform/telink/tlsr9118bdk40d.overlay | 11 +---------- 2 files changed, 4 insertions(+), 12 deletions(-) diff --git a/examples/platform/telink/common/src/AppTaskCommon.cpp b/examples/platform/telink/common/src/AppTaskCommon.cpp index 59ad41b3c4..d2ad2a6fd8 100644 --- a/examples/platform/telink/common/src/AppTaskCommon.cpp +++ b/examples/platform/telink/common/src/AppTaskCommon.cpp @@ -414,8 +414,9 @@ void AppTaskCommon::InitPwms() void AppTaskCommon::LinkPwms(PwmManager & pwmManager) { -#if CONFIG_WS2812_STRIP || \ - CONFIG_BOARD_TLSR9118BDK40D // TLSR9118BDK40D EVK buttons located on 4th PWM channel (see tlsr9118bdk40d.overlay) +#if CONFIG_BOARD_TLSR9118BDK40D // TLSR9118BDK40D EVK supports only 1 PWM channel connected to LED + pwmManager.linkPwm(PwmManager::EAppPwm_Red, 0); +#elif CONFIG_WS2812_STRIP pwmManager.linkPwm(PwmManager::EAppPwm_Red, 0); pwmManager.linkPwm(PwmManager::EAppPwm_Green, 1); pwmManager.linkPwm(PwmManager::EAppPwm_Blue, 2); diff --git a/src/platform/telink/tlsr9118bdk40d.overlay b/src/platform/telink/tlsr9118bdk40d.overlay index 6dddbe61c9..3c44668724 100644 --- a/src/platform/telink/tlsr9118bdk40d.overlay +++ b/src/platform/telink/tlsr9118bdk40d.overlay @@ -33,16 +33,7 @@ pwm_pool { compatible = "pwm-leds"; out { - pwms = <&pwm0 4 PWM_MSEC(1) PWM_POLARITY_NORMAL>, - <&pwm0 2 PWM_MSEC(1) PWM_POLARITY_NORMAL>, - <&pwm0 3 PWM_MSEC(1) PWM_POLARITY_NORMAL>; + pwms = <&pwm0 4 PWM_MSEC(1) PWM_POLARITY_NORMAL>; }; }; -}; - -&pwm0 { - /* On board RGB LEDs */ - pinctrl-ch4 = <&pwm_ch4_p20_default>; - pinctrl-ch2 = <&pwm_ch2_p17_default>; - pinctrl-ch3 = <&pwm_ch3_p18_default>; }; \ No newline at end of file From 081598e6d811fe0a4f6384263e96f24e15986b3c Mon Sep 17 00:00:00 2001 From: Andrei Litvin Date: Fri, 16 Aug 2024 11:03:42 -0400 Subject: [PATCH 070/165] Optimize RAM utilization for WriteHandler (#34992) * Pull RAM usage reduction from write impl * remove some extra added includes * Apply review comment from previous PR --- src/app/WriteHandler.cpp | 66 ++++++++++++++++++++++++---------------- src/app/WriteHandler.h | 50 +++++++++++++++++++----------- 2 files changed, 71 insertions(+), 45 deletions(-) diff --git a/src/app/WriteHandler.cpp b/src/app/WriteHandler.cpp index 8d4a82d116..15776eb545 100644 --- a/src/app/WriteHandler.cpp +++ b/src/app/WriteHandler.cpp @@ -16,7 +16,6 @@ * limitations under the License. */ -#include "messaging/ExchangeContext.h" #include #include #include @@ -28,6 +27,7 @@ #include #include #include +#include #include #include @@ -62,7 +62,7 @@ void WriteHandler::Close() // successful. DeliverFinalListWriteEnd(false /* wasSuccessful */); mExchangeCtx.Release(); - mSuppressResponse = false; + mStateFlags.Clear(StateBits::kSuppressResponse); MoveToState(State::Uninitialized); } @@ -106,7 +106,7 @@ Status WriteHandler::OnWriteRequest(Messaging::ExchangeContext * apExchangeConte Status status = HandleWriteRequestMessage(apExchangeContext, std::move(aPayload), aIsTimedWrite); // The write transaction will be alive only when the message was handled successfully and there are more chunks. - if (!(status == Status::Success && mHasMoreChunks)) + if (!(status == Status::Success && mStateFlags.Has(StateBits::kHasMoreChunks))) { Close(); } @@ -142,7 +142,7 @@ CHIP_ERROR WriteHandler::OnMessageReceived(Messaging::ExchangeContext * apExchan if (status == Status::Success) { // We have no more chunks, the write response has been sent in HandleWriteRequestMessage, so close directly. - if (!mHasMoreChunks) + if (!mStateFlags.Has(StateBits::kHasMoreChunks)) { Close(); } @@ -184,8 +184,8 @@ CHIP_ERROR WriteHandler::SendWriteResponse(System::PacketBufferTLVWriter && aMes VerifyOrExit(mExchangeCtx, err = CHIP_ERROR_INCORRECT_STATE); mExchangeCtx->UseSuggestedResponseTimeout(app::kExpectedIMProcessingTime); err = mExchangeCtx->SendMessage(Protocols::InteractionModel::MsgType::WriteResponse, std::move(packet), - mHasMoreChunks ? Messaging::SendMessageFlags::kExpectResponse - : Messaging::SendMessageFlags::kNone); + mStateFlags.Has(StateBits::kHasMoreChunks) ? Messaging::SendMessageFlags::kExpectResponse + : Messaging::SendMessageFlags::kNone); SuccessOrExit(err); MoveToState(State::Sending); @@ -212,7 +212,7 @@ void WriteHandler::DeliverListWriteEnd(const ConcreteAttributePath & aPath, bool void WriteHandler::DeliverFinalListWriteEnd(bool writeWasSuccessful) { - if (mProcessingAttributePath.HasValue() && mProcessingAttributeIsList) + if (mProcessingAttributePath.HasValue() && mStateFlags.Has(StateBits::kProcessingAttributeIsList)) { DeliverListWriteEnd(mProcessingAttributePath.Value(), writeWasSuccessful); } @@ -221,7 +221,8 @@ void WriteHandler::DeliverFinalListWriteEnd(bool writeWasSuccessful) CHIP_ERROR WriteHandler::DeliverFinalListWriteEndForGroupWrite(bool writeWasSuccessful) { - VerifyOrReturnError(mProcessingAttributePath.HasValue() && mProcessingAttributeIsList, CHIP_NO_ERROR); + VerifyOrReturnError(mProcessingAttributePath.HasValue() && mStateFlags.Has(StateBits::kProcessingAttributeIsList), + CHIP_NO_ERROR); Credentials::GroupDataProvider::GroupEndpoint mapping; Credentials::GroupDataProvider * groupDataProvider = Credentials::GetGroupDataProvider(); @@ -321,18 +322,20 @@ CHIP_ERROR WriteHandler::ProcessAttributeDataIBs(TLV::TLVReader & aAttributeData continue; } - if (ShouldReportListWriteEnd(mProcessingAttributePath, mProcessingAttributeIsList, dataAttributePath)) + if (ShouldReportListWriteEnd(mProcessingAttributePath, mStateFlags.Has(StateBits::kProcessingAttributeIsList), + dataAttributePath)) { - DeliverListWriteEnd(mProcessingAttributePath.Value(), mAttributeWriteSuccessful); + DeliverListWriteEnd(mProcessingAttributePath.Value(), mStateFlags.Has(StateBits::kAttributeWriteSuccessful)); } - if (ShouldReportListWriteBegin(mProcessingAttributePath, mProcessingAttributeIsList, dataAttributePath)) + if (ShouldReportListWriteBegin(mProcessingAttributePath, mStateFlags.Has(StateBits::kProcessingAttributeIsList), + dataAttributePath)) { DeliverListWriteBegin(dataAttributePath); - mAttributeWriteSuccessful = true; + mStateFlags.Set(StateBits::kAttributeWriteSuccessful); } - mProcessingAttributeIsList = dataAttributePath.IsListOperation(); + mStateFlags.Set(StateBits::kProcessingAttributeIsList, dataAttributePath.IsListOperation()); mProcessingAttributePath.SetValue(dataAttributePath); DataModelCallbacks::GetInstance()->AttributeOperation(DataModelCallbacks::OperationType::Write, @@ -370,9 +373,9 @@ CHIP_ERROR WriteHandler::ProcessAttributeDataIBs(TLV::TLVReader & aAttributeData SuccessOrExit(err); - if (!mHasMoreChunks) + if (!mStateFlags.Has(StateBits::kHasMoreChunks)) { - DeliverFinalListWriteEnd(mAttributeWriteSuccessful); + DeliverFinalListWriteEnd(mStateFlags.Has(StateBits::kAttributeWriteSuccessful)); } exit: @@ -426,8 +429,8 @@ CHIP_ERROR WriteHandler::ProcessGroupAttributeDataIBs(TLV::TLVReader & aAttribut iterator = groupDataProvider->IterateEndpoints(fabric); VerifyOrExit(iterator != nullptr, err = CHIP_ERROR_NO_MEMORY); - bool shouldReportListWriteEnd = - ShouldReportListWriteEnd(mProcessingAttributePath, mProcessingAttributeIsList, dataAttributePath); + bool shouldReportListWriteEnd = ShouldReportListWriteEnd( + mProcessingAttributePath, mStateFlags.Has(StateBits::kProcessingAttributeIsList), dataAttributePath); bool shouldReportListWriteBegin = false; // This will be set below. const EmberAfAttributeMetadata * attributeMetadata = nullptr; @@ -457,7 +460,8 @@ CHIP_ERROR WriteHandler::ProcessGroupAttributeDataIBs(TLV::TLVReader & aAttribut dataAttributePath.mEndpointId, dataAttributePath.mListOp, dataAttributePath.mListIndex); shouldReportListWriteBegin = - ShouldReportListWriteBegin(mProcessingAttributePath, mProcessingAttributeIsList, pathForCheckingListWriteBegin); + ShouldReportListWriteBegin(mProcessingAttributePath, mStateFlags.Has(StateBits::kProcessingAttributeIsList), + pathForCheckingListWriteBegin); } if (shouldReportListWriteEnd) @@ -498,11 +502,10 @@ CHIP_ERROR WriteHandler::ProcessGroupAttributeDataIBs(TLV::TLVReader & aAttribut DataModelCallbacks::GetInstance()->AttributeOperation(DataModelCallbacks::OperationType::Write, DataModelCallbacks::OperationOrder::Pre, dataAttributePath); err = WriteSingleClusterData(subjectDescriptor, dataAttributePath, tmpDataReader, this); - if (err != CHIP_NO_ERROR) { ChipLogError(DataManagement, - "WriteSingleClusterData Endpoint=%u Cluster=" ChipLogFormatMEI " Attribute =" ChipLogFormatMEI + "WriteClusterData Endpoint=%u Cluster=" ChipLogFormatMEI " Attribute =" ChipLogFormatMEI " failed: %" CHIP_ERROR_FORMAT, mapping.endpoint_id, ChipLogValueMEI(dataAttributePath.mClusterId), ChipLogValueMEI(dataAttributePath.mAttributeId), err.Format()); @@ -512,7 +515,7 @@ CHIP_ERROR WriteHandler::ProcessGroupAttributeDataIBs(TLV::TLVReader & aAttribut } dataAttributePath.mEndpointId = kInvalidEndpointId; - mProcessingAttributeIsList = dataAttributePath.IsListOperation(); + mStateFlags.Set(StateBits::kProcessingAttributeIsList, dataAttributePath.IsListOperation()); mProcessingAttributePath.SetValue(dataAttributePath); iterator->Release(); } @@ -557,24 +560,33 @@ Status WriteHandler::ProcessWriteRequest(System::PacketBufferHandle && aPayload, #if CHIP_CONFIG_IM_PRETTY_PRINT writeRequestParser.PrettyPrint(); #endif - err = writeRequestParser.GetSuppressResponse(&mSuppressResponse); + bool boolValue; + + boolValue = mStateFlags.Has(StateBits::kSuppressResponse); + err = writeRequestParser.GetSuppressResponse(&boolValue); if (err == CHIP_END_OF_TLV) { err = CHIP_NO_ERROR; } SuccessOrExit(err); + mStateFlags.Set(StateBits::kSuppressResponse, boolValue); - err = writeRequestParser.GetTimedRequest(&mIsTimedRequest); + boolValue = mStateFlags.Has(StateBits::kIsTimedRequest); + err = writeRequestParser.GetTimedRequest(&boolValue); SuccessOrExit(err); + mStateFlags.Set(StateBits::kIsTimedRequest, boolValue); - err = writeRequestParser.GetMoreChunkedMessages(&mHasMoreChunks); + boolValue = mStateFlags.Has(StateBits::kHasMoreChunks); + err = writeRequestParser.GetMoreChunkedMessages(&boolValue); if (err == CHIP_ERROR_END_OF_TLV) { err = CHIP_NO_ERROR; } SuccessOrExit(err); + mStateFlags.Set(StateBits::kHasMoreChunks, boolValue); - if (mHasMoreChunks && (mExchangeCtx->IsGroupExchangeContext() || mIsTimedRequest)) + if (mStateFlags.Has(StateBits::kHasMoreChunks) && + (mExchangeCtx->IsGroupExchangeContext() || mStateFlags.Has(StateBits::kIsTimedRequest))) { // Sanity check: group exchange context should only have one chunk. // Also, timed requests should not have more than one chunk. @@ -584,7 +596,7 @@ Status WriteHandler::ProcessWriteRequest(System::PacketBufferHandle && aPayload, err = writeRequestParser.GetWriteRequests(&AttributeDataIBsParser); SuccessOrExit(err); - if (mIsTimedRequest != aIsTimedWrite) + if (mStateFlags.Has(StateBits::kIsTimedRequest) != aIsTimedWrite) { // The message thinks it should be part of a timed interaction but it's // not, or vice versa. @@ -641,7 +653,7 @@ CHIP_ERROR WriteHandler::AddStatusInternal(const ConcreteDataAttributePath & aPa if (!aStatus.IsSuccess()) { - mAttributeWriteSuccessful = false; + mStateFlags.Clear(StateBits::kAttributeWriteSuccessful); } ReturnErrorOnFailure(writeResponses.GetError()); diff --git a/src/app/WriteHandler.h b/src/app/WriteHandler.h index 1884654f07..0723a31673 100644 --- a/src/app/WriteHandler.h +++ b/src/app/WriteHandler.h @@ -17,12 +17,15 @@ */ #pragma once + +#include #include #include #include #include #include #include +#include #include #include #include @@ -68,9 +71,11 @@ class WriteHandler : public Messaging::ExchangeDelegate * * @param[in] apWriteHandlerDelegate A Valid pointer to the WriteHandlerDelegate. * + * @retval #CHIP_ERROR_INVALID_ARGUMENT on invalid pointers * @retval #CHIP_ERROR_INCORRECT_STATE If the state is not equal to * kState_NotInitialized. * @retval #CHIP_NO_ERROR On success. + * */ CHIP_ERROR Init(WriteHandlerDelegate * apWriteHandlerDelegate); @@ -115,7 +120,7 @@ class WriteHandler : public Messaging::ExchangeDelegate /** * Check whether the WriteRequest we are handling is a timed write. */ - bool IsTimedWrite() const { return mIsTimedRequest; } + bool IsTimedWrite() const { return mStateFlags.Has(StateBits::kIsTimedRequest); } bool MatchesExchangeContext(Messaging::ExchangeContext * apExchangeContext) const { @@ -136,7 +141,7 @@ class WriteHandler : public Messaging::ExchangeDelegate private: friend class TestWriteInteraction; - enum class State + enum class State : uint8_t { Uninitialized = 0, // The handler has not been initialized Initialized, // The handler has been initialized and is ready @@ -172,7 +177,6 @@ class WriteHandler : public Messaging::ExchangeDelegate CHIP_ERROR AddStatusInternal(const ConcreteDataAttributePath & aPath, const StatusIB & aStatus); -private: // ExchangeDelegate CHIP_ERROR OnMessageReceived(Messaging::ExchangeContext * apExchangeContext, const PayloadHeader & aPayloadHeader, System::PacketBufferHandle && aPayload) override; @@ -180,22 +184,7 @@ class WriteHandler : public Messaging::ExchangeDelegate Messaging::ExchangeHolder mExchangeCtx; WriteResponseMessage::Builder mWriteResponseBuilder; - State mState = State::Uninitialized; - bool mIsTimedRequest = false; - bool mSuppressResponse = false; - bool mHasMoreChunks = false; Optional mProcessingAttributePath; - bool mProcessingAttributeIsList = false; - // We record the Status when AddStatus is called to determine whether all data of a list write is accepted. - // This value will be used by DeliverListWriteEnd and DeliverFinalListWriteEnd but it won't be used by group writes based on the - // fact that the errors that won't be delivered to AttributeAccessInterface are: - // (1) Attribute not found - // (2) Access control failed - // (3) Write request to a read-only attribute - // (4) Data version mismatch - // (5) Not using timed write. - // Where (1)-(3) will be consistent among the whole list write request, while (4) and (5) are not appliable to group writes. - bool mAttributeWriteSuccessful = false; Optional mACLCheckCache = NullOptional; // This may be a "fake" pointer or a real delegate pointer, depending @@ -205,6 +194,31 @@ class WriteHandler : public Messaging::ExchangeDelegate // set to the global InteractionModelEngine and the size of this // member is 1 byte. InteractionModelDelegatePointer mDelegate; + + // bit level enums to save storage for this object. InteractionModelEngine maintains + // several of these objects, so every bit of storage multiplies storage usage. + enum class StateBits : uint8_t + { + kIsTimedRequest = 0x01, + kSuppressResponse = 0x02, + kHasMoreChunks = 0x04, + kProcessingAttributeIsList = 0x08, + // We record the Status when AddStatus is called to determine whether all data of a list write is accepted. + // This value will be used by DeliverListWriteEnd and DeliverFinalListWriteEnd but it won't be used by group writes based on + // the fact that the errors that won't be delivered to AttributeAccessInterface are: + // (1) Attribute not found + // (2) Access control failed + // (3) Write request to a read-only attribute + // (4) Data version mismatch + // (5) Not using timed write. + // Where (1)-(3) will be consistent among the whole list write request, while (4) and (5) are not appliable to group + // writes. + kAttributeWriteSuccessful = 0x10, + }; + + BitFlags mStateFlags; + State mState = State::Uninitialized; }; + } // namespace app } // namespace chip From 0da50e96245d312967fd2b720ac0c76af29af0a6 Mon Sep 17 00:00:00 2001 From: Arkadiusz Bokowy Date: Fri, 16 Aug 2024 17:04:48 +0200 Subject: [PATCH 071/165] [Tizen] Implement GetThreadVersion() for Thread driver (#34976) * [Tizen] Implement GetThreadVersion in thread stack manager * Move otThreadGetVersion() usage to Thread stack manager class * Update C++ style * Make GetThreadVersion public interface * Implement mock _GetThreadVersion() for Linux, NuttX and WebOS --- src/include/platform/ThreadStackManager.h | 6 +++ .../NetworkCommissioningThreadDriver.cpp | 6 +-- src/platform/Linux/ThreadStackManagerImpl.cpp | 7 ++++ src/platform/Linux/ThreadStackManagerImpl.h | 2 +- .../NetworkCommissioningThreadDriver.cpp | 6 +-- src/platform/NuttX/ThreadStackManagerImpl.cpp | 7 ++++ src/platform/NuttX/ThreadStackManagerImpl.h | 2 +- ...enericNetworkCommissioningThreadDriver.cpp | 4 +- ...GenericThreadStackManagerImpl_OpenThread.h | 41 ++++++++++--------- ...nericThreadStackManagerImpl_OpenThread.hpp | 35 +++++++++------- src/platform/OpenThread/OpenThreadUtils.cpp | 2 +- src/platform/OpenThread/OpenThreadUtils.h | 2 +- .../NetworkCommissioningThreadDriver.cpp | 14 +++---- src/platform/Tizen/ThreadStackManagerImpl.cpp | 15 +++++++ src/platform/Tizen/ThreadStackManagerImpl.h | 6 +-- .../NetworkCommissioningThreadDriver.cpp | 6 +-- src/platform/webos/ThreadStackManagerImpl.cpp | 7 ++++ src/platform/webos/ThreadStackManagerImpl.h | 2 +- 18 files changed, 109 insertions(+), 61 deletions(-) diff --git a/src/include/platform/ThreadStackManager.h b/src/include/platform/ThreadStackManager.h index a28aea640b..f9f7aed04e 100644 --- a/src/include/platform/ThreadStackManager.h +++ b/src/include/platform/ThreadStackManager.h @@ -105,6 +105,7 @@ class ThreadStackManager CHIP_ERROR GetAndLogThreadTopologyFull(); CHIP_ERROR GetPrimary802154MACAddress(uint8_t * buf); CHIP_ERROR GetExternalIPv6Address(chip::Inet::IPAddress & addr); + CHIP_ERROR GetThreadVersion(uint16_t & version); CHIP_ERROR GetPollPeriod(uint32_t & buf); CHIP_ERROR SetThreadProvision(ByteSpan aDataset); @@ -444,6 +445,11 @@ inline CHIP_ERROR ThreadStackManager::GetExternalIPv6Address(chip::Inet::IPAddre return static_cast(this)->_GetExternalIPv6Address(addr); } +inline CHIP_ERROR ThreadStackManager::GetThreadVersion(uint16_t & version) +{ + return static_cast(this)->_GetThreadVersion(version); +} + inline CHIP_ERROR ThreadStackManager::GetPollPeriod(uint32_t & buf) { return static_cast(this)->_GetPollPeriod(buf); diff --git a/src/platform/Linux/NetworkCommissioningThreadDriver.cpp b/src/platform/Linux/NetworkCommissioningThreadDriver.cpp index 9bb6015809..6792e9c044 100644 --- a/src/platform/Linux/NetworkCommissioningThreadDriver.cpp +++ b/src/platform/Linux/NetworkCommissioningThreadDriver.cpp @@ -211,9 +211,9 @@ ThreadCapabilities LinuxThreadDriver::GetSupportedThreadFeatures() uint16_t LinuxThreadDriver::GetThreadVersion() { - // TODO https://github.com/project-chip/connectedhomeip/issues/30602 - // Needs to be implemented with DBUS io.openthread.BorderRouter Thread API - return 0; + uint16_t version = 0; + ThreadStackMgrImpl().GetThreadVersion(version); + return version; } #endif // CHIP_DEVICE_CONFIG_ENABLE_THREAD diff --git a/src/platform/Linux/ThreadStackManagerImpl.cpp b/src/platform/Linux/ThreadStackManagerImpl.cpp index 126d301644..76fd478a05 100644 --- a/src/platform/Linux/ThreadStackManagerImpl.cpp +++ b/src/platform/Linux/ThreadStackManagerImpl.cpp @@ -563,6 +563,13 @@ CHIP_ERROR ThreadStackManagerImpl::_GetExternalIPv6Address(chip::Inet::IPAddress return CHIP_ERROR_NOT_IMPLEMENTED; } +CHIP_ERROR ThreadStackManagerImpl::_GetThreadVersion(uint16_t & version) +{ + // TODO https://github.com/project-chip/connectedhomeip/issues/30602 + // Needs to be implemented with DBUS io.openthread.BorderRouter Thread API + return CHIP_ERROR_NOT_IMPLEMENTED; +} + CHIP_ERROR ThreadStackManagerImpl::_GetPollPeriod(uint32_t & buf) { // TODO: Remove Weave legacy APIs diff --git a/src/platform/Linux/ThreadStackManagerImpl.h b/src/platform/Linux/ThreadStackManagerImpl.h index e9c1a825d3..685348a4ae 100755 --- a/src/platform/Linux/ThreadStackManagerImpl.h +++ b/src/platform/Linux/ThreadStackManagerImpl.h @@ -113,7 +113,7 @@ class ThreadStackManagerImpl : public ThreadStackManager CHIP_ERROR _GetPrimary802154MACAddress(uint8_t * buf); CHIP_ERROR _GetExternalIPv6Address(chip::Inet::IPAddress & addr); - + CHIP_ERROR _GetThreadVersion(uint16_t & version); CHIP_ERROR _GetPollPeriod(uint32_t & buf); void _ResetThreadNetworkDiagnosticsCounts(); diff --git a/src/platform/NuttX/NetworkCommissioningThreadDriver.cpp b/src/platform/NuttX/NetworkCommissioningThreadDriver.cpp index 79da48d49c..27c4104004 100644 --- a/src/platform/NuttX/NetworkCommissioningThreadDriver.cpp +++ b/src/platform/NuttX/NetworkCommissioningThreadDriver.cpp @@ -211,9 +211,9 @@ ThreadCapabilities LinuxThreadDriver::GetSupportedThreadFeatures() uint16_t LinuxThreadDriver::GetThreadVersion() { - // TODO https://github.com/project-chip/connectedhomeip/issues/30602 - // Needs to be implemented with DBUS io.openthread.BorderRouter Thread API - return 0; + uint16_t version = 0; + ThreadStackMgrImpl().GetThreadVersion(version); + return version; } #endif // CHIP_DEVICE_CONFIG_ENABLE_THREAD diff --git a/src/platform/NuttX/ThreadStackManagerImpl.cpp b/src/platform/NuttX/ThreadStackManagerImpl.cpp index cb717324fc..8eb1538128 100644 --- a/src/platform/NuttX/ThreadStackManagerImpl.cpp +++ b/src/platform/NuttX/ThreadStackManagerImpl.cpp @@ -568,6 +568,13 @@ CHIP_ERROR ThreadStackManagerImpl::_GetExternalIPv6Address(chip::Inet::IPAddress return CHIP_ERROR_NOT_IMPLEMENTED; } +CHIP_ERROR ThreadStackManagerImpl::_GetThreadVersion(uint16_t & version) +{ + // TODO https://github.com/project-chip/connectedhomeip/issues/30602 + // Needs to be implemented with DBUS io.openthread.BorderRouter Thread API + return CHIP_ERROR_NOT_IMPLEMENTED; +} + CHIP_ERROR ThreadStackManagerImpl::_GetPollPeriod(uint32_t & buf) { // TODO: Remove Weave legacy APIs diff --git a/src/platform/NuttX/ThreadStackManagerImpl.h b/src/platform/NuttX/ThreadStackManagerImpl.h index 5ef3d8ed36..ce66d51c22 100644 --- a/src/platform/NuttX/ThreadStackManagerImpl.h +++ b/src/platform/NuttX/ThreadStackManagerImpl.h @@ -114,7 +114,7 @@ class ThreadStackManagerImpl : public ThreadStackManager CHIP_ERROR _GetPrimary802154MACAddress(uint8_t * buf); CHIP_ERROR _GetExternalIPv6Address(chip::Inet::IPAddress & addr); - + CHIP_ERROR _GetThreadVersion(uint16_t & version); CHIP_ERROR _GetPollPeriod(uint32_t & buf); CHIP_ERROR _JoinerStart(); diff --git a/src/platform/OpenThread/GenericNetworkCommissioningThreadDriver.cpp b/src/platform/OpenThread/GenericNetworkCommissioningThreadDriver.cpp index 711ad4930f..0e7701ec48 100644 --- a/src/platform/OpenThread/GenericNetworkCommissioningThreadDriver.cpp +++ b/src/platform/OpenThread/GenericNetworkCommissioningThreadDriver.cpp @@ -325,7 +325,9 @@ ThreadCapabilities GenericThreadDriver::GetSupportedThreadFeatures() uint16_t GenericThreadDriver::GetThreadVersion() { - return otThreadGetVersion(); + uint16_t version = 0; + ThreadStackMgrImpl().GetThreadVersion(version); + return version; } } // namespace NetworkCommissioning diff --git a/src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread.h b/src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread.h index c45ff84bb0..169820c103 100644 --- a/src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread.h +++ b/src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread.h @@ -70,7 +70,7 @@ class GenericThreadStackManagerImpl_OpenThread otInstance * OTInstance() const; static void OnOpenThreadStateChange(uint32_t flags, void * context); - inline void OverrunErrorTally(void); + inline void OverrunErrorTally(); void SetNetworkStatusChangeCallback(NetworkCommissioning::Internal::BaseDriver::NetworkStatusChangeCallback * statusChangeCallback) { @@ -80,21 +80,21 @@ class GenericThreadStackManagerImpl_OpenThread protected: // ===== Methods that implement the ThreadStackManager abstract interface. - void _ProcessThreadActivity(void); + void _ProcessThreadActivity(); bool _HaveRouteToAddress(const Inet::IPAddress & destAddr); void _OnPlatformEvent(const ChipDeviceEvent * event); - bool _IsThreadEnabled(void); + bool _IsThreadEnabled(); CHIP_ERROR _SetThreadEnabled(bool val); - bool _IsThreadProvisioned(void); - bool _IsThreadAttached(void); + bool _IsThreadProvisioned(); + bool _IsThreadAttached(); CHIP_ERROR _GetThreadProvision(Thread::OperationalDataset & dataset); CHIP_ERROR _SetThreadProvision(ByteSpan netInfo); CHIP_ERROR _AttachToThreadNetwork(const Thread::OperationalDataset & dataset, NetworkCommissioning::Internal::WirelessDriver::ConnectCallback * callback); - void _OnThreadAttachFinished(void); - void _ErasePersistentInfo(void); - ConnectivityManager::ThreadDeviceType _GetThreadDeviceType(void); + void _OnThreadAttachFinished(); + void _ErasePersistentInfo(); + ConnectivityManager::ThreadDeviceType _GetThreadDeviceType(); CHIP_ERROR _SetThreadDeviceType(ConnectivityManager::ThreadDeviceType deviceType); CHIP_ERROR _StartThreadScan(NetworkCommissioning::ThreadDriver::ScanCallback * callback); static void _OnNetworkScanFinished(otActiveScanResult * aResult, void * aContext); @@ -105,16 +105,17 @@ class GenericThreadStackManagerImpl_OpenThread CHIP_ERROR _SetPollingInterval(System::Clock::Milliseconds32 pollingInterval); #endif // CHIP_CONFIG_ENABLE_ICD_SERVER - bool _HaveMeshConnectivity(void); - CHIP_ERROR _GetAndLogThreadStatsCounters(void); - CHIP_ERROR _GetAndLogThreadTopologyMinimal(void); - CHIP_ERROR _GetAndLogThreadTopologyFull(void); + bool _HaveMeshConnectivity(); + CHIP_ERROR _GetAndLogThreadStatsCounters(); + CHIP_ERROR _GetAndLogThreadTopologyMinimal(); + CHIP_ERROR _GetAndLogThreadTopologyFull(); CHIP_ERROR _GetPrimary802154MACAddress(uint8_t * buf); CHIP_ERROR _GetExternalIPv6Address(chip::Inet::IPAddress & addr); - void _ResetThreadNetworkDiagnosticsCounts(void); + CHIP_ERROR _GetThreadVersion(uint16_t & version); + void _ResetThreadNetworkDiagnosticsCounts(); CHIP_ERROR _GetPollPeriod(uint32_t & buf); - void _OnWoBLEAdvertisingStart(void); - void _OnWoBLEAdvertisingStop(void); + void _OnWoBLEAdvertisingStart(); + void _OnWoBLEAdvertisingStop(); #if CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT CHIP_ERROR _AddSrpService(const char * aInstanceName, const char * aName, uint16_t aPort, @@ -144,8 +145,8 @@ class GenericThreadStackManagerImpl_OpenThread CHIP_ERROR ConfigureThreadStack(otInstance * otInst); CHIP_ERROR DoInit(otInstance * otInst); - bool IsThreadAttachedNoLock(void); - bool IsThreadInterfaceUpNoLock(void); + bool IsThreadAttachedNoLock(); + bool IsThreadInterfaceUpNoLock(); private: // ===== Private members for use by this class only. @@ -282,19 +283,19 @@ inline otInstance * GenericThreadStackManagerImpl_OpenThread::OTInsta } template -inline void GenericThreadStackManagerImpl_OpenThread::OverrunErrorTally(void) +inline void GenericThreadStackManagerImpl_OpenThread::OverrunErrorTally() { mOverrunCount++; } template -inline void GenericThreadStackManagerImpl_OpenThread::_OnWoBLEAdvertisingStart(void) +inline void GenericThreadStackManagerImpl_OpenThread::_OnWoBLEAdvertisingStart() { // Do nothing by default. } template -inline void GenericThreadStackManagerImpl_OpenThread::_OnWoBLEAdvertisingStop(void) +inline void GenericThreadStackManagerImpl_OpenThread::_OnWoBLEAdvertisingStop() { // Do nothing by default. } diff --git a/src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread.hpp b/src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread.hpp index 61452f5ff0..6916c096c9 100644 --- a/src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread.hpp +++ b/src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread.hpp @@ -27,6 +27,7 @@ #define GENERIC_THREAD_STACK_MANAGER_IMPL_OPENTHREAD_IPP #include +#include #include #include @@ -59,7 +60,6 @@ #include #include -#include extern "C" void otSysProcessDrivers(otInstance * aInstance); #if CHIP_DEVICE_CONFIG_THREAD_ENABLE_CLI @@ -80,7 +80,7 @@ app::Clusters::NetworkCommissioning::Instance sThreadNetworkCommissioningInstance(CHIP_DEVICE_CONFIG_THREAD_NETWORK_ENDPOINT_ID /* Endpoint Id */, &sGenericThreadDriver); #endif -void initNetworkCommissioningThreadDriver(void) +void initNetworkCommissioningThreadDriver() { #ifndef _NO_GENERIC_THREAD_NETWORK_COMMISSIONING_DRIVER_ sThreadNetworkCommissioningInstance.Init(); @@ -143,7 +143,7 @@ void GenericThreadStackManagerImpl_OpenThread::OnOpenThreadStateChang } template -void GenericThreadStackManagerImpl_OpenThread::_ProcessThreadActivity(void) +void GenericThreadStackManagerImpl_OpenThread::_ProcessThreadActivity() { otTaskletsProcess(mOTInst); otSysProcessDrivers(mOTInst); @@ -256,7 +256,7 @@ void GenericThreadStackManagerImpl_OpenThread::_OnPlatformEvent(const } template -bool GenericThreadStackManagerImpl_OpenThread::_IsThreadEnabled(void) +bool GenericThreadStackManagerImpl_OpenThread::_IsThreadEnabled() { VerifyOrReturnValue(mOTInst, false); otDeviceRole curRole; @@ -330,7 +330,7 @@ CHIP_ERROR GenericThreadStackManagerImpl_OpenThread::_SetThreadProvis } template -bool GenericThreadStackManagerImpl_OpenThread::_IsThreadProvisioned(void) +bool GenericThreadStackManagerImpl_OpenThread::_IsThreadProvisioned() { VerifyOrReturnValue(mOTInst, false); bool provisioned; @@ -363,7 +363,7 @@ CHIP_ERROR GenericThreadStackManagerImpl_OpenThread::_GetThreadProvis } template -bool GenericThreadStackManagerImpl_OpenThread::_IsThreadAttached(void) +bool GenericThreadStackManagerImpl_OpenThread::_IsThreadAttached() { VerifyOrReturnValue(mOTInst, false); otDeviceRole curRole; @@ -525,7 +525,7 @@ void GenericThreadStackManagerImpl_OpenThread::_OnNetworkScanFinished } template -ConnectivityManager::ThreadDeviceType GenericThreadStackManagerImpl_OpenThread::_GetThreadDeviceType(void) +ConnectivityManager::ThreadDeviceType GenericThreadStackManagerImpl_OpenThread::_GetThreadDeviceType() { VerifyOrReturnValue(mOTInst, ConnectivityManager::kThreadDeviceType_NotSupported); ConnectivityManager::ThreadDeviceType deviceType; @@ -651,7 +651,7 @@ GenericThreadStackManagerImpl_OpenThread::_SetThreadDeviceType(Connec } template -bool GenericThreadStackManagerImpl_OpenThread::_HaveMeshConnectivity(void) +bool GenericThreadStackManagerImpl_OpenThread::_HaveMeshConnectivity() { VerifyOrReturnValue(mOTInst, false); bool res; @@ -700,7 +700,7 @@ bool GenericThreadStackManagerImpl_OpenThread::_HaveMeshConnectivity( } template -CHIP_ERROR GenericThreadStackManagerImpl_OpenThread::_GetAndLogThreadStatsCounters(void) +CHIP_ERROR GenericThreadStackManagerImpl_OpenThread::_GetAndLogThreadStatsCounters() { VerifyOrReturnError(mOTInst, CHIP_ERROR_INCORRECT_STATE); CHIP_ERROR err = CHIP_NO_ERROR; @@ -795,7 +795,7 @@ CHIP_ERROR GenericThreadStackManagerImpl_OpenThread::_GetAndLogThread } template -CHIP_ERROR GenericThreadStackManagerImpl_OpenThread::_GetAndLogThreadTopologyMinimal(void) +CHIP_ERROR GenericThreadStackManagerImpl_OpenThread::_GetAndLogThreadTopologyMinimal() { VerifyOrReturnError(mOTInst, CHIP_ERROR_INCORRECT_STATE); CHIP_ERROR err = CHIP_NO_ERROR; @@ -1072,7 +1072,14 @@ CHIP_ERROR GenericThreadStackManagerImpl_OpenThread::_GetExternalIPv6 } template -void GenericThreadStackManagerImpl_OpenThread::_ResetThreadNetworkDiagnosticsCounts(void) +CHIP_ERROR GenericThreadStackManagerImpl_OpenThread::_GetThreadVersion(uint16_t & version) +{ + version = otThreadGetVersion(); + return CHIP_NO_ERROR; +} + +template +void GenericThreadStackManagerImpl_OpenThread::_ResetThreadNetworkDiagnosticsCounts() { // Based on the spec, only OverrunCount should be resetted. mOverrunCount = 0; @@ -1175,14 +1182,14 @@ CHIP_ERROR GenericThreadStackManagerImpl_OpenThread::DoInit(otInstanc } template -bool GenericThreadStackManagerImpl_OpenThread::IsThreadAttachedNoLock(void) +bool GenericThreadStackManagerImpl_OpenThread::IsThreadAttachedNoLock() { otDeviceRole curRole = otThreadGetDeviceRole(mOTInst); return (curRole != OT_DEVICE_ROLE_DISABLED && curRole != OT_DEVICE_ROLE_DETACHED); } template -bool GenericThreadStackManagerImpl_OpenThread::IsThreadInterfaceUpNoLock(void) +bool GenericThreadStackManagerImpl_OpenThread::IsThreadInterfaceUpNoLock() { return otIp6IsEnabled(mOTInst); } @@ -1242,7 +1249,7 @@ CHIP_ERROR GenericThreadStackManagerImpl_OpenThread::_SetPollingInter #endif // CHIP_CONFIG_ENABLE_ICD_SERVER template -void GenericThreadStackManagerImpl_OpenThread::_ErasePersistentInfo(void) +void GenericThreadStackManagerImpl_OpenThread::_ErasePersistentInfo() { VerifyOrReturn(mOTInst); ChipLogProgress(DeviceLayer, "Erasing Thread persistent info..."); diff --git a/src/platform/OpenThread/OpenThreadUtils.cpp b/src/platform/OpenThread/OpenThreadUtils.cpp index 093997c66f..f2470b38ce 100644 --- a/src/platform/OpenThread/OpenThreadUtils.cpp +++ b/src/platform/OpenThread/OpenThreadUtils.cpp @@ -80,7 +80,7 @@ bool FormatOpenThreadError(char * buf, uint16_t bufSize, CHIP_ERROR err) /** * Register a text error formatter for OpenThread errors. */ -void RegisterOpenThreadErrorFormatter(void) +void RegisterOpenThreadErrorFormatter() { static ErrorFormatter sOpenThreadErrorFormatter = { FormatOpenThreadError, NULL }; diff --git a/src/platform/OpenThread/OpenThreadUtils.h b/src/platform/OpenThread/OpenThreadUtils.h index f9609e8d87..ab0cdd06a8 100644 --- a/src/platform/OpenThread/OpenThreadUtils.h +++ b/src/platform/OpenThread/OpenThreadUtils.h @@ -59,7 +59,7 @@ namespace Internal { #endif // CHIP_CONFIG_OPENTHREAD_ERROR_MAX extern CHIP_ERROR MapOpenThreadError(otError otErr); -extern void RegisterOpenThreadErrorFormatter(void); +extern void RegisterOpenThreadErrorFormatter(); /** * Log information related to a state change in the OpenThread stack. diff --git a/src/platform/Tizen/NetworkCommissioningThreadDriver.cpp b/src/platform/Tizen/NetworkCommissioningThreadDriver.cpp index 003564b4c9..f954e6c2fc 100644 --- a/src/platform/Tizen/NetworkCommissioningThreadDriver.cpp +++ b/src/platform/Tizen/NetworkCommissioningThreadDriver.cpp @@ -28,7 +28,6 @@ #include #include "NetworkCommissioningDriver.h" -#include "ThreadStackManagerImpl.h" namespace chip { namespace DeviceLayer { @@ -38,8 +37,8 @@ namespace NetworkCommissioning { CHIP_ERROR TizenThreadDriver::Init(BaseDriver::NetworkStatusChangeCallback * networkStatusChangeCallback) { - VerifyOrReturnError(ConnectivityMgrImpl().IsThreadAttached(), CHIP_NO_ERROR); - VerifyOrReturnError(ThreadStackMgrImpl().GetThreadProvision(mStagingNetwork) == CHIP_NO_ERROR, CHIP_NO_ERROR); + VerifyOrReturnError(ConnectivityMgr().IsThreadAttached(), CHIP_NO_ERROR); + VerifyOrReturnError(ThreadStackMgr().GetThreadProvision(mStagingNetwork) == CHIP_NO_ERROR, CHIP_NO_ERROR); mSavedNetwork.Init(mStagingNetwork.AsByteSpan()); @@ -133,7 +132,7 @@ void TizenThreadDriver::ConnectNetwork(ByteSpan networkId, ConnectCallback * cal (networkId.size() == Thread::kSizeExtendedPanId && memcmp(networkId.data(), extpanid, Thread::kSizeExtendedPanId) == 0), status = Status::kNetworkNotFound); - VerifyOrExit(DeviceLayer::ThreadStackMgrImpl().AttachToThreadNetwork(mStagingNetwork, callback) == CHIP_NO_ERROR, + VerifyOrExit(DeviceLayer::ThreadStackMgr().AttachToThreadNetwork(mStagingNetwork, callback) == CHIP_NO_ERROR, status = Status::kUnknownError); exit: @@ -145,7 +144,7 @@ void TizenThreadDriver::ConnectNetwork(ByteSpan networkId, ConnectCallback * cal void TizenThreadDriver::ScanNetworks(ThreadDriver::ScanCallback * callback) { - CHIP_ERROR err = DeviceLayer::ThreadStackMgrImpl().StartThreadScan(callback); + CHIP_ERROR err = DeviceLayer::ThreadStackMgr().StartThreadScan(callback); if (err != CHIP_NO_ERROR) { callback->OnFinished(Status::kUnknownError, CharSpan(), nullptr); @@ -179,8 +178,9 @@ ThreadCapabilities TizenThreadDriver::GetSupportedThreadFeatures() uint16_t TizenThreadDriver::GetThreadVersion() { - // TODO Needs to be implemented with Tizen Thread stack api - return 0; + uint16_t version = 0; + DeviceLayer::ThreadStackMgr().GetThreadVersion(version); + return version; } #endif // CHIP_DEVICE_CONFIG_ENABLE_THREAD diff --git a/src/platform/Tizen/ThreadStackManagerImpl.cpp b/src/platform/Tizen/ThreadStackManagerImpl.cpp index 950b6ec300..0ae0f8f84a 100644 --- a/src/platform/Tizen/ThreadStackManagerImpl.cpp +++ b/src/platform/Tizen/ThreadStackManagerImpl.cpp @@ -54,9 +54,12 @@ #include #include +#include #include #include +using chip::DeviceLayer::Internal::TizenToChipError; + namespace chip { namespace DeviceLayer { @@ -514,6 +517,18 @@ CHIP_ERROR ThreadStackManagerImpl::_GetExternalIPv6Address(chip::Inet::IPAddress return CHIP_ERROR_NOT_IMPLEMENTED; } +CHIP_ERROR ThreadStackManagerImpl::_GetThreadVersion(uint16_t & version) +{ + VerifyOrReturnError(mIsInitialized, CHIP_ERROR_UNINITIALIZED); + + int threadErr = thread_get_version(mThreadInstance, &version); + VerifyOrReturnError(threadErr == THREAD_ERROR_NONE, TizenToChipError(threadErr), + ChipLogError(DeviceLayer, "FAIL: Get thread version: %s", get_error_message(threadErr))); + + ChipLogProgress(DeviceLayer, "Thread version [%u]", version); + return CHIP_NO_ERROR; +} + CHIP_ERROR ThreadStackManagerImpl::_GetPollPeriod(uint32_t & buf) { ChipLogError(DeviceLayer, "Not implemented"); diff --git a/src/platform/Tizen/ThreadStackManagerImpl.h b/src/platform/Tizen/ThreadStackManagerImpl.h index 3c0206cfd5..2bb0954bc8 100644 --- a/src/platform/Tizen/ThreadStackManagerImpl.h +++ b/src/platform/Tizen/ThreadStackManagerImpl.h @@ -91,15 +91,11 @@ class ThreadStackManagerImpl : public ThreadStackManager bool _HaveMeshConnectivity(); CHIP_ERROR _GetAndLogThreadStatsCounters(); - CHIP_ERROR _GetAndLogThreadTopologyMinimal(); - CHIP_ERROR _GetAndLogThreadTopologyFull(); - CHIP_ERROR _GetPrimary802154MACAddress(uint8_t * buf); - CHIP_ERROR _GetExternalIPv6Address(chip::Inet::IPAddress & addr); - + CHIP_ERROR _GetThreadVersion(uint16_t & version); CHIP_ERROR _GetPollPeriod(uint32_t & buf); void _ResetThreadNetworkDiagnosticsCounts(); diff --git a/src/platform/webos/NetworkCommissioningThreadDriver.cpp b/src/platform/webos/NetworkCommissioningThreadDriver.cpp index 557d3f6f7f..7a9f5873d5 100644 --- a/src/platform/webos/NetworkCommissioningThreadDriver.cpp +++ b/src/platform/webos/NetworkCommissioningThreadDriver.cpp @@ -211,9 +211,9 @@ ThreadCapabilities LinuxThreadDriver::GetSupportedThreadFeatures() uint16_t LinuxThreadDriver::GetThreadVersion() { - // TODO https://github.com/project-chip/connectedhomeip/issues/30602 - // Needs to be implemented with DBUS io.openthread.BorderRouter Thread API - return 0; + uint16_t version = 0; + ThreadStackMgrImpl().GetThreadVersion(version); + return version; } #endif // CHIP_DEVICE_CONFIG_ENABLE_THREAD diff --git a/src/platform/webos/ThreadStackManagerImpl.cpp b/src/platform/webos/ThreadStackManagerImpl.cpp index cb538fa34e..cda82e673a 100644 --- a/src/platform/webos/ThreadStackManagerImpl.cpp +++ b/src/platform/webos/ThreadStackManagerImpl.cpp @@ -525,6 +525,13 @@ CHIP_ERROR ThreadStackManagerImpl::_GetExternalIPv6Address(chip::Inet::IPAddress return CHIP_ERROR_NOT_IMPLEMENTED; } +CHIP_ERROR ThreadStackManagerImpl::_GetThreadVersion(uint16_t & version) +{ + // TODO https://github.com/project-chip/connectedhomeip/issues/30602 + // Needs to be implemented with DBUS io.openthread.BorderRouter Thread API + return CHIP_ERROR_NOT_IMPLEMENTED; +} + CHIP_ERROR ThreadStackManagerImpl::_GetPollPeriod(uint32_t & buf) { // TODO: Remove Weave legacy APIs diff --git a/src/platform/webos/ThreadStackManagerImpl.h b/src/platform/webos/ThreadStackManagerImpl.h index b102e16ab5..64c3b8f620 100644 --- a/src/platform/webos/ThreadStackManagerImpl.h +++ b/src/platform/webos/ThreadStackManagerImpl.h @@ -101,7 +101,7 @@ class ThreadStackManagerImpl : public ThreadStackManager CHIP_ERROR _GetPrimary802154MACAddress(uint8_t * buf); CHIP_ERROR _GetExternalIPv6Address(chip::Inet::IPAddress & addr); - + CHIP_ERROR _GetThreadVersion(uint16_t & version); CHIP_ERROR _GetPollPeriod(uint32_t & buf); void _ResetThreadNetworkDiagnosticsCounts(); From eaddbe33b21a5ec0cca0f8a9b25a08d7c53d41cf Mon Sep 17 00:00:00 2001 From: Andrei Litvin Date: Fri, 16 Aug 2024 11:32:18 -0400 Subject: [PATCH 072/165] Copy over data model flags (#34995) --- scripts/build/build/targets.py | 10 ++++++---- scripts/build/builders/host.py | 10 +++++----- scripts/build/testdata/all_targets_linux_x64.txt | 2 +- 3 files changed, 12 insertions(+), 10 deletions(-) diff --git a/scripts/build/build/targets.py b/scripts/build/build/targets.py index bf21adf48e..8ab6e2ca4e 100755 --- a/scripts/build/build/targets.py +++ b/scripts/build/build/targets.py @@ -110,10 +110,9 @@ def BuildHostTarget(): TargetPart('all-clusters-minimal', app=HostApp.ALL_CLUSTERS_MINIMAL), TargetPart('chip-tool', app=HostApp.CHIP_TOOL), TargetPart('thermostat', app=HostApp.THERMOSTAT), - TargetPart('java-matter-controller', - app=HostApp.JAVA_MATTER_CONTROLLER), - TargetPart('kotlin-matter-controller', - app=HostApp.KOTLIN_MATTER_CONTROLLER), + # 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('minmdns', app=HostApp.MIN_MDNS), TargetPart('light', app=HostApp.LIGHT), TargetPart('lock', app=HostApp.LOCK), @@ -189,6 +188,9 @@ 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)') return target diff --git a/scripts/build/builders/host.py b/scripts/build/builders/host.py index 4ea5a9aae0..8c03ac7b13 100644 --- a/scripts/build/builders/host.py +++ b/scripts/build/builders/host.py @@ -317,7 +317,8 @@ def __init__(self, root, runner, app: HostApp, board=HostBoard.NATIVE, minmdns_high_verbosity=False, imgui_ui=False, crypto_library: HostCryptoLibrary = None, enable_test_event_triggers=None, enable_dnssd_tests: Optional[bool] = None, - chip_casting_simplified: Optional[bool] = None + chip_casting_simplified: Optional[bool] = None, + data_model_interface: Optional[bool] = None, ): super(HostBuilder, self).__init__( root=os.path.join(root, 'examples', app.ExamplePath()), @@ -352,6 +353,9 @@ 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') @@ -457,10 +461,6 @@ def __init__(self, root, runner, app: HostApp, board=HostBoard.NATIVE, if self.app == HostApp.SIMULATED_APP2: self.extra_gn_options.append('chip_tests_zap_config="app2"') - if self.app in {HostApp.JAVA_MATTER_CONTROLLER, HostApp.KOTLIN_MATTER_CONTROLLER}: - # TODO: controllers depending on a datamodel is odd. For now fix compile dependencies on ember. - self.extra_gn_options.append('chip_use_data_model_interface="disabled"') - if self.app == HostApp.TESTS and fuzzing_type != HostFuzzingType.NONE: self.build_command = 'fuzz_tests' diff --git a/scripts/build/testdata/all_targets_linux_x64.txt b/scripts/build/testdata/all_targets_linux_x64.txt index a8e5b8770c..d202b8aea3 100644 --- a/scripts/build/testdata/all_targets_linux_x64.txt +++ b/scripts/build/testdata/all_targets_linux_x64.txt @@ -9,7 +9,7 @@ efr32-{brd2704b,brd4316a,brd4317a,brd4318a,brd4319a,brd4186a,brd4187a,brd2601b,b 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][-coverage][-dmalloc][-clang] -linux-{x64,arm64}-{rpc-console,all-clusters,all-clusters-minimal,chip-tool,thermostat,java-matter-controller,kotlin-matter-controller,minmdns,light,lock,shell,ota-provider,ota-requestor,simulated-app1,simulated-app2,python-bindings,tv-app,tv-casting-app,bridge,fabric-admin,fabric-bridge,tests,chip-cert,address-resolve-tool,contact-sensor,dishwasher,microwave-oven,refrigerator,rvc,air-purifier,lit-icd,air-quality-sensor,network-manager,energy-management}[-nodeps][-nlfaultinject][-platform-mdns][-minmdns-verbose][-libnl][-same-event-loop][-no-interactive][-ipv6only][-no-ble][-no-wifi][-no-thread][-mbedtls][-boringssl][-asan][-tsan][-ubsan][-libfuzzer][-ossfuzz][-coverage][-dmalloc][-clang][-test][-rpc][-with-ui][-evse-test-event][-enable-dnssd-tests][-disable-dnssd-tests][-chip-casting-simplified] +linux-{x64,arm64}-{rpc-console,all-clusters,all-clusters-minimal,chip-tool,thermostat,java-matter-controller,kotlin-matter-controller,minmdns,light,lock,shell,ota-provider,ota-requestor,simulated-app1,simulated-app2,python-bindings,tv-app,tv-casting-app,bridge,fabric-admin,fabric-bridge,tests,chip-cert,address-resolve-tool,contact-sensor,dishwasher,microwave-oven,refrigerator,rvc,air-purifier,lit-icd,air-quality-sensor,network-manager,energy-management}[-nodeps][-nlfaultinject][-platform-mdns][-minmdns-verbose][-libnl][-same-event-loop][-no-interactive][-ipv6only][-no-ble][-no-wifi][-no-thread][-mbedtls][-boringssl][-asan][-tsan][-ubsan][-libfuzzer][-ossfuzz][-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] 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] From 18fefb1d2cf5ea23dc38595db7a109e21a664b25 Mon Sep 17 00:00:00 2001 From: C Freeman Date: Fri, 16 Aug 2024 12:44:35 -0400 Subject: [PATCH 073/165] TC-IDM-10.5: Plumb through allow_provisional flag (#35037) --- src/python_testing/TC_DeviceConformance.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/python_testing/TC_DeviceConformance.py b/src/python_testing/TC_DeviceConformance.py index 2a0fe309f2..d847ef6aeb 100644 --- a/src/python_testing/TC_DeviceConformance.py +++ b/src/python_testing/TC_DeviceConformance.py @@ -354,7 +354,8 @@ def test_TC_IDM_10_3(self): def test_TC_IDM_10_5(self): fail_on_extra_clusters = self.user_params.get("fail_on_extra_clusters", True) - success, problems = self.check_device_type(fail_on_extra_clusters) + allow_provisional = self.user_params.get("allow_provisional", False) + success, problems = self.check_device_type(fail_on_extra_clusters, allow_provisional) self.problems.extend(problems) if not success: self.fail_current_test("Problems with Device type conformance on one or more endpoints") From bbc773a07f0953fe19760ac9c8375a2f23ffbac7 Mon Sep 17 00:00:00 2001 From: William Date: Fri, 16 Aug 2024 18:11:05 +0100 Subject: [PATCH 074/165] Fixes the Service Area server's `SkipArea` handling (#35019) * Updated the rvc-example PICS XML files. * update the handling of the SkipArea command to match the latest spec. * Updated the name of SkipCurrentArea to SkipArea in the Instance and Delegate classes. * Refactored SkipCurrentArea names to SkipArea in the RVC example app. * Restyled by clang-format --------- Co-authored-by: Restyled.io --- .../rvc-app/rvc-common/include/rvc-device.h | 4 +- .../include/rvc-service-area-delegate.h | 14 +- .../pics/RVC Clean Mode Cluster Test Plan.xml | 66 +++-- ...VC Operational State Cluster Test Plan.xml | 92 ++++--- .../pics/RVC Run Mode Cluster Test Plan.xml | 83 +++--- .../pics/Service Area Cluster Test Plan.xml | 243 ++++++++++++++++++ .../rvc-app/rvc-common/src/rvc-device.cpp | 2 +- .../src/rvc-service-area-delegate.cpp | 4 +- .../service-area-delegate.h | 2 +- .../service-area-server.cpp | 16 +- .../service-area-server/service-area-server.h | 2 +- 11 files changed, 399 insertions(+), 129 deletions(-) create mode 100644 examples/rvc-app/rvc-common/pics/Service Area Cluster Test Plan.xml diff --git a/examples/rvc-app/rvc-common/include/rvc-device.h b/examples/rvc-app/rvc-common/include/rvc-device.h index b66ce3251f..e2011f6c83 100644 --- a/examples/rvc-app/rvc-common/include/rvc-device.h +++ b/examples/rvc-app/rvc-common/include/rvc-device.h @@ -61,7 +61,7 @@ class RvcDevice mOperationalStateDelegate.SetGoHomeCallback(&RvcDevice::HandleOpStateGoHomeCallback, this); mServiceAreaDelegate.SetIsSetSelectedAreasAllowedCallback(&RvcDevice::SaIsSetSelectedAreasAllowed, this); - mServiceAreaDelegate.SetHandleSkipCurrentAreaCallback(&RvcDevice::SaHandleSkipCurrentArea, this); + mServiceAreaDelegate.SetHandleSkipAreaCallback(&RvcDevice::SaHandleSkipArea, this); mServiceAreaDelegate.SetIsSupportedAreasChangeAllowedCallback(&RvcDevice::SaIsSupportedAreasChangeAllowed, this); mServiceAreaDelegate.SetIsSupportedMapChangeAllowedCallback(&RvcDevice::SaIsSupportedMapChangeAllowed, this); } @@ -104,7 +104,7 @@ class RvcDevice bool SaIsSetSelectedAreasAllowed(MutableCharSpan & statusText); - bool SaHandleSkipCurrentArea(uint32_t skippedArea, MutableCharSpan & skipStatusText); + bool SaHandleSkipArea(uint32_t skippedArea, MutableCharSpan & skipStatusText); bool SaIsSupportedAreasChangeAllowed(); diff --git a/examples/rvc-app/rvc-common/include/rvc-service-area-delegate.h b/examples/rvc-app/rvc-common/include/rvc-service-area-delegate.h index fdad4f83f0..c6be8aa5bb 100644 --- a/examples/rvc-app/rvc-common/include/rvc-service-area-delegate.h +++ b/examples/rvc-app/rvc-common/include/rvc-service-area-delegate.h @@ -30,7 +30,7 @@ namespace Clusters { class RvcDevice; typedef bool (RvcDevice::*IsSetSelectedAreasAllowedCallback)(MutableCharSpan & statusText); -typedef bool (RvcDevice::*HandleSkipCurrentAreaCallback)(uint32_t skippedArea, MutableCharSpan & skipStatusText); +typedef bool (RvcDevice::*HandleSkipAreaCallback)(uint32_t skippedArea, MutableCharSpan & skipStatusText); typedef bool (RvcDevice::*IsChangeAllowedSimpleCallback)(); namespace ServiceArea { @@ -46,8 +46,8 @@ class RvcServiceAreaDelegate : public Delegate RvcDevice * mIsSetSelectedAreasAllowedDeviceInstance; IsSetSelectedAreasAllowedCallback mIsSetSelectedAreasAllowedCallback; - RvcDevice * mHandleSkipCurrentAreaDeviceInstance; - HandleSkipCurrentAreaCallback mHandleSkipCurrentAreaCallback; + RvcDevice * mHandleSkipAreaDeviceInstance; + HandleSkipAreaCallback mHandleSkipAreaCallback; RvcDevice * mIsSupportedAreasChangeAllowedDeviceInstance; IsChangeAllowedSimpleCallback mIsSupportedAreasChangeAllowedCallback; RvcDevice * mIsSupportedMapChangeAllowedDeviceInstance; @@ -82,7 +82,7 @@ class RvcServiceAreaDelegate : public Delegate bool IsValidSelectAreasSet(const ServiceArea::Commands::SelectAreas::DecodableType & req, ServiceArea::SelectAreasStatus & areaStatus, MutableCharSpan & statusText) override; - bool HandleSkipCurrentArea(uint32_t skippedArea, MutableCharSpan & skipStatusText) override; + bool HandleSkipArea(uint32_t skippedArea, MutableCharSpan & skipStatusText) override; //************************************************************************* // Supported Areas accessors @@ -169,10 +169,10 @@ class RvcServiceAreaDelegate : public Delegate mIsSetSelectedAreasAllowedDeviceInstance = instance; } - void SetHandleSkipCurrentAreaCallback(HandleSkipCurrentAreaCallback callback, RvcDevice * instance) + void SetHandleSkipAreaCallback(HandleSkipAreaCallback callback, RvcDevice * instance) { - mHandleSkipCurrentAreaCallback = callback; - mHandleSkipCurrentAreaDeviceInstance = instance; + mHandleSkipAreaCallback = callback; + mHandleSkipAreaDeviceInstance = instance; } void SetIsSupportedAreasChangeAllowedCallback(IsChangeAllowedSimpleCallback callback, RvcDevice * instance) diff --git a/examples/rvc-app/rvc-common/pics/RVC Clean Mode Cluster Test Plan.xml b/examples/rvc-app/rvc-common/pics/RVC Clean Mode Cluster Test Plan.xml index ce0ddaa38b..fa0b258557 100644 --- a/examples/rvc-app/rvc-common/pics/RVC Clean Mode Cluster Test Plan.xml +++ b/examples/rvc-app/rvc-common/pics/RVC Clean Mode Cluster Test Plan.xml @@ -1,13 +1,20 @@ - + RVC Clean Mode Cluster Test Plan @@ -16,7 +23,7 @@ Draft RVCCLEANM.S Does the device implement the RVCCLEANM cluster as a server? - 89.1. Role - allclusters.html[pdf] + 99.1. Role - allclusters.html[pdf] O true @@ -26,16 +33,14 @@ Draft PIXIT.RVCCLEANM.MODE_CHANGE_FAIL Id of mode the device will fail to transition to, given its current state - 90. PIXIT Definition - allclusters.html[pdf] - O - 0x01 + 100. PIXIT Definition - allclusters.html[pdf] + On/a PIXIT.RVCCLEANM.MODE_CHANGE_OK Id of mode the device will successfully transition to, given its current state - 90. PIXIT Definition - allclusters.html[pdf] - O - 0x01 + 100. PIXIT Definition - allclusters.html[pdf] + On/a @@ -45,31 +50,17 @@ Draft RVCCLEANM.S.A0000 Does the device implement the SupportedModes attribute? - 89.2.2. Attributes - allclusters.html[pdf] + 99.2.1. Attributes - allclusters.html[pdf] M true RVCCLEANM.S.A0001 Does the device implement the CurrentMode attribute? - 89.2.2. Attributes - allclusters.html[pdf] + 99.2.1. Attributes - allclusters.html[pdf] M true - - RVCCLEANM.S.A0002 - Does the device implement the StartUpMode attribute? - 89.2.2. Attributes - allclusters.html[pdf] - O - false - - - RVCCLEANM.S.A0003 - Does the device implement the OnMode attribute? - 89.2.2. Attributes - allclusters.html[pdf] - M - false - @@ -78,7 +69,7 @@ Draft RVCCLEANM.S.C01.Tx Does the device implement sending the ChangeToModeResponse command? - 89.2.4. Commands generated - allclusters.html[pdf] + 99.2.3. Commands generated - allclusters.html[pdf] M true @@ -88,7 +79,7 @@ Draft RVCCLEANM.S.C00.Rsp Does the device implement receiving the ChangeToMode command? - 89.2.3. Commands received - allclusters.html[pdf] + 99.2.2. Commands received - allclusters.html[pdf] M true @@ -96,9 +87,9 @@ Draft - RVCCLEANM.S.F00 - Does the device support depending on an On/Off cluster implemented on the same endpoint? - 89.2.1. Features - allclusters.html[pdf] + RVCCLEANM.S.F16 + Does the device support changing clean modes from non-Idle states? + 101.1. Features - allclusters.html[pdf] O false @@ -108,10 +99,17 @@ Draft RVCCLEANM.S.M.CAN_TEST_MODE_FAILURE Does the DUT support testing the failed ChangeToMode command? - 89.2.5. Manual controllable - allclusters.html[pdf] + 99.2.4. Manual controllable - allclusters.html[pdf] O true + + RVCCLEANM.S.M.CAN_MANUALLY_CONTROLLED + Can the mode change be manually controlled? + 99.2.4. Manual controllable - allclusters.html[pdf] + O + false + diff --git a/examples/rvc-app/rvc-common/pics/RVC Operational State Cluster Test Plan.xml b/examples/rvc-app/rvc-common/pics/RVC Operational State Cluster Test Plan.xml index c600445a35..59028fa95e 100644 --- a/examples/rvc-app/rvc-common/pics/RVC Operational State Cluster Test Plan.xml +++ b/examples/rvc-app/rvc-common/pics/RVC Operational State Cluster Test Plan.xml @@ -1,11 +1,11 @@ RVC Operational State Cluster Test Plan @@ -15,8 +15,8 @@ Draft RVCOPSTATE.S - Does the device implement the RVC Operational State cluster as a server? - 223.1. Role - allclusters.html[pdf] + Does the device implement the RVC Operational State Cluster as a server? + 238.1. Role - allclusters.html[pdf] O true @@ -30,42 +30,42 @@ Draft RVCOPSTATE.S.A0000 Does the device implement the PhaseList attribute? - 223.2.1. Attributes - allclusters.html[pdf] + 238.2.1. Attributes - allclusters.html[pdf] M true RVCOPSTATE.S.A0001 Does the device implement the CurrentPhase attribute? - 223.2.1. Attributes - allclusters.html[pdf] + 238.2.1. Attributes - allclusters.html[pdf] M true RVCOPSTATE.S.A0002 Does the device implement the CountdownTime attribute? - 223.2.1. Attributes - allclusters.html[pdf] + 238.2.1. Attributes - allclusters.html[pdf] O false RVCOPSTATE.S.A0003 Does the device implement the OperationalStateList attribute? - 223.2.1. Attributes - allclusters.html[pdf] + 238.2.1. Attributes - allclusters.html[pdf] M true RVCOPSTATE.S.A0004 Does the device implement the OperationalState attribute? - 223.2.1. Attributes - allclusters.html[pdf] + 238.2.1. Attributes - allclusters.html[pdf] M true RVCOPSTATE.S.A0005 Does the device implement the OperationalError attribute? - 223.2.1. Attributes - allclusters.html[pdf] + 238.2.1. Attributes - allclusters.html[pdf] M true @@ -75,14 +75,14 @@ Draft RVCOPSTATE.S.E00 Does the device implement the OperationalError Event ? - 223.2.4. Events - allclusters.html[pdf] + 238.2.4. Events - allclusters.html[pdf] M true RVCOPSTATE.S.E01 Does the device implement the OperationCompletion Event ? - 223.2.4. Events - allclusters.html[pdf] + 238.2.4. Events - allclusters.html[pdf] O true @@ -92,8 +92,8 @@ Draft RVCOPSTATE.S.C04.Tx Does the device implement generating the OperationalCommandResponse command? - 223.2.3. Commands generated - allclusters.html[pdf] - M + 238.2.3. Commands generated - allclusters.html[pdf] + M true @@ -102,28 +102,35 @@ Draft RVCOPSTATE.S.C00.Rsp Does the device implement receiving the Pause command? - 223.2.2. Commands received - allclusters.html[pdf] + 238.2.2. Commands received - allclusters.html[pdf] O true RVCOPSTATE.S.C01.Rsp Does the device implement receiving the Stop command? - 223.2.2. Commands received - allclusters.html[pdf] + 238.2.2. Commands received - allclusters.html[pdf] O false RVCOPSTATE.S.C02.Rsp Does the device implement receiving the Start command? - 223.2.2. Commands received - allclusters.html[pdf] + 238.2.2. Commands received - allclusters.html[pdf] O false RVCOPSTATE.S.C03.Rsp Does the device implement receiving the Resume command? - 223.2.2. Commands received - allclusters.html[pdf] + 238.2.2. Commands received - allclusters.html[pdf] + O + true + + + RVCOPSTATE.S.C80.Rsp + Does the device implement receiving the GoHome command? + 238.2.2. Commands received - allclusters.html[pdf] O true @@ -135,136 +142,143 @@ Draft RVCOPSTATE.S.M.ST_STOPPED Does the DUT support testing the Stopped(0x00) operational state? - 223.2.5. Manual controllable - allclusters.html[pdf] + 238.2.5. Manual controllable - allclusters.html[pdf] O true RVCOPSTATE.S.M.ST_RUNNING Does the DUT support testing the Running(0x01) operational state? - 223.2.5. Manual controllable - allclusters.html[pdf] + 238.2.5. Manual controllable - allclusters.html[pdf] O true RVCOPSTATE.S.M.ST_PAUSED Does the DUT support testing the Paused(0x02) operational state? - 223.2.5. Manual controllable - allclusters.html[pdf] + 238.2.5. Manual controllable - allclusters.html[pdf] O true RVCOPSTATE.S.M.ST_ERROR Does the DUT support testing the Error(0x03) operational state? - 223.2.5. Manual controllable - allclusters.html[pdf] + 238.2.5. Manual controllable - allclusters.html[pdf] O true RVCOPSTATE.S.M.ST_SEEKING_CHARGER Does the DUT support testing the SeekingCharger(0x40) operational state? - 223.2.5. Manual controllable - allclusters.html[pdf] + 238.2.5. Manual controllable - allclusters.html[pdf] O true RVCOPSTATE.S.M.ST_CHARGING Does the DUT support testing the Charging(0x41) operational state? - 223.2.5. Manual controllable - allclusters.html[pdf] + 238.2.5. Manual controllable - allclusters.html[pdf] O true RVCOPSTATE.S.M.ST_DOCKED Does the DUT support testing the Docked(0x42) operational state? - 223.2.5. Manual controllable - allclusters.html[pdf] + 238.2.5. Manual controllable - allclusters.html[pdf] O true RVCOPSTATE.S.M.ERR_NO_ERROR Does the DUT support testing the NoError(0x00) error state? - 223.2.5. Manual controllable - allclusters.html[pdf] + 238.2.5. Manual controllable - allclusters.html[pdf] O true RVCOPSTATE.S.M.ERR_UNABLE_TO_START_OR_RESUME Does the DUT support testing the UnableToStartOrResume(0x01) error state? - 223.2.5. Manual controllable - allclusters.html[pdf] + 238.2.5. Manual controllable - allclusters.html[pdf] O true RVCOPSTATE.S.M.ERR_UNABLE_TO_COMPLETE_OPERATION Does the DUT support testing the UnableToCompleteOperation(0x02) error state? - 223.2.5. Manual controllable - allclusters.html[pdf] + 238.2.5. Manual controllable - allclusters.html[pdf] O true RVCOPSTATE.S.M.ERR_COMMAND_INVALID_IN_STATE Does the DUT support testing the CommandInvalidInState(0x03) error state? - 223.2.5. Manual controllable - allclusters.html[pdf] + 238.2.5. Manual controllable - allclusters.html[pdf] O true RVCOPSTATE.S.M.ERR_FAILED_TO_FIND_CHARGING_DOCK Does the DUT support testing the FailedToFindChargingDock(0x40) error state? - 223.2.5. Manual controllable - allclusters.html[pdf] + 238.2.5. Manual controllable - allclusters.html[pdf] O true RVCOPSTATE.S.M.ERR_STUCK Does the DUT support testing the Stuck(0x41) error state? - 223.2.5. Manual controllable - allclusters.html[pdf] + 238.2.5. Manual controllable - allclusters.html[pdf] O true RVCOPSTATE.S.M.ERR_DUST_BIN_MISSING Does the DUT support testing the DustBinMissing(0x42) error state? - 223.2.5. Manual controllable - allclusters.html[pdf] + 238.2.5. Manual controllable - allclusters.html[pdf] O true RVCOPSTATE.S.M.ERR_DUST_BIN_FULL Does the DUT support testing the DustBinFull(0x43) error state? - 223.2.5. Manual controllable - allclusters.html[pdf] + 238.2.5. Manual controllable - allclusters.html[pdf] O true RVCOPSTATE.S.M.ERR_WATER_TANK_EMPTY Does the DUT support testing the WaterTankEmpty(0x44) error state? - 223.2.5. Manual controllable - allclusters.html[pdf] + 238.2.5. Manual controllable - allclusters.html[pdf] O true RVCOPSTATE.S.M.ERR_WATER_TANK_MISSING Does the DUT support testing the WaterTankMissing(0x45) error state? - 223.2.5. Manual controllable - allclusters.html[pdf] + 238.2.5. Manual controllable - allclusters.html[pdf] O true RVCOPSTATE.S.M.ERR_WATER_TANK_LID_OPEN Does the DUT support testing the WaterTankLidOpen(0x46) error state? - 223.2.5. Manual controllable - allclusters.html[pdf] + 238.2.5. Manual controllable - allclusters.html[pdf] O true RVCOPSTATE.S.M.ERR_MOP_CLEANING_PAD_MISSING Does the DUT support testing the MopCleaningPadMissing(0x47) error state? - 223.2.5. Manual controllable - allclusters.html[pdf] + 238.2.5. Manual controllable - allclusters.html[pdf] O true + + RVCOPSTATE.S.M.RESUME_AFTER_ERR + Does the DUT support testing the Resume command after cleared error? + 238.2.5. Manual controllable - allclusters.html[pdf] + O + false + diff --git a/examples/rvc-app/rvc-common/pics/RVC Run Mode Cluster Test Plan.xml b/examples/rvc-app/rvc-common/pics/RVC Run Mode Cluster Test Plan.xml index 0bdd95322e..a3305b8b92 100644 --- a/examples/rvc-app/rvc-common/pics/RVC Run Mode Cluster Test Plan.xml +++ b/examples/rvc-app/rvc-common/pics/RVC Run Mode Cluster Test Plan.xml @@ -1,13 +1,19 @@ - + RVC Run Mode Cluster Test Plan @@ -16,7 +22,7 @@ Draft RVCRUNM.S Does the device implement the RVCRUNM cluster as a server? - 84.1. Role - allclusters.html[pdf] + 93.1. Role - allclusters.html[pdf] O true @@ -26,16 +32,26 @@ Draft PIXIT.RVCRUNM.MODE_CHANGE_FAIL Id of mode the device will fail to transition to, given its current state - 85. PIXIT Definition - allclusters.html[pdf] - O - 0x02 + 95. PIXIT Definition - allclusters.html[pdf] + O PIXIT.RVCRUNM.MODE_CHANGE_OK Id of mode the device will successfully transition to, given its current state - 85. PIXIT Definition - allclusters.html[pdf] - O - 0x00 + 95. PIXIT Definition - allclusters.html[pdf] + O + + + PIXIT.RVCRUNM.MODE_A + Id of non-Idle mode the device can successfully switch to, given its current state + 95. PIXIT Definition - allclusters.html[pdf] + O0x01 + + + PIXIT.RVCRUNM.MODE_B + Id of non-Idle mode the device can successfully switch to, given its current state + 95. PIXIT Definition - allclusters.html[pdf] + O0x02 @@ -45,31 +61,17 @@ Draft RVCRUNM.S.A0000 Does the device implement the SupportedModes attribute? - 84.2.2. Attributes - allclusters.html[pdf] + 93.2.1. Attributes - allclusters.html[pdf] M true RVCRUNM.S.A0001 Does the device implement the CurrentMode attribute? - 84.2.2. Attributes - allclusters.html[pdf] + 93.2.1. Attributes - allclusters.html[pdf] M true - - RVCRUNM.S.A0002 - Does the device implement the StartUpMode attribute? - 84.2.2. Attributes - allclusters.html[pdf] - O - false - - - RVCRUNM.S.A0003 - Does the device implement the OnMode attribute? - 84.2.2. Attributes - allclusters.html[pdf] - M - false - @@ -78,7 +80,7 @@ Draft RVCRUNM.S.C01.Tx Does the device implement sending the ChangeToModeResponse command? - 84.2.4. Commands generated - allclusters.html[pdf] + 93.2.3. Commands generated - allclusters.html[pdf] M true @@ -88,7 +90,7 @@ Draft RVCRUNM.S.C00.Rsp Does the device implement receiving the ChangeToMode command? - 84.2.3. Commands received - allclusters.html[pdf] + 93.2.2. Commands received - allclusters.html[pdf] M true @@ -96,9 +98,9 @@ Draft - RVCRUNM.S.F00 - Does the device support depending on an On/Off cluster implemented on the same endpoint? - 84.2.1. Features - allclusters.html[pdf] + RVCRUNM.S.F16 + Does the device support support changing run modes from non-Idle states? + 94.1. Features - allclusters.html[pdf] O false @@ -108,10 +110,23 @@ Draft RVCRUNM.S.M.CAN_TEST_MODE_FAILURE Does the DUT support testing the failed ChangeToMode command? - 84.2.5. Manual controllable - allclusters.html[pdf] + 93.2.4. Manual controllable - allclusters.html[pdf] O true + + RVCRUNM.S.M.CAN_MANUALLY_CONTROLLED + Can the mode change be manually controlled? + 93.2.4. Manual controllable - allclusters.html[pdf] + O + true + + + RVCOPSTATE.M.ST_STOPPED | RVCOPSTATE.M.ST_PAUSED | RVCOPSTATE.M.ST_CHARGING | RVCOPSTATE.M.ST_DOCKED + 97.2.2. [TC-RVCRUNM-2.2] Change to Mode restrictions with DUT as Server - allclusters.html[pdf] + O + true + diff --git a/examples/rvc-app/rvc-common/pics/Service Area Cluster Test Plan.xml b/examples/rvc-app/rvc-common/pics/Service Area Cluster Test Plan.xml new file mode 100644 index 0000000000..665504f1a2 --- /dev/null +++ b/examples/rvc-app/rvc-common/pics/Service Area Cluster Test Plan.xml @@ -0,0 +1,243 @@ + + + Service Area Cluster Test Plan + + + + + + SEAR.S + Does the device implement the Service Area cluster as a server? + 306.1. Role - allclusters.html[pdf] + O + true + + + + + + + + + + SEAR.S.A0000 + Does the device implement the SupportedAreas attribute? + 306.2.2. Attributes - allclusters.html[pdf] + M + true + + + SEAR.S.A0001 + Does the device implement the SupportedMaps attribute? + 306.2.2. Attributes - allclusters.html[pdf] + M + true + + + SEAR.S.A0002 + Does the device implement the SelectedAreas attribute? + 306.2.2. Attributes - allclusters.html[pdf] + M + true + + + SEAR.S.A0003 + Does the device implement the CurrentArea attribute? + 306.2.2. Attributes - allclusters.html[pdf] + O + true + + + SEAR.S.A0004 + Does the device implement the EstimatedEndTime attribute? + 306.2.2. Attributes - allclusters.html[pdf] + O + true + + + SEAR.S.A0005 + Does the device implement the Progress attribute? + 306.2.2. Attributes - allclusters.html[pdf] + M + true + + + + + + + + SEAR.S.C01.Tx + Does the device implement generating the SelectAreasResponse command? + 306.2.4. Commands generated - allclusters.html[pdf] + M + true + + + SEAR.S.C03.Tx + Does the device implement generating the SkipAreaResponse command? + 306.2.4. Commands generated - allclusters.html[pdf] + M + true + + + + + + SEAR.S.C00.Rsp + Does the device implement receiving the SelectAreas command? + 306.2.3. Commands received - allclusters.html[pdf] + M + true + + + SEAR.S.C02.Rsp + Does the device implement receiving the SkipArea command? + 306.2.3. Commands received - allclusters.html[pdf] + O + true + + + + + + SEAR.S.F00 + Does the device support changing the selected areas while running? + 306.2.1. Features - allclusters.html[pdf] + O + false + + + SEAR.S.F01 + Does the device support reporting the progress? + 306.2.1. Features - allclusters.html[pdf] + O + true + + + SEAR.S.F02 + Does the device support the maps feature? + 306.2.1. Features - allclusters.html[pdf] + O + true + + + + + + SEAR.S.M.REMOVE_AREA + Does the DUT support testing the effects of removing a SupportedAreas entry? + 306.2.5. Manual controllable - allclusters.html[pdf] + O + true + + + SEAR.S.M.ADD_AREA + Does the DUT support testing the effects of adding a SupportedAreas entry? + 306.2.5. Manual controllable - allclusters.html[pdf] + O + true + + + SEAR.S.M.REMOVE_MAP + Does the DUT support testing the effects of removing a SupportedMaps entry? + 306.2.5. Manual controllable - allclusters.html[pdf] + O + true + + + SEAR.S.M.ADD_MAP + Does the DUT support testing the effects of adding a SupportedMaps entry? + 306.2.5. Manual controllable - allclusters.html[pdf] + O + true + + + SEAR.S.M.INVALID_STATE_FOR_SELECT_AREAS + Does the DUT support testing the selecting areas while the device doesn’t allow that? + 306.2.5. Manual controllable - allclusters.html[pdf] + O + true + + + SEAR.S.M.VALID_STATE_FOR_SELECT_AREAS + Does the DUT support testing the selecting areas while the device allows that? + 306.2.5. Manual controllable - allclusters.html[pdf] + O + false + + + SEAR.S.M.SELECT_AREAS_WHILE_NON_IDLE + Does the DUT support testing the selecting areas while the device is a non-idle state? + 306.2.5. Manual controllable - allclusters.html[pdf] + O + true + + + SEAR.S.M.HAS_MANUAL_SELAREA_STATE_CONTROL + Can the device state affecting SelectAreas be manually controlled? + 306.2.5. Manual controllable - allclusters.html[pdf] + O + true + + + SEAR.S.M.HAS_MANUAL_SKIP_STATE_CONTROL + Can the device state affecting SkipArea be manually controlled? + 306.2.5. Manual controllable - allclusters.html[pdf] + O + true + + + SEAR.S.M.INVALID_STATE_FOR_SKIP + Does the DUT support testing the SkipArea command while the device doesn’t allow that? + 306.2.5. Manual controllable - allclusters.html[pdf] + O + true + + + SEAR.S.M.NO_SELAREA_FOR_SKIP + Does the DUT support testing the SkipArea command while SelectedAreas is null? + 306.2.5. Manual controllable - allclusters.html[pdf] + O + true + + + SEAR.S.M.VALID_STATE_FOR_SKIP + Does the DUT support testing the SkipArea command while the device allows that? + 306.2.5. Manual controllable - allclusters.html[pdf] + O + true + + + SEAR.S.M.HAS_MANUAL_OPERATING_STATE_CONTROL + Can the device operating state (idle, operating, terminate operating) be manually controlled? + 306.2.5. Manual controllable - allclusters.html[pdf] + O + true + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/examples/rvc-app/rvc-common/src/rvc-device.cpp b/examples/rvc-app/rvc-common/src/rvc-device.cpp index 623c95963f..dac7db9e43 100644 --- a/examples/rvc-app/rvc-common/src/rvc-device.cpp +++ b/examples/rvc-app/rvc-common/src/rvc-device.cpp @@ -174,7 +174,7 @@ bool RvcDevice::SaIsSetSelectedAreasAllowed(MutableCharSpan & statusText) return true; } -bool RvcDevice::SaHandleSkipCurrentArea(uint32_t skippedArea, MutableCharSpan & skipStatusText) +bool RvcDevice::SaHandleSkipArea(uint32_t skippedArea, MutableCharSpan & skipStatusText) { if (mServiceAreaInstance.GetCurrentArea() != skippedArea) { diff --git a/examples/rvc-app/rvc-common/src/rvc-service-area-delegate.cpp b/examples/rvc-app/rvc-common/src/rvc-service-area-delegate.cpp index 984472977a..9041efd3d9 100644 --- a/examples/rvc-app/rvc-common/src/rvc-service-area-delegate.cpp +++ b/examples/rvc-app/rvc-common/src/rvc-service-area-delegate.cpp @@ -180,9 +180,9 @@ bool RvcServiceAreaDelegate::IsValidSelectAreasSet(const Commands::SelectAreas:: return true; }; -bool RvcServiceAreaDelegate::HandleSkipCurrentArea(uint32_t skippedArea, MutableCharSpan & skipStatusText) +bool RvcServiceAreaDelegate::HandleSkipArea(uint32_t skippedArea, MutableCharSpan & skipStatusText) { - return (mHandleSkipCurrentAreaDeviceInstance->*mHandleSkipCurrentAreaCallback)(skippedArea, skipStatusText); + return (mHandleSkipAreaDeviceInstance->*mHandleSkipAreaCallback)(skippedArea, skipStatusText); }; //************************************************************************* diff --git a/src/app/clusters/service-area-server/service-area-delegate.h b/src/app/clusters/service-area-server/service-area-delegate.h index 01df2faeb0..2e9422840a 100644 --- a/src/app/clusters/service-area-server/service-area-delegate.h +++ b/src/app/clusters/service-area-server/service-area-delegate.h @@ -120,7 +120,7 @@ class Delegate * InvalidInMode, the StatusText field SHOULD indicate why the request is not allowed, given the current mode of the * device, which may involve other clusters. */ - virtual bool HandleSkipCurrentArea(uint32_t skippedArea, MutableCharSpan & skipStatusText) + virtual bool HandleSkipArea(uint32_t skippedArea, MutableCharSpan & skipStatusText) { // device support of this command is optional CopyCharSpanToMutableCharSpan("Skip Current Area command not supported by device"_span, skipStatusText); diff --git a/src/app/clusters/service-area-server/service-area-server.cpp b/src/app/clusters/service-area-server/service-area-server.cpp index 0e562c7875..a7e8127883 100644 --- a/src/app/clusters/service-area-server/service-area-server.cpp +++ b/src/app/clusters/service-area-server/service-area-server.cpp @@ -123,7 +123,7 @@ void Instance::InvokeCommand(HandlerContext & handlerContext) case Commands::SkipArea::Id: return CommandHandlerInterface::HandleCommand( - handlerContext, [this](HandlerContext & ctx, const auto & req) { HandleSkipCurrentAreaCmd(ctx, req); }); + handlerContext, [this](HandlerContext & ctx, const auto & req) { HandleSkipAreaCmd(ctx, req); }); } } @@ -356,11 +356,11 @@ void Instance::HandleSelectAreasCmd(HandlerContext & ctx, const Commands::Select exitResponse(SelectAreasStatus::kSuccess, ""_span); } -void Instance::HandleSkipCurrentAreaCmd(HandlerContext & ctx, const Commands::SkipArea::DecodableType & req) +void Instance::HandleSkipAreaCmd(HandlerContext & ctx, const Commands::SkipArea::DecodableType & req) { - ChipLogDetail(Zcl, "Service Area: HandleSkipCurrentArea"); + ChipLogDetail(Zcl, "Service Area: HandleSkipArea"); - // On receipt of this command the device SHALL respond with a SkipCurrentAreaResponse command. + // On receipt of this command the device SHALL respond with a SkipAreaResponse command. auto exitResponse = [ctx](SkipAreaStatus status, CharSpan statusText) { Commands::SkipAreaResponse::Type response{ .status = status, @@ -369,11 +369,11 @@ void Instance::HandleSkipCurrentAreaCmd(HandlerContext & ctx, const Commands::Sk ctx.mCommandHandler.AddResponse(ctx.mRequestPath, response); }; - // If the SelectedAreas attribute is null, the response status should be set to InvalidAreaList. + // The SkippedArea field SHALL match an entry in the SupportedAreas list. // If the Status field is set to InvalidAreaList, the StatusText field SHALL be an empty string. - if (mDelegate->GetNumberOfSelectedAreas() == 0) + if (!IsSupportedArea(req.skippedArea)) { - ChipLogError(Zcl, "Selected Areas attribute is null"); + ChipLogError(Zcl, "SkippedArea (%u) is not in the SupportedAreas attribute.", req.skippedArea); exitResponse(SkipAreaStatus::kInvalidAreaList, ""_span); return; } @@ -394,7 +394,7 @@ void Instance::HandleSkipCurrentAreaCmd(HandlerContext & ctx, const Commands::Sk char skipStatusBuffer[kMaxSizeStatusText]; MutableCharSpan skipStatusText(skipStatusBuffer); - if (!mDelegate->HandleSkipCurrentArea(req.skippedArea, skipStatusText)) + if (!mDelegate->HandleSkipArea(req.skippedArea, skipStatusText)) { exitResponse(SkipAreaStatus::kInvalidInMode, skipStatusText); return; diff --git a/src/app/clusters/service-area-server/service-area-server.h b/src/app/clusters/service-area-server/service-area-server.h index 811499f3ff..e023f24d12 100644 --- a/src/app/clusters/service-area-server/service-area-server.h +++ b/src/app/clusters/service-area-server/service-area-server.h @@ -124,7 +124,7 @@ class Instance : public AttributeAccessInterface, public CommandHandlerInterface * If the input value is invalid, returns the Interaction Model status code of INVALID_COMMAND. * @param[in] req the command parameters. */ - void HandleSkipCurrentAreaCmd(HandlerContext & ctx, const Commands::SkipArea::DecodableType & req); + void HandleSkipAreaCmd(HandlerContext & ctx, const Commands::SkipArea::DecodableType & req); //************************************************************************* // attribute notifications From 15032f18656d2f95c5e162de721e9f36355cf1e5 Mon Sep 17 00:00:00 2001 From: Tennessee Carmel-Veilleux Date: Fri, 16 Aug 2024 13:15:40 -0400 Subject: [PATCH 075/165] Minimal TC_SWTCH fixes for 1.4-TE2 (#34986) - Fixes only issues raised on script that block success - https://github.com/project-chip/matter-test-scripts/issues/337 - https://github.com/project-chip/matter-test-scripts/issues/338 - Fixes done: - Prompt text improvement/fixes - Fixed crash in 2.5/2.6 --- src/python_testing/TC_SWTCH.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/python_testing/TC_SWTCH.py b/src/python_testing/TC_SWTCH.py index e2ef307973..d6c4694560 100644 --- a/src/python_testing/TC_SWTCH.py +++ b/src/python_testing/TC_SWTCH.py @@ -114,7 +114,7 @@ def _ask_for_switch_position(self, endpoint_id: int, new_position: int): def _ask_for_multi_press_short_long(self, endpoint_id: int, pressed_position: int, feature_map: uint, multi_press_max: uint): if not self._use_button_simulator(): msg = f""" - Actuate the switch in the following sequence: + Actuate the switch in the following sequence (read full sequence first): 1. Operate switch (press briefly) associated with position {pressed_position} on the DUT then release switch from DUT 2. Operate switch (keep pressed for long time, e.g. 5 seconds) on the DUT immediately after the previous step 3. Release switch from the DUT @@ -128,7 +128,7 @@ def _ask_for_multi_press_short_long(self, endpoint_id: int, pressed_position: in def _ask_for_multi_press_long_short(self, endpoint_id, pressed_position, feature_map: int): if not self._use_button_simulator(): msg = f""" - Actuate the switch in the following sequence: + Actuate the switch in the following sequence (read full sequence first): 1. Operate switch (keep pressed for long time, e.g. 5 seconds) on the DUT 2. Releases switch from the DUT 3. Immediately after the previous step completes, operate switch (press briefly) associated with position {pressed_position} on the DUT then release switch from DUT @@ -142,7 +142,7 @@ def _ask_for_multi_press_long_short(self, endpoint_id, pressed_position, feature def _ask_for_multi_press(self, endpoint_id: int, number_of_presses: int, pressed_position: int, feature_map: uint, multi_press_max: uint): if not self._use_button_simulator(): self.wait_for_user_input( - f'Operate the switch (press briefly) associated with position {pressed_position} then release {number_of_presses} times') + f'Execute {number_of_presses} separate brief press/release cycles on position {pressed_position}.') else: self._send_multi_press_named_pipe_command(endpoint_id, number_of_presses, pressed_position, feature_map, multi_press_max) @@ -157,7 +157,7 @@ def _ask_for_long_press(self, endpoint_id: int, pressed_position: int, feature_m def _ask_for_keep_pressed(self, endpoint_id: int, pressed_position: int, feature_map: int): if not self._use_button_simulator(): self.wait_for_user_input( - prompt_msg=f"Press switch position {pressed_position} for a long time (around 5 seconds) on the DUT, then release it.") + prompt_msg=f"Press switch position {pressed_position} for a long time (around 5 seconds) on the DUT, keep it pressed, do NOT release it.") else: self._send_long_press_named_pipe_command(endpoint_id, pressed_position, feature_map) @@ -676,7 +676,7 @@ def test_multi_press_sequence(starting_step: str, count: int, short_long: bool = asserts.assert_equal(event.newPosition, pressed_position, "Unexpected NewPosition on LongPress") event = event_listener.wait_for_event_report(cluster.Events.LongRelease) asserts.assert_equal(event.previousPosition, pressed_position, "Unexpected PreviousPosition on LongRelease") - if self._use_button_simulator: + if self._use_button_simulator(): # simulator can't sequence so we need to help it along here self._send_multi_press_named_pipe_command(endpoint_id, number_of_presses=1, pressed_position=1, feature_map=feature_map, multi_press_max=multi_press_max) @@ -839,7 +839,7 @@ def test_multi_press_sequence(starting_step: str, count: int, short_long: bool = asserts.assert_equal(event.newPosition, pressed_position, "Unexpected NewPosition on LongPress") event = event_listener.wait_for_event_report(cluster.Events.LongRelease) asserts.assert_equal(event.previousPosition, pressed_position, "Unexpected PreviousPosition on LongRelease") - if self._use_button_simulator: + if self._use_button_simulator(): # simulator can't sequence so we need to help it along here self._send_multi_press_named_pipe_command(endpoint_id, number_of_presses=1, pressed_position=1, feature_map=feature_map, multi_press_max=multi_press_max) From 4e6847d085c069e31ab0c256b7f03857ae4a7ba0 Mon Sep 17 00:00:00 2001 From: Andrei Litvin Date: Fri, 16 Aug 2024 14:30:44 -0400 Subject: [PATCH 076/165] [MCORE.FS 1.3] make "app not found" easier to debug (#35038) * Remove unused method, make missing app error easier to find * Remove more todo for confirm we can run apps: we confirmed we can --------- Co-authored-by: Andrei Litvin --- src/python_testing/TC_CCTRL_2_2.py | 1 - src/python_testing/TC_MCORE_FS_1_1.py | 1 - src/python_testing/TC_MCORE_FS_1_3.py | 36 +++++++++------------------ 3 files changed, 12 insertions(+), 26 deletions(-) diff --git a/src/python_testing/TC_CCTRL_2_2.py b/src/python_testing/TC_CCTRL_2_2.py index 53c196113d..4d11692d14 100644 --- a/src/python_testing/TC_CCTRL_2_2.py +++ b/src/python_testing/TC_CCTRL_2_2.py @@ -44,7 +44,6 @@ class TC_CCTRL_2_2(MatterBaseTest): @async_test_body async def setup_class(self): super().setup_class() - # TODO: confirm whether we can open processes like this on the TH self.app_process = None app = self.user_params.get("th_server_app_path", None) if not app: diff --git a/src/python_testing/TC_MCORE_FS_1_1.py b/src/python_testing/TC_MCORE_FS_1_1.py index 6753db81a3..f64b718e96 100755 --- a/src/python_testing/TC_MCORE_FS_1_1.py +++ b/src/python_testing/TC_MCORE_FS_1_1.py @@ -36,7 +36,6 @@ class TC_MCORE_FS_1_1(MatterBaseTest): @async_test_body async def setup_class(self): super().setup_class() - # TODO: confirm whether we can open processes like this on the TH self.app_process = None app = self.user_params.get("th_server_app_path", None) if not app: diff --git a/src/python_testing/TC_MCORE_FS_1_3.py b/src/python_testing/TC_MCORE_FS_1_3.py index 791d3785f2..e707b500a6 100644 --- a/src/python_testing/TC_MCORE_FS_1_3.py +++ b/src/python_testing/TC_MCORE_FS_1_3.py @@ -68,18 +68,25 @@ def teardown_class(self): super().teardown_class() async def create_device_and_commission_to_th_fabric(self, kvs, port, node_id_for_th, device_info): - # TODO: confirm whether we can open processes like this on the TH app = self.user_params.get("th_server_app_path", None) if not app: asserts.fail('This test requires a TH_SERVER app. Specify app path with --string-arg th_server_app_path:') + if not os.path.exists(app): + asserts.fail(f'The path {app} does not exist') + discriminator = random.randint(0, 4095) passcode = 20202021 - app_args = f'--secured-device-port {port} --discriminator {discriminator} --passcode {passcode} --KVS {kvs}' - cmd = f'{app} {app_args}' + + cmd = [app] + cmd.extend(['--secured-device-port', str(port)]) + cmd.extend(['--discriminator', str(discriminator)]) + cmd.extend(['--passcode', str(passcode)]) + cmd.extend(['--KVS', kvs]) + # TODO: Determine if we want these logs cooked or pushed to somewhere else logging.info(f"Starting TH device for {device_info}") - self.app_process_for_dut_eco = subprocess.Popen(cmd, bufsize=0, shell=True) + self.app_process_for_dut_eco = subprocess.Popen(cmd) logging.info(f"Started TH device for {device_info}") time.sleep(3) @@ -87,26 +94,6 @@ async def create_device_and_commission_to_th_fabric(self, kvs, port, node_id_for await self.TH_server_controller.CommissionOnNetwork(nodeId=node_id_for_th, setupPinCode=passcode, filterType=ChipDeviceCtrl.DiscoveryFilterType.LONG_DISCRIMINATOR, filter=discriminator) logging.info("Commissioning device for DUT ecosystem onto TH for managing") - async def create_and_commission_device_for_th_ecosystem(self): - # TODO: confirm whether we can open processes like this on the TH - app = self.user_params.get("th_server_app_path", None) - - self.device_for_th_eco_kvs = f'kvs_{str(uuid.uuid4())}' - discriminator = random.randint(0, 4095) - passcode = 20202021 - app_args = f'--secured-device-port {self.device_for_th_eco_port} --discriminator {discriminator} --passcode {passcode} --KVS {self.device_for_th_eco_kvs}' - cmd = f'{app} {app_args}' - # TODO: Determine if we want these logs cooked or pushed to somewhere else - logging.info("Starting TH device for TH ecosystem") - self.app_process_for_th_eco = subprocess.Popen(cmd, bufsize=0, shell=True) - logging.info("Started TH device for TH ecosystem") - time.sleep(3) - - logging.info("Commissioning from separate fabric") - self.server_nodeid = 1112 - await self.TH_server_controller.CommissionOnNetwork(nodeId=self.server_nodeid, setupPinCode=passcode, filterType=ChipDeviceCtrl.DiscoveryFilterType.LONG_DISCRIMINATOR, filter=discriminator) - logging.info("Commissioning TH device for TH ecosystem") - def steps_TC_MCORE_FS_1_3(self) -> list[TestStep]: steps = [TestStep(1, "DUT_FSA commissions TH_SED_DUT to DUT_FSAs fabric and generates a UniqueID", is_commissioning=True), TestStep(2, "TH_FSA commissions TH_SED_TH onto TH_FSAs fabric and generates a UniqueID."), @@ -127,6 +114,7 @@ async def test_TC_MCORE_FS_1_3(self): kvs = f'kvs_{str(uuid.uuid4())}' device_info = "for DUT ecosystem" await self.create_device_and_commission_to_th_fabric(kvs, self.device_for_dut_eco_port, self.device_for_dut_eco_nodeid, device_info) + self.device_for_dut_eco_kvs = kvs read_result = await self.TH_server_controller.ReadAttribute(self.device_for_dut_eco_nodeid, [(root_node_endpoint, Clusters.BasicInformation.Attributes.UniqueID)]) result = read_result[root_node_endpoint][Clusters.BasicInformation][Clusters.BasicInformation.Attributes.UniqueID] From e0a4e792d03a9e03cbf1b3911a7cc74fb6f99e61 Mon Sep 17 00:00:00 2001 From: Yufeng Wang Date: Fri, 16 Aug 2024 12:55:30 -0700 Subject: [PATCH 077/165] [FS Example] Update the FS Example apps to support fabric sync setup process part II (#34990) * examples/fabric-bridge-app/linux/CommissionerControl.cpp * Implement reverse commissioning * Update function names to align with spec --- .../protos/fabric_admin_service.options | 1 + .../pigweed/protos/fabric_admin_service.proto | 9 ++ .../common/pigweed/rpc_services/FabricAdmin.h | 5 + .../commands/clusters/ClusterCommand.h | 9 +- .../device_manager/DeviceManager.cpp | 107 ++++++++++++------ .../device_manager/DeviceManager.h | 14 ++- examples/fabric-admin/rpc/RpcServer.cpp | 40 +++++++ .../fabric-bridge-common/BUILD.gn | 2 - examples/fabric-bridge-app/linux/BUILD.gn | 1 + .../src => linux}/CommissionerControl.cpp | 51 +++++++-- .../fabric-bridge-app/linux/RpcClient.cpp | 25 ++++ .../include/CommissionerControl.h | 10 +- .../linux/include/RpcClient.h | 11 ++ examples/fabric-bridge-app/linux/main.cpp | 4 +- .../commissioner-control-server.cpp | 6 +- .../commissioner-control-server.h | 13 +-- 16 files changed, 235 insertions(+), 73 deletions(-) rename examples/fabric-bridge-app/{fabric-bridge-common/src => linux}/CommissionerControl.cpp (70%) rename examples/fabric-bridge-app/{fabric-bridge-common => linux}/include/CommissionerControl.h (80%) diff --git a/examples/common/pigweed/protos/fabric_admin_service.options b/examples/common/pigweed/protos/fabric_admin_service.options index 9a65ae8a2b..c7dbc02f1b 100644 --- a/examples/common/pigweed/protos/fabric_admin_service.options +++ b/examples/common/pigweed/protos/fabric_admin_service.options @@ -1,2 +1,3 @@ chip.rpc.DeviceCommissioningWindowInfo.verifier max_size:97 // kSpake2p_VerifierSerialized_Length chip.rpc.DeviceCommissioningWindowInfo.salt max_size:32 // kSpake2p_Max_PBKDF_Salt_Length +chip.rpc.DeviceCommissioningInfo.salt max_size:32 // kSpake2p_Max_PBKDF_Salt_Length diff --git a/examples/common/pigweed/protos/fabric_admin_service.proto b/examples/common/pigweed/protos/fabric_admin_service.proto index b2c81d5ee0..3c311493d1 100644 --- a/examples/common/pigweed/protos/fabric_admin_service.proto +++ b/examples/common/pigweed/protos/fabric_admin_service.proto @@ -14,6 +14,14 @@ message DeviceCommissioningWindowInfo { bytes verifier = 6; } +// Define the message for commissioning a device with necessary fields +message DeviceCommissioningInfo { + uint32 discriminator = 1; + uint32 iterations = 2; + uint32 setup_pin = 3; + bytes salt = 4; +} + message KeepActiveParameters { uint64 node_id = 1; uint32 stay_active_duration_ms = 2; @@ -26,5 +34,6 @@ message OperationStatus { service FabricAdmin { rpc OpenCommissioningWindow(DeviceCommissioningWindowInfo) returns (OperationStatus){} + rpc CommissionNode(DeviceCommissioningInfo) returns (pw.protobuf.Empty){} rpc KeepActive(KeepActiveParameters) returns (pw.protobuf.Empty){} } diff --git a/examples/common/pigweed/rpc_services/FabricAdmin.h b/examples/common/pigweed/rpc_services/FabricAdmin.h index 125d322e3a..256b06c73e 100644 --- a/examples/common/pigweed/rpc_services/FabricAdmin.h +++ b/examples/common/pigweed/rpc_services/FabricAdmin.h @@ -40,6 +40,11 @@ class FabricAdmin : public pw_rpc::nanopb::FabricAdmin::Service return pw::Status::Unimplemented(); } + virtual pw::Status CommissionNode(const chip_rpc_DeviceCommissioningInfo & request, pw_protobuf_Empty & response) + { + return pw::Status::Unimplemented(); + } + virtual pw::Status KeepActive(const chip_rpc_KeepActiveParameters & request, pw_protobuf_Empty & response) { return pw::Status::Unimplemented(); diff --git a/examples/fabric-admin/commands/clusters/ClusterCommand.h b/examples/fabric-admin/commands/clusters/ClusterCommand.h index 4865f056e1..ab2a535da4 100644 --- a/examples/fabric-admin/commands/clusters/ClusterCommand.h +++ b/examples/fabric-admin/commands/clusters/ClusterCommand.h @@ -84,14 +84,7 @@ class ClusterCommand : public InteractionModelCommands, public ModelCommand, pub if (data != nullptr) { LogErrorOnFailure(RemoteDataModelLogger::LogCommandAsJSON(path, data)); - - error = DataModelLogger::LogCommand(path, data); - if (CHIP_NO_ERROR != error) - { - ChipLogError(NotSpecified, "Response Failure: Can not decode Data"); - mError = error; - return; - } + DeviceMgr().HandleCommandResponse(path, data); } } diff --git a/examples/fabric-admin/device_manager/DeviceManager.cpp b/examples/fabric-admin/device_manager/DeviceManager.cpp index 17adcc2427..fe0c8aea4d 100644 --- a/examples/fabric-admin/device_manager/DeviceManager.cpp +++ b/examples/fabric-admin/device_manager/DeviceManager.cpp @@ -56,12 +56,12 @@ void DeviceManager::Init() NodeId DeviceManager::GetNextAvailableNodeId() { mLastUsedNodeId++; - VerifyOrDieWithMsg(mLastUsedNodeId < std::numeric_limits::max(), NotSpecified, "No more available NodeIds."); + VerifyOrDieWithMsg(mLastUsedNodeId < std::numeric_limits::max(), NotSpecified, "No more available NodeIds."); return mLastUsedNodeId; } -void DeviceManager::UpdateLastUsedNodeId(chip::NodeId nodeId) +void DeviceManager::UpdateLastUsedNodeId(NodeId nodeId) { if (nodeId > mLastUsedNodeId) { @@ -159,7 +159,7 @@ void DeviceManager::PairRemoteFabricBridge(NodeId nodeId, const char * deviceRem PushCommand(commandBuilder.c_str()); } -void DeviceManager::PairRemoteDevice(chip::NodeId nodeId, const char * payload) +void DeviceManager::PairRemoteDevice(NodeId nodeId, const char * payload) { StringBuilder commandBuilder; @@ -238,7 +238,7 @@ void DeviceManager::ReadSupportedDeviceCategories() PushCommand(commandBuilder.c_str()); } -void DeviceManager::StartReverseCommissioning() +void DeviceManager::RequestCommissioningApproval() { ChipLogProgress(NotSpecified, "Starting reverse commissioning for bridge device: NodeId: " ChipLogFormatX64, ChipLogValueX64(mRemoteBridgeNodeId)); @@ -255,7 +255,36 @@ void DeviceManager::StartReverseCommissioning() PushCommand(commandBuilder.c_str()); } -void DeviceManager::CommissionApprovedRequest(uint64_t requestId, uint16_t responseTimeoutSeconds) +void DeviceManager::HandleCommissioningRequestResult(TLV::TLVReader * data) +{ + ChipLogProgress(NotSpecified, "CommissioningRequestResult event received."); + + CommissionerControl::Events::CommissioningRequestResult::DecodableType value; + CHIP_ERROR error = app::DataModel::Decode(*data, value); + if (error != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to decode event value. Error: %" CHIP_ERROR_FORMAT, error.Format()); + return; + } + + if (value.requestId != mRequestId) + { + ChipLogError(NotSpecified, "The RequestId does not match the RequestId provided to RequestCommissioningApproval"); + return; + } + + if (value.statusCode != static_cast(Protocols::InteractionModel::Status::Success)) + { + ChipLogError(NotSpecified, "The server is not ready to begin commissioning the requested device"); + return; + } + + // The server is ready to begin commissioning the requested device, request the Commissioner Control Server to begin + // commissioning a previously approved request. + SendCommissionNodeRequest(value.requestId, kResponseTimeoutSeconds); +} + +void DeviceManager::SendCommissionNodeRequest(uint64_t requestId, uint16_t responseTimeoutSeconds) { ChipLogProgress(NotSpecified, "Request the Commissioner Control Server to begin commissioning a previously approved request."); @@ -266,6 +295,35 @@ void DeviceManager::CommissionApprovedRequest(uint64_t requestId, uint16_t respo PushCommand(commandBuilder.c_str()); } +void DeviceManager::HandleReverseOpenCommissioningWindow(TLV::TLVReader * data) +{ + CommissionerControl::Commands::ReverseOpenCommissioningWindow::DecodableType value; + CHIP_ERROR error = app::DataModel::Decode(*data, value); + if (error != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to decode command response value. Error: %" CHIP_ERROR_FORMAT, error.Format()); + return; + } + + // Log all fields + ChipLogProgress(NotSpecified, "DecodableType fields:"); + ChipLogProgress(NotSpecified, " commissioningTimeout: %u", value.commissioningTimeout); + ChipLogProgress(NotSpecified, " discriminator: %u", value.discriminator); + ChipLogProgress(NotSpecified, " iterations: %u", value.iterations); + + char verifierHex[Crypto::kSpake2p_VerifierSerialized_Length * 2 + 1]; + Encoding::BytesToHex(value.PAKEPasscodeVerifier.data(), value.PAKEPasscodeVerifier.size(), verifierHex, sizeof(verifierHex), + Encoding::HexFlags::kNullTerminate); + ChipLogProgress(NotSpecified, " PAKEPasscodeVerifier: %s", verifierHex); + + char saltHex[Crypto::kSpake2p_Max_PBKDF_Salt_Length * 2 + 1]; + Encoding::BytesToHex(value.salt.data(), value.salt.size(), saltHex, sizeof(saltHex), Encoding::HexFlags::kNullTerminate); + ChipLogProgress(NotSpecified, " salt: %s", saltHex); + + OpenDeviceCommissioningWindow(mLocalBridgeNodeId, value.commissioningTimeout, value.iterations, value.discriminator, saltHex, + verifierHex); +} + void DeviceManager::HandleAttributeData(const app::ConcreteDataAttributePath & path, TLV::TLVReader * data) { if (path.mClusterId == CommissionerControl::Id && @@ -284,7 +342,7 @@ void DeviceManager::HandleAttributeData(const app::ConcreteDataAttributePath & p if (value.Has(CommissionerControl::SupportedDeviceCategoryBitmap::kFabricSynchronization)) { ChipLogProgress(NotSpecified, "Remote Fabric-Bridge supports Fabric Synchronization, start reverse commissioning."); - StartReverseCommissioning(); + RequestCommissioningApproval(); } return; @@ -399,39 +457,24 @@ void DeviceManager::HandleAttributeData(const app::ConcreteDataAttributePath & p } } -void DeviceManager::HandleEventData(const chip::app::EventHeader & header, chip::TLV::TLVReader * data) +void DeviceManager::HandleEventData(const app::EventHeader & header, TLV::TLVReader * data) { - if (header.mPath.mClusterId != CommissionerControl::Id || - header.mPath.mEventId != CommissionerControl::Events::CommissioningRequestResult::Id) - { - return; - } - - ChipLogProgress(NotSpecified, "CommissioningRequestResult event received."); - - CommissionerControl::Events::CommissioningRequestResult::DecodableType value; - CHIP_ERROR error = app::DataModel::Decode(*data, value); - if (error != CHIP_NO_ERROR) + if (header.mPath.mClusterId == CommissionerControl::Id && + header.mPath.mEventId == CommissionerControl::Events::CommissioningRequestResult::Id) { - ChipLogError(NotSpecified, "Failed to decode event value. Error: %" CHIP_ERROR_FORMAT, error.Format()); - return; + HandleCommissioningRequestResult(data); } +} - if (value.requestId != mRequestId) - { - ChipLogError(NotSpecified, "The RequestId does not match the RequestId provided to RequestCommissioningApproval"); - return; - } +void DeviceManager::HandleCommandResponse(const app::ConcreteCommandPath & path, TLV::TLVReader * data) +{ + ChipLogProgress(NotSpecified, "Command Response received."); - if (value.statusCode != static_cast(Protocols::InteractionModel::Status::Success)) + if (path.mClusterId == CommissionerControl::Id && + path.mCommandId == CommissionerControl::Commands::ReverseOpenCommissioningWindow::Id) { - ChipLogError(NotSpecified, "The server is not ready to begin commissioning the requested device"); - return; + HandleReverseOpenCommissioningWindow(data); } - - // The server is ready to begin commissioning the requested device, request the Commissioner Control Server to begin - // commissioning a previously approved request. - CommissionApprovedRequest(value.requestId, kResponseTimeoutSeconds); } void DeviceManager::OnDeviceRemoved(NodeId deviceId, CHIP_ERROR err) diff --git a/examples/fabric-admin/device_manager/DeviceManager.h b/examples/fabric-admin/device_manager/DeviceManager.h index 454986bd7a..b6c7dc0e65 100644 --- a/examples/fabric-admin/device_manager/DeviceManager.h +++ b/examples/fabric-admin/device_manager/DeviceManager.h @@ -148,21 +148,27 @@ class DeviceManager : public PairingDelegate void SubscribeRemoteFabricBridge(); - void StartReverseCommissioning(); - void ReadSupportedDeviceCategories(); - void CommissionApprovedRequest(uint64_t requestId, uint16_t responseTimeoutSeconds); - void HandleAttributeData(const chip::app::ConcreteDataAttributePath & path, chip::TLV::TLVReader * data); void HandleEventData(const chip::app::EventHeader & header, chip::TLV::TLVReader * data); + void HandleCommandResponse(const chip::app::ConcreteCommandPath & path, chip::TLV::TLVReader * data); + void OnDeviceRemoved(chip::NodeId deviceId, CHIP_ERROR err) override; private: friend DeviceManager & DeviceMgr(); + void RequestCommissioningApproval(); + + void HandleCommissioningRequestResult(chip::TLV::TLVReader * data); + + void SendCommissionNodeRequest(uint64_t requestId, uint16_t responseTimeoutSeconds); + + void HandleReverseOpenCommissioningWindow(chip::TLV::TLVReader * data); + static DeviceManager sInstance; chip::NodeId mLastUsedNodeId = 0; diff --git a/examples/fabric-admin/rpc/RpcServer.cpp b/examples/fabric-admin/rpc/RpcServer.cpp index 86d90ad294..f240feda22 100644 --- a/examples/fabric-admin/rpc/RpcServer.cpp +++ b/examples/fabric-admin/rpc/RpcServer.cpp @@ -29,6 +29,7 @@ #include #include #include +#include #include #if defined(PW_RPC_FABRIC_ADMIN_SERVICE) && PW_RPC_FABRIC_ADMIN_SERVICE @@ -91,6 +92,45 @@ class FabricAdmin final : public rpc::FabricAdmin, public IcdManager::Delegate return pw::OkStatus(); } + pw::Status CommissionNode(const chip_rpc_DeviceCommissioningInfo & request, pw_protobuf_Empty & response) override + { + char saltHex[Crypto::kSpake2p_Max_PBKDF_Salt_Length * 2 + 1]; + Encoding::BytesToHex(request.salt.bytes, request.salt.size, saltHex, sizeof(saltHex), Encoding::HexFlags::kNullTerminate); + + ChipLogProgress(NotSpecified, "Received CommissionNode request"); + + SetupPayload setupPayload = SetupPayload(); + + setupPayload.setUpPINCode = request.setup_pin; + setupPayload.version = 0; + setupPayload.rendezvousInformation.SetValue(RendezvousInformationFlag::kOnNetwork); + + SetupDiscriminator discriminator{}; + discriminator.SetLongValue(request.discriminator); + setupPayload.discriminator = discriminator; + + char payloadBuffer[kMaxManualCodeLength + 1]; + MutableCharSpan manualCode(payloadBuffer); + + CHIP_ERROR error = ManualSetupPayloadGenerator(setupPayload).payloadDecimalStringRepresentation(manualCode); + if (error == CHIP_NO_ERROR) + { + NodeId nodeId = DeviceMgr().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, payloadBuffer); + } + else + { + ChipLogError(NotSpecified, "Unable to generate manual code for setup payload: %" CHIP_ERROR_FORMAT, error.Format()); + } + + return pw::OkStatus(); + } + pw::Status KeepActive(const chip_rpc_KeepActiveParameters & request, pw_protobuf_Empty & response) override { ChipLogProgress(NotSpecified, "Received KeepActive request: 0x%lx, %u", request.node_id, request.stay_active_duration_ms); diff --git a/examples/fabric-bridge-app/fabric-bridge-common/BUILD.gn b/examples/fabric-bridge-app/fabric-bridge-common/BUILD.gn index b7b07d3be3..7f2fbcbbfe 100644 --- a/examples/fabric-bridge-app/fabric-bridge-common/BUILD.gn +++ b/examples/fabric-bridge-app/fabric-bridge-common/BUILD.gn @@ -45,11 +45,9 @@ source_set("fabric-bridge-lib") { "include/BridgedDeviceBasicInformationImpl.h", "include/BridgedDeviceManager.h", "include/CHIPProjectAppConfig.h", - "include/CommissionerControl.h", "src/BridgedDevice.cpp", "src/BridgedDeviceBasicInformationImpl.cpp", "src/BridgedDeviceManager.cpp", - "src/CommissionerControl.cpp", "src/ZCLCallbacks.cpp", ] diff --git a/examples/fabric-bridge-app/linux/BUILD.gn b/examples/fabric-bridge-app/linux/BUILD.gn index d0f60f30fb..d0e92a408e 100644 --- a/examples/fabric-bridge-app/linux/BUILD.gn +++ b/examples/fabric-bridge-app/linux/BUILD.gn @@ -33,6 +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", "main.cpp", ] diff --git a/examples/fabric-bridge-app/fabric-bridge-common/src/CommissionerControl.cpp b/examples/fabric-bridge-app/linux/CommissionerControl.cpp similarity index 70% rename from examples/fabric-bridge-app/fabric-bridge-common/src/CommissionerControl.cpp rename to examples/fabric-bridge-app/linux/CommissionerControl.cpp index 076ced8165..9f3180668d 100644 --- a/examples/fabric-bridge-app/fabric-bridge-common/src/CommissionerControl.cpp +++ b/examples/fabric-bridge-app/linux/CommissionerControl.cpp @@ -17,17 +17,26 @@ */ #include "CommissionerControl.h" +#include "RpcClient.h" #include #include +#include #include #include +#include using namespace chip; using namespace chip::app; namespace { +// Constants +constexpr uint16_t kDiscriminator = 3840; +constexpr uint16_t kWindowTimeout = 300; +constexpr uint16_t kIteration = 1000; +constexpr uint32_t kSetupPinCode = 20202021; + std::unique_ptr sCommissionerControlDelegate; } // namespace @@ -96,23 +105,43 @@ CHIP_ERROR CommissionerControlDelegate::ValidateCommissionNodeCommand(NodeId cli CHIP_ERROR CommissionerControlDelegate::GetCommissioningWindowParams(CommissioningWindowParams & outParams) { - // TODO: Populate outParams with the required details. - // outParams.commissioningWindowParams.iterations = mIterations; - // outParams.commissioningWindowParams.commissioningTimeout = mCommissioningTimeout; - // outParams.commissioningWindowParams.discriminator = mDiscriminator; - // outParams.commissioningWindowParams.PAKEPasscodeVerifier = mPAKEPasscodeVerifier; - // outParams.commissioningWindowParams.salt = mSalt; + // Populate outParams with the required details. + outParams.iterations = kIteration; + outParams.commissioningTimeout = kWindowTimeout; + outParams.discriminator = kDiscriminator; + + ReturnErrorOnFailure(Crypto::DRBG_get_bytes(mPBKDFSaltBuffer, sizeof(mPBKDFSaltBuffer))); + mPBKDFSalt = ByteSpan(mPBKDFSaltBuffer); + outParams.salt = mPBKDFSalt; - // outParams.ipAddress = mIpAddress; - // outParams.port = mPort; + Crypto::Spake2pVerifier verifier; + uint32_t setupPIN = kSetupPinCode; + ReturnErrorOnFailure(PASESession::GeneratePASEVerifier(verifier, kIteration, mPBKDFSalt, false, setupPIN)); + + MutableByteSpan serializedVerifierSpan(mPAKEPasscodeVerifierBuffer); + ReturnErrorOnFailure(verifier.Serialize(serializedVerifierSpan)); + mPAKEPasscodeVerifier = serializedVerifierSpan; + outParams.PAKEPasscodeVerifier = mPAKEPasscodeVerifier; return CHIP_NO_ERROR; } -CHIP_ERROR CommissionerControlDelegate::ReverseCommissionNode(const CommissioningWindowParams & params, - const Optional & ipAddress, const Optional & port) +CHIP_ERROR CommissionerControlDelegate::HandleCommissionNode(const CommissioningWindowParams & params, + const Optional & ipAddress, const Optional & port) { - return CHIP_NO_ERROR; + ChipLogProgress(NotSpecified, "CommissionerControlDelegate::HandleCommissionNode"); + +#if defined(PW_RPC_FABRIC_BRIDGE_SERVICE) && PW_RPC_FABRIC_BRIDGE_SERVICE + return CommissionNode(Controller::CommissioningWindowPasscodeParams() + .SetSetupPIN(kSetupPinCode) + .SetTimeout(params.commissioningTimeout) + .SetDiscriminator(params.discriminator) + .SetIteration(params.iterations) + .SetSalt(params.salt)); +#else + ChipLogProgress(NotSpecified, "Failed to reverse commission bridge: PW_RPC_FABRIC_BRIDGE_SERVICE not defined"); + return CHIP_ERROR_NOT_IMPLEMENTED; +#endif // defined(PW_RPC_FABRIC_BRIDGE_SERVICE) && PW_RPC_FABRIC_BRIDGE_SERVICE } } // namespace CommissionerControl diff --git a/examples/fabric-bridge-app/linux/RpcClient.cpp b/examples/fabric-bridge-app/linux/RpcClient.cpp index 1260c8744b..b3c82303be 100644 --- a/examples/fabric-bridge-app/linux/RpcClient.cpp +++ b/examples/fabric-bridge-app/linux/RpcClient.cpp @@ -162,6 +162,31 @@ OpenCommissioningWindow(chip::Controller::CommissioningWindowVerifierParams para return OpenCommissioningWindow(device); } +CHIP_ERROR +CommissionNode(chip::Controller::CommissioningWindowPasscodeParams params) +{ + chip_rpc_DeviceCommissioningInfo device; + device.setup_pin = params.GetSetupPIN(); + device.discriminator = params.GetDiscriminator(); + device.iterations = params.GetIteration(); + + VerifyOrReturnError(params.GetSalt().size() <= sizeof(device.salt.bytes), CHIP_ERROR_BUFFER_TOO_SMALL); + memcpy(device.salt.bytes, params.GetSalt().data(), params.GetSalt().size()); + device.salt.size = static_cast(params.GetSalt().size()); + + // The RPC call is kept alive until it completes. When a response is received, it will be logged by the handler + // function and the call will complete. + auto call = fabricAdminClient.CommissionNode(device, RpcCompletedWithEmptyResponse); + + if (!call.active()) + { + // The RPC call was not sent. This could occur due to, for example, an invalid channel ID. Handle if necessary. + return CHIP_ERROR_INTERNAL; + } + + return WaitForResponse(call); +} + CHIP_ERROR KeepActive(chip::NodeId nodeId, uint32_t stayActiveDurationMs) { chip_rpc_KeepActiveParameters params; diff --git a/examples/fabric-bridge-app/fabric-bridge-common/include/CommissionerControl.h b/examples/fabric-bridge-app/linux/include/CommissionerControl.h similarity index 80% rename from examples/fabric-bridge-app/fabric-bridge-common/include/CommissionerControl.h rename to examples/fabric-bridge-app/linux/include/CommissionerControl.h index b5caa6a2ce..633be761ba 100644 --- a/examples/fabric-bridge-app/fabric-bridge-common/include/CommissionerControl.h +++ b/examples/fabric-bridge-app/linux/include/CommissionerControl.h @@ -32,8 +32,8 @@ class CommissionerControlDelegate : public Delegate CHIP_ERROR HandleCommissioningApprovalRequest(const CommissioningApprovalRequest & request) override; CHIP_ERROR ValidateCommissionNodeCommand(NodeId clientNodeId, uint64_t requestId) override; CHIP_ERROR GetCommissioningWindowParams(CommissioningWindowParams & outParams) override; - CHIP_ERROR ReverseCommissionNode(const CommissioningWindowParams & params, const Optional & ipAddress, - const Optional & port) override; + CHIP_ERROR HandleCommissionNode(const CommissioningWindowParams & params, const Optional & ipAddress, + const Optional & port) override; ~CommissionerControlDelegate() = default; @@ -46,6 +46,12 @@ class CommissionerControlDelegate : public Delegate uint16_t mProductId = 0; char mLabelBuffer[kLabelBufferSize + 1]; Optional mLabel; + + // Parameters needed for non-basic commissioning. + uint8_t mPBKDFSaltBuffer[Crypto::kSpake2p_Max_PBKDF_Salt_Length]; + ByteSpan mPBKDFSalt; + Crypto::Spake2pVerifierSerialized mPAKEPasscodeVerifierBuffer; + ByteSpan mPAKEPasscodeVerifier; }; } // namespace CommissionerControl diff --git a/examples/fabric-bridge-app/linux/include/RpcClient.h b/examples/fabric-bridge-app/linux/include/RpcClient.h index 6913a66d8c..87ccba24f6 100644 --- a/examples/fabric-bridge-app/linux/include/RpcClient.h +++ b/examples/fabric-bridge-app/linux/include/RpcClient.h @@ -57,4 +57,15 @@ OpenCommissioningWindow(chip::Controller::CommissioningWindowPasscodeParams para CHIP_ERROR OpenCommissioningWindow(chip::Controller::CommissioningWindowVerifierParams params); +/** + * Commission a node using the specified parameters. + * + * @param params Params for commissioning the device using passcode. + * @return CHIP_ERROR An error code indicating the success or failure of the operation. + * - CHIP_NO_ERROR: The RPC command was successfully sent. + * - CHIP_ERROR_INTERNAL: An internal error occurred. + */ +CHIP_ERROR +CommissionNode(chip::Controller::CommissioningWindowPasscodeParams params); + CHIP_ERROR KeepActive(chip::NodeId nodeId, uint32_t stayActiveDurationMs); diff --git a/examples/fabric-bridge-app/linux/main.cpp b/examples/fabric-bridge-app/linux/main.cpp index 57907db887..3b65024210 100644 --- a/examples/fabric-bridge-app/linux/main.cpp +++ b/examples/fabric-bridge-app/linux/main.cpp @@ -82,7 +82,7 @@ void BridgePollingThread() #if defined(PW_RPC_FABRIC_BRIDGE_SERVICE) && PW_RPC_FABRIC_BRIDGE_SERVICE else if (ch == 'o') { - CHIP_ERROR err = OpenCommissioningWindow(chip::Controller::CommissioningWindowPasscodeParams() + CHIP_ERROR err = OpenCommissioningWindow(Controller::CommissioningWindowPasscodeParams() .SetNodeId(0x1234) .SetTimeout(300) .SetDiscriminator(3840) @@ -157,7 +157,7 @@ void AdministratorCommissioningCommandHandler::InvokeCommand(HandlerContext & ha // TODO: issues:#33784, need to make OpenCommissioningWindow synchronous if (device != nullptr && - OpenCommissioningWindow(chip::Controller::CommissioningWindowVerifierParams() + OpenCommissioningWindow(Controller::CommissioningWindowVerifierParams() .SetNodeId(device->GetNodeId()) .SetTimeout(commandData.commissioningTimeout) .SetDiscriminator(commandData.discriminator) diff --git a/src/app/clusters/commissioner-control-server/commissioner-control-server.cpp b/src/app/clusters/commissioner-control-server/commissioner-control-server.cpp index d8a655f6af..4df3973268 100644 --- a/src/app/clusters/commissioner-control-server/commissioner-control-server.cpp +++ b/src/app/clusters/commissioner-control-server/commissioner-control-server.cpp @@ -71,15 +71,15 @@ void RunDeferredCommissionNode(intptr_t commandArg) if (delegate != nullptr) { - CHIP_ERROR err = delegate->ReverseCommissionNode(info->params, info->ipAddress.GetIPAddress(), info->port); + CHIP_ERROR err = delegate->HandleCommissionNode(info->params, info->ipAddress.GetIPAddress(), info->port); if (err != CHIP_NO_ERROR) { - ChipLogError(Zcl, "ReverseCommissionNode error: %" CHIP_ERROR_FORMAT, err.Format()); + ChipLogError(Zcl, "HandleCommissionNode error: %" CHIP_ERROR_FORMAT, err.Format()); } } else { - ChipLogError(Zcl, "No delegate available for ReverseCommissionNode"); + ChipLogError(Zcl, "No delegate available for HandleCommissionNode"); } delete info; diff --git a/src/app/clusters/commissioner-control-server/commissioner-control-server.h b/src/app/clusters/commissioner-control-server/commissioner-control-server.h index 5e2422f5eb..60a4e81a93 100644 --- a/src/app/clusters/commissioner-control-server/commissioner-control-server.h +++ b/src/app/clusters/commissioner-control-server/commissioner-control-server.h @@ -101,9 +101,6 @@ class Delegate /** * @brief Validate a commission node command. * - * This command is sent by a client to request that the server begins commissioning a previously - * approved request. - * * The server SHALL return FAILURE if the CommissionNode command is not sent from the same * NodeId as the RequestCommissioningApproval or if the provided RequestId to CommissionNode * does not match the value provided to RequestCommissioningApproval. @@ -128,19 +125,17 @@ class Delegate virtual CHIP_ERROR GetCommissioningWindowParams(CommissioningWindowParams & outParams) = 0; /** - * @brief Reverse the commission node process. + * @brief Handle a commission node request. * - * When received within the timeout specified by CommissionNode, the client SHALL open a - * commissioning window on the node which the client called RequestCommissioningApproval to - * have commissioned. + * Commission a node specified by the previously approved request. * * @param params The parameters for the commissioning window. * @param ipAddress Optional IP address for the commissioning window. * @param port Optional port for the commissioning window. * @return CHIP_ERROR indicating the success or failure of the operation. */ - virtual CHIP_ERROR ReverseCommissionNode(const CommissioningWindowParams & params, const Optional & ipAddress, - const Optional & port) = 0; + virtual CHIP_ERROR HandleCommissionNode(const CommissioningWindowParams & params, const Optional & ipAddress, + const Optional & port) = 0; virtual ~Delegate() = default; }; From ae1546a3e4a692edd3c7e7bde3ea3f9bd303ab40 Mon Sep 17 00:00:00 2001 From: Alex Tsitsiura Date: Sat, 17 Aug 2024 01:10:49 +0300 Subject: [PATCH 078/165] Update compatible builds to docker version 74 (#35009) * Check which build can update to latest version * temporarry use docker version 72 * revert image for failed builds * downgrade K32W image * use K32W docker image 69 * Update compatible builds to docker version 74 * use docker version 73 for EFR32 * Prevent cancellation of task with timeout in asyncio runner. I am yet unclear why on new python/os/websocket we do not get a timeout error, however from what I could tell, wait_for would cancel the websocket.recv and that stops instead of throwing a timeout exception, resulting in a full success result. Making this change seems to make the test TestPurposefulFailureExtraReportingOnToggle pass on my machine (well ... fail as expected instead of passing with a successful stop) --------- Co-authored-by: Andrei Litvin --- .github/workflows/bloat_check.yaml | 2 +- .github/workflows/build.yaml | 6 +++--- .github/workflows/chef.yaml | 8 ++++---- .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-linux-arm.yaml | 2 +- .github/workflows/examples-linux-imx.yaml | 2 +- .github/workflows/examples-linux-standalone.yaml | 2 +- .../workflows/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 | 6 +++--- .github/workflows/examples-openiotsdk.yaml | 2 +- .github/workflows/examples-qpg.yaml | 2 +- .github/workflows/examples-stm32.yaml | 2 +- .github/workflows/examples-telink.yaml | 2 +- .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 | 2 +- .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 +- examples/all-clusters-app/ameba/README.md | 4 ++-- examples/all-clusters-minimal-app/ameba/README.md | 4 ++-- examples/light-switch-app/ameba/README.md | 4 ++-- examples/lighting-app/ameba/README.md | 4 ++-- examples/ota-requestor-app/ameba/README.md | 4 ++-- examples/pigweed-app/ameba/README.md | 4 ++-- integrations/cloudbuild/chef.yaml | 8 ++++---- integrations/cloudbuild/smoke-test.yaml | 14 +++++++------- .../py_matter_yamltests/matter_yamltests/runner.py | 3 ++- 45 files changed, 72 insertions(+), 71 deletions(-) diff --git a/.github/workflows/bloat_check.yaml b/.github/workflows/bloat_check.yaml index 12c7ee42e8..870c5f379e 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:66 + image: ghcr.io/project-chip/chip-build:74 steps: - name: Checkout diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index 58e6d14cd8..3e4f9d5705 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -42,7 +42,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build:66 + image: ghcr.io/project-chip/chip-build:74 volumes: - "/:/runner-root-volume" - "/tmp/log_output:/tmp/test_logs" @@ -138,7 +138,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build:65 + image: ghcr.io/project-chip/chip-build:74 volumes: - "/:/runner-root-volume" - "/tmp/log_output:/tmp/test_logs" @@ -455,7 +455,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build:66 + image: ghcr.io/project-chip/chip-build:74 volumes: - "/:/runner-root-volume" - "/tmp/log_output:/tmp/test_logs" diff --git a/.github/workflows/chef.yaml b/.github/workflows/chef.yaml index efb408f80b..642cdb6cf8 100644 --- a/.github/workflows/chef.yaml +++ b/.github/workflows/chef.yaml @@ -35,7 +35,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build:66 + image: ghcr.io/project-chip/chip-build:74 options: --user root steps: @@ -56,7 +56,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-esp32:67 + image: ghcr.io/project-chip/chip-build-esp32:74 options: --user root steps: @@ -77,7 +77,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-nrf-platform:66 + image: ghcr.io/project-chip/chip-build-nrf-platform:74 options: --user root steps: @@ -98,7 +98,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-telink:66 + image: ghcr.io/project-chip/chip-build-telink:74 options: --user root steps: diff --git a/.github/workflows/doxygen.yaml b/.github/workflows/doxygen.yaml index df53d87c4a..d29b620c37 100644 --- a/.github/workflows/doxygen.yaml +++ b/.github/workflows/doxygen.yaml @@ -81,7 +81,7 @@ jobs: runs-on: ubuntu-latest container: - image: ghcr.io/project-chip/chip-build-doxygen:66 + image: ghcr.io/project-chip/chip-build-doxygen:74 if: github.actor != 'restyled-io[bot]' diff --git a/.github/workflows/examples-ameba.yaml b/.github/workflows/examples-ameba.yaml index 93ae9ce31d..62a3bf5511 100644 --- a/.github/workflows/examples-ameba.yaml +++ b/.github/workflows/examples-ameba.yaml @@ -38,7 +38,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-ameba:68 + image: ghcr.io/project-chip/chip-build-ameba:74 options: --user root steps: diff --git a/.github/workflows/examples-asr.yaml b/.github/workflows/examples-asr.yaml index b6fdcfd849..840811d13d 100644 --- a/.github/workflows/examples-asr.yaml +++ b/.github/workflows/examples-asr.yaml @@ -36,7 +36,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-asr:66 + image: ghcr.io/project-chip/chip-build-asr:74 options: --user root steps: diff --git a/.github/workflows/examples-bouffalolab.yaml b/.github/workflows/examples-bouffalolab.yaml index 933a9b6036..af20a4c5b0 100644 --- a/.github/workflows/examples-bouffalolab.yaml +++ b/.github/workflows/examples-bouffalolab.yaml @@ -37,7 +37,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-bouffalolab:68 + image: ghcr.io/project-chip/chip-build-bouffalolab:74 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 9d1ba6aa6c..b486415dbc 100644 --- a/.github/workflows/examples-cc13xx_26xx.yaml +++ b/.github/workflows/examples-cc13xx_26xx.yaml @@ -45,7 +45,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-ti:54 + image: ghcr.io/project-chip/chip-build-ti:74 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" steps: diff --git a/.github/workflows/examples-cc32xx.yaml b/.github/workflows/examples-cc32xx.yaml index dedf9e9c79..091a5eeabc 100644 --- a/.github/workflows/examples-cc32xx.yaml +++ b/.github/workflows/examples-cc32xx.yaml @@ -43,7 +43,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-ti:54 + image: ghcr.io/project-chip/chip-build-ti:74 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" steps: diff --git a/.github/workflows/examples-efr32.yaml b/.github/workflows/examples-efr32.yaml index 5a8f535935..ed6f5b45fa 100644 --- a/.github/workflows/examples-efr32.yaml +++ b/.github/workflows/examples-efr32.yaml @@ -40,7 +40,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-efr32:66 + image: ghcr.io/project-chip/chip-build-efr32:73 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" steps: diff --git a/.github/workflows/examples-esp32.yaml b/.github/workflows/examples-esp32.yaml index fb0d2bc29b..5d84540eda 100644 --- a/.github/workflows/examples-esp32.yaml +++ b/.github/workflows/examples-esp32.yaml @@ -36,7 +36,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-esp32:67 + image: ghcr.io/project-chip/chip-build-esp32:74 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" @@ -126,7 +126,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-esp32:67 + image: ghcr.io/project-chip/chip-build-esp32:74 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" diff --git a/.github/workflows/examples-linux-arm.yaml b/.github/workflows/examples-linux-arm.yaml index eec3e41ec8..41fe245651 100644 --- a/.github/workflows/examples-linux-arm.yaml +++ b/.github/workflows/examples-linux-arm.yaml @@ -36,7 +36,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-crosscompile:66 + image: ghcr.io/project-chip/chip-build-crosscompile:74 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" diff --git a/.github/workflows/examples-linux-imx.yaml b/.github/workflows/examples-linux-imx.yaml index ab32eef080..6ad5f4c9d9 100644 --- a/.github/workflows/examples-linux-imx.yaml +++ b/.github/workflows/examples-linux-imx.yaml @@ -36,7 +36,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-imx:54 + image: ghcr.io/project-chip/chip-build-imx:74 steps: - name: Checkout diff --git a/.github/workflows/examples-linux-standalone.yaml b/.github/workflows/examples-linux-standalone.yaml index 5ece2df040..aa4051ea30 100644 --- a/.github/workflows/examples-linux-standalone.yaml +++ b/.github/workflows/examples-linux-standalone.yaml @@ -36,7 +36,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build:66 + image: ghcr.io/project-chip/chip-build:74 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 4ab6bbbb1c..e2ff0f9f66 100644 --- a/.github/workflows/examples-linux-tv-casting-app.yaml +++ b/.github/workflows/examples-linux-tv-casting-app.yaml @@ -36,7 +36,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build:66 + image: ghcr.io/project-chip/chip-build:74 steps: - name: Checkout diff --git a/.github/workflows/examples-mw320.yaml b/.github/workflows/examples-mw320.yaml index cd4081c51c..04664c28cf 100644 --- a/.github/workflows/examples-mw320.yaml +++ b/.github/workflows/examples-mw320.yaml @@ -39,7 +39,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build:66 + image: ghcr.io/project-chip/chip-build:74 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" steps: diff --git a/.github/workflows/examples-nrfconnect.yaml b/.github/workflows/examples-nrfconnect.yaml index 3e0452b525..13b0ae9c69 100644 --- a/.github/workflows/examples-nrfconnect.yaml +++ b/.github/workflows/examples-nrfconnect.yaml @@ -39,7 +39,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-nrf-platform:66 + image: ghcr.io/project-chip/chip-build-nrf-platform:74 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" diff --git a/.github/workflows/examples-nuttx.yaml b/.github/workflows/examples-nuttx.yaml index 3fc296f4a6..d1bf7594b0 100644 --- a/.github/workflows/examples-nuttx.yaml +++ b/.github/workflows/examples-nuttx.yaml @@ -35,7 +35,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-nuttx:66 + image: ghcr.io/project-chip/chip-build-nuttx:74 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" steps: diff --git a/.github/workflows/examples-nxp.yaml b/.github/workflows/examples-nxp.yaml index 975d9292a1..04094f0b20 100644 --- a/.github/workflows/examples-nxp.yaml +++ b/.github/workflows/examples-nxp.yaml @@ -39,7 +39,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-k32w:71 + image: ghcr.io/project-chip/chip-build-k32w:74 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" steps: @@ -150,7 +150,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-rw61x:66 + image: ghcr.io/project-chip/chip-build-rw61x:74 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" steps: @@ -212,7 +212,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-nxp-zephyr:66 + image: ghcr.io/project-chip/chip-build-nxp-zephyr:74 steps: - name: Checkout diff --git a/.github/workflows/examples-openiotsdk.yaml b/.github/workflows/examples-openiotsdk.yaml index 57577e02e7..d85a789a0b 100644 --- a/.github/workflows/examples-openiotsdk.yaml +++ b/.github/workflows/examples-openiotsdk.yaml @@ -40,7 +40,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-openiotsdk:66 + image: ghcr.io/project-chip/chip-build-openiotsdk:74 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" options: --privileged diff --git a/.github/workflows/examples-qpg.yaml b/.github/workflows/examples-qpg.yaml index 9c6f300a86..18d47cf8ef 100644 --- a/.github/workflows/examples-qpg.yaml +++ b/.github/workflows/examples-qpg.yaml @@ -39,7 +39,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build:66 + image: ghcr.io/project-chip/chip-build:74 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" steps: diff --git a/.github/workflows/examples-stm32.yaml b/.github/workflows/examples-stm32.yaml index 897f047708..6c4fa05864 100644 --- a/.github/workflows/examples-stm32.yaml +++ b/.github/workflows/examples-stm32.yaml @@ -40,7 +40,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build:66 + image: ghcr.io/project-chip/chip-build:74 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" steps: diff --git a/.github/workflows/examples-telink.yaml b/.github/workflows/examples-telink.yaml index 22007fb77a..904ae98fbc 100644 --- a/.github/workflows/examples-telink.yaml +++ b/.github/workflows/examples-telink.yaml @@ -38,7 +38,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-telink:66 + image: ghcr.io/project-chip/chip-build-telink:74 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" diff --git a/.github/workflows/examples-tizen.yaml b/.github/workflows/examples-tizen.yaml index 8c1dc592d6..f6571342a8 100644 --- a/.github/workflows/examples-tizen.yaml +++ b/.github/workflows/examples-tizen.yaml @@ -36,7 +36,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-tizen:66 + image: ghcr.io/project-chip/chip-build-tizen:74 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 0acfb21557..43aee09a82 100644 --- a/.github/workflows/full-android.yaml +++ b/.github/workflows/full-android.yaml @@ -38,7 +38,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-android:66 + image: ghcr.io/project-chip/chip-build-android:74 volumes: - "/tmp/log_output:/tmp/test_logs" diff --git a/.github/workflows/fuzzing-build.yaml b/.github/workflows/fuzzing-build.yaml index e9f2061a2c..d839317bc4 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:66 + image: ghcr.io/project-chip/chip-build:74 volumes: - "/tmp/log_output:/tmp/test_logs" diff --git a/.github/workflows/java-tests.yaml b/.github/workflows/java-tests.yaml index c70cfa6c37..a43fdfb7f4 100644 --- a/.github/workflows/java-tests.yaml +++ b/.github/workflows/java-tests.yaml @@ -42,7 +42,7 @@ jobs: runs-on: ubuntu-latest container: - image: ghcr.io/project-chip/chip-build-java:66 + image: ghcr.io/project-chip/chip-build-java:74 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 6694decc42..26e8f93920 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -35,7 +35,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build:66 + image: ghcr.io/project-chip/chip-build:74 steps: - name: Checkout diff --git a/.github/workflows/minimal-build.yaml b/.github/workflows/minimal-build.yaml index 57ccaef312..9ba9565b44 100644 --- a/.github/workflows/minimal-build.yaml +++ b/.github/workflows/minimal-build.yaml @@ -33,7 +33,7 @@ jobs: runs-on: ubuntu-latest container: - image: ghcr.io/project-chip/chip-build-minimal:66 + image: ghcr.io/project-chip/chip-build-minimal:74 steps: - name: Checkout @@ -55,7 +55,7 @@ jobs: runs-on: ubuntu-latest container: - image: ghcr.io/project-chip/chip-build-minimal:66 + image: ghcr.io/project-chip/chip-build-minimal:74 steps: - name: Checkout diff --git a/.github/workflows/qemu.yaml b/.github/workflows/qemu.yaml index 051af08a28..7c8564958d 100644 --- a/.github/workflows/qemu.yaml +++ b/.github/workflows/qemu.yaml @@ -40,7 +40,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-esp32-qemu:67 + image: ghcr.io/project-chip/chip-build-esp32-qemu:74 volumes: - "/tmp/log_output:/tmp/test_logs" diff --git a/.github/workflows/release_artifacts.yaml b/.github/workflows/release_artifacts.yaml index 481def01c6..9f25dee513 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:67 + image: ghcr.io/project-chip/chip-build-esp32:74 steps: - name: Checkout @@ -64,7 +64,7 @@ jobs: runs-on: ubuntu-latest container: - image: ghcr.io/project-chip/chip-build-efr32:56 + image: ghcr.io/project-chip/chip-build-efr32:74 steps: - name: Checkout uses: actions/checkout@v4 diff --git a/.github/workflows/smoketest-android.yaml b/.github/workflows/smoketest-android.yaml index f6e06fc1db..8ac6cd9313 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:66 + image: ghcr.io/project-chip/chip-build-android:74 volumes: - "/:/runner-root-volume" - "/tmp/log_output:/tmp/test_logs" diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml index 6974999d0d..dbbda0aa36 100644 --- a/.github/workflows/tests.yaml +++ b/.github/workflows/tests.yaml @@ -49,7 +49,7 @@ jobs: runs-on: ubuntu-latest container: - image: ghcr.io/project-chip/chip-build:54 + image: ghcr.io/project-chip/chip-build:74 options: --privileged --sysctl "net.ipv6.conf.all.disable_ipv6=0 net.ipv4.conf.all.forwarding=1 net.ipv6.conf.all.forwarding=1" @@ -455,7 +455,7 @@ jobs: runs-on: ubuntu-latest container: - image: ghcr.io/project-chip/chip-build:66 + image: ghcr.io/project-chip/chip-build:74 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 33f9cefae6..5716df1a5d 100644 --- a/.github/workflows/unit_integration_test.yaml +++ b/.github/workflows/unit_integration_test.yaml @@ -39,7 +39,7 @@ jobs: runs-on: ubuntu-latest container: - image: ghcr.io/project-chip/chip-build:66 + image: ghcr.io/project-chip/chip-build:74 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 68faf6b066..dca68cc94e 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:66 + image: ghcr.io/project-chip/chip-build:74 defaults: run: shell: sh diff --git a/.github/workflows/zap_templates.yaml b/.github/workflows/zap_templates.yaml index 8ffe08e158..5ed20b29ad 100644 --- a/.github/workflows/zap_templates.yaml +++ b/.github/workflows/zap_templates.yaml @@ -34,7 +34,7 @@ jobs: runs-on: ubuntu-20.04 container: - image: ghcr.io/project-chip/chip-build:66 + image: ghcr.io/project-chip/chip-build:74 defaults: run: shell: sh diff --git a/examples/all-clusters-app/ameba/README.md b/examples/all-clusters-app/ameba/README.md index adf6e59059..4251291f48 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:54 + $ docker pull ghcr.io/project-chip/chip-build-ameba:74 - Run docker container: - $ docker run -it -v ${CHIP_DIR}:/root/chip ghcr.io/project-chip/chip-build-ameba:54 + $ docker run -it -v ${CHIP_DIR}:/root/chip ghcr.io/project-chip/chip-build-ameba:74 - Setup build environment: diff --git a/examples/all-clusters-minimal-app/ameba/README.md b/examples/all-clusters-minimal-app/ameba/README.md index b4e72ca32d..31969a2196 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:54 + $ docker pull ghcr.io/project-chip/chip-build-ameba:74 ``` - Run docker container: ``` - $ docker run -it -v ${CHIP_DIR}:/root/chip ghcr.io/project-chip/chip-build-ameba:54 + $ docker run -it -v ${CHIP_DIR}:/root/chip ghcr.io/project-chip/chip-build-ameba:74 ``` - Setup build environment: diff --git a/examples/light-switch-app/ameba/README.md b/examples/light-switch-app/ameba/README.md index 3476d6d8cd..7d168d3f48 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:54 + $ docker pull ghcr.io/project-chip/chip-build-ameba:74 - Run docker container: - $ docker run -it -v ${CHIP_DIR}:/root/chip ghcr.io/project-chip/chip-build-ameba:54 + $ docker run -it -v ${CHIP_DIR}:/root/chip ghcr.io/project-chip/chip-build-ameba:74 - Setup build environment: diff --git a/examples/lighting-app/ameba/README.md b/examples/lighting-app/ameba/README.md index b170e90263..d94d642dbd 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:54 + $ docker pull ghcr.io/project-chip/chip-build-ameba:74 - Run docker container: - $ docker run -it -v ${CHIP_DIR}:/root/chip ghcr.io/project-chip/chip-build-ameba:54 + $ docker run -it -v ${CHIP_DIR}:/root/chip ghcr.io/project-chip/chip-build-ameba:74 - Setup build environment: diff --git a/examples/ota-requestor-app/ameba/README.md b/examples/ota-requestor-app/ameba/README.md index a5de1316eb..607a9abd08 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:54 + $ docker pull ghcr.io/project-chip/chip-build-ameba:74 - Run docker container: - $ docker run -it -v ${CHIP_DIR}:/root/chip ghcr.io/project-chip/chip-build-ameba:54 + $ docker run -it -v ${CHIP_DIR}:/root/chip ghcr.io/project-chip/chip-build-ameba:74 - Setup build environment: diff --git a/examples/pigweed-app/ameba/README.md b/examples/pigweed-app/ameba/README.md index 7086f7fe87..da4dd83ca3 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:54 + $ docker pull ghcr.io/project-chip/chip-build-ameba:74 - Run docker container: - $ docker run -it -v ${CHIP_DIR}:/root/chip ghcr.io/project-chip/chip-build-ameba:54 + $ docker run -it -v ${CHIP_DIR}:/root/chip ghcr.io/project-chip/chip-build-ameba:74 - Setup build environment: diff --git a/integrations/cloudbuild/chef.yaml b/integrations/cloudbuild/chef.yaml index 0c4035fcb6..7ba0882e03 100644 --- a/integrations/cloudbuild/chef.yaml +++ b/integrations/cloudbuild/chef.yaml @@ -1,5 +1,5 @@ steps: - - name: "ghcr.io/project-chip/chip-build-vscode:66" + - name: "ghcr.io/project-chip/chip-build-vscode:74" 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:66" + - name: "ghcr.io/project-chip/chip-build-vscode:74" # 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:66" + - name: "ghcr.io/project-chip/chip-build-vscode:74" env: - PW_ENVIRONMENT_ROOT=/pwenv args: @@ -38,7 +38,7 @@ steps: - name: pwenv path: /pwenv - - name: "ghcr.io/project-chip/chip-build-vscode:66" + - name: "ghcr.io/project-chip/chip-build-vscode:74" env: - PW_ENVIRONMENT_ROOT=/pwenv args: diff --git a/integrations/cloudbuild/smoke-test.yaml b/integrations/cloudbuild/smoke-test.yaml index ef69af5db7..af3ed1f3b4 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:66" + - name: "ghcr.io/project-chip/chip-build-vscode:74" 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:66" + - name: "ghcr.io/project-chip/chip-build-vscode:74" # 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:66" + - name: "ghcr.io/project-chip/chip-build-vscode:74" 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:66" + - name: "ghcr.io/project-chip/chip-build-vscode:74" id: NRFConnect env: - PW_ENVIRONMENT_ROOT=/pwenv @@ -66,7 +66,7 @@ steps: - name: pwenv path: /pwenv - - name: "ghcr.io/project-chip/chip-build-vscode:66" + - name: "ghcr.io/project-chip/chip-build-vscode:74" id: EFR32 env: - PW_ENVIRONMENT_ROOT=/pwenv @@ -88,7 +88,7 @@ steps: - name: pwenv path: /pwenv - - name: "ghcr.io/project-chip/chip-build-vscode:66" + - name: "ghcr.io/project-chip/chip-build-vscode:74" id: Linux env: - PW_ENVIRONMENT_ROOT=/pwenv @@ -141,7 +141,7 @@ steps: - name: pwenv path: /pwenv - - name: "ghcr.io/project-chip/chip-build-vscode:66" + - name: "ghcr.io/project-chip/chip-build-vscode:74" id: Android env: - PW_ENVIRONMENT_ROOT=/pwenv diff --git a/scripts/py_matter_yamltests/matter_yamltests/runner.py b/scripts/py_matter_yamltests/matter_yamltests/runner.py index 541a261a43..05fe8fc54e 100644 --- a/scripts/py_matter_yamltests/matter_yamltests/runner.py +++ b/scripts/py_matter_yamltests/matter_yamltests/runner.py @@ -162,7 +162,8 @@ async def _run_with_timeout(self, parser: TestParser, config: TestRunnerConfig): try: if config.auto_start_stop: await self.start() - status = await asyncio.wait_for(self._run(parser, config), parser.timeout) + task = self._run(parser, config) + status = await asyncio.wait_for(asyncio.shield(task), parser.timeout) except (Exception, CancelledError) as exception: status = exception finally: From cd04522004de548373d99e06b61b3af3fd718139 Mon Sep 17 00:00:00 2001 From: Pradip De Date: Fri, 16 Aug 2024 15:27:46 -0700 Subject: [PATCH 079/165] Fix test code build issues when INET_CONFIG_TCP_ENDPOINT is set to false (#35027) --- src/inet/tests/TestInetEndPoint.cpp | 16 +++++- src/inet/tests/inet-layer-test-tool.cpp | 21 ++++++- src/messaging/tests/echo/echo_requester.cpp | 64 ++++++++++++++------- src/messaging/tests/echo/echo_responder.cpp | 10 +++- src/transport/SessionManager.cpp | 12 ++-- 5 files changed, 89 insertions(+), 34 deletions(-) diff --git a/src/inet/tests/TestInetEndPoint.cpp b/src/inet/tests/TestInetEndPoint.cpp index 10209c0ba9..426f749f09 100644 --- a/src/inet/tests/TestInetEndPoint.cpp +++ b/src/inet/tests/TestInetEndPoint.cpp @@ -256,9 +256,11 @@ TEST_F(TestInetEndPoint, TestInetEndPointInternal) InterfaceId intId; // EndPoint - UDPEndPoint * testUDPEP = nullptr; + UDPEndPoint * testUDPEP = nullptr; +#if INET_CONFIG_ENABLE_TCP_ENDPOINT TCPEndPoint * testTCPEP1 = nullptr; - PacketBufferHandle buf = PacketBufferHandle::New(PacketBuffer::kMaxSize); +#endif // INET_CONFIG_ENABLE_TCP_ENDPOINT + PacketBufferHandle buf = PacketBufferHandle::New(PacketBuffer::kMaxSize); // init all the EndPoints SYSTEM_STATS_RESET(System::Stats::kInetLayer_NumUDPEps); @@ -266,10 +268,12 @@ TEST_F(TestInetEndPoint, TestInetEndPointInternal) ASSERT_EQ(err, CHIP_NO_ERROR); EXPECT_TRUE(SYSTEM_STATS_TEST_IN_USE(System::Stats::kInetLayer_NumUDPEps, 1)); +#if INET_CONFIG_ENABLE_TCP_ENDPOINT SYSTEM_STATS_RESET(System::Stats::kInetLayer_NumTCPEps); err = gTCP.NewEndPoint(&testTCPEP1); ASSERT_EQ(err, CHIP_NO_ERROR); - EXPECT_TRUE(SYSTEM_STATS_TEST_IN_USE(System::Stats::kInetLayer_NumUDPEps, 1)); + EXPECT_TRUE(SYSTEM_STATS_TEST_IN_USE(System::Stats::kInetLayer_NumTCPEps, 1)); +#endif // INET_CONFIG_ENABLE_TCP_ENDPOINT err = InterfaceId::Null().GetLinkLocalAddr(&addr); @@ -323,6 +327,7 @@ TEST_F(TestInetEndPoint, TestInetEndPointInternal) testUDPEP->Free(); EXPECT_TRUE(SYSTEM_STATS_TEST_IN_USE(System::Stats::kInetLayer_NumUDPEps, 0)); +#if INET_CONFIG_ENABLE_TCP_ENDPOINT // TcpEndPoint special cases to cover the error branch err = testTCPEP1->GetPeerInfo(nullptr, nullptr); EXPECT_EQ(err, CHIP_ERROR_INCORRECT_STATE); @@ -362,6 +367,7 @@ TEST_F(TestInetEndPoint, TestInetEndPointInternal) testTCPEP1->Free(); EXPECT_TRUE(SYSTEM_STATS_TEST_IN_USE(System::Stats::kInetLayer_NumTCPEps, 0)); EXPECT_TRUE(SYSTEM_STATS_TEST_HIGH_WATER_MARK(System::Stats::kInetLayer_NumTCPEps, 1)); +#endif // INET_CONFIG_ENABLE_TCP_ENDPOINT } #if !CHIP_SYSTEM_CONFIG_POOL_USE_HEAP @@ -369,7 +375,9 @@ TEST_F(TestInetEndPoint, TestInetEndPointInternal) TEST_F(TestInetEndPoint, TestInetEndPointLimit) { UDPEndPoint * testUDPEP[INET_CONFIG_NUM_UDP_ENDPOINTS + 1] = { nullptr }; +#if INET_CONFIG_ENABLE_TCP_ENDPOINT TCPEndPoint * testTCPEP[INET_CONFIG_NUM_TCP_ENDPOINTS + 1] = { nullptr }; +#endif // INET_CONFIG_ENABLE_TCP_ENDPOINT CHIP_ERROR err = CHIP_NO_ERROR; @@ -388,6 +396,7 @@ TEST_F(TestInetEndPoint, TestInetEndPointLimit) const int udpHighWaterMark = udpCount; EXPECT_TRUE(SYSTEM_STATS_TEST_HIGH_WATER_MARK(System::Stats::kInetLayer_NumUDPEps, udpHighWaterMark)); +#if INET_CONFIG_ENABLE_TCP_ENDPOINT int tcpCount = 0; SYSTEM_STATS_RESET(System::Stats::kInetLayer_NumTCPEps); for (int i = INET_CONFIG_NUM_TCP_ENDPOINTS; i >= 0; --i) @@ -402,6 +411,7 @@ TEST_F(TestInetEndPoint, TestInetEndPointLimit) } const int tcpHighWaterMark = tcpCount; EXPECT_TRUE(SYSTEM_STATS_TEST_HIGH_WATER_MARK(System::Stats::kInetLayer_NumTCPEps, tcpHighWaterMark)); +#endif // INET_CONFIG_ENABLE_TCP_ENDPOINT #if CHIP_SYSTEM_CONFIG_NUM_TIMERS // Verify same aComplete and aAppState args do not exhaust timer pool diff --git a/src/inet/tests/inet-layer-test-tool.cpp b/src/inet/tests/inet-layer-test-tool.cpp index e276600fa1..0c1158a9ed 100644 --- a/src/inet/tests/inet-layer-test-tool.cpp +++ b/src/inet/tests/inet-layer-test-tool.cpp @@ -88,11 +88,14 @@ static const uint32_t kExpectedTxSizeDefault = kExpectedRxSizeDefault; static const uint32_t kOptFlagsDefault = (kOptFlagUseIPv6 | kOptFlagUseUDPIP); +#if INET_CONFIG_ENABLE_TCP_ENDPOINT static TCPEndPoint * sTCPIPEndPoint = nullptr; // Used for connect/send/receive static TCPEndPoint * sTCPIPListenEndPoint = nullptr; // Used for accept/listen -static UDPEndPoint * sUDPIPEndPoint = nullptr; +static const uint16_t kTCPPort = kUDPPort; +#endif // INET_CONFIG_ENABLE_TCP_ENDPOINT + +static UDPEndPoint * sUDPIPEndPoint = nullptr; -static const uint16_t kTCPPort = kUDPPort; // clang-format off static TestState sTestState = { @@ -184,6 +187,7 @@ static OptionSet * sToolOptionSets[] = namespace chip { namespace Inet { +#if INET_CONFIG_ENABLE_TCP_ENDPOINT class TCPTest { public: @@ -193,6 +197,7 @@ class TCPTest return endPoint->mState == TCPEndPoint::State::kConnected || endPoint->mState == TCPEndPoint::State::kReceiveShutdown; } }; +#endif // INET_CONFIG_ENABLE_TCP_ENDPOINT } // namespace Inet } // namespace chip @@ -502,6 +507,7 @@ static bool HandleDataReceived(const PacketBufferHandle & aBuffer, bool aCheckBu // TCP Endpoint Callbacks +#if INET_CONFIG_ENABLE_TCP_ENDPOINT void HandleTCPConnectionComplete(TCPEndPoint * aEndPoint, CHIP_ERROR aError) { CHIP_ERROR lStatus; @@ -636,6 +642,7 @@ static void HandleTCPConnectionReceived(TCPEndPoint * aListenEndPoint, TCPEndPoi sTCPIPEndPoint = aConnectEndPoint; } +#endif // INET_CONFIG_ENABLE_TCP_ENDPOINT // UDP Endpoint Callbacks @@ -673,11 +680,13 @@ static bool IsTransportReadyForSend() return (sUDPIPEndPoint != nullptr); } +#if INET_CONFIG_ENABLE_TCP_ENDPOINT if ((gOptFlags & kOptFlagUseTCPIP) == kOptFlagUseTCPIP) { return (sTCPIPEndPoint != nullptr) && (sTCPIPEndPoint->PendingSendLength() == 0) && TCPTest::StateIsConnectedOrReceiveShutdown(sTCPIPEndPoint); } +#endif // INET_CONFIG_ENABLE_TCP_ENDPOINT return false; } @@ -686,6 +695,7 @@ static CHIP_ERROR PrepareTransportForSend() { CHIP_ERROR lStatus = CHIP_NO_ERROR; +#if INET_CONFIG_ENABLE_TCP_ENDPOINT if (gOptFlags & kOptFlagUseTCPIP) { if (sTCPIPEndPoint == nullptr) @@ -702,6 +712,7 @@ static CHIP_ERROR PrepareTransportForSend() INET_FAIL_ERROR(lStatus, "TCPEndPoint::Connect failed"); } } +#endif // INET_CONFIG_ENABLE_TCP_ENDPOINT return (lStatus); } @@ -722,6 +733,7 @@ static CHIP_ERROR DriveSendForDestination(const IPAddress & aAddress, uint16_t a ReturnErrorOnFailure(sUDPIPEndPoint->SendTo(aAddress, kUDPPort, std::move(lBuffer))); } +#if INET_CONFIG_ENABLE_TCP_ENDPOINT else if ((gOptFlags & kOptFlagUseTCPIP) == kOptFlagUseTCPIP) { const uint32_t lFirstValue = sTestState.mStats.mTransmit.mActual; @@ -737,6 +749,7 @@ static CHIP_ERROR DriveSendForDestination(const IPAddress & aAddress, uint16_t a ReturnErrorOnFailure(sTCPIPEndPoint->Send(std::move(lBuffer))); } +#endif // INET_CONFIG_ENABLE_TCP_ENDPOINT return CHIP_NO_ERROR; } @@ -838,6 +851,7 @@ static void StartTest() lStatus = sUDPIPEndPoint->Listen(HandleUDPMessageReceived, HandleUDPReceiveError); INET_FAIL_ERROR(lStatus, "UDPEndPoint::Listen failed"); } +#if INET_CONFIG_ENABLE_TCP_ENDPOINT else if (gOptFlags & kOptFlagUseTCPIP) { const uint16_t lConnectionBacklogMax = 1; @@ -855,6 +869,7 @@ static void StartTest() lStatus = sTCPIPListenEndPoint->Listen(lConnectionBacklogMax); INET_FAIL_ERROR(lStatus, "TCPEndPoint::Listen failed"); } +#endif // INET_CONFIG_ENABLE_TCP_ENDPOINT } if (Common::IsReceiver()) @@ -870,6 +885,7 @@ static void CleanupTest() // Release the resources associated with the allocated end points. +#if INET_CONFIG_ENABLE_TCP_ENDPOINT if (sTCPIPEndPoint != nullptr) { sTCPIPEndPoint->Close(); @@ -881,6 +897,7 @@ static void CleanupTest() sTCPIPListenEndPoint->Shutdown(); sTCPIPListenEndPoint->Free(); } +#endif // INET_CONFIG_ENABLE_TCP_ENDPOINT if (sUDPIPEndPoint != nullptr) { diff --git a/src/messaging/tests/echo/echo_requester.cpp b/src/messaging/tests/echo/echo_requester.cpp index b06edb359b..c3aa3f6085 100644 --- a/src/messaging/tests/echo/echo_requester.cpp +++ b/src/messaging/tests/echo/echo_requester.cpp @@ -51,9 +51,6 @@ namespace { // Max value for the number of EchoRequests sent. constexpr size_t kMaxEchoCount = 3; -// Max value for the number of tcp connect attempts. -constexpr size_t kMaxTCPConnectAttempts = 3; - // The CHIP Echo interval time. constexpr chip::System::Clock::Timeout gEchoInterval = chip::System::Clock::Seconds16(1); @@ -63,15 +60,17 @@ constexpr chip::FabricIndex gFabricIndex = 0; chip::Protocols::Echo::EchoClient gEchoClient; chip::TransportMgr gUDPManager; +#if INET_CONFIG_ENABLE_TCP_ENDPOINT +// Max value for the number of tcp connect attempts. +constexpr size_t kMaxTCPConnectAttempts = 3; + chip::TransportMgr> gTCPManager; -chip::Inet::IPAddress gDestAddr; -chip::SessionHolder gSession; chip::Transport::AppTCPConnectionCallbackCtxt gAppTCPConnCbCtxt; chip::Transport::ActiveTCPConnectionState * gActiveTCPConnState = nullptr; -// The last time a CHIP Echo was attempted to be sent. -chip::System::Clock::Timestamp gLastEchoTime = chip::System::Clock::kZero; +static void HandleConnectionAttemptComplete(chip::Transport::ActiveTCPConnectionState * conn, CHIP_ERROR conErr); +static void HandleConnectionClosed(chip::Transport::ActiveTCPConnectionState * conn, CHIP_ERROR conErr); // True, if client is still connecting to the server, false otherwise. static bool gClientConInProgress = false; @@ -79,6 +78,16 @@ static bool gClientConInProgress = false; // True, once client connection to server is established. static bool gClientConEstablished = false; +bool gUseTCP = false; +uint64_t gTCPConnAttemptCount = 0; +#endif // INET_CONFIG_ENABLE_TCP_ENDPOINT + +chip::Inet::IPAddress gDestAddr; +chip::SessionHolder gSession; + +// The last time a CHIP Echo was attempted to be sent. +chip::System::Clock::Timestamp gLastEchoTime = chip::System::Clock::kZero; + // The handle to the TCP connection to the peer. // static chip::Transport::ActiveTCPConnectionState * gCon = nullptr; @@ -88,16 +97,9 @@ uint64_t gEchoCount = 0; // Count of the number of EchoResponses received. uint64_t gEchoRespCount = 0; -bool gUseTCP = false; - -uint64_t gTCPConnAttemptCount = 0; - CHIP_ERROR SendEchoRequest(); void EchoTimerHandler(chip::System::Layer * systemLayer, void * appState); -static void HandleConnectionAttemptComplete(chip::Transport::ActiveTCPConnectionState * conn, CHIP_ERROR conErr); -static void HandleConnectionClosed(chip::Transport::ActiveTCPConnectionState * conn, CHIP_ERROR conErr); - void Shutdown() { chip::DeviceLayer::SystemLayer().CancelTimer(EchoTimerHandler, nullptr); @@ -170,15 +172,17 @@ CHIP_ERROR SendEchoRequest() return err; } -CHIP_ERROR EstablishSecureSession(chip::Transport::ActiveTCPConnectionState * conn = nullptr) +CHIP_ERROR EstablishSecureSession() { char peerAddrBuf[chip::Transport::PeerAddress::kMaxToStringSize]; chip::Transport::PeerAddress peerAddr; +#if INET_CONFIG_ENABLE_TCP_ENDPOINT if (gUseTCP) { peerAddr = chip::Transport::PeerAddress::TCP(gDestAddr, CHIP_PORT); } else +#endif // INET_CONFIG_ENABLE_TCP_ENDPOINT { peerAddr = chip::Transport::PeerAddress::UDP(gDestAddr, CHIP_PORT, chip::Inet::InterfaceId::Null()); } @@ -195,11 +199,13 @@ CHIP_ERROR EstablishSecureSession(chip::Transport::ActiveTCPConnectionState * co } else { +#if INET_CONFIG_ENABLE_TCP_ENDPOINT if (gUseTCP) { - printf("Associating secure session with connection %p\n", conn); - gSession.Get().Value()->AsSecureSession()->SetTCPConnection(conn); + printf("Associating secure session with connection %p\n", gActiveTCPConnState); + gSession.Get().Value()->AsSecureSession()->SetTCPConnection(gActiveTCPConnState); } +#endif // INET_CONFIG_ENABLE_TCP_ENDPOINT printf("Successfully established secure session with peer at %s\n", peerAddrBuf); } @@ -207,6 +213,7 @@ CHIP_ERROR EstablishSecureSession(chip::Transport::ActiveTCPConnectionState * co return err; } +#if INET_CONFIG_ENABLE_TCP_ENDPOINT void CloseConnection() { char peerAddrBuf[chip::Transport::PeerAddress::kMaxToStringSize]; @@ -225,7 +232,7 @@ void HandleConnectionAttemptComplete(chip::Transport::ActiveTCPConnectionState * { chip::DeviceLayer::PlatformMgr().StopEventLoopTask(); - if (err != CHIP_NO_ERROR) + if (err != CHIP_NO_ERROR || conn != gActiveTCPConnState) { printf("Connection FAILED with err: %s\n", chip::ErrorStr(err)); @@ -235,7 +242,7 @@ void HandleConnectionAttemptComplete(chip::Transport::ActiveTCPConnectionState * return; } - err = EstablishSecureSession(conn); + err = EstablishSecureSession(); if (err != CHIP_NO_ERROR) { printf("Secure session FAILED with err: %s\n", chip::ErrorStr(err)); @@ -281,6 +288,7 @@ void EstablishTCPConnection() gClientConInProgress = true; } +#endif // INET_CONFIG_ENABLE_TCP_ENDPOINT void HandleEchoResponseReceived(chip::Messaging::ExchangeContext * ec, chip::System::PacketBufferHandle && payload) { @@ -313,10 +321,12 @@ int main(int argc, char * argv[]) ExitNow(err = CHIP_ERROR_INVALID_ARGUMENT); } +#if INET_CONFIG_ENABLE_TCP_ENDPOINT if ((argc == 3) && (strcmp(argv[2], "--tcp") == 0)) { gUseTCP = true; } +#endif // INET_CONFIG_ENABLE_TCP_ENDPOINT if (!chip::Inet::IPAddress::FromString(argv[1], gDestAddr)) { @@ -332,6 +342,7 @@ int main(int argc, char * argv[]) InitializeChip(); +#if INET_CONFIG_ENABLE_TCP_ENDPOINT if (gUseTCP) { err = gTCPManager.Init(chip::Transport::TcpListenParameters(chip::DeviceLayer::TCPEndPointManager()) @@ -348,6 +359,7 @@ int main(int argc, char * argv[]) gAppTCPConnCbCtxt.connClosedCb = HandleConnectionClosed; } else +#endif // INET_CONFIG_ENABLE_TCP_ENDPOINT { err = gUDPManager.Init(chip::Transport::UdpListenParameters(chip::DeviceLayer::UDPEndPointManager()) .SetAddressType(chip::Inet::IPAddressType::kIPv6) @@ -365,13 +377,14 @@ int main(int argc, char * argv[]) err = gMessageCounterManager.Init(&gExchangeManager); SuccessOrExit(err); +#if INET_CONFIG_ENABLE_TCP_ENDPOINT if (gUseTCP) { while (!gClientConEstablished) { // For TCP transport, attempt to establish the connection to the CHIP echo responder. - // On Connection completion, call EstablishSecureSession(conn); + // On Connection completion, call EstablishSecureSession(); EstablishTCPConnection(); chip::DeviceLayer::PlatformMgr().RunEventLoop(); @@ -383,9 +396,10 @@ int main(int argc, char * argv[]) } } else +#endif // INET_CONFIG_ENABLE_TCP_ENDPOINT { // Start the CHIP session to the CHIP echo responder. - err = EstablishSecureSession(nullptr); + err = EstablishSecureSession(); SuccessOrExit(err); } @@ -402,16 +416,22 @@ int main(int argc, char * argv[]) gUDPManager.Close(); +#if INET_CONFIG_ENABLE_TCP_ENDPOINT if (gUseTCP) { gTCPManager.TCPDisconnect(chip::Transport::PeerAddress::TCP(gDestAddr)); } gTCPManager.Close(); +#endif // INET_CONFIG_ENABLE_TCP_ENDPOINT Shutdown(); exit: - if ((err != CHIP_NO_ERROR) || (gEchoRespCount != kMaxEchoCount) || (gTCPConnAttemptCount > kMaxTCPConnectAttempts)) + if ((err != CHIP_NO_ERROR) || (gEchoRespCount != kMaxEchoCount) +#if INET_CONFIG_ENABLE_TCP_ENDPOINT + || (gTCPConnAttemptCount > kMaxTCPConnectAttempts) +#endif // INET_CONFIG_ENABLE_TCP_ENDPOINT + ) { printf("ChipEchoClient failed: %s\n", chip::ErrorStr(err)); exit(EXIT_FAILURE); diff --git a/src/messaging/tests/echo/echo_responder.cpp b/src/messaging/tests/echo/echo_responder.cpp index 0cd2366a1f..4655063584 100644 --- a/src/messaging/tests/echo/echo_responder.cpp +++ b/src/messaging/tests/echo/echo_responder.cpp @@ -45,7 +45,9 @@ namespace { // The EchoServer object. chip::Protocols::Echo::EchoServer gEchoServer; chip::TransportMgr gUDPManager; +#if INET_CONFIG_ENABLE_TCP_ENDPOINT chip::TransportMgr> gTCPManager; +#endif // INET_CONFIG_ENABLE_TCP_ENDPOINT chip::SessionHolder gSession; // Callback handler when a CHIP EchoRequest is received. @@ -60,7 +62,9 @@ int main(int argc, char * argv[]) { CHIP_ERROR err = CHIP_NO_ERROR; chip::Transport::PeerAddress peer(chip::Transport::Type::kUndefined); - bool useTCP = false; +#if INET_CONFIG_ENABLE_TCP_ENDPOINT + bool useTCP = false; +#endif // INET_CONFIG_ENABLE_TCP_ENDPOINT bool disableEcho = false; const chip::FabricIndex gFabricIndex = 0; @@ -71,10 +75,12 @@ int main(int argc, char * argv[]) ExitNow(err = CHIP_ERROR_INVALID_ARGUMENT); } +#if INET_CONFIG_ENABLE_TCP_ENDPOINT if ((argc == 2) && (strcmp(argv[1], "--tcp") == 0)) { useTCP = true; } +#endif // INET_CONFIG_ENABLE_TCP_ENDPOINT if ((argc == 2) && (strcmp(argv[1], "--disable") == 0)) { @@ -83,6 +89,7 @@ int main(int argc, char * argv[]) InitializeChip(); +#if INET_CONFIG_ENABLE_TCP_ENDPOINT if (useTCP) { err = gTCPManager.Init(chip::Transport::TcpListenParameters(chip::DeviceLayer::TCPEndPointManager()) @@ -94,6 +101,7 @@ int main(int argc, char * argv[]) SuccessOrExit(err); } else +#endif // INET_CONFIG_ENABLE_TCP_ENDPOINT { err = gUDPManager.Init(chip::Transport::UdpListenParameters(chip::DeviceLayer::UDPEndPointManager()) .SetAddressType(chip::Inet::IPAddressType::kIPv6)); diff --git a/src/transport/SessionManager.cpp b/src/transport/SessionManager.cpp index 17065e319c..d958247945 100644 --- a/src/transport/SessionManager.cpp +++ b/src/transport/SessionManager.cpp @@ -1269,18 +1269,18 @@ Optional SessionManager::FindSecureSessionForNode(ScopedNodeId pe if (session->IsActiveSession() && session->GetPeer() == peerNodeId && (!type.HasValue() || type.Value() == session->GetSecureSessionType())) { -#if INET_CONFIG_ENABLE_TCP_ENDPOINT - if ((transportPayloadCapability == TransportPayloadCapability::kMRPOrTCPCompatiblePayload || - transportPayloadCapability == TransportPayloadCapability::kLargePayload) && - session->GetTCPConnection() != nullptr) + if (transportPayloadCapability == TransportPayloadCapability::kMRPOrTCPCompatiblePayload || + transportPayloadCapability == TransportPayloadCapability::kLargePayload) { +#if INET_CONFIG_ENABLE_TCP_ENDPOINT // Set up a TCP transport based session as standby - if ((tcpSession == nullptr) || (tcpSession->GetLastActivityTime() < session->GetLastActivityTime())) + if ((tcpSession == nullptr || tcpSession->GetLastActivityTime() < session->GetLastActivityTime()) && + session->GetTCPConnection() != nullptr) { tcpSession = session; } - } #endif // INET_CONFIG_ENABLE_TCP_ENDPOINT + } if ((mrpSession == nullptr) || (mrpSession->GetLastActivityTime() < session->GetLastActivityTime())) { From 44456d77f7176bf590f08fb021d53b7c5741af6a Mon Sep 17 00:00:00 2001 From: Andrei Litvin Date: Fri, 16 Aug 2024 21:35:18 -0400 Subject: [PATCH 080/165] Prevent cancellation of task with timeout in asyncio runner. (#35045) I am yet unclear why on new python/os/websocket we do not get a timeout error, however from what I could tell, wait_for would cancel the websocket.recv and that stops instead of throwing a timeout exception, resulting in a full success result. Making this change seems to make the test TestPurposefulFailureExtraReportingOnToggle pass on my machine (well ... fail as expected instead of passing with a successful stop) Co-authored-by: Andrei Litvin From ebc2576cc6fa5427484be6b3a6e3c0d5802aeff9 Mon Sep 17 00:00:00 2001 From: C Freeman Date: Sat, 17 Aug 2024 16:41:17 -0400 Subject: [PATCH 081/165] TC-IDM-10.2: Fix error message (#35044) --- src/python_testing/TC_DeviceConformance.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/python_testing/TC_DeviceConformance.py b/src/python_testing/TC_DeviceConformance.py index d847ef6aeb..3cc57e2b01 100644 --- a/src/python_testing/TC_DeviceConformance.py +++ b/src/python_testing/TC_DeviceConformance.py @@ -136,7 +136,7 @@ def record_warning(location, problem): conformance_decision_with_choice = xml_feature.conformance(feature_map, attribute_list, all_command_list) if conformance_decision_with_choice.decision == ConformanceDecision.MANDATORY and feature_mask not in feature_masks: record_error( - location=location, problem=f'Required feature with mask 0x{f:02x} is not present in feature map. {conformance_str(xml_feature.conformance, feature_map, self.xml_clusters[cluster_id].features)}') + location=location, problem=f'Required feature with mask 0x{feature_mask:02x} is not present in feature map. {conformance_str(xml_feature.conformance, feature_map, self.xml_clusters[cluster_id].features)}') # Attribute conformance checking for attribute_id, attribute in cluster.items(): From 1e58f964d693cb803be59d67b54b194dff83bc22 Mon Sep 17 00:00:00 2001 From: Kiel Oleson Date: Sat, 17 Aug 2024 15:00:16 -0700 Subject: [PATCH 082/165] [Darwin] New XPC Service (#34961) * empty xpc service files * XPC service needs to be C++ to use MTRLogging * add tests; stub method signature * start configuring test XPC listener * add first test method to XPC service protocol * tests: remove peformance test; add headers * make MTRXPCService testable * more working lines of XPC listener setup * add dummy XPC service for testing * add replying method to service protocol / implementation * remove log - reply contents can be asserted * make test interesting * linty formatty * remove personal development team from pbxproj * fix new file headers * less whitespace * Restyled by whitespace * Restyled by clang-format * add new XPC device controller * sketch out a first XPC method * store WIP for rebase * fix pbxproj merge mistake * make WIP slightly more sensible * WIP: remote proxy obj in `MTRDeviceController_XPC` * more experiments * WIP: return type issue run `MTRXPCServiceTests testMTRXPCServiceSetup` and see selection of proxy object method in `MTRDeviceController_XPC.m`/`initWithXPCListenerEndpointForTesting` around line 44 to see the problem. * add `MTRDevice_XPC` nothing exciting yet * add device controller over XPC parameters stub * add init split for XPC device controllers not yet implemented, but there * rename new XPC parameters class `OverXPC` is already taken / means something else * Restyled by whitespace * Restyled by clang-format * remove failing exploratory test * lintfix * Examples * quickly attempt to fix test unused variable -> warning -> error * Restyled by whitespace * Restyled by clang-format * inevitably the file will need to be obj-C++ * prepare to use mach service name to create XPC connection * allow for other XPC controller connection types for now once mach service is working, i don't expect to need others, but easier to collapse classes than raise. * constant for well-known matter plugin service name * note to self and re-ordering of this code now what `XPCParameters` is a subclass * XPC parameters should support secure coding * don't keep around object proxy; make a new one when needed. try calling the `checkIn` method when connecting. remove old test methods that served their purpose. * that doesn't need to be there. * Restyled by whitespace * Restyled by clang-format * no longer fighting with compiler, have some `instancetype` * extremely normal object construction * somehow this header got thrown out * Restyled by whitespace * Restyled by clang-format * Updating XPC interfaces * hide `initWithMachServiceName:options:` constructor tvOS/iOS compilation issues need a look * make `MTRDeviceController_XPC` an XPC client via `MTRXPCClientProtocol_MTRDeviceController`, which for the moment is empty * remove initial tests they served their purpose well but are no longer relevant * call mach service constructor when appropriate also logging * remove some obsolete test methods * more obsoletes fixed * more obsolete removal and logging tweaks * buildability tweaks * Moving along * Fixing header * Fixing macros and codable * Adding invoke? * Restyled by whitespace * Restyled by clang-format * Actually hooking up to XPCConnection * Actually hooking up to XPCConnection * Adding XPC Parameters * Adding XPC Parameter hookup * Restyled by whitespace * Restyled by clang-format * true => YES --------- Co-authored-by: Restyled.io Co-authored-by: Justin Wood --- src/darwin/Framework/CHIP/MTRCluster.h | 6 +- src/darwin/Framework/CHIP/MTRCluster.mm | 123 ++++++++++ .../Framework/CHIP/MTRDefines_Internal.h | 47 ++++ .../Framework/CHIP/MTRDeviceController.mm | 7 +- .../CHIP/MTRDeviceControllerParameters.h | 22 ++ .../CHIP/MTRDeviceControllerStartupParams.mm | 17 ++ .../CHIP/MTRDeviceControllerXPCParameters.h | 31 +++ .../CHIP/MTRDeviceControllerXPCParameters.mm | 35 +++ .../CHIP/MTRDeviceController_Concrete.mm | 69 +++--- .../Framework/CHIP/MTRDeviceController_XPC.h | 35 +++ .../Framework/CHIP/MTRDeviceController_XPC.mm | 196 +++++++++++++++ .../CHIP/MTRDeviceController_XPC_Internal.h | 23 ++ .../Framework/CHIP/MTRDevice_Internal.h | 2 + src/darwin/Framework/CHIP/MTRDevice_XPC.h | 26 ++ src/darwin/Framework/CHIP/MTRDevice_XPC.mm | 227 ++++++++++++++++++ .../CHIP/XPC Protocol/MTRXPCClientProtocol.h | 3 + .../CHIP/XPC Protocol/MTRXPCServerProtocol.h | 2 +- .../Matter.xcodeproj/project.pbxproj | 39 ++- 18 files changed, 872 insertions(+), 38 deletions(-) create mode 100644 src/darwin/Framework/CHIP/MTRDeviceControllerXPCParameters.h create mode 100644 src/darwin/Framework/CHIP/MTRDeviceControllerXPCParameters.mm create mode 100644 src/darwin/Framework/CHIP/MTRDeviceController_XPC.h create mode 100644 src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm create mode 100644 src/darwin/Framework/CHIP/MTRDeviceController_XPC_Internal.h create mode 100644 src/darwin/Framework/CHIP/MTRDevice_XPC.h create mode 100644 src/darwin/Framework/CHIP/MTRDevice_XPC.mm diff --git a/src/darwin/Framework/CHIP/MTRCluster.h b/src/darwin/Framework/CHIP/MTRCluster.h index b3543d67b3..8184d3c684 100644 --- a/src/darwin/Framework/CHIP/MTRCluster.h +++ b/src/darwin/Framework/CHIP/MTRCluster.h @@ -73,7 +73,7 @@ MTR_AVAILABLE(ios(17.4), macos(14.4), watchos(10.4), tvos(17.4)) * treated as if a default-initialized object was passed in. */ MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) -@interface MTRWriteParams : NSObject +@interface MTRWriteParams : NSObject /** * Controls whether the write is a timed write. @@ -109,7 +109,7 @@ MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) * treated as if a default-initialized object was passed in. */ MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) -@interface MTRReadParams : NSObject +@interface MTRReadParams : NSObject /** * Whether the read/subscribe is fabric-filtered. The default is YES. @@ -152,7 +152,7 @@ MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) * treated as if a default-initialized object was passed in. */ MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) -@interface MTRSubscribeParams : MTRReadParams +@interface MTRSubscribeParams : MTRReadParams /** * Whether the subscribe should replace already-existing diff --git a/src/darwin/Framework/CHIP/MTRCluster.mm b/src/darwin/Framework/CHIP/MTRCluster.mm index 9bcb38e4cb..b80c909316 100644 --- a/src/darwin/Framework/CHIP/MTRCluster.mm +++ b/src/darwin/Framework/CHIP/MTRCluster.mm @@ -69,6 +69,8 @@ - (instancetype)init return self; } +#pragma mark - Copying + - (id)copyWithZone:(NSZone * _Nullable)zone { auto other = [[MTRWriteParams alloc] init]; @@ -77,6 +79,38 @@ - (id)copyWithZone:(NSZone * _Nullable)zone return other; } +#pragma mark - Coding + ++ (BOOL)supportsSecureCoding +{ + return YES; +} + +static NSString * sTimedWriteTimeoutCodingKey = @"sTimedWriteTimeoutKey"; +static NSString * sDataVersionCodingKey = @"sDataVersionKey"; + +- (nullable instancetype)initWithCoder:(NSCoder *)decoder +{ + self = [super init]; + + if (self == nil) { + return nil; + } + + self.timedWriteTimeout = [decoder decodeObjectOfClass:[NSNumber class] forKey:sTimedWriteTimeoutCodingKey]; + self.dataVersion = [decoder decodeObjectOfClass:[NSNumber class] forKey:sDataVersionCodingKey]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder +{ + if (self.timedWriteTimeout) + [coder encodeObject:self.timedWriteTimeout forKey:sTimedWriteTimeoutCodingKey]; + if (self.dataVersion) + [coder encodeObject:self.dataVersion forKey:sDataVersionCodingKey]; +} + @end @implementation MTRReadParams @@ -89,6 +123,43 @@ - (instancetype)init return self; } +#pragma mark - Coding + ++ (BOOL)supportsSecureCoding +{ + return YES; +} + +static NSString * sFilterByFabricCoderKey = @"sFilterByFabricKey"; +static NSString * sMinEventNumberCoderKey = @"sMinEventNumberKey"; +static NSString * sAssumeUnknownAttributesReportableCoderKey = @"sAssumeUnknownAttributesReportableKey"; + +- (nullable instancetype)initWithCoder:(NSCoder *)decoder +{ + self = [super init]; + + if (self == nil) { + return nil; + } + + self.filterByFabric = [decoder decodeBoolForKey:sFilterByFabricCoderKey]; + self.assumeUnknownAttributesReportable = [decoder decodeBoolForKey:sAssumeUnknownAttributesReportableCoderKey]; + self.minEventNumber = [decoder decodeObjectOfClass:[NSNumber class] forKey:sMinEventNumberCoderKey]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder +{ + [coder encodeBool:self.filterByFabric forKey:sFilterByFabricCoderKey]; + [coder encodeBool:self.assumeUnknownAttributesReportable forKey:sAssumeUnknownAttributesReportableCoderKey]; + + if (self.minEventNumber) + [coder encodeObject:self.minEventNumber forKey:sMinEventNumberCoderKey]; +} + +#pragma mark - Copying + - (id)copyWithZone:(NSZone * _Nullable)zone { auto other = [[MTRReadParams alloc] init]; @@ -98,6 +169,8 @@ - (id)copyWithZone:(NSZone * _Nullable)zone return other; } +#pragma mark - Other + - (void)toReadPrepareParams:(chip::app::ReadPrepareParams &)readPrepareParams { readPrepareParams.mIsFabricFiltered = self.filterByFabric; @@ -121,18 +194,68 @@ - (instancetype)initWithMinInterval:(NSNumber *)minInterval maxInterval:(NSNumbe return self; } +#pragma mark - Copying - (id)copyWithZone:(NSZone * _Nullable)zone { auto other = [[MTRSubscribeParams alloc] initWithMinInterval:self.minInterval maxInterval:self.maxInterval]; + other.filterByFabric = self.filterByFabric; other.minEventNumber = self.minEventNumber; other.assumeUnknownAttributesReportable = self.assumeUnknownAttributesReportable; other.replaceExistingSubscriptions = self.replaceExistingSubscriptions; other.reportEventsUrgently = self.reportEventsUrgently; other.resubscribeAutomatically = self.resubscribeAutomatically; + other.minInterval = self.minInterval; + other.maxInterval = self.maxInterval; + return other; } +#pragma mark - Coding ++ (BOOL)supportsSecureCoding +{ + return YES; +} + +static NSString * sReplaceExistingSubscriptionsCoderKey = @"sFilterByFabricKey"; +static NSString * sReportEventsUrgentlyCoderKey = @"sMinEventNumberKey"; +static NSString * sResubscribeAutomaticallyCoderKey = @"sAssumeUnknownAttributesReportableKey"; +static NSString * sMinIntervalKeyCoderKey = @"sMinIntervalKeyKey"; +static NSString * sMaxIntervalKeyCoderKey = @"sMaxIntervalKeyKey"; + +- (nullable instancetype)initWithCoder:(NSCoder *)decoder +{ + self = [super initWithCoder:decoder]; + + if (self == nil) { + return nil; + } + + self.replaceExistingSubscriptions = [decoder decodeBoolForKey:sReplaceExistingSubscriptionsCoderKey]; + self.reportEventsUrgently = [decoder decodeBoolForKey:sReportEventsUrgentlyCoderKey]; + self.resubscribeAutomatically = [decoder decodeBoolForKey:sResubscribeAutomaticallyCoderKey]; + self.minInterval = [decoder decodeObjectOfClass:[NSNumber class] forKey:sMinIntervalKeyCoderKey]; + self.maxInterval = [decoder decodeObjectOfClass:[NSNumber class] forKey:sMaxIntervalKeyCoderKey]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder +{ + [super encodeWithCoder:coder]; + + [coder encodeBool:self.replaceExistingSubscriptions forKey:sReplaceExistingSubscriptionsCoderKey]; + [coder encodeBool:self.reportEventsUrgently forKey:sReportEventsUrgentlyCoderKey]; + [coder encodeBool:self.resubscribeAutomatically forKey:sResubscribeAutomaticallyCoderKey]; + + if (self.minInterval) + [coder encodeObject:self.minInterval forKey:sMinIntervalKeyCoderKey]; + if (self.maxInterval) + [coder encodeObject:self.maxInterval forKey:sMaxIntervalKeyCoderKey]; +} + +#pragma mark - Main + - (void)toReadPrepareParams:(chip::app::ReadPrepareParams &)readPrepareParams { [super toReadPrepareParams:readPrepareParams]; diff --git a/src/darwin/Framework/CHIP/MTRDefines_Internal.h b/src/darwin/Framework/CHIP/MTRDefines_Internal.h index da31ce1b54..7894f31835 100644 --- a/src/darwin/Framework/CHIP/MTRDefines_Internal.h +++ b/src/darwin/Framework/CHIP/MTRDefines_Internal.h @@ -64,3 +64,50 @@ typedef struct {} variable_hidden_by_mtr_hide; // Default timed interaction timeout, in ms, if another one is not provided. #define MTR_DEFAULT_TIMED_INTERACTION_TIMEOUT_MS 10000 + +#pragma mark - XPC Defines + +#define MTR_SIMPLE_REMOTE_XPC_GETTER(XPC_CONNECTION, NAME, TYPE, DEFAULT_VALUE, GETTER_NAME, PREFIX) \ + \ + -(TYPE) NAME \ + { \ + __block TYPE outValue = DEFAULT_VALUE; \ + \ + NSXPCConnection * xpcConnection = XPC_CONNECTION; \ + \ + [[xpcConnection synchronousRemoteObjectProxyWithErrorHandler:^(NSError * _Nonnull error) { \ + MTR_LOG_ERROR("Error: %@", error); \ + }] PREFIX \ + GETTER_NAME:^(TYPE returnValue) { \ + outValue = returnValue; \ + }]; \ + \ + return outValue; \ + } + +#define MTR_SIMPLE_REMOTE_XPC_COMMAND(XPC_CONNECTION, METHOD_SIGNATURE, ADDITIONAL_ARGUMENTS, PREFIX) \ + \ + -(void) METHOD_SIGNATURE \ + { \ + NSXPCConnection * xpcConnection = XPC_CONNECTION; \ + \ + [[xpcConnection synchronousRemoteObjectProxyWithErrorHandler:^(NSError * _Nonnull error) { \ + MTR_LOG_ERROR("Error: %@", error); \ + }] PREFIX ADDITIONAL_ARGUMENTS]; \ + } + +#define MTR_COMPLEX_REMOTE_XPC_GETTER(XPC_CONNECTION, SIGNATURE, TYPE, DEFAULT_VALUE, ADDITIONAL_ARGUMENTS, PREFIX) \ + -(TYPE) SIGNATURE \ + { \ + __block TYPE outValue = DEFAULT_VALUE; \ + \ + NSXPCConnection * xpcConnection = XPC_CONNECTION; \ + \ + [[xpcConnection synchronousRemoteObjectProxyWithErrorHandler:^(NSError * _Nonnull error) { \ + MTR_LOG_ERROR("Error: %@", error); \ + }] PREFIX ADDITIONAL_ARGUMENTS:^(TYPE returnValue) { \ + outValue = returnValue; \ + }]; \ + \ + return outValue; \ + } diff --git a/src/darwin/Framework/CHIP/MTRDeviceController.mm b/src/darwin/Framework/CHIP/MTRDeviceController.mm index ee8cc2b754..3483ff3332 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController.mm +++ b/src/darwin/Framework/CHIP/MTRDeviceController.mm @@ -31,6 +31,7 @@ #import "MTRDeviceControllerLocalTestStorage.h" #import "MTRDeviceControllerStartupParams.h" #import "MTRDeviceControllerStartupParams_Internal.h" +#import "MTRDeviceController_XPC.h" #import "MTRDevice_Concrete.h" #import "MTRDevice_Internal.h" #import "MTRError_Internal.h" @@ -144,7 +145,11 @@ - (instancetype)initForSubclasses - (nullable MTRDeviceController *)initWithParameters:(MTRDeviceControllerAbstractParameters *)parameters error:(NSError * __autoreleasing *)error { - if (![parameters isKindOfClass:MTRDeviceControllerParameters.class]) { + if ([parameters isKindOfClass:MTRXPCDeviceControllerParameters.class]) { + MTRXPCDeviceControllerParameters * resolvedParameters = (MTRXPCDeviceControllerParameters *) parameters; + MTR_LOG("Starting up with XPC Device Controller Parameters: %@", parameters); + return [[MTRDeviceController_XPC alloc] initWithUniqueIdentifier:resolvedParameters.uniqueIdentifier xpConnectionBlock:resolvedParameters.xpcConnectionBlock]; + } else if (![parameters isKindOfClass:MTRDeviceControllerParameters.class]) { MTR_LOG_ERROR("Unsupported type of MTRDeviceControllerAbstractParameters: %@", parameters); if (error) { *error = [MTRError errorForCHIPErrorCode:CHIP_ERROR_INVALID_ARGUMENT]; diff --git a/src/darwin/Framework/CHIP/MTRDeviceControllerParameters.h b/src/darwin/Framework/CHIP/MTRDeviceControllerParameters.h index ffccc18b03..caedc20229 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceControllerParameters.h +++ b/src/darwin/Framework/CHIP/MTRDeviceControllerParameters.h @@ -145,4 +145,26 @@ MTR_AVAILABLE(ios(17.6), macos(14.6), watchos(10.6), tvos(17.6)) @end +MTR_NEWLY_AVAILABLE +@interface MTRXPCDeviceControllerParameters : MTRDeviceControllerAbstractParameters + +- (instancetype)init NS_UNAVAILABLE; ++ (instancetype)new NS_UNAVAILABLE; + +/** + * A controller created from this way will connect to a remote instance of an MTRDeviceController loaded in an XPC Service + * + * @param xpcConnectionBlock The XPC Connection block that will return an NSXPCConnection to the indended listener. + * + * @param uniqueIdentifier The unique id to assign to the controller. + * + */ +- (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; + +@end + NS_ASSUME_NONNULL_END diff --git a/src/darwin/Framework/CHIP/MTRDeviceControllerStartupParams.mm b/src/darwin/Framework/CHIP/MTRDeviceControllerStartupParams.mm index f393d48d0a..c5923ad4e5 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceControllerStartupParams.mm +++ b/src/darwin/Framework/CHIP/MTRDeviceControllerStartupParams.mm @@ -331,6 +331,23 @@ - (instancetype)initWithStorageDelegate:(id) } @end +@implementation MTRXPCDeviceControllerParameters + +@synthesize uniqueIdentifier = _uniqueIdentifier; +@synthesize xpcConnectionBlock = _xpcConnectionBlock; + +- (instancetype)initWithXPConnectionBlock:(NSXPCConnection * (^)(void) )xpcConnectionBlock + uniqueIdentifier:(NSUUID *)uniqueIdentifier; +{ + if (self = [super _initInternal]) { + _xpcConnectionBlock = [xpcConnectionBlock copy]; + _uniqueIdentifier = [uniqueIdentifier copy]; + } + + return self; +} +@end + @implementation MTRDeviceControllerStartupParamsInternal - (instancetype)initWithParams:(MTRDeviceControllerStartupParams *)params diff --git a/src/darwin/Framework/CHIP/MTRDeviceControllerXPCParameters.h b/src/darwin/Framework/CHIP/MTRDeviceControllerXPCParameters.h new file mode 100644 index 0000000000..9218ff2a99 --- /dev/null +++ b/src/darwin/Framework/CHIP/MTRDeviceControllerXPCParameters.h @@ -0,0 +1,31 @@ +/** + * 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 + +NS_ASSUME_NONNULL_BEGIN + +@interface MTRDeviceControllerXPCParameters : MTRDeviceControllerParameters +@end + +@interface MTRDeviceControllerMachServiceXPCParameters : MTRDeviceControllerXPCParameters + +@property (atomic, retain) NSString * machServiceName; +@property (atomic, readwrite) NSXPCConnectionOptions connectionOptions; + +@end + +NS_ASSUME_NONNULL_END diff --git a/src/darwin/Framework/CHIP/MTRDeviceControllerXPCParameters.mm b/src/darwin/Framework/CHIP/MTRDeviceControllerXPCParameters.mm new file mode 100644 index 0000000000..5178873ec2 --- /dev/null +++ b/src/darwin/Framework/CHIP/MTRDeviceControllerXPCParameters.mm @@ -0,0 +1,35 @@ +/** + * 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 "MTRDeviceControllerXPCParameters.h" + +@implementation MTRDeviceControllerXPCParameters + ++ (BOOL)supportsSecureCoding +{ + return YES; +} + +@end + +@implementation MTRDeviceControllerMachServiceXPCParameters + ++ (BOOL)supportsSecureCoding +{ + return YES; +} + +@end diff --git a/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.mm b/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.mm index c7ccab25e1..d53d94b83d 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.mm +++ b/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.mm @@ -32,7 +32,10 @@ #import "MTRDeviceControllerLocalTestStorage.h" #import "MTRDeviceControllerStartupParams.h" #import "MTRDeviceControllerStartupParams_Internal.h" +#import "MTRDeviceControllerXPCParameters.h" #import "MTRDeviceController_Concrete.h" +#import "MTRDeviceController_XPC.h" +#import "MTRDeviceController_XPC_Internal.h" #import "MTRDevice_Concrete.h" #import "MTRDevice_Internal.h" #import "MTRError_Internal.h" @@ -134,44 +137,52 @@ @implementation MTRDeviceController_Concrete { @synthesize concurrentSubscriptionPool = _concurrentSubscriptionPool; @synthesize storageBehaviorConfiguration = _storageBehaviorConfiguration; -- (nullable MTRDeviceController_Concrete *)initWithParameters:(MTRDeviceControllerAbstractParameters *)parameters - error:(NSError * __autoreleasing *)error +- (nullable instancetype)initWithParameters:(MTRDeviceControllerAbstractParameters *)parameters + error:(NSError * __autoreleasing *)error { - if (![parameters isKindOfClass:MTRDeviceControllerParameters.class]) { - MTR_LOG_ERROR("Unsupported type of MTRDeviceControllerAbstractParameters: %@", parameters); - if (error) { - *error = [MTRError errorForCHIPErrorCode:CHIP_ERROR_INVALID_ARGUMENT]; - } - return nil; - } - auto * controllerParameters = static_cast(parameters); + /// IF YOU ARE ALARMED BY TYPES: You are right to be alarmed, but do not panic. + /// _ORDER MATTERS HERE:_ XPC parameters are a subclass of `MTRDeviceControllerParameters` + /// because of the enormous overlap of params. + if ([parameters isKindOfClass:MTRDeviceControllerXPCParameters.class]) { + if ([parameters isKindOfClass:MTRDeviceControllerMachServiceXPCParameters.class]) { + MTRDeviceControllerMachServiceXPCParameters * xpcParameters = (MTRDeviceControllerMachServiceXPCParameters *) parameters; + MTR_LOG_DEBUG("%s: got XPC parameters, getting XPC device controller", __PRETTY_FUNCTION__); - // or, if necessary, MTRDeviceControllerFactory will auto-start in per-controller-storage mode if necessary - MTRDeviceControllerFactory * factory = MTRDeviceControllerFactory.sharedInstance; - id controller = [factory initializeController:self - withParameters:controllerParameters - error:error]; - return controller; -} + NSString * machServiceName = xpcParameters.machServiceName; + MTR_LOG_DEBUG("%s: machServiceName %@", __PRETTY_FUNCTION__, machServiceName); -- (nullable MTRDeviceController *)bogusWithParameters:(MTRDeviceControllerAbstractParameters *)parameters - error:(NSError * __autoreleasing *)error -{ - if (![parameters isKindOfClass:MTRDeviceControllerParameters.class]) { + MTRDeviceController * xpcDeviceController = [[MTRDeviceController_XPC alloc] initWithMachServiceName:machServiceName options:xpcParameters.connectionOptions]; + + /// Being of sound mind, I willfully and voluntarily make this static cast. + return static_cast(xpcDeviceController); + } else { + MTR_LOG_ERROR("%s: unrecognized XPC parameters class %@", __PRETTY_FUNCTION__, NSStringFromClass(parameters.class)); + + // TODO: there's probably a more appropriate error here. + if (error) { + *error = [MTRError errorForCHIPErrorCode:CHIP_ERROR_NOT_IMPLEMENTED]; + } + + return nil; + } + } else if ([parameters isKindOfClass:MTRDeviceControllerParameters.class]) { + MTR_LOG_DEBUG("%s: got standard parameters, getting standard device controller from factory", __PRETTY_FUNCTION__); + auto * controllerParameters = static_cast(parameters); + + // or, if necessary, MTRDeviceControllerFactory will auto-start in per-controller-storage mode if necessary + MTRDeviceControllerFactory * factory = MTRDeviceControllerFactory.sharedInstance; + id controller = [factory initializeController:self + withParameters:controllerParameters + error:error]; + return controller; + } else { + // way out of our league MTR_LOG_ERROR("Unsupported type of MTRDeviceControllerAbstractParameters: %@", parameters); if (error) { *error = [MTRError errorForCHIPErrorCode:CHIP_ERROR_INVALID_ARGUMENT]; } return nil; } - auto * controllerParameters = static_cast(parameters); - - // MTRDeviceControllerFactory will auto-start in per-controller-storage mode if necessary - MTRDeviceControllerFactory * factory = MTRDeviceControllerFactory.sharedInstance; - MTRDeviceController * controller = [factory initializeController:self - withParameters:controllerParameters - error:error]; - return controller; } - (instancetype)initWithFactory:(MTRDeviceControllerFactory *)factory diff --git a/src/darwin/Framework/CHIP/MTRDeviceController_XPC.h b/src/darwin/Framework/CHIP/MTRDeviceController_XPC.h new file mode 100644 index 0000000000..574d3eac62 --- /dev/null +++ b/src/darwin/Framework/CHIP/MTRDeviceController_XPC.h @@ -0,0 +1,35 @@ +/** + * 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 "MTRDefines_Internal.h" // MTR_TESTABLE +#import "MTRDeviceController.h" +#import "MTRXPCClientProtocol.h" // MTRXPCClientProtocol_MTRDeviceController +#import + +NS_ASSUME_NONNULL_BEGIN + +MTR_TESTABLE +@interface MTRDeviceController_XPC : MTRDeviceController +- (id)initWithUniqueIdentifier:(NSUUID *)UUID xpConnectionBlock:(NSXPCConnection * (^)(void) )connectionBlock; +#ifdef MTR_HAVE_MACH_SERVICE_NAME_CONSTRUCTOR +- (id)initWithUniqueIdentifier:(NSUUID *)UUID machServiceName:(NSString *)machServiceName options:(NSXPCConnectionOptions)options +#endif + + @property(atomic, retain, readwrite)NSXPCConnection * xpcConnection; + +@end + +NS_ASSUME_NONNULL_END diff --git a/src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm b/src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm new file mode 100644 index 0000000000..1d91ae0d5d --- /dev/null +++ b/src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm @@ -0,0 +1,196 @@ +/** + * 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 "MTRDeviceController_XPC.h" +#import "MTRDefines_Internal.h" +#import "MTRDeviceController_Internal.h" +#import "MTRDevice_XPC.h" +#import "MTRLogging_Internal.h" +#import "MTRXPCClientProtocol.h" +#import "MTRXPCServerProtocol.h" + +#define MTR_DEVICECONTROLLER_SIMPLE_REMOTE_XPC_GETTER(NAME, TYPE, DEFAULT_VALUE, GETTER_NAME) \ + MTR_SIMPLE_REMOTE_XPC_GETTER(self.xpcConnection, NAME, TYPE, DEFAULT_VALUE, GETTER_NAME, deviceController \ + : self.uniqueIdentifier) + +#define MTR_DEVICECONTROLLER_SIMPLE_REMOTE_XPC_COMMAND(METHOD_SIGNATURE, ADDITIONAL_ARGUMENTS) \ + MTR_SIMPLE_REMOTE_XPC_COMMAND(self.xpcConnection, METHOD_SIGNATURE, ADDITIONAL_ARGUMENTS, deviceController \ + : self.uniqueIdentifier) + +@interface MTRDeviceController_XPC () + +@property (nonatomic, retain, readwrite) NSUUID * uniqueIdentifier; + +@end + +// #define MTR_HAVE_MACH_SERVICE_NAME_CONSTRUCTOR + +@implementation MTRDeviceController_XPC + +@synthesize uniqueIdentifier = _uniqueIdentifier; + +- (id)initWithUniqueIdentifier:(NSUUID *)UUID xpConnectionBlock:(NSXPCConnection * (^)(void) )connectionBlock +{ + if (self = [super initForSubclasses]) { + MTR_LOG("Setting up XPC Controller for UUID: %@ with connection block: %p", UUID, connectionBlock); + + if (UUID == nil) { + MTR_LOG_ERROR("MTRDeviceController_XPC initWithUniqueIdentifier failed, nil UUID"); + return nil; + } + if (connectionBlock == nil) { + MTR_LOG_ERROR("MTRDeviceController_XPC initWithUniqueIdentifier failed, nil connectionBlock"); + return nil; + } + + self.xpcConnection = connectionBlock(); + self.uniqueIdentifier = UUID; + + MTR_LOG("Set up XPC Connection: %@", self.xpcConnection); + if (self.xpcConnection) { + self.xpcConnection.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(MTRXPCServerProtocol)]; + + self.xpcConnection.exportedInterface = [NSXPCInterface interfaceWithProtocol:@protocol(MTRXPCClientProtocol)]; + self.xpcConnection.exportedObject = self; + + MTR_LOG("Resuming new XPC connection"); + [self.xpcConnection resume]; + } else { + MTR_LOG_ERROR("Failed to set up XPC Connection"); + return nil; + } + } + + return self; +} + +#ifdef MTR_HAVE_MACH_SERVICE_NAME_CONSTRUCTOR +- (id)initWithUniqueIdentifier:(NSUUID *)UUID machServiceName:(NSString *)machServiceName options:(NSXPCConnectionOptions)options +{ + if (self = [super initForSubclasses]) { + MTR_LOG("Setting up XPC Controller for UUID: %@ with machServiceName: %s options: %d", UUID, machServiceName, options); + self.xpcConnection = [[NSXPCConnection alloc] initWithMachServiceName:machServiceName options:options]; + self.uniqueIdentifier = UUID; + + MTR_LOG("Set up XPC Connection: %@", self.xpcConnection); + if (self.xpcConnection) { + self.xpcConnection.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(MTRXPCServerProtocol)]; + + self.xpcConnection.exportedInterface = [NSXPCInterface interfaceWithProtocol:@protocol(MTRXPCClientProtocol)]; + self.xpcConnection.exportedObject = self; + + MTR_LOG("%s: resuming new XPC connection"); + [self.xpcConnection resume]; + } else { + MTR_LOG_ERROR("Failed to set up XPC Connection"); + return nil; + } + } + + return self; +} +#endif // MTR_HAVE_MACH_SERVICE_NAME_CONSTRUCTOR + +- (nullable instancetype)initWithParameters:(MTRDeviceControllerAbstractParameters *)parameters + error:(NSError * __autoreleasing *)error +{ + MTR_LOG_ERROR("%s: unimplemented method called", __PRETTY_FUNCTION__); + return nil; +} + +#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; +// - (oneway void)deviceController:(NSUUID *)controller commissionNodeWithID:(NSNumber *)nodeID commissioningParams:(MTRCommissioningParameters *)commissioningParams withReply:(void(^)(BOOL success, NSError * _Nullable error))reply; +// - (oneway void)deviceController:(NSUUID *)controller continueCommissioningDevice:(void *)opaqueDeviceHandle ignoreAttestationFailure:(BOOL)ignoreAttestationFailure withReply:(void(^)(BOOL success, NSError * _Nullable error))reply; +// - (oneway void)deviceController:(NSUUID *)controller cancelCommissioningForNodeID:(NSNumber *)nodeID withReply:(void(^)(BOOL success, NSError * _Nullable error))reply; +// - (nullable MTRBaseDevice *)deviceController:(NSUUID *)controller deviceBeingCommissionedWithNodeID:(NSNumber *)nodeID error:(NSError * __autoreleasing *)error; +// - (oneway void)deviceController:(NSUUID *)controller startBrowseForCommissionables:(id)delegate withReply:(void(^)(BOOL success))reply; +// - (oneway void)deviceController:(NSUUID *)controller stopBrowseForCommissionablesWithReply:(void(^)(BOOL success))reply; +// - (oneway void)deviceController:(NSUUID *)controller attestationChallengeForDeviceID:(NSNumber *)deviceID withReply:(void(^)(NSData * _Nullable))reply; + +//- (oneway void)deviceController:(NSUUID *)controller addServerEndpoint:(MTRServerEndpoint *)endpoint withReply:(void(^)(BOOL success))reply; +//- (oneway void)deviceController:(NSUUID *)controller removeServerEndpoint:(MTRServerEndpoint *)endpoint; + +MTR_DEVICECONTROLLER_SIMPLE_REMOTE_XPC_COMMAND(shutdown, shutdownDeviceController + : self.uniqueIdentifier) + +#pragma mark - MTRDeviceProtocol Client + +// All pass through, we could do some fancy redirection here based on protocol, but that's that for another day +- (oneway void)device:(NSNumber *)nodeID stateChanged:(MTRDeviceState)state +{ + MTRDevice_XPC * device = (MTRDevice_XPC *) [self deviceForNodeID:nodeID]; + MTR_LOG("Received device: %@ stateChanged: %lu found device: %@", nodeID, (unsigned long) state, device); + [device device:nodeID stateChanged:state]; +} +- (oneway void)device:(NSNumber *)nodeID receivedAttributeReport:(NSArray *> *)attributeReport +{ + MTRDevice_XPC * device = (MTRDevice_XPC *) [self deviceForNodeID:nodeID]; + MTR_LOG("Received device: %@ receivedAttributeReport: %@ found device: %@", nodeID, attributeReport, device); + + [device device:nodeID receivedAttributeReport:attributeReport]; +} +- (oneway void)device:(NSNumber *)nodeID receivedEventReport:(NSArray *> *)eventReport +{ + MTRDevice_XPC * device = (MTRDevice_XPC *) [self deviceForNodeID:nodeID]; + MTR_LOG("Received device: %@ receivedEventReport: %@ found device: %@", nodeID, eventReport, device); + + [device device:nodeID receivedEventReport:eventReport]; +} +- (oneway void)deviceBecameActive:(NSNumber *)nodeID +{ + MTRDevice_XPC * device = (MTRDevice_XPC *) [self deviceForNodeID:nodeID]; + MTR_LOG("Received deviceBecameActive: %@ found device: %@", nodeID, device); + + [device deviceBecameActive:nodeID]; +} +- (oneway void)deviceCachePrimed:(NSNumber *)nodeID +{ + MTRDevice_XPC * device = (MTRDevice_XPC *) [self deviceForNodeID:nodeID]; + MTR_LOG("Received deviceCachePrimed: %@ found device: %@", nodeID, device); + + [device deviceCachePrimed:nodeID]; +} +- (oneway void)deviceConfigurationChanged:(NSNumber *)nodeID +{ + MTRDevice_XPC * device = (MTRDevice_XPC *) [self deviceForNodeID:nodeID]; + MTR_LOG("Received deviceConfigurationChanged: %@ found device: %@", nodeID, device); + + [device deviceConfigurationChanged:nodeID]; +} + +#pragma mark - MTRDeviceController Protocol Client + +// Not Supported via XPC +//- (oneway void)controller:(NSUUID *)controller statusUpdate:(MTRCommissioningStatus)status { +// } +//- (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 { +// +//} + +@end diff --git a/src/darwin/Framework/CHIP/MTRDeviceController_XPC_Internal.h b/src/darwin/Framework/CHIP/MTRDeviceController_XPC_Internal.h new file mode 100644 index 0000000000..e6c85b1f8d --- /dev/null +++ b/src/darwin/Framework/CHIP/MTRDeviceController_XPC_Internal.h @@ -0,0 +1,23 @@ +/** + * 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 "MTRDeviceController_XPC.h" + +@interface MTRDeviceController_XPC (Internal) + +- (id)initWithMachServiceName:(NSString *)machServiceName options:(NSXPCConnectionOptions)options; + +@end diff --git a/src/darwin/Framework/CHIP/MTRDevice_Internal.h b/src/darwin/Framework/CHIP/MTRDevice_Internal.h index 943e939f47..4c1b51f51c 100644 --- a/src/darwin/Framework/CHIP/MTRDevice_Internal.h +++ b/src/darwin/Framework/CHIP/MTRDevice_Internal.h @@ -81,6 +81,8 @@ MTR_TESTABLE // false-positives, for example due to compressed fabric id collisions. - (void)nodeMayBeAdvertisingOperational; +- (BOOL)_callDelegatesWithBlock:(void (^)(id delegate))block; + /** * Like the public invokeCommandWithEndpointID but: * diff --git a/src/darwin/Framework/CHIP/MTRDevice_XPC.h b/src/darwin/Framework/CHIP/MTRDevice_XPC.h new file mode 100644 index 0000000000..a2df4a6044 --- /dev/null +++ b/src/darwin/Framework/CHIP/MTRDevice_XPC.h @@ -0,0 +1,26 @@ +// +/** + * Copyright (c) 2023 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface MTRDevice_XPC : MTRDevice + +@end + +NS_ASSUME_NONNULL_END diff --git a/src/darwin/Framework/CHIP/MTRDevice_XPC.mm b/src/darwin/Framework/CHIP/MTRDevice_XPC.mm new file mode 100644 index 0000000000..95f69cb7d4 --- /dev/null +++ b/src/darwin/Framework/CHIP/MTRDevice_XPC.mm @@ -0,0 +1,227 @@ +// +/** + * Copyright (c) 2023 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "MTRDevice_XPC.h" + +// Need to move these to PCHs... +#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 "MTRDeviceAttestationDelegateBridge.h" +#import "MTRDeviceConnectionBridge.h" +#import "MTRDeviceController.h" +#import "MTRDeviceControllerDelegateBridge.h" +#import "MTRDeviceControllerFactory_Internal.h" +#import "MTRDeviceControllerLocalTestStorage.h" +#import "MTRDeviceControllerStartupParams.h" +#import "MTRDeviceControllerStartupParams_Internal.h" +#import "MTRDeviceControllerXPCParameters.h" +#import "MTRDeviceController_Concrete.h" +#import "MTRDeviceController_XPC.h" +#import "MTRDevice_Concrete.h" +#import "MTRDevice_Internal.h" +#import "MTRError_Internal.h" +#import "MTRKeypair.h" +#import "MTRLogging_Internal.h" +#import "MTRMetricKeys.h" +#import "MTRMetricsCollector.h" +#import "MTROperationalCredentialsDelegate.h" +#import "MTRP256KeypairBridge.h" +#import "MTRPersistentStorageDelegateBridge.h" +#import "MTRServerEndpoint_Internal.h" +#import "MTRSetupPayload.h" +#import "MTRTimeUtils.h" +#import "MTRUnfairLock.h" +#import "NSDataSpanConversion.h" +#import "NSStringSpanConversion.h" + +#include +#include +#include + +#import + +#define MTR_DEVICE_SIMPLE_REMOTE_XPC_GETTER(NAME, TYPE, DEFAULT_VALUE, GETTER_NAME) \ + MTR_SIMPLE_REMOTE_XPC_GETTER([(MTRDeviceController_XPC *) [self deviceController] xpcConnection], NAME, TYPE, DEFAULT_VALUE, GETTER_NAME, deviceController \ + : [[self deviceController] uniqueIdentifier] nodeID \ + : [self nodeID]) + +#define MTR_DEVICE_COMPLEX_REMOTE_XPC_GETTER(SIGNATURE, TYPE, DEFAULT_VALUE, ADDITIONAL_ARGUMENTS) \ + MTR_COMPLEX_REMOTE_XPC_GETTER([(MTRDeviceController_XPC *) [self deviceController] xpcConnection], SIGNATURE, TYPE, DEFAULT_VALUE, ADDITIONAL_ARGUMENTS, deviceController \ + : [[self deviceController] uniqueIdentifier] nodeID \ + : [self nodeID]) + +#define MTR_DEVICE_SIMPLE_REMOTE_XPC_COMMAND(METHOD_SIGNATURE, ADDITIONAL_ARGUMENTS) \ + MTR_SIMPLE_REMOTE_XPC_COMMAND([(MTRDeviceController_XPC *) [self deviceController] xpcConnection], METHOD_SIGNATURE, ADDITIONAL_ARGUMENTS, deviceController \ + : [[self deviceController] uniqueIdentifier] nodeID \ + : [self nodeID]) + +@implementation MTRDevice_XPC + +#pragma mark - Client Callbacks +- (oneway void)device:(NSNumber *)nodeID stateChanged:(MTRDeviceState)state +{ + [self _callDelegatesWithBlock:^(id delegate) { + [delegate device:self stateChanged:state]; + }]; +} +- (oneway void)device:(NSNumber *)nodeID receivedAttributeReport:(NSArray *> *)attributeReport +{ + [self _callDelegatesWithBlock:^(id delegate) { + [delegate device:self receivedAttributeReport:attributeReport]; + }]; +} +- (oneway void)device:(NSNumber *)nodeID receivedEventReport:(NSArray *> *)eventReport +{ + [self _callDelegatesWithBlock:^(id delegate) { + [delegate device:self receivedEventReport:eventReport]; + }]; +} +- (oneway void)deviceBecameActive:(NSNumber *)nodeID +{ + [self _callDelegatesWithBlock:^(id delegate) { + [delegate deviceBecameActive:self]; + }]; +} +- (oneway void)deviceCachePrimed:(NSNumber *)nodeID +{ + [self _callDelegatesWithBlock:^(id delegate) { + [delegate deviceCachePrimed:self]; + }]; +} +- (oneway void)deviceConfigurationChanged:(NSNumber *)nodeID +{ + [self _callDelegatesWithBlock:^(id delegate) { + [delegate deviceConfigurationChanged:self]; + }]; +} + +#pragma mark - Remote Commands + +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 *, nil, getEstimatedStartTimeWithReply) +MTR_DEVICE_SIMPLE_REMOTE_XPC_GETTER(estimatedSubscriptionLatency, NSNumber *, nil, getEstimatedSubscriptionLatencyWithReply) + +typedef NSDictionary * readAttributeResponseType; +MTR_DEVICE_COMPLEX_REMOTE_XPC_GETTER(readAttributeWithEndpointID + : (NSNumber *) endpointID clusterID + : (NSNumber *) clusterID attributeID + : (NSNumber *) attributeID params + : (MTRReadParams * _Nullable) params, + readAttributeResponseType, + nil, + readAttributeWithEndpointID + : endpointID clusterID + : clusterID attributeID + : attributeID params + : params withReply) + +MTR_DEVICE_SIMPLE_REMOTE_XPC_COMMAND(writeAttributeWithEndpointID + : (NSNumber *) endpointID clusterID + : (NSNumber *) clusterID attributeID + : (NSNumber *) attributeID value + : (id) value expectedValueInterval + : (NSNumber *) expectedValueInterval timedWriteTimeout + : (NSNumber * _Nullable) timeout, writeAttributeWithEndpointID + : endpointID clusterID + : clusterID attributeID + : attributeID value + : value expectedValueInterval + : expectedValueInterval timedWriteTimeout + : timeout) + +- (void)invokeCommandWithEndpointID:(NSNumber *)endpointID + clusterID:(NSNumber *)clusterID + commandID:(NSNumber *)commandID + commandFields:(id)commandFields + expectedValues:(NSArray *> * _Nullable)expectedValues + expectedValueInterval:(NSNumber * _Nullable)expectedValueInterval + timedInvokeTimeout:(NSNumber * _Nullable)timeout + queue:(dispatch_queue_t)queue + completion:(MTRDeviceResponseHandler)completion +{ + NSXPCConnection * xpcConnection = [(MTRDeviceController_XPC *) [self deviceController] xpcConnection]; + + [[xpcConnection synchronousRemoteObjectProxyWithErrorHandler:^(NSError * _Nonnull error) { + MTR_LOG_ERROR("Error: %@", error); + }] deviceController:[[self deviceController] uniqueIdentifier] + nodeID:[self nodeID] + invokeCommandWithEndpointID:endpointID + clusterID:clusterID + commandID:commandID + commandFields:commandFields + expectedValues:expectedValues + expectedValueInterval:expectedValueInterval + timedInvokeTimeout:timeout + completion:completion]; +} + +// Not Supported via XPC +//- (oneway void)deviceController:(NSUUID *)controller nodeID:(NSNumber *)nodeID openCommissioningWindowWithSetupPasscode:(NSNumber *)setupPasscode discriminator:(NSNumber *)discriminator duration:(NSNumber *)duration completion:(MTRDeviceOpenCommissioningWindowHandler)completion; + +MTR_DEVICE_SIMPLE_REMOTE_XPC_GETTER(clientDataKeys, NSArray *, nil, getClientDataKeysWithReply) +MTR_DEVICE_COMPLEX_REMOTE_XPC_GETTER(clientDataForKey + : (NSString *) key, id _Nullable, nil, clientDataForKey + : key withReply) + +MTR_DEVICE_SIMPLE_REMOTE_XPC_COMMAND(setClientDataForKey + : (NSString *) key value + : (id) value, setClientDataForKey + : key value + : value) +MTR_DEVICE_SIMPLE_REMOTE_XPC_COMMAND(removeClientDataForKey + : (NSString *) key, removeClientDataForKey + : key) + +MTR_DEVICE_COMPLEX_REMOTE_XPC_GETTER(clientDataKeysForEndpointID + : (NSNumber *) endpointID, NSArray * _Nullable, nil, clientDataKeysForEndpointID + : (NSNumber *) endpointID withReply) +MTR_DEVICE_COMPLEX_REMOTE_XPC_GETTER(clientDataForKey + : (NSString *) key endpointID + : (NSNumber *) endpointID, id _Nullable, nil, clientDataForKey + : key endpointID + : endpointID withReply) + +MTR_DEVICE_SIMPLE_REMOTE_XPC_COMMAND(setClientDataForKey + : (NSString *) key endpointID + : (NSNumber *) endpointID value + : (id) value, setClientDataForKey + : key endpointID + : endpointID value + : value) +MTR_DEVICE_SIMPLE_REMOTE_XPC_COMMAND(removeClientDataForKey + : (NSString *) key endpointID + : (NSNumber *) endpointID value + : (id) value, removeClientDataForKey + : key endpointID + : endpointID) + +// Not Supported via XPC +// - (oneway void)downloadLogOfType:(MTRDiagnosticLogType)type nodeID:(NSNumber *)nodeID timeout:(NSTimeInterval)timeout completion:(void (^)(NSURL * _Nullable url, NSError * _Nullable error))completion; + +@end diff --git a/src/darwin/Framework/CHIP/XPC Protocol/MTRXPCClientProtocol.h b/src/darwin/Framework/CHIP/XPC Protocol/MTRXPCClientProtocol.h index 0d518f525f..a571ebc07a 100644 --- a/src/darwin/Framework/CHIP/XPC Protocol/MTRXPCClientProtocol.h +++ b/src/darwin/Framework/CHIP/XPC Protocol/MTRXPCClientProtocol.h @@ -14,6 +14,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + +#import // for MTRDeviceState + NS_ASSUME_NONNULL_BEGIN @protocol MTRXPCClientProtocol_MTRDevice diff --git a/src/darwin/Framework/CHIP/XPC Protocol/MTRXPCServerProtocol.h b/src/darwin/Framework/CHIP/XPC Protocol/MTRXPCServerProtocol.h index 56077897a9..5d619453b5 100644 --- a/src/darwin/Framework/CHIP/XPC Protocol/MTRXPCServerProtocol.h +++ b/src/darwin/Framework/CHIP/XPC Protocol/MTRXPCServerProtocol.h @@ -65,7 +65,7 @@ NS_ASSUME_NONNULL_BEGIN //- (oneway void)deviceController:(NSUUID *)controller addServerEndpoint:(MTRServerEndpoint *)endpoint withReply:(void(^)(BOOL success))reply; //- (oneway void)deviceController:(NSUUID *)controller removeServerEndpoint:(MTRServerEndpoint *)endpoint; -- (oneway void)shutdownDeviceController:(NSUUID *)controller; +- (oneway void)deviceController:(NSUUID *)controller shutdownDeviceController:(NSUUID *)controller; @end diff --git a/src/darwin/Framework/Matter.xcodeproj/project.pbxproj b/src/darwin/Framework/Matter.xcodeproj/project.pbxproj index 69ef3bdc71..3a5968072d 100644 --- a/src/darwin/Framework/Matter.xcodeproj/project.pbxproj +++ b/src/darwin/Framework/Matter.xcodeproj/project.pbxproj @@ -302,10 +302,18 @@ 99AECC802798A57F00B6355B /* MTRCommissioningParameters.mm in Sources */ = {isa = PBXBuildFile; fileRef = 99AECC7F2798A57E00B6355B /* MTRCommissioningParameters.mm */; }; 99C65E10267282F1003402F6 /* MTRControllerTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 99C65E0F267282F1003402F6 /* MTRControllerTests.m */; }; 99D466E12798936D0089A18F /* MTRCommissioningParameters.h in Headers */ = {isa = PBXBuildFile; fileRef = 99D466E02798936D0089A18F /* MTRCommissioningParameters.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 9B231B042C62EF650030EB37 /* MTRDeviceController_Concrete.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B231B022C62EF650030EB37 /* MTRDeviceController_Concrete.h */; }; + 9B0484F52C701154006C2D5F /* MTRDeviceController_Concrete.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B0484F42C701154006C2D5F /* MTRDeviceController_Concrete.h */; }; + 9B231B042C62EF650030EB37 /* (null) in Headers */ = {isa = PBXBuildFile; }; 9B231B052C62EF650030EB37 /* MTRDeviceController_Concrete.mm in Sources */ = {isa = PBXBuildFile; fileRef = 9B231B032C62EF650030EB37 /* MTRDeviceController_Concrete.mm */; }; + 9B5CCB592C6E6FD3009DD99B /* MTRDeviceController_XPC_Internal.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B5CCB582C6E6FD3009DD99B /* MTRDeviceController_XPC_Internal.h */; }; + 9B5CCB5C2C6EC890009DD99B /* MTRDevice_XPC.mm in Sources */ = {isa = PBXBuildFile; fileRef = 9B5CCB5B2C6EC890009DD99B /* MTRDevice_XPC.mm */; }; + 9B5CCB5D2C6EC890009DD99B /* MTRDevice_XPC.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B5CCB5A2C6EC890009DD99B /* MTRDevice_XPC.h */; }; + 9B5CCB602C6EE29E009DD99B /* MTRDeviceControllerXPCParameters.mm in Sources */ = {isa = PBXBuildFile; fileRef = 9B5CCB5F2C6EE29E009DD99B /* MTRDeviceControllerXPCParameters.mm */; }; + 9B5CCB612C6EE29E009DD99B /* MTRDeviceControllerXPCParameters.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B5CCB5E2C6EE29E009DD99B /* MTRDeviceControllerXPCParameters.h */; }; 9BDA2A062C5D9AF800A32BDD /* MTRDevice_Concrete.mm in Sources */ = {isa = PBXBuildFile; fileRef = 9BDA2A052C5D9AF800A32BDD /* MTRDevice_Concrete.mm */; }; 9BDA2A082C5D9AFB00A32BDD /* MTRDevice_Concrete.h in Headers */ = {isa = PBXBuildFile; fileRef = 9BDA2A072C5D9AFB00A32BDD /* MTRDevice_Concrete.h */; }; + 9BFE5D502C6D3075007D4319 /* MTRDeviceController_XPC.h in Headers */ = {isa = PBXBuildFile; fileRef = 9BFE5D4E2C6D3075007D4319 /* MTRDeviceController_XPC.h */; }; + 9BFE5D512C6D3075007D4319 /* MTRDeviceController_XPC.mm in Sources */ = {isa = PBXBuildFile; fileRef = 9BFE5D4F2C6D3075007D4319 /* MTRDeviceController_XPC.mm */; }; AF1CB86E2874B03B00865A96 /* MTROTAProviderDelegate.h in Headers */ = {isa = PBXBuildFile; fileRef = AF1CB86D2874B03B00865A96 /* MTROTAProviderDelegate.h */; settings = {ATTRIBUTES = (Public, ); }; }; AF1CB8702874B04C00865A96 /* MTROTAProviderDelegateBridge.h in Headers */ = {isa = PBXBuildFile; fileRef = AF1CB86F2874B04C00865A96 /* MTROTAProviderDelegateBridge.h */; }; AF5F90FF2878D351005503FA /* MTROTAProviderDelegateBridge.mm in Sources */ = {isa = PBXBuildFile; fileRef = AF5F90FE2878D351005503FA /* MTROTAProviderDelegateBridge.mm */; }; @@ -735,10 +743,17 @@ 99AECC7F2798A57E00B6355B /* MTRCommissioningParameters.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = MTRCommissioningParameters.mm; sourceTree = ""; }; 99C65E0F267282F1003402F6 /* MTRControllerTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = MTRControllerTests.m; sourceTree = ""; }; 99D466E02798936D0089A18F /* MTRCommissioningParameters.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MTRCommissioningParameters.h; sourceTree = ""; }; - 9B231B022C62EF650030EB37 /* MTRDeviceController_Concrete.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MTRDeviceController_Concrete.h; sourceTree = ""; }; + 9B0484F42C701154006C2D5F /* MTRDeviceController_Concrete.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MTRDeviceController_Concrete.h; sourceTree = ""; }; 9B231B032C62EF650030EB37 /* MTRDeviceController_Concrete.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = MTRDeviceController_Concrete.mm; sourceTree = ""; }; + 9B5CCB582C6E6FD3009DD99B /* MTRDeviceController_XPC_Internal.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MTRDeviceController_XPC_Internal.h; sourceTree = ""; }; + 9B5CCB5A2C6EC890009DD99B /* MTRDevice_XPC.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MTRDevice_XPC.h; sourceTree = ""; }; + 9B5CCB5B2C6EC890009DD99B /* MTRDevice_XPC.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = MTRDevice_XPC.mm; sourceTree = ""; }; + 9B5CCB5E2C6EE29E009DD99B /* MTRDeviceControllerXPCParameters.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MTRDeviceControllerXPCParameters.h; sourceTree = ""; }; + 9B5CCB5F2C6EE29E009DD99B /* MTRDeviceControllerXPCParameters.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = MTRDeviceControllerXPCParameters.mm; sourceTree = ""; }; 9BDA2A052C5D9AF800A32BDD /* MTRDevice_Concrete.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = MTRDevice_Concrete.mm; sourceTree = ""; }; 9BDA2A072C5D9AFB00A32BDD /* MTRDevice_Concrete.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MTRDevice_Concrete.h; sourceTree = ""; }; + 9BFE5D4E2C6D3075007D4319 /* MTRDeviceController_XPC.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MTRDeviceController_XPC.h; sourceTree = ""; }; + 9BFE5D4F2C6D3075007D4319 /* MTRDeviceController_XPC.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = MTRDeviceController_XPC.mm; sourceTree = ""; }; AF1CB86D2874B03B00865A96 /* MTROTAProviderDelegate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MTROTAProviderDelegate.h; sourceTree = ""; }; AF1CB86F2874B04C00865A96 /* MTROTAProviderDelegateBridge.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MTROTAProviderDelegateBridge.h; sourceTree = ""; }; AF5F90FE2878D351005503FA /* MTROTAProviderDelegateBridge.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = MTROTAProviderDelegateBridge.mm; sourceTree = ""; }; @@ -1251,8 +1266,8 @@ isa = PBXGroup; children = ( D444F9A12C6E8058007761E5 /* XPC Protocol */, - 9B231B022C62EF650030EB37 /* MTRDeviceController_Concrete.h */, 9B231B032C62EF650030EB37 /* MTRDeviceController_Concrete.mm */, + 9B0484F42C701154006C2D5F /* MTRDeviceController_Concrete.h */, 88E07D602B9A89A4005FD53E /* MTRMetricKeys.h */, 88FA798B2B7B257100CD4B6F /* MTRMetricsCollector.h */, 88FA798C2B7B257100CD4B6F /* MTRMetricsCollector.mm */, @@ -1316,6 +1331,8 @@ 7596A84A287636C1004DAE0E /* MTRDevice_Internal.h */, 7596A84228762729004DAE0E /* MTRDevice.h */, 7596A84328762729004DAE0E /* MTRDevice.mm */, + 9B5CCB5A2C6EC890009DD99B /* MTRDevice_XPC.h */, + 9B5CCB5B2C6EC890009DD99B /* MTRDevice_XPC.mm */, 9BDA2A072C5D9AFB00A32BDD /* MTRDevice_Concrete.h */, 9BDA2A052C5D9AF800A32BDD /* MTRDevice_Concrete.mm */, 88EBF8CB27FABDD500686BC1 /* MTRDeviceAttestationDelegate.h */, @@ -1328,6 +1345,9 @@ 75B3269B2BCDB9D600E17C4E /* MTRDeviceConnectivityMonitor.h */, 75B3269D2BCDB9EA00E17C4E /* MTRDeviceConnectivityMonitor.mm */, 991DC0822475F45400C13860 /* MTRDeviceController.h */, + 9BFE5D4E2C6D3075007D4319 /* MTRDeviceController_XPC.h */, + 9B5CCB582C6E6FD3009DD99B /* MTRDeviceController_XPC_Internal.h */, + 9BFE5D4F2C6D3075007D4319 /* MTRDeviceController_XPC.mm */, 5136660F28067D540025EDAE /* MTRDeviceController_Internal.h */, 991DC0872475F47D00C13860 /* MTRDeviceController.mm */, 5A7947E227C0101200434CF2 /* MTRDeviceController+XPC.h */, @@ -1349,6 +1369,8 @@ 51E51FBD282AD37A00FC978D /* MTRDeviceControllerStartupParams_Internal.h */, 51E51FBE282AD37A00FC978D /* MTRDeviceControllerStartupParams.mm */, 51565CB52A7B0D6600469F18 /* MTRDeviceControllerParameters.h */, + 9B5CCB5E2C6EE29E009DD99B /* MTRDeviceControllerXPCParameters.h */, + 9B5CCB5F2C6EE29E009DD99B /* MTRDeviceControllerXPCParameters.mm */, 51565CB32A7AD78D00469F18 /* MTRDeviceControllerStorageDelegate.h */, 5A6FEC9427B5976200F25F42 /* MTRDeviceControllerXPCConnection.h */, 5A6FEC9527B5983000F25F42 /* MTRDeviceControllerXPCConnection.mm */, @@ -1611,6 +1633,7 @@ 517BF3F0282B62B800A8B7DB /* MTRCertificates.h in Headers */, 51E51FBF282AD37A00FC978D /* MTRDeviceControllerStartupParams.h in Headers */, 5136661628067D550025EDAE /* MTRDeviceControllerFactory.h in Headers */, + 9B5CCB592C6E6FD3009DD99B /* MTRDeviceController_XPC_Internal.h in Headers */, 5178E6812AE098520069DF72 /* MTRCommandTimedCheck.h in Headers */, 7596A84B287636C1004DAE0E /* MTRDevice_Internal.h in Headers */, 514C7A042B6436D500DD6D7B /* MTRServerCluster_Internal.h in Headers */, @@ -1621,6 +1644,7 @@ 51B22C1E2740CB0A008D5055 /* MTRStructsObjc.h in Headers */, 2CB7163B252E8A7B0026E2BB /* MTRDeviceControllerDelegateBridge.h in Headers */, 75B765C12A1D71BC0014719B /* MTRAttributeSpecifiedCheck.h in Headers */, + 9B0484F52C701154006C2D5F /* MTRDeviceController_Concrete.h in Headers */, 5ACDDD7A27CD129700EFD68A /* MTRClusterStateCacheContainer.h in Headers */, 5A6FEC9227B5669C00F25F42 /* MTRDeviceControllerOverXPC.h in Headers */, D444F9AA2C6E9A08007761E5 /* MTRXPCClientProtocol.h in Headers */, @@ -1644,8 +1668,10 @@ 88EBF8CE27FABDD500686BC1 /* MTRDeviceAttestationDelegate.h in Headers */, 2C222AD0255C620600E446B9 /* MTRBaseDevice.h in Headers */, 7596A84F2877E6A9004DAE0E /* MTRCluster_Internal.h in Headers */, + 9B5CCB612C6EE29E009DD99B /* MTRDeviceControllerXPCParameters.h in Headers */, 991DC0842475F45400C13860 /* MTRDeviceController.h in Headers */, 88FA798D2B7B257100CD4B6F /* MTRMetricsCollector.h in Headers */, + 9BFE5D502C6D3075007D4319 /* MTRDeviceController_XPC.h in Headers */, 88E6C9462B6334ED001A1FE0 /* MTRMetrics.h in Headers */, AF1CB86E2874B03B00865A96 /* MTROTAProviderDelegate.h in Headers */, 51D0B1402B61B3A4006E3511 /* MTRServerCluster.h in Headers */, @@ -1697,7 +1723,7 @@ 51E51FC0282AD37A00FC978D /* MTRDeviceControllerStartupParams_Internal.h in Headers */, 3DECCB702934AECD00585AEC /* MTRLogging.h in Headers */, 1E4D654E29C208DD00BC3478 /* MTRCommissionableBrowserResult.h in Headers */, - 9B231B042C62EF650030EB37 /* MTRDeviceController_Concrete.h in Headers */, + 9B231B042C62EF650030EB37 /* (null) in Headers */, 515BE4ED2B72C0C5000BC1FD /* MTRUnfairLock.h in Headers */, 998F286F26D55EC5001846C6 /* MTRP256KeypairBridge.h in Headers */, 2C222ADF255C811800E446B9 /* MTRBaseDevice_Internal.h in Headers */, @@ -1705,6 +1731,7 @@ 511913FC28C100EF009235E9 /* MTRBaseSubscriptionCallback.h in Headers */, 51565CB12A7AD77600469F18 /* MTRDeviceControllerDataStore.h in Headers */, 3D843713294977000070D20A /* NSDataSpanConversion.h in Headers */, + 9B5CCB5D2C6EC890009DD99B /* MTRDevice_XPC.h in Headers */, 991DC08B247704DC00C13860 /* MTRLogging_Internal.h in Headers */, 51FE723F2ACDEF3E00437032 /* MTRCommandPayloadExtensions_Internal.h in Headers */, 51D0B12E2B6177FD006E3511 /* MTRAccessGrant.h in Headers */, @@ -1974,6 +2001,7 @@ 51D0B1392B618CC6006E3511 /* MTRServerAttribute.mm in Sources */, 51B22C2A2740CB47008D5055 /* MTRCommandPayloadsObjc.mm in Sources */, 51F522682AE70734000C4050 /* MTRDeviceTypeMetadata.mm in Sources */, + 9B5CCB602C6EE29E009DD99B /* MTRDeviceControllerXPCParameters.mm in Sources */, 75B765C32A1D82D30014719B /* MTRAttributeSpecifiedCheck.mm in Sources */, AF5F90FF2878D351005503FA /* MTROTAProviderDelegateBridge.mm in Sources */, 516415FF2B6B132200D5CE11 /* DataModelHandler.cpp in Sources */, @@ -2001,6 +2029,7 @@ 51D0B12F2B617800006E3511 /* MTRAccessGrant.mm in Sources */, 88E6C9482B6334ED001A1FE0 /* MTRMetrics.mm in Sources */, 1ED276E226C5812A00547A89 /* MTRCluster.mm in Sources */, + 9BFE5D512C6D3075007D4319 /* MTRDeviceController_XPC.mm in Sources */, B2E0D7B3245B0B5C003C5B48 /* MTRError.mm in Sources */, 51E51FC1282AD37A00FC978D /* MTRDeviceControllerStartupParams.mm in Sources */, 51565CAE2A79D42100469F18 /* MTRConversion.mm in Sources */, @@ -2012,6 +2041,7 @@ 9B231B052C62EF650030EB37 /* MTRDeviceController_Concrete.mm in Sources */, 5ACDDD7D27CD16D200EFD68A /* MTRClusterStateCacheContainer.mm in Sources */, 75B3269E2BCDB9EA00E17C4E /* MTRDeviceConnectivityMonitor.mm in Sources */, + 9B5CCB5C2C6EC890009DD99B /* MTRDevice_XPC.mm in Sources */, 513DDB8A2761F6F900DAA01A /* MTRAttributeTLVValueDecoder.mm in Sources */, 5117DD3829A931AE00FFA1AA /* MTROperationalBrowser.mm in Sources */, 514C79F02B62ADDA00DD6D7B /* descriptor.cpp in Sources */, @@ -2410,6 +2440,7 @@ buildSettings = { CLANG_ENABLE_MODULES = YES; CODE_SIGN_STYLE = Automatic; + DEVELOPMENT_TEAM = ""; "HEADER_SEARCH_PATHS[arch=*]" = "$(PROJECT_DIR)/../../../src"; INFOPLIST_FILE = CHIPTests/Info.plist; LD_RUNPATH_SEARCH_PATHS = ( From 2787db2b445cc2c066fff52de5ae9250d18ff601 Mon Sep 17 00:00:00 2001 From: Kiel Oleson Date: Sat, 17 Aug 2024 19:09:24 -0700 Subject: [PATCH 083/165] [Darwin] more XPC service tweaks (#35048) * return `MTRDevice_XPC`s from XPC controller * more logging * move shadow property declarations to internal header * declare `_setupDeviceForNodeID` as common internal device controller method * prefetchedClusterData is nullable * fix a few properties that needed raising to base class * you get a log and you get a log EVERYONE GETS A LOG * convert device map lock for use in subclasses * check for optional delegate method impl before calling * ivar no longer necessary with accessor method underlying lock is the only state needed * Restyled by clang-format * remove more obsolete lock bits from `MTRDeviceController_XPC` --------- Co-authored-by: Restyled.io --- .../Framework/CHIP/MTRDeviceController.mm | 29 +++++++----- .../CHIP/MTRDeviceController_Concrete.mm | 44 ++++++++----------- .../CHIP/MTRDeviceController_Internal.h | 6 +++ .../Framework/CHIP/MTRDeviceController_XPC.mm | 21 ++++++++- src/darwin/Framework/CHIP/MTRDevice_XPC.mm | 26 +++++++++-- 5 files changed, 84 insertions(+), 42 deletions(-) diff --git a/src/darwin/Framework/CHIP/MTRDeviceController.mm b/src/darwin/Framework/CHIP/MTRDeviceController.mm index 3483ff3332..bfbb62fa2f 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController.mm +++ b/src/darwin/Framework/CHIP/MTRDeviceController.mm @@ -120,7 +120,7 @@ @implementation MTRDeviceController { MTRDeviceAttestationDelegateBridge * _deviceAttestationDelegateBridge; MTRDeviceControllerFactory * _factory; NSMapTable * _nodeIDToDeviceMap; - os_unfair_lock _deviceMapLock; // protects nodeIDToDeviceMap + os_unfair_lock _underlyingDeviceMapLock; MTRCommissionableBrowser * _commissionableBrowser; MTRAttestationTrustStoreBridge * _attestationTrustStoreBridge; @@ -134,12 +134,17 @@ @implementation MTRDeviceController { MTRP256KeypairBridge _operationalKeypairBridge; } +- (os_unfair_lock_t)deviceMapLock +{ + return &_underlyingDeviceMapLock; +} + - (instancetype)initForSubclasses { if (self = [super init]) { // nothing, as superclass of MTRDeviceController is NSObject } - + _underlyingDeviceMapLock = OS_UNFAIR_LOCK_INIT; return self; } @@ -250,7 +255,7 @@ - (instancetype)initWithFactory:(MTRDeviceControllerFactory *)factory _chipWorkQueue = queue; _factory = factory; - _deviceMapLock = OS_UNFAIR_LOCK_INIT; + _underlyingDeviceMapLock = OS_UNFAIR_LOCK_INIT; _nodeIDToDeviceMap = [NSMapTable strongToWeakObjectsMapTable]; _serverEndpoints = [[NSMutableArray alloc] init]; _commissionableBrowser = nil; @@ -330,10 +335,10 @@ - (void)cleanupAfterStartup // while calling out into arbitrary invalidation code, snapshot the list of // devices before we start invalidating. MTR_LOG("cleanupAfterStartup MTRDeviceController: %@", self); - os_unfair_lock_lock(&_deviceMapLock); + os_unfair_lock_lock(self.deviceMapLock); NSEnumerator * devices = [_nodeIDToDeviceMap objectEnumerator]; [_nodeIDToDeviceMap removeAllObjects]; - os_unfair_lock_unlock(&_deviceMapLock); + os_unfair_lock_unlock(self.deviceMapLock); for (MTRDevice * device in devices) { [device invalidate]; @@ -634,7 +639,7 @@ - (BOOL)startup:(MTRDeviceControllerStartupParamsInternal *)startupParams [_controllerDataStore fetchAttributeDataForAllDevices:^(NSDictionary *> * _Nonnull clusterDataByNode) { MTR_LOG("%@ Loaded attribute values for %lu nodes from storage for controller uuid %@", self, static_cast(clusterDataByNode.count), self->_uniqueIdentifier); - std::lock_guard lock(self->_deviceMapLock); + std::lock_guard lock(*self.deviceMapLock); NSMutableArray * deviceList = [NSMutableArray array]; for (NSNumber * nodeID in clusterDataByNode) { NSDictionary * clusterData = clusterDataByNode[nodeID]; @@ -1004,7 +1009,7 @@ - (MTRBaseDevice *)baseDeviceForNodeID:(NSNumber *)nodeID // If prefetchedClusterData is not provided, load attributes individually from controller data store - (MTRDevice *)_setupDeviceForNodeID:(NSNumber *)nodeID prefetchedClusterData:(NSDictionary *)prefetchedClusterData { - os_unfair_lock_assert_owner(&_deviceMapLock); + os_unfair_lock_assert_owner(self.deviceMapLock); MTRDevice * deviceToReturn = [[MTRDevice_Concrete alloc] initWithNodeID:nodeID controller:self]; // If we're not running, don't add the device to our map. That would @@ -1043,7 +1048,7 @@ - (MTRDevice *)_setupDeviceForNodeID:(NSNumber *)nodeID prefetchedClusterData:(N - (MTRDevice *)deviceForNodeID:(NSNumber *)nodeID { - std::lock_guard lock(_deviceMapLock); + std::lock_guard lock(*self.deviceMapLock); MTRDevice * deviceToReturn = [_nodeIDToDeviceMap objectForKey:nodeID]; if (!deviceToReturn) { deviceToReturn = [self _setupDeviceForNodeID:nodeID prefetchedClusterData:nil]; @@ -1054,7 +1059,7 @@ - (MTRDevice *)deviceForNodeID:(NSNumber *)nodeID - (void)removeDevice:(MTRDevice *)device { - std::lock_guard lock(_deviceMapLock); + std::lock_guard lock(*self.deviceMapLock); auto * nodeID = device.nodeID; MTRDevice * deviceToRemove = [_nodeIDToDeviceMap objectForKey:nodeID]; if (deviceToRemove == device) { @@ -1068,7 +1073,7 @@ - (void)removeDevice:(MTRDevice *)device #ifdef DEBUG - (NSDictionary *)unitTestGetDeviceAttributeCounts { - std::lock_guard lock(_deviceMapLock); + std::lock_guard lock(*self.deviceMapLock); NSMutableDictionary * deviceAttributeCounts = [NSMutableDictionary dictionary]; for (NSNumber * nodeID in _nodeIDToDeviceMap) { deviceAttributeCounts[nodeID] = @([[_nodeIDToDeviceMap objectForKey:nodeID] unitTestAttributeCount]); @@ -1508,9 +1513,9 @@ - (void)operationalInstanceAdded:(chip::NodeId)nodeID { // Don't use deviceForNodeID here, because we don't want to create the // device if it does not already exist. - os_unfair_lock_lock(&_deviceMapLock); + os_unfair_lock_lock(self.deviceMapLock); MTRDevice * device = [_nodeIDToDeviceMap objectForKey:@(nodeID)]; - os_unfair_lock_unlock(&_deviceMapLock); + os_unfair_lock_unlock(self.deviceMapLock); if (device == nil) { return; diff --git a/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.mm b/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.mm index d53d94b83d..b3152a9e34 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.mm +++ b/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.mm @@ -82,8 +82,6 @@ #include #include -#import - typedef void (^SyncWorkQueueBlock)(void); typedef id (^SyncWorkQueueBlockWithReturnValue)(void); typedef BOOL (^SyncWorkQueueBlockWithBoolReturnValue)(void); @@ -103,8 +101,6 @@ @interface MTRDeviceController_Concrete () @property (nonatomic, readwrite) NSUUID * uniqueIdentifier; @property (nonatomic, readonly) dispatch_queue_t chipWorkQueue; @property (nonatomic, readonly, nullable) MTRDeviceControllerFactory * factory; -@property (nonatomic, readonly, nullable) NSMapTable * nodeIDToDeviceMap; -@property (nonatomic, readonly) os_unfair_lock deviceMapLock; @property (nonatomic, readonly, nullable) id otaProviderDelegate; @property (nonatomic, readonly, nullable) dispatch_queue_t otaProviderDelegateQueue; @property (nonatomic, readonly, nullable) MTRCommissionableBrowser * commissionableBrowser; @@ -270,11 +266,9 @@ - (instancetype)initWithFactory:(MTRDeviceControllerFactory *)factory _otaProviderDelegate = otaProviderDelegate; _otaProviderDelegateQueue = otaProviderDelegateQueue; - _chipWorkQueue = queue; _factory = factory; - _deviceMapLock = OS_UNFAIR_LOCK_INIT; - _nodeIDToDeviceMap = [NSMapTable strongToWeakObjectsMapTable]; + self.nodeIDToDeviceMap = [NSMapTable strongToWeakObjectsMapTable]; _serverEndpoints = [[NSMutableArray alloc] init]; _commissionableBrowser = nil; @@ -352,10 +346,10 @@ - (void)cleanupAfterStartup // while calling out into arbitrary invalidation code, snapshot the list of // devices before we start invalidating. MTR_LOG("cleanupAfterStartup MTRDeviceController: %@", self); - os_unfair_lock_lock(&_deviceMapLock); - NSEnumerator * devices = [_nodeIDToDeviceMap objectEnumerator]; - [_nodeIDToDeviceMap removeAllObjects]; - os_unfair_lock_unlock(&_deviceMapLock); + os_unfair_lock_lock(self.deviceMapLock); + NSEnumerator * devices = [self.nodeIDToDeviceMap objectEnumerator]; + [self.nodeIDToDeviceMap removeAllObjects]; + os_unfair_lock_unlock(self.deviceMapLock); for (MTRDevice * device in devices) { [device invalidate]; @@ -654,7 +648,7 @@ - (BOOL)startup:(MTRDeviceControllerStartupParamsInternal *)startupParams [_controllerDataStore fetchAttributeDataForAllDevices:^(NSDictionary *> * _Nonnull clusterDataByNode) { MTR_LOG("%@ Loaded attribute values for %lu nodes from storage for controller uuid %@", self, static_cast(clusterDataByNode.count), self->_uniqueIdentifier); - std::lock_guard lock(self->_deviceMapLock); + std::lock_guard lock(*self.deviceMapLock); NSMutableArray * deviceList = [NSMutableArray array]; for (NSNumber * nodeID in clusterDataByNode) { NSDictionary * clusterData = clusterDataByNode[nodeID]; @@ -1024,7 +1018,7 @@ - (MTRBaseDevice *)baseDeviceForNodeID:(NSNumber *)nodeID // If prefetchedClusterData is not provided, load attributes individually from controller data store - (MTRDevice *)_setupDeviceForNodeID:(NSNumber *)nodeID prefetchedClusterData:(NSDictionary *)prefetchedClusterData { - os_unfair_lock_assert_owner(&_deviceMapLock); + os_unfair_lock_assert_owner(self.deviceMapLock); MTRDevice * deviceToReturn = [[MTRDevice alloc] initWithNodeID:nodeID controller:self]; // If we're not running, don't add the device to our map. That would @@ -1032,7 +1026,7 @@ - (MTRDevice *)_setupDeviceForNodeID:(NSNumber *)nodeID prefetchedClusterData:(N // which will be in exactly the state it would be in if it were created // while we were running and then we got shut down. if ([self isRunning]) { - [_nodeIDToDeviceMap setObject:deviceToReturn forKey:nodeID]; + [self.nodeIDToDeviceMap setObject:deviceToReturn forKey:nodeID]; } if (prefetchedClusterData) { @@ -1063,8 +1057,8 @@ - (MTRDevice *)_setupDeviceForNodeID:(NSNumber *)nodeID prefetchedClusterData:(N - (MTRDevice *)deviceForNodeID:(NSNumber *)nodeID { - std::lock_guard lock(_deviceMapLock); - MTRDevice * deviceToReturn = [_nodeIDToDeviceMap objectForKey:nodeID]; + std::lock_guard lock(*self.deviceMapLock); + MTRDevice * deviceToReturn = [self.nodeIDToDeviceMap objectForKey:nodeID]; if (!deviceToReturn) { deviceToReturn = [self _setupDeviceForNodeID:nodeID prefetchedClusterData:nil]; } @@ -1074,12 +1068,12 @@ - (MTRDevice *)deviceForNodeID:(NSNumber *)nodeID - (void)removeDevice:(MTRDevice *)device { - std::lock_guard lock(_deviceMapLock); + std::lock_guard lock(*self.deviceMapLock); auto * nodeID = device.nodeID; - MTRDevice * deviceToRemove = [_nodeIDToDeviceMap objectForKey:nodeID]; + MTRDevice * deviceToRemove = [self.nodeIDToDeviceMap objectForKey:nodeID]; if (deviceToRemove == device) { [deviceToRemove invalidate]; - [_nodeIDToDeviceMap removeObjectForKey:nodeID]; + [self.nodeIDToDeviceMap removeObjectForKey:nodeID]; } else { MTR_LOG_ERROR("%@ Error: Cannot remove device %p with nodeID %llu", self, device, nodeID.unsignedLongLongValue); } @@ -1088,10 +1082,10 @@ - (void)removeDevice:(MTRDevice *)device #ifdef DEBUG - (NSDictionary *)unitTestGetDeviceAttributeCounts { - std::lock_guard lock(_deviceMapLock); + std::lock_guard lock(*self.deviceMapLock); NSMutableDictionary * deviceAttributeCounts = [NSMutableDictionary dictionary]; - for (NSNumber * nodeID in _nodeIDToDeviceMap) { - deviceAttributeCounts[nodeID] = @([[_nodeIDToDeviceMap objectForKey:nodeID] unitTestAttributeCount]); + for (NSNumber * nodeID in self.nodeIDToDeviceMap) { + deviceAttributeCounts[nodeID] = @([[self.nodeIDToDeviceMap objectForKey:nodeID] unitTestAttributeCount]); } return deviceAttributeCounts; } @@ -1540,9 +1534,9 @@ - (void)operationalInstanceAdded:(chip::NodeId)nodeID { // Don't use deviceForNodeID here, because we don't want to create the // device if it does not already exist. - os_unfair_lock_lock(&_deviceMapLock); - MTRDevice * device = [_nodeIDToDeviceMap objectForKey:@(nodeID)]; - os_unfair_lock_unlock(&_deviceMapLock); + os_unfair_lock_lock(self.deviceMapLock); + MTRDevice * device = [self.nodeIDToDeviceMap objectForKey:@(nodeID)]; + os_unfair_lock_unlock(self.deviceMapLock); if (device == nil) { return; diff --git a/src/darwin/Framework/CHIP/MTRDeviceController_Internal.h b/src/darwin/Framework/CHIP/MTRDeviceController_Internal.h index d943775d43..85d2c2e069 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController_Internal.h +++ b/src/darwin/Framework/CHIP/MTRDeviceController_Internal.h @@ -29,6 +29,8 @@ #include #include +#import + #import "MTRBaseDevice.h" #import "MTRDeviceController.h" #import "MTRDeviceControllerDataStore.h" @@ -63,6 +65,9 @@ NS_ASSUME_NONNULL_BEGIN @interface MTRDeviceController () +@property (nonatomic, readwrite, nullable) NSMapTable * nodeIDToDeviceMap; +@property (readonly, assign) os_unfair_lock_t deviceMapLock; + - (instancetype)initForSubclasses; #pragma mark - MTRDeviceControllerFactory methods @@ -270,6 +275,7 @@ NS_ASSUME_NONNULL_BEGIN #pragma mark - Device-specific data and SDK access // DeviceController will act as a central repository for this opaque dictionary that MTRDevice manages - (MTRDevice *)deviceForNodeID:(NSNumber *)nodeID; +- (MTRDevice *)_setupDeviceForNodeID:(NSNumber *)nodeID prefetchedClusterData:(nullable NSDictionary *)prefetchedClusterData; - (void)removeDevice:(MTRDevice *)device; /** diff --git a/src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm b/src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm index 1d91ae0d5d..d93a379ae3 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm +++ b/src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm @@ -15,6 +15,7 @@ */ #import "MTRDeviceController_XPC.h" + #import "MTRDefines_Internal.h" #import "MTRDeviceController_Internal.h" #import "MTRDevice_XPC.h" @@ -45,7 +46,7 @@ @implementation MTRDeviceController_XPC - (id)initWithUniqueIdentifier:(NSUUID *)UUID xpConnectionBlock:(NSXPCConnection * (^)(void) )connectionBlock { if (self = [super initForSubclasses]) { - MTR_LOG("Setting up XPC Controller for UUID: %@ with connection block: %p", UUID, connectionBlock); + MTR_LOG("Setting up XPC Controller for UUID: %@ with connection block: %p", UUID, connectionBlock); if (UUID == nil) { MTR_LOG_ERROR("MTRDeviceController_XPC initWithUniqueIdentifier failed, nil UUID"); @@ -111,6 +112,24 @@ - (nullable instancetype)initWithParameters:(MTRDeviceControllerAbstractParamete return nil; } +// If prefetchedClusterData is not provided, load attributes individually from controller data store +- (MTRDevice *)_setupDeviceForNodeID:(NSNumber *)nodeID prefetchedClusterData:(NSDictionary *)prefetchedClusterData +{ + MTR_LOG("%s", __PRETTY_FUNCTION__); + os_unfair_lock_assert_owner(self.deviceMapLock); + + MTRDevice * deviceToReturn = [[MTRDevice_XPC alloc] initWithNodeID:nodeID controller:self]; + // If we're not running, don't add the device to our map. That would + // create a cycle that nothing would break. Just return the device, + // which will be in exactly the state it would be in if it were created + // while we were running and then we got shut down. + if ([self isRunning]) { + [self.nodeIDToDeviceMap setObject:deviceToReturn forKey:nodeID]; + } + MTR_LOG("%s: returning XPC device for node id %@", __PRETTY_FUNCTION__, nodeID); + return deviceToReturn; +} + #pragma mark - XPC Action Overrides MTR_DEVICECONTROLLER_SIMPLE_REMOTE_XPC_GETTER(isRunning, BOOL, NO, getIsRunningWithReply) diff --git a/src/darwin/Framework/CHIP/MTRDevice_XPC.mm b/src/darwin/Framework/CHIP/MTRDevice_XPC.mm index 95f69cb7d4..69eba5bc6f 100644 --- a/src/darwin/Framework/CHIP/MTRDevice_XPC.mm +++ b/src/darwin/Framework/CHIP/MTRDevice_XPC.mm @@ -82,41 +82,59 @@ @implementation MTRDevice_XPC -#pragma mark - Client Callbacks +#pragma mark - Client Callbacks (MTRDeviceDelegate) + +// required methods for MTRDeviceDelegates - (oneway void)device:(NSNumber *)nodeID stateChanged:(MTRDeviceState)state { + MTR_LOG("%s", __PRETTY_FUNCTION__); [self _callDelegatesWithBlock:^(id delegate) { [delegate device:self stateChanged:state]; }]; } + - (oneway void)device:(NSNumber *)nodeID receivedAttributeReport:(NSArray *> *)attributeReport { + MTR_LOG("%s", __PRETTY_FUNCTION__); [self _callDelegatesWithBlock:^(id delegate) { [delegate device:self receivedAttributeReport:attributeReport]; }]; } + - (oneway void)device:(NSNumber *)nodeID receivedEventReport:(NSArray *> *)eventReport { + MTR_LOG("%s", __PRETTY_FUNCTION__); [self _callDelegatesWithBlock:^(id delegate) { [delegate device:self receivedEventReport:eventReport]; }]; } + +// optional methods for MTRDeviceDelegates - check for implementation before calling - (oneway void)deviceBecameActive:(NSNumber *)nodeID { + MTR_LOG("%s", __PRETTY_FUNCTION__); [self _callDelegatesWithBlock:^(id delegate) { - [delegate deviceBecameActive:self]; + if ([delegate respondsToSelector:@selector(deviceBecameActive:)]) { + [delegate deviceBecameActive:self]; + } }]; } + - (oneway void)deviceCachePrimed:(NSNumber *)nodeID { [self _callDelegatesWithBlock:^(id delegate) { - [delegate deviceCachePrimed:self]; + if ([delegate respondsToSelector:@selector(deviceCachePrimed:)]) { + [delegate deviceCachePrimed:self]; + } }]; } + - (oneway void)deviceConfigurationChanged:(NSNumber *)nodeID { [self _callDelegatesWithBlock:^(id delegate) { - [delegate deviceConfigurationChanged:self]; + if ([delegate respondsToSelector:@selector(deviceConfigurationChanged:)]) { + [delegate deviceConfigurationChanged:self]; + } }]; } From 1d4f684d70c80c5dc306b35b6e7492e4812c099f Mon Sep 17 00:00:00 2001 From: Rohit Jadhav <69809379+jadhavrohit924@users.noreply.github.com> Date: Sun, 18 Aug 2024 08:40:34 +0530 Subject: [PATCH 084/165] ModeSelect: Add setter API for SupportedModesManager. (#34809) * Add setter API for SupportedModesManager * Example changes * Restyled by clang-format * Fix namespace usage * Address review comments --------- Co-authored-by: Restyled.io --- .../include/static-supported-modes-manager.h | 8 +---- .../src/static-supported-modes-manager.cpp | 7 ---- .../ameba/main/chipinterface.cpp | 3 ++ examples/all-clusters-app/asr/src/AppTask.cpp | 3 ++ .../cc13x4_26x4/main/AppTask.cpp | 3 ++ .../esp32/main/CMakeLists.txt | 6 +--- examples/all-clusters-app/esp32/main/main.cpp | 11 ++---- .../infineon/psoc6/src/AppTask.cpp | 3 ++ .../all-clusters-app/linux/main-common.cpp | 3 ++ .../all-clusters-app/mbed/main/AppTask.cpp | 5 ++- .../nrfconnect/main/AppTask.cpp | 3 ++ examples/all-clusters-app/nxp/mw320/main.cpp | 3 ++ .../all-clusters-app/telink/src/AppTask.cpp | 3 ++ examples/all-clusters-app/tizen/src/main.cpp | 3 ++ .../ameba/main/chipinterface.cpp | 3 ++ .../asr/src/AppTask.cpp | 3 ++ .../esp32/main/main.cpp | 3 ++ .../infineon/psoc6/src/AppTask.cpp | 3 ++ .../linux/main-common.cpp | 7 +++- .../mbed/main/AppTask.cpp | 3 ++ .../nrfconnect/main/AppTask.cpp | 3 ++ .../telink/src/AppTask.cpp | 3 ++ .../tizen/src/main.cpp | 3 ++ .../include/static-supported-modes-manager.h | 8 +---- .../linux/static-supported-modes-manager.cpp | 7 ---- .../static-supported-modes-manager.cpp | 7 ---- .../static-supported-modes-manager.h | 8 +---- examples/shell/cc13x4_26x4/main/AppTask.cpp | 3 ++ .../mode-select-server/mode-select-server.cpp | 35 +++++++++++++++++-- .../supported-modes-manager.h | 2 ++ 30 files changed, 105 insertions(+), 60 deletions(-) diff --git a/examples/all-clusters-app/all-clusters-common/include/static-supported-modes-manager.h b/examples/all-clusters-app/all-clusters-common/include/static-supported-modes-manager.h index b4ce50b8cd..168482e030 100644 --- a/examples/all-clusters-app/all-clusters-common/include/static-supported-modes-manager.h +++ b/examples/all-clusters-app/all-clusters-common/include/static-supported-modes-manager.h @@ -31,7 +31,7 @@ namespace ModeSelect { * This implementation statically defines the options. */ -class StaticSupportedModesManager : public chip::app::Clusters::ModeSelect::SupportedModesManager +class StaticSupportedModesManager : public SupportedModesManager { using ModeOptionStructType = Structs::ModeOptionStruct::Type; using storage_value_type = const ModeOptionStructType; @@ -52,8 +52,6 @@ class StaticSupportedModesManager : public chip::app::Clusters::ModeSelect::Supp static const EndpointSpanPair supportedOptionsByEndpoints[MATTER_DM_MODE_SELECT_CLUSTER_SERVER_ENDPOINT_COUNT]; public: - static const StaticSupportedModesManager instance; - SupportedModesManager::ModeOptionsProvider getModeOptionsProvider(EndpointId endpointId) const override; Protocols::InteractionModel::Status getModeOptionByMode(EndpointId endpointId, uint8_t mode, @@ -62,12 +60,8 @@ class StaticSupportedModesManager : public chip::app::Clusters::ModeSelect::Supp ~StaticSupportedModesManager(){}; StaticSupportedModesManager() {} - - static inline const StaticSupportedModesManager & getStaticSupportedModesManagerInstance() { return instance; } }; -const SupportedModesManager * getSupportedModesManager(); - } // namespace ModeSelect } // namespace Clusters } // namespace app diff --git a/examples/all-clusters-app/all-clusters-common/src/static-supported-modes-manager.cpp b/examples/all-clusters-app/all-clusters-common/src/static-supported-modes-manager.cpp index 4060d4be85..94345600cf 100644 --- a/examples/all-clusters-app/all-clusters-common/src/static-supported-modes-manager.cpp +++ b/examples/all-clusters-app/all-clusters-common/src/static-supported-modes-manager.cpp @@ -39,8 +39,6 @@ const StaticSupportedModesManager::EndpointSpanPair EndpointSpanPair(1, Span(StaticSupportedModesManager::coffeeOptions)) // Options for Endpoint 1 }; -const StaticSupportedModesManager StaticSupportedModesManager::instance = StaticSupportedModesManager(); - SupportedModesManager::ModeOptionsProvider StaticSupportedModesManager::getModeOptionsProvider(EndpointId endpointId) const { for (auto & endpointSpanPair : supportedOptionsByEndpoints) @@ -76,8 +74,3 @@ Status StaticSupportedModesManager::getModeOptionByMode(unsigned short endpointI ChipLogProgress(Zcl, "Cannot find the mode %u", mode); return Status::InvalidCommand; } - -const ModeSelect::SupportedModesManager * ModeSelect::getSupportedModesManager() -{ - return &StaticSupportedModesManager::instance; -} diff --git a/examples/all-clusters-app/ameba/main/chipinterface.cpp b/examples/all-clusters-app/ameba/main/chipinterface.cpp index 2a35d86ead..99ed719f0f 100644 --- a/examples/all-clusters-app/ameba/main/chipinterface.cpp +++ b/examples/all-clusters-app/ameba/main/chipinterface.cpp @@ -47,6 +47,7 @@ #include #include #include +#include #include #include #if CONFIG_ENABLE_AMEBA_TEST_EVENT_TRIGGER @@ -77,6 +78,7 @@ app::Clusters::NetworkCommissioning::Instance &(NetworkCommissioning::AmebaWiFiDriver::GetInstance())); app::Clusters::TemperatureControl::AppSupportedTemperatureLevelsDelegate sAppSupportedTemperatureLevelsDelegate; +Clusters::ModeSelect::StaticSupportedModesManager sStaticSupportedModesManager; } // namespace void NetWorkCommissioningInstInit() @@ -181,6 +183,7 @@ static void InitServer(intptr_t context) InitManualOperation(); #endif app::Clusters::TemperatureControl::SetInstance(&sAppSupportedTemperatureLevelsDelegate); + Clusters::ModeSelect::setSupportedModesManager(&sStaticSupportedModesManager); MatterMicrowaveOvenServerInit(); #if CONFIG_ENABLE_AMEBA_TEST_EVENT_TRIGGER static SmokeCOTestEventTriggerHandler sSmokeCOTestEventTriggerHandler; diff --git a/examples/all-clusters-app/asr/src/AppTask.cpp b/examples/all-clusters-app/asr/src/AppTask.cpp index 1a829ca3de..ef3c86d272 100644 --- a/examples/all-clusters-app/asr/src/AppTask.cpp +++ b/examples/all-clusters-app/asr/src/AppTask.cpp @@ -42,6 +42,7 @@ #include #include #include +#include #include using chip::Protocols::InteractionModel::Status; @@ -66,6 +67,7 @@ app::Clusters::NetworkCommissioning::Instance sWiFiNetworkCommissioningInstance(kNetworkCommissioningEndpointMain /* Endpoint Id */, &(NetworkCommissioning::ASRWiFiDriver::GetInstance())); app::Clusters::TemperatureControl::AppSupportedTemperatureLevelsDelegate sAppSupportedTemperatureLevelsDelegate; +app::Clusters::ModeSelect::StaticSupportedModesManager sStaticSupportedModesManager; } // namespace AppTask AppTask::sAppTask; @@ -131,6 +133,7 @@ CHIP_ERROR AppTask::Init() #endif /* CONFIG_NETWORK_LAYER_BLE */ app::Clusters::TemperatureControl::SetInstance(&sAppSupportedTemperatureLevelsDelegate); + app::Clusters::ModeSelect::setSupportedModesManager(&sStaticSupportedModesManager); return CHIP_NO_ERROR; } diff --git a/examples/all-clusters-app/cc13x4_26x4/main/AppTask.cpp b/examples/all-clusters-app/cc13x4_26x4/main/AppTask.cpp index 88099f009f..c9a5434765 100644 --- a/examples/all-clusters-app/cc13x4_26x4/main/AppTask.cpp +++ b/examples/all-clusters-app/cc13x4_26x4/main/AppTask.cpp @@ -49,6 +49,7 @@ #include #include +#include #include #include @@ -73,6 +74,7 @@ static Button_Handle sAppRightHandle; static DeviceInfoProviderImpl sExampleDeviceInfoProvider; AppTask AppTask::sAppTask; +app::Clusters::ModeSelect::StaticSupportedModesManager sStaticSupportedModesManager; constexpr EndpointId kNetworkCommissioningEndpointSecondary = 0xFFFE; @@ -334,6 +336,7 @@ int AppTask::Init() // QR code will be used with CHIP Tool PrintOnboardingCodes(RendezvousInformationFlags(RendezvousInformationFlag::kBLE)); + app::Clusters::ModeSelect::setSupportedModesManager(&sStaticSupportedModesManager); return 0; } diff --git a/examples/all-clusters-app/esp32/main/CMakeLists.txt b/examples/all-clusters-app/esp32/main/CMakeLists.txt index 3e80b995c5..9dfd4ffc50 100644 --- a/examples/all-clusters-app/esp32/main/CMakeLists.txt +++ b/examples/all-clusters-app/esp32/main/CMakeLists.txt @@ -40,7 +40,6 @@ set(SRC_DIRS_LIST "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/platform/esp32/ota" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/platform/esp32/common" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/platform/esp32/shell_extension" - "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/platform/esp32/mode-support" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/server" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/icd/server" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/util" @@ -112,8 +111,6 @@ set(SRC_DIRS_LIST ) -set(EXCLUDE_SRCS "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/all-clusters-app/all-clusters-common/src/static-supported-modes-manager.cpp") - if (CONFIG_ENABLE_PW_RPC) # Append additional directories for RPC build set(PRIV_INCLUDE_DIRS_LIST "${PRIV_INCLUDE_DIRS_LIST}" @@ -143,8 +140,7 @@ if (CONFIG_ENABLE_ICD_SERVER) endif() idf_component_register(PRIV_INCLUDE_DIRS ${PRIV_INCLUDE_DIRS_LIST} - SRC_DIRS ${SRC_DIRS_LIST} - EXCLUDE_SRCS ${EXCLUDE_SRCS}) + SRC_DIRS ${SRC_DIRS_LIST}) get_filename_component(CHIP_ROOT ${CMAKE_SOURCE_DIR}/third_party/connectedhomeip REALPATH) diff --git a/examples/all-clusters-app/esp32/main/main.cpp b/examples/all-clusters-app/esp32/main/main.cpp index af94d2b2d3..6a0d0d389a 100644 --- a/examples/all-clusters-app/esp32/main/main.cpp +++ b/examples/all-clusters-app/esp32/main/main.cpp @@ -41,8 +41,8 @@ #include #include #include -#include #include +#include #include #if CONFIG_HAVE_DISPLAY @@ -95,6 +95,7 @@ class AppCallbacks : public AppDelegate AppCallbacks sCallbacks; app::Clusters::TemperatureControl::AppSupportedTemperatureLevelsDelegate sAppSupportedTemperatureLevelsDelegate; +app::Clusters::ModeSelect::StaticSupportedModesManager sStaticSupportedModesManager; constexpr EndpointId kNetworkCommissioningEndpointSecondary = 0xFFFE; @@ -122,15 +123,9 @@ static void InitServer(intptr_t context) #if CONFIG_DEVICE_TYPE_M5STACK SetupPretendDevices(); #endif - CHIP_ERROR err = - app::Clusters::ModeSelect::StaticSupportedModesManager::getStaticSupportedModesManagerInstance().InitEndpointArray( - FIXED_ENDPOINT_COUNT); - if (err != CHIP_NO_ERROR) - { - ESP_LOGE(TAG, "Failed to initialize endpoint array for supported-modes, err:%" CHIP_ERROR_FORMAT, err.Format()); - } app::Clusters::TemperatureControl::SetInstance(&sAppSupportedTemperatureLevelsDelegate); + app::Clusters::ModeSelect::setSupportedModesManager(&sStaticSupportedModesManager); } // #include diff --git a/examples/all-clusters-app/infineon/psoc6/src/AppTask.cpp b/examples/all-clusters-app/infineon/psoc6/src/AppTask.cpp index 143e25e87e..bb499d2009 100644 --- a/examples/all-clusters-app/infineon/psoc6/src/AppTask.cpp +++ b/examples/all-clusters-app/infineon/psoc6/src/AppTask.cpp @@ -41,6 +41,7 @@ #include #include #include +#include #include /* OTA related includes */ @@ -98,6 +99,7 @@ OTAImageProcessorImpl gImageProcessor; #endif chip::app::Clusters::TemperatureControl::AppSupportedTemperatureLevelsDelegate sAppSupportedTemperatureLevelsDelegate; +chip::app::Clusters::ModeSelect::StaticSupportedModesManager sStaticSupportedModesManager; } // namespace using namespace ::chip; @@ -141,6 +143,7 @@ static void InitServer(intptr_t context) GetAppTask().InitOTARequestor(); #endif chip::app::Clusters::TemperatureControl::SetInstance(&sAppSupportedTemperatureLevelsDelegate); + chip::app::Clusters::ModeSelect::setSupportedModesManager(&sStaticSupportedModesManager); } CHIP_ERROR AppTask::StartAppTask() diff --git a/examples/all-clusters-app/linux/main-common.cpp b/examples/all-clusters-app/linux/main-common.cpp index edddc6a8a7..badda7f3b6 100644 --- a/examples/all-clusters-app/linux/main-common.cpp +++ b/examples/all-clusters-app/linux/main-common.cpp @@ -58,6 +58,7 @@ #include #include #include +#include #include #include #include @@ -80,6 +81,7 @@ AllClustersCommandDelegate sAllClustersCommandDelegate; Clusters::WindowCovering::WindowCoveringManager sWindowCoveringManager; Clusters::TemperatureControl::AppSupportedTemperatureLevelsDelegate sAppSupportedTemperatureLevelsDelegate; +Clusters::ModeSelect::StaticSupportedModesManager sStaticSupportedModesManager; Clusters::ValveConfigurationAndControl::ValveControlDelegate sValveDelegate; Clusters::TimeSynchronization::ExtendedTimeSyncDelegate sTimeSyncDelegate; @@ -246,6 +248,7 @@ void ApplicationInit() MatterDishwasherAlarmServerInit(); #endif Clusters::TemperatureControl::SetInstance(&sAppSupportedTemperatureLevelsDelegate); + Clusters::ModeSelect::setSupportedModesManager(&sStaticSupportedModesManager); Clusters::ValveConfigurationAndControl::SetDefaultDelegate(chip::EndpointId(1), &sValveDelegate); Clusters::TimeSynchronization::SetDefaultDelegate(&sTimeSyncDelegate); diff --git a/examples/all-clusters-app/mbed/main/AppTask.cpp b/examples/all-clusters-app/mbed/main/AppTask.cpp index b497ea7919..f67876b1da 100644 --- a/examples/all-clusters-app/mbed/main/AppTask.cpp +++ b/examples/all-clusters-app/mbed/main/AppTask.cpp @@ -25,6 +25,7 @@ #include #include #include +#include #include #include @@ -45,7 +46,8 @@ using namespace ::chip::Credentials; namespace { app::Clusters::TemperatureControl::AppSupportedTemperatureLevelsDelegate sAppSupportedTemperatureLevelsDelegate; -} +app::Clusters::ModeSelect::StaticSupportedModesManager sStaticSupportedModesManager; +} // namespace AppTask AppTask::sAppTask; @@ -90,6 +92,7 @@ int AppTask::Init() return EXIT_FAILURE; } app::Clusters::TemperatureControl::SetInstance(&sAppSupportedTemperatureLevelsDelegate); + app::Clusters::ModeSelect::setSupportedModesManager(&sStaticSupportedModesManager); return 0; } diff --git a/examples/all-clusters-app/nrfconnect/main/AppTask.cpp b/examples/all-clusters-app/nrfconnect/main/AppTask.cpp index 3551087a96..067e8113c4 100644 --- a/examples/all-clusters-app/nrfconnect/main/AppTask.cpp +++ b/examples/all-clusters-app/nrfconnect/main/AppTask.cpp @@ -35,6 +35,7 @@ #include #include +#include #include #ifdef CONFIG_CHIP_WIFI @@ -95,6 +96,7 @@ bool sIsNetworkEnabled = false; bool sHaveBLEConnections = false; app::Clusters::TemperatureControl::AppSupportedTemperatureLevelsDelegate sAppSupportedTemperatureLevelsDelegate; +app::Clusters::ModeSelect::StaticSupportedModesManager sStaticSupportedModesManager; #ifdef CONFIG_CHIP_CRYPTO_PSA chip::Crypto::PSAOperationalKeystore sPSAOperationalKeystore{}; @@ -257,6 +259,7 @@ CHIP_ERROR AppTask::Init() } app::Clusters::TemperatureControl::SetInstance(&sAppSupportedTemperatureLevelsDelegate); + app::Clusters::ModeSelect::setSupportedModesManager(&sStaticSupportedModesManager); return err; } diff --git a/examples/all-clusters-app/nxp/mw320/main.cpp b/examples/all-clusters-app/nxp/mw320/main.cpp index 5f2df7b501..82d335cccb 100644 --- a/examples/all-clusters-app/nxp/mw320/main.cpp +++ b/examples/all-clusters-app/nxp/mw320/main.cpp @@ -41,6 +41,7 @@ #include #include #include +#include #include #include @@ -121,6 +122,7 @@ static struct wlan_network sta_network; static struct wlan_network uap_network; chip::app::Clusters::TemperatureControl::AppSupportedTemperatureLevelsDelegate sAppSupportedTemperatureLevelsDelegate; +chip::app::Clusters::ModeSelect::StaticSupportedModesManager sStaticSupportedModesManager; const int TASK_MAIN_PRIO = OS_PRIO_3; const int TASK_MAIN_STACK_SIZE = 800; @@ -1083,6 +1085,7 @@ static void run_chip_srv(System::Layer * aSystemLayer, void * aAppState) // binding -- chip::app::Clusters::TemperatureControl::SetInstance(&sAppSupportedTemperatureLevelsDelegate); + chip::app::Clusters::ModeSelect::setSupportedModesManager(&sStaticSupportedModesManager); return; } diff --git a/examples/all-clusters-app/telink/src/AppTask.cpp b/examples/all-clusters-app/telink/src/AppTask.cpp index 03b81fb434..909f89af22 100644 --- a/examples/all-clusters-app/telink/src/AppTask.cpp +++ b/examples/all-clusters-app/telink/src/AppTask.cpp @@ -18,10 +18,12 @@ #include "AppTask.h" #include "binding-handler.h" +#include LOG_MODULE_DECLARE(app, CONFIG_CHIP_APP_LOG_LEVEL); AppTask AppTask::sAppTask; +chip::app::Clusters::ModeSelect::StaticSupportedModesManager sStaticSupportedModesManager; CHIP_ERROR AppTask::Init(void) { @@ -35,5 +37,6 @@ CHIP_ERROR AppTask::Init(void) return err; } + chip::app::Clusters::ModeSelect::setSupportedModesManager(&sStaticSupportedModesManager); return CHIP_NO_ERROR; } diff --git a/examples/all-clusters-app/tizen/src/main.cpp b/examples/all-clusters-app/tizen/src/main.cpp index 49c9f06ad9..191138c1f3 100644 --- a/examples/all-clusters-app/tizen/src/main.cpp +++ b/examples/all-clusters-app/tizen/src/main.cpp @@ -22,6 +22,7 @@ #include #include #include +#include #include #include @@ -40,6 +41,7 @@ NetworkCommissioning::TizenEthernetDriver sEthernetDriver; Clusters::NetworkCommissioning::Instance sEthernetNetworkCommissioningInstance(kNetworkCommissioningEndpointMain, &sEthernetDriver); app::Clusters::TemperatureControl::AppSupportedTemperatureLevelsDelegate sAppSupportedTemperatureLevelsDelegate; +Clusters::ModeSelect::StaticSupportedModesManager sStaticSupportedModesManager; } // namespace void ApplicationInit() @@ -49,6 +51,7 @@ void ApplicationInit() sEthernetNetworkCommissioningInstance.Init(); app::Clusters::TemperatureControl::SetInstance(&sAppSupportedTemperatureLevelsDelegate); + Clusters::ModeSelect::setSupportedModesManager(&sStaticSupportedModesManager); } void ApplicationShutdown() {} diff --git a/examples/all-clusters-minimal-app/ameba/main/chipinterface.cpp b/examples/all-clusters-minimal-app/ameba/main/chipinterface.cpp index abb0791ac9..61f7db147f 100644 --- a/examples/all-clusters-minimal-app/ameba/main/chipinterface.cpp +++ b/examples/all-clusters-minimal-app/ameba/main/chipinterface.cpp @@ -37,6 +37,7 @@ #include #include #include +#include #include #if CONFIG_ENABLE_OTA_REQUESTOR @@ -64,6 +65,7 @@ namespace { // Network Commissioning constexpr EndpointId kNetworkCommissioningEndpointMain = 0; constexpr EndpointId kNetworkCommissioningEndpointSecondary = 0xFFFE; +Clusters::ModeSelect::StaticSupportedModesManager sStaticSupportedModesManager; app::Clusters::NetworkCommissioning::Instance sWiFiNetworkCommissioningInstance(kNetworkCommissioningEndpointMain /* Endpoint Id */, &(NetworkCommissioning::AmebaWiFiDriver::GetInstance())); @@ -170,6 +172,7 @@ static void InitServer(intptr_t context) // QR code will be used with CHIP Tool PrintOnboardingCodes(chip::RendezvousInformationFlags(chip::RendezvousInformationFlag::kBLE)); } + Clusters::ModeSelect::setSupportedModesManager(&sStaticSupportedModesManager); } extern "C" void ChipTest(void) diff --git a/examples/all-clusters-minimal-app/asr/src/AppTask.cpp b/examples/all-clusters-minimal-app/asr/src/AppTask.cpp index f9d05c2157..7e33211b8a 100644 --- a/examples/all-clusters-minimal-app/asr/src/AppTask.cpp +++ b/examples/all-clusters-minimal-app/asr/src/AppTask.cpp @@ -42,6 +42,7 @@ #include #include #include +#include #include "init_Matter.h" #include "lega_rtos_api.h" @@ -60,6 +61,7 @@ QueueHandle_t sAppEventQueue; constexpr EndpointId kNetworkCommissioningEndpointMain = 0; constexpr EndpointId kNetworkCommissioningEndpointSecondary = 0xFFFE; +app::Clusters::ModeSelect::StaticSupportedModesManager sStaticSupportedModesManager; app::Clusters::NetworkCommissioning::Instance sWiFiNetworkCommissioningInstance(kNetworkCommissioningEndpointMain /* Endpoint Id */, &(NetworkCommissioning::ASRWiFiDriver::GetInstance())); @@ -120,6 +122,7 @@ CHIP_ERROR AppTask::Init() sLightLED.Init(LIGHT_LED); + app::Clusters::ModeSelect::setSupportedModesManager(&sStaticSupportedModesManager); return CHIP_NO_ERROR; } diff --git a/examples/all-clusters-minimal-app/esp32/main/main.cpp b/examples/all-clusters-minimal-app/esp32/main/main.cpp index 993dc60930..4972e775bd 100644 --- a/examples/all-clusters-minimal-app/esp32/main/main.cpp +++ b/examples/all-clusters-minimal-app/esp32/main/main.cpp @@ -43,6 +43,7 @@ #include #include #include +#include #if CONFIG_HAVE_DISPLAY #include "DeviceWithDisplay.h" @@ -74,6 +75,7 @@ extern const char TAG[] = "all-clusters-minimal-app"; static AppDeviceCallbacks EchoCallbacks; static AppDeviceCallbacksDelegate sAppDeviceCallbacksDelegate; +app::Clusters::ModeSelect::StaticSupportedModesManager sStaticSupportedModesManager; namespace { class AppCallbacks : public AppDelegate @@ -116,6 +118,7 @@ static void InitServer(intptr_t context) #if CONFIG_DEVICE_TYPE_M5STACK SetupPretendDevices(); #endif + app::Clusters::ModeSelect::setSupportedModesManager(&sStaticSupportedModesManager); } extern "C" void app_main() diff --git a/examples/all-clusters-minimal-app/infineon/psoc6/src/AppTask.cpp b/examples/all-clusters-minimal-app/infineon/psoc6/src/AppTask.cpp index 169b2f88ac..56327c56dd 100644 --- a/examples/all-clusters-minimal-app/infineon/psoc6/src/AppTask.cpp +++ b/examples/all-clusters-minimal-app/infineon/psoc6/src/AppTask.cpp @@ -41,6 +41,7 @@ #include #include #include +#include /* OTA related includes */ #if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR @@ -87,6 +88,7 @@ StaticQueue_t sAppEventQueueStruct; StackType_t appStack[APP_TASK_STACK_SIZE / sizeof(StackType_t)]; StaticTask_t appTaskStruct; +chip::app::Clusters::ModeSelect::StaticSupportedModesManager sStaticSupportedModesManager; #if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR DefaultOTARequestor gRequestorCore; @@ -138,6 +140,7 @@ static void InitServer(intptr_t context) #if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR GetAppTask().InitOTARequestor(); #endif + chip::app::Clusters::ModeSelect::setSupportedModesManager(&sStaticSupportedModesManager); } CHIP_ERROR AppTask::StartAppTask() diff --git a/examples/all-clusters-minimal-app/linux/main-common.cpp b/examples/all-clusters-minimal-app/linux/main-common.cpp index f0bf3cafe8..d99927cea0 100644 --- a/examples/all-clusters-minimal-app/linux/main-common.cpp +++ b/examples/all-clusters-minimal-app/linux/main-common.cpp @@ -25,6 +25,7 @@ #include #include #include +#include #include #include #include @@ -37,6 +38,7 @@ using namespace chip::DeviceLayer; namespace { static LowPowerManager lowPowerManager; +Clusters::ModeSelect::StaticSupportedModesManager sStaticSupportedModesManager; } // namespace void OnIdentifyStart(::Identify *) @@ -81,7 +83,10 @@ static Identify gIdentify1 = { OnTriggerEffect, }; -void ApplicationInit() {} +void ApplicationInit() +{ + Clusters::ModeSelect::setSupportedModesManager(&sStaticSupportedModesManager); +} void ApplicationShutdown() {} diff --git a/examples/all-clusters-minimal-app/mbed/main/AppTask.cpp b/examples/all-clusters-minimal-app/mbed/main/AppTask.cpp index 62317774c1..eb1188b93a 100644 --- a/examples/all-clusters-minimal-app/mbed/main/AppTask.cpp +++ b/examples/all-clusters-minimal-app/mbed/main/AppTask.cpp @@ -27,6 +27,7 @@ #include #include +#include static LEDWidget sStatusLED(MBED_CONF_APP_SYSTEM_STATE_LED); @@ -43,6 +44,7 @@ using namespace ::chip::DeviceLayer; using namespace ::chip::Credentials; AppTask AppTask::sAppTask; +app::Clusters::ModeSelect::StaticSupportedModesManager sStaticSupportedModesManager; int AppTask::Init() { @@ -85,6 +87,7 @@ int AppTask::Init() return EXIT_FAILURE; } + app::Clusters::ModeSelect::setSupportedModesManager(&sStaticSupportedModesManager); return 0; } diff --git a/examples/all-clusters-minimal-app/nrfconnect/main/AppTask.cpp b/examples/all-clusters-minimal-app/nrfconnect/main/AppTask.cpp index 86bfe7a9aa..be858eae56 100644 --- a/examples/all-clusters-minimal-app/nrfconnect/main/AppTask.cpp +++ b/examples/all-clusters-minimal-app/nrfconnect/main/AppTask.cpp @@ -30,6 +30,7 @@ #include #include +#include #if CONFIG_CHIP_OTA_REQUESTOR #include "OTAUtil.h" @@ -63,6 +64,7 @@ static k_timer sFunctionTimer; LEDWidget sStatusLED; FactoryResetLEDsWrapper<3> sFactoryResetLEDs{ { FACTORY_RESET_SIGNAL_LED, FACTORY_RESET_SIGNAL_LED1, FACTORY_RESET_SIGNAL_LED2 } }; +app::Clusters::ModeSelect::StaticSupportedModesManager sStaticSupportedModesManager; bool sIsNetworkProvisioned = false; bool sIsNetworkEnabled = false; @@ -198,6 +200,7 @@ CHIP_ERROR AppTask::Init() { LOG_ERR("PlatformMgr().StartEventLoopTask() failed"); } + app::Clusters::ModeSelect::setSupportedModesManager(&sStaticSupportedModesManager); return err; } diff --git a/examples/all-clusters-minimal-app/telink/src/AppTask.cpp b/examples/all-clusters-minimal-app/telink/src/AppTask.cpp index 55d46154f9..ee78fddf5b 100644 --- a/examples/all-clusters-minimal-app/telink/src/AppTask.cpp +++ b/examples/all-clusters-minimal-app/telink/src/AppTask.cpp @@ -18,10 +18,12 @@ #include "AppTask.h" #include "binding-handler.h" +#include LOG_MODULE_DECLARE(app, CONFIG_CHIP_APP_LOG_LEVEL); AppTask AppTask::sAppTask; +chip::app::Clusters::ModeSelect::StaticSupportedModesManager sStaticSupportedModesManager; CHIP_ERROR AppTask::Init() { @@ -35,5 +37,6 @@ CHIP_ERROR AppTask::Init() return err; } + chip::app::Clusters::ModeSelect::setSupportedModesManager(&sStaticSupportedModesManager); return CHIP_NO_ERROR; } diff --git a/examples/all-clusters-minimal-app/tizen/src/main.cpp b/examples/all-clusters-minimal-app/tizen/src/main.cpp index fd2a345c95..2d37747fe8 100644 --- a/examples/all-clusters-minimal-app/tizen/src/main.cpp +++ b/examples/all-clusters-minimal-app/tizen/src/main.cpp @@ -22,6 +22,7 @@ #include #include #include +#include #include #include @@ -36,6 +37,7 @@ constexpr EndpointId kNetworkCommissioningEndpointMain = 0; constexpr EndpointId kNetworkCommissioningEndpointSecondary = 0xFFFE; NetworkCommissioning::TizenEthernetDriver sEthernetDriver; +Clusters::ModeSelect::StaticSupportedModesManager sStaticSupportedModesManager; Clusters::NetworkCommissioning::Instance sEthernetNetworkCommissioningInstance(kNetworkCommissioningEndpointMain, &sEthernetDriver); } // namespace @@ -45,6 +47,7 @@ void ApplicationInit() emberAfEndpointEnableDisable(kNetworkCommissioningEndpointSecondary, false); sEthernetNetworkCommissioningInstance.Init(); + Clusters::ModeSelect::setSupportedModesManager(&sStaticSupportedModesManager); } void ApplicationShutdown(){}; diff --git a/examples/placeholder/linux/include/static-supported-modes-manager.h b/examples/placeholder/linux/include/static-supported-modes-manager.h index b4ce50b8cd..168482e030 100644 --- a/examples/placeholder/linux/include/static-supported-modes-manager.h +++ b/examples/placeholder/linux/include/static-supported-modes-manager.h @@ -31,7 +31,7 @@ namespace ModeSelect { * This implementation statically defines the options. */ -class StaticSupportedModesManager : public chip::app::Clusters::ModeSelect::SupportedModesManager +class StaticSupportedModesManager : public SupportedModesManager { using ModeOptionStructType = Structs::ModeOptionStruct::Type; using storage_value_type = const ModeOptionStructType; @@ -52,8 +52,6 @@ class StaticSupportedModesManager : public chip::app::Clusters::ModeSelect::Supp static const EndpointSpanPair supportedOptionsByEndpoints[MATTER_DM_MODE_SELECT_CLUSTER_SERVER_ENDPOINT_COUNT]; public: - static const StaticSupportedModesManager instance; - SupportedModesManager::ModeOptionsProvider getModeOptionsProvider(EndpointId endpointId) const override; Protocols::InteractionModel::Status getModeOptionByMode(EndpointId endpointId, uint8_t mode, @@ -62,12 +60,8 @@ class StaticSupportedModesManager : public chip::app::Clusters::ModeSelect::Supp ~StaticSupportedModesManager(){}; StaticSupportedModesManager() {} - - static inline const StaticSupportedModesManager & getStaticSupportedModesManagerInstance() { return instance; } }; -const SupportedModesManager * getSupportedModesManager(); - } // namespace ModeSelect } // namespace Clusters } // namespace app diff --git a/examples/placeholder/linux/static-supported-modes-manager.cpp b/examples/placeholder/linux/static-supported-modes-manager.cpp index 4060d4be85..94345600cf 100644 --- a/examples/placeholder/linux/static-supported-modes-manager.cpp +++ b/examples/placeholder/linux/static-supported-modes-manager.cpp @@ -39,8 +39,6 @@ const StaticSupportedModesManager::EndpointSpanPair EndpointSpanPair(1, Span(StaticSupportedModesManager::coffeeOptions)) // Options for Endpoint 1 }; -const StaticSupportedModesManager StaticSupportedModesManager::instance = StaticSupportedModesManager(); - SupportedModesManager::ModeOptionsProvider StaticSupportedModesManager::getModeOptionsProvider(EndpointId endpointId) const { for (auto & endpointSpanPair : supportedOptionsByEndpoints) @@ -76,8 +74,3 @@ Status StaticSupportedModesManager::getModeOptionByMode(unsigned short endpointI ChipLogProgress(Zcl, "Cannot find the mode %u", mode); return Status::InvalidCommand; } - -const ModeSelect::SupportedModesManager * ModeSelect::getSupportedModesManager() -{ - return &StaticSupportedModesManager::instance; -} diff --git a/examples/platform/esp32/mode-support/static-supported-modes-manager.cpp b/examples/platform/esp32/mode-support/static-supported-modes-manager.cpp index d06a8b8b7d..fc9a94cbb3 100644 --- a/examples/platform/esp32/mode-support/static-supported-modes-manager.cpp +++ b/examples/platform/esp32/mode-support/static-supported-modes-manager.cpp @@ -33,8 +33,6 @@ using List = app::DataModel::List; SupportedModesManager::ModeOptionsProvider * StaticSupportedModesManager::epModeOptionsProviderList = nullptr; -const StaticSupportedModesManager StaticSupportedModesManager::instance = StaticSupportedModesManager(); - int StaticSupportedModesManager::mSize = 0; CHIP_ERROR StaticSupportedModesManager::InitEndpointArray(int size) @@ -194,11 +192,6 @@ Status StaticSupportedModesManager::getModeOptionByMode(unsigned short endpointI return Status::InvalidCommand; } -const ModeSelect::SupportedModesManager * ModeSelect::getSupportedModesManager() -{ - return &StaticSupportedModesManager::getStaticSupportedModesManagerInstance(); -} - void StaticSupportedModesManager::FreeSupportedModes(EndpointId endpointId) const { if (epModeOptionsProviderList[endpointId].begin() != nullptr) diff --git a/examples/platform/esp32/mode-support/static-supported-modes-manager.h b/examples/platform/esp32/mode-support/static-supported-modes-manager.h index 8d6bb3c665..658b256254 100644 --- a/examples/platform/esp32/mode-support/static-supported-modes-manager.h +++ b/examples/platform/esp32/mode-support/static-supported-modes-manager.h @@ -25,7 +25,7 @@ namespace app { namespace Clusters { namespace ModeSelect { -class StaticSupportedModesManager : public chip::app::Clusters::ModeSelect::SupportedModesManager +class StaticSupportedModesManager : public SupportedModesManager { private: using ModeOptionStructType = Structs::ModeOptionStruct::Type; @@ -36,8 +36,6 @@ class StaticSupportedModesManager : public chip::app::Clusters::ModeSelect::Supp void FreeSupportedModes(EndpointId endpointId) const; - static const StaticSupportedModesManager instance; - public: // InitEndpointArray should be called only once in the application. Memory allocated to the // epModeOptionsProviderList will be needed for the lifetime of the program, so it's never deallocated. @@ -68,12 +66,8 @@ class StaticSupportedModesManager : public chip::app::Clusters::ModeSelect::Supp FreeSupportedModes(i); } } - - static inline const StaticSupportedModesManager & getStaticSupportedModesManagerInstance() { return instance; } }; -const SupportedModesManager * getSupportedModesManager(); - } // namespace ModeSelect } // namespace Clusters } // namespace app diff --git a/examples/shell/cc13x4_26x4/main/AppTask.cpp b/examples/shell/cc13x4_26x4/main/AppTask.cpp index 86432279d5..3f5ff1e659 100644 --- a/examples/shell/cc13x4_26x4/main/AppTask.cpp +++ b/examples/shell/cc13x4_26x4/main/AppTask.cpp @@ -41,6 +41,7 @@ #include #include +#include /* syscfg */ #include @@ -54,6 +55,7 @@ using namespace ::chip::DeviceLayer; using chip::Shell::Engine; AppTask AppTask::sAppTask; +Clusters::ModeSelect::StaticSupportedModesManager sStaticSupportedModesManager; static TaskHandle_t sAppTaskHandle; @@ -171,6 +173,7 @@ CHIP_ERROR AppTask::Init() #if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR InitializeOTARequestor(); #endif + Clusters::ModeSelect::setSupportedModesManager(&sStaticSupportedModesManager); return err; } diff --git a/src/app/clusters/mode-select-server/mode-select-server.cpp b/src/app/clusters/mode-select-server/mode-select-server.cpp index c5fb49708a..5f247bb4b2 100644 --- a/src/app/clusters/mode-select-server/mode-select-server.cpp +++ b/src/app/clusters/mode-select-server/mode-select-server.cpp @@ -49,6 +49,17 @@ using BootReasonType = GeneralDiagnostics::BootReasonEnum; static InteractionModel::Status verifyModeValue(const EndpointId endpointId, const uint8_t newMode); +static ModeSelect::SupportedModesManager * sSupportedModesManager = nullptr; + +const SupportedModesManager * ModeSelect::getSupportedModesManager() +{ + return sSupportedModesManager; +} + +void ModeSelect::setSupportedModesManager(ModeSelect::SupportedModesManager * aSupportedModesManager) +{ + sSupportedModesManager = aSupportedModesManager; +} namespace { inline bool areStartUpModeAndCurrentModeNonVolatile(EndpointId endpoint); @@ -71,6 +82,12 @@ CHIP_ERROR ModeSelectAttrAccess::Read(const ConcreteReadAttributePath & aPath, A if (ModeSelect::Attributes::SupportedModes::Id == aPath.mAttributeId) { + if (gSupportedModeManager == nullptr) + { + ChipLogError(Zcl, "ModeSelect: SupportedModesManager is NULL"); + aEncoder.EncodeEmptyList(); + return CHIP_NO_ERROR; + } const ModeSelect::SupportedModesManager::ModeOptionsProvider modeOptionsProvider = gSupportedModeManager->getModeOptionsProvider(aPath.mEndpointId); if (modeOptionsProvider.begin() == nullptr) @@ -104,8 +121,14 @@ bool emberAfModeSelectClusterChangeToModeCallback(CommandHandler * commandHandle uint8_t newMode = commandData.newMode; // Check that the newMode matches one of the supported options const ModeSelect::Structs::ModeOptionStruct::Type * modeOptionPtr; - Status checkSupportedModeStatus = - ModeSelect::getSupportedModesManager()->getModeOptionByMode(endpointId, newMode, &modeOptionPtr); + const ModeSelect::SupportedModesManager * gSupportedModeManager = ModeSelect::getSupportedModesManager(); + if (gSupportedModeManager == nullptr) + { + ChipLogError(Zcl, "ModeSelect: SupportedModesManager is NULL"); + commandHandler->AddStatus(commandPath, Status::Failure); + return true; + } + Status checkSupportedModeStatus = gSupportedModeManager->getModeOptionByMode(endpointId, newMode, &modeOptionPtr); if (Status::Success != checkSupportedModeStatus) { ChipLogProgress(Zcl, "ModeSelect: Failed to find the option with mode %u", newMode); @@ -265,5 +288,11 @@ static InteractionModel::Status verifyModeValue(const EndpointId endpointId, con return InteractionModel::Status::Success; } const ModeSelect::Structs::ModeOptionStruct::Type * modeOptionPtr; - return ModeSelect::getSupportedModesManager()->getModeOptionByMode(endpointId, newMode, &modeOptionPtr); + const ModeSelect::SupportedModesManager * gSupportedModeManager = ModeSelect::getSupportedModesManager(); + if (gSupportedModeManager == nullptr) + { + ChipLogError(Zcl, "ModeSelect: SupportedModesManager is NULL"); + return Status::Failure; + } + return gSupportedModeManager->getModeOptionByMode(endpointId, newMode, &modeOptionPtr); } diff --git a/src/app/clusters/mode-select-server/supported-modes-manager.h b/src/app/clusters/mode-select-server/supported-modes-manager.h index 3c36f188cb..7231268554 100644 --- a/src/app/clusters/mode-select-server/supported-modes-manager.h +++ b/src/app/clusters/mode-select-server/supported-modes-manager.h @@ -84,6 +84,8 @@ class SupportedModesManager const SupportedModesManager * getSupportedModesManager(); +void setSupportedModesManager(SupportedModesManager * aSupportedModesManager); + } // namespace ModeSelect } // namespace Clusters } // namespace app From f9ad5bff2a914d502603270f169f902f1bc7101b Mon Sep 17 00:00:00 2001 From: C Freeman Date: Sat, 17 Aug 2024 23:43:11 -0400 Subject: [PATCH 085/165] Python testing: Fix reporting on setup_class error (#35016) * Python testing: Fix reporting on setup_class error Also add error text to make the error easier to find. * Restyled by isort * Fix lint * Change exemption to not carry chip_error reference chip_error is a ctypes struct with a const char* pointer internally. This cannot be pickled, so it's causing problems with the mobly framework. * Fix some tests using removed class member --------- Co-authored-by: Restyled.io --- .../python/chip/exceptions/__init__.py | 14 ++--- src/controller/python/chip/native/__init__.py | 6 ++- src/python_testing/TC_CADMIN_1_9.py | 3 +- src/python_testing/TC_CGEN_2_4.py | 3 +- src/python_testing/matter_testing_support.py | 53 ++++++++++++++++++- 5 files changed, 65 insertions(+), 14 deletions(-) diff --git a/src/controller/python/chip/exceptions/__init__.py b/src/controller/python/chip/exceptions/__init__.py index c7f692e928..b293a68eac 100644 --- a/src/controller/python/chip/exceptions/__init__.py +++ b/src/controller/python/chip/exceptions/__init__.py @@ -39,21 +39,17 @@ class ChipStackException(Exception): class ChipStackError(ChipStackException): - def __init__(self, chip_error: PyChipError, msg=None): - self._chip_error = chip_error - self.msg = msg if msg else "Chip Stack Error %d" % chip_error.code + def __init__(self, code: int, msg=None): + self.code = code + self.msg = msg if msg else "Chip Stack Error %d" % self.code @classmethod def from_chip_error(cls, chip_error: PyChipError) -> ChipStackError: - return cls(chip_error, str(chip_error)) - - @property - def chip_error(self) -> PyChipError | None: - return self._chip_error + return cls(chip_error.code, str(chip_error)) @property def err(self) -> int: - return self._chip_error.code + return self.code def __str__(self): return self.msg diff --git a/src/controller/python/chip/native/__init__.py b/src/controller/python/chip/native/__init__.py index 518339017b..2528aeca32 100644 --- a/src/controller/python/chip/native/__init__.py +++ b/src/controller/python/chip/native/__init__.py @@ -69,7 +69,7 @@ class ErrorSDKPart(enum.IntEnum): class PyChipError(ctypes.Structure): ''' The ChipError for Python library. - We are using the following struct for passing the infomations of CHIP_ERROR between C++ and Python: + We are using the following struct for passing the information of CHIP_ERROR between C++ and Python: ```c struct PyChipError @@ -88,6 +88,10 @@ def raise_on_error(self) -> None: if exception is not None: # Ensure exception is not None to avoid mypy error and only raise valid exceptions raise exception + @classmethod + def from_code(cls, code): + return cls(code=code, line=0, file=ctypes.c_void_p()) + @property def is_success(self) -> bool: return self.code == 0 diff --git a/src/python_testing/TC_CADMIN_1_9.py b/src/python_testing/TC_CADMIN_1_9.py index f37e3723ed..c3d67b9bf6 100644 --- a/src/python_testing/TC_CADMIN_1_9.py +++ b/src/python_testing/TC_CADMIN_1_9.py @@ -31,6 +31,7 @@ from chip import ChipDeviceCtrl from chip.ChipDeviceCtrl import CommissioningParameters from chip.exceptions import ChipStackError +from chip.native import PyChipError from matter_testing_support import MatterBaseTest, TestStep, async_test_body, default_matter_test_main from mobly import asserts @@ -74,7 +75,7 @@ async def CommissionOnNetwork( await self.th2.CommissionOnNetwork( nodeId=self.dut_node_id, setupPinCode=setup_code, filterType=ChipDeviceCtrl.DiscoveryFilterType.LONG_DISCRIMINATOR, filter=self.discriminator) - errcode = ctx.exception.chip_error + errcode = PyChipError.from_code(ctx.exception.err) return errcode async def CommissionAttempt( diff --git a/src/python_testing/TC_CGEN_2_4.py b/src/python_testing/TC_CGEN_2_4.py index 7d9d075dc1..09fbc6d593 100644 --- a/src/python_testing/TC_CGEN_2_4.py +++ b/src/python_testing/TC_CGEN_2_4.py @@ -38,6 +38,7 @@ from chip import ChipDeviceCtrl from chip.ChipDeviceCtrl import CommissioningParameters from chip.exceptions import ChipStackError +from chip.native import PyChipError from matter_testing_support import MatterBaseTest, async_test_body, default_matter_test_main from mobly import asserts @@ -78,7 +79,7 @@ async def CommissionToStageSendCompleteAndCleanup( await self.th2.CommissionOnNetwork( nodeId=self.dut_node_id, setupPinCode=params.setupPinCode, filterType=ChipDeviceCtrl.DiscoveryFilterType.LONG_DISCRIMINATOR, filter=self.discriminator) - errcode = ctx.exception.chip_error + errcode = PyChipError.from_code(ctx.exception.err) asserts.assert_true(errcode.sdk_part == expectedErrorPart, 'Unexpected error type returned from CommissioningComplete') asserts.assert_true(errcode.sdk_code == expectedErrCode, 'Unexpected error code returned from CommissioningComplete') revokeCmd = Clusters.AdministratorCommissioning.Commands.RevokeCommissioning() diff --git a/src/python_testing/matter_testing_support.py b/src/python_testing/matter_testing_support.py index d44754f379..eb8a6ba20d 100644 --- a/src/python_testing/matter_testing_support.py +++ b/src/python_testing/matter_testing_support.py @@ -27,6 +27,7 @@ import random import re import sys +import textwrap import time import typing import uuid @@ -1123,12 +1124,60 @@ def on_fail(self, record): self.failed = True if self.runner_hook and not self.is_commissioning: exception = record.termination_signal.exception - step_duration = (datetime.now(timezone.utc) - self.step_start_time) / timedelta(microseconds=1) - test_duration = (datetime.now(timezone.utc) - self.test_start_time) / timedelta(microseconds=1) + + try: + step_duration = (datetime.now(timezone.utc) - self.step_start_time) / timedelta(microseconds=1) + except AttributeError: + # If we failed during setup, these may not be populated + step_duration = 0 + try: + test_duration = (datetime.now(timezone.utc) - self.test_start_time) / timedelta(microseconds=1) + except AttributeError: + test_duration = 0 # TODO: I have no idea what logger, logs, request or received are. Hope None works because I have nothing to give self.runner_hook.step_failure(logger=None, logs=None, duration=step_duration, request=None, received=None) self.runner_hook.test_stop(exception=exception, duration=test_duration) + def extract_error_text() -> tuple[str, str]: + no_stack_trace = ("Stack Trace Unavailable", "") + if not record.termination_signal.stacktrace: + return no_stack_trace + trace = record.termination_signal.stacktrace.splitlines() + if not trace: + return no_stack_trace + + if isinstance(exception, signals.TestError): + # Exception gets raised by the mobly framework, so the proximal error is one line back in the stack trace + assert_candidates = [idx for idx, line in enumerate(trace) if "asserts" in line and "asserts.py" not in line] + if not assert_candidates: + return "Unknown error, please see stack trace above", "" + assert_candidate_idx = assert_candidates[-1] + else: + # Normal assert is on the Last line + assert_candidate_idx = -1 + probable_error = trace[assert_candidate_idx] + + # Find the file marker immediately above the probable error + file_candidates = [idx for idx, line in enumerate(trace[:assert_candidate_idx]) if "File" in line] + if not file_candidates: + return probable_error, "Unknown file" + return probable_error.strip(), trace[file_candidates[-1]].strip() + + probable_error, probable_file = extract_error_text() + logging.error(textwrap.dedent(f""" + + ****************************************************************** + * + * Test {self.current_test_info.name} failed for the following reason: + * {exception} + * + * {probable_file} + * {probable_error} + * + ******************************************************************* + + """)) + def on_pass(self, record): ''' Called by Mobly on test pass From b823a29a2498806e53adb80b30de82519d1ea3df Mon Sep 17 00:00:00 2001 From: Justin Wood Date: Sun, 18 Aug 2024 15:30:27 -0700 Subject: [PATCH 086/165] Fixing darwin crashes, and XPC invalidation (#35056) * Fixing crashes * Restyled by clang-format --------- Co-authored-by: Restyled.io --- src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm | 12 ++++++++++-- src/platform/Darwin/DnssdContexts.cpp | 1 + 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm b/src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm index d93a379ae3..157a38199f 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm +++ b/src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm @@ -67,8 +67,16 @@ - (id)initWithUniqueIdentifier:(NSUUID *)UUID xpConnectionBlock:(NSXPCConnection self.xpcConnection.exportedInterface = [NSXPCInterface interfaceWithProtocol:@protocol(MTRXPCClientProtocol)]; self.xpcConnection.exportedObject = self; - MTR_LOG("Resuming new XPC connection"); - [self.xpcConnection resume]; + self.xpcConnection.interruptionHandler = ^{ + MTR_LOG_ERROR("XPC Connection for device controller interrupted: %@", UUID); + }; + + self.xpcConnection.invalidationHandler = ^{ + MTR_LOG_ERROR("XPC Connection for device controller invalidated: %@", UUID); + }; + + MTR_LOG("Activating new XPC connection"); + [self.xpcConnection activate]; } else { MTR_LOG_ERROR("Failed to set up XPC Connection"); return nil; diff --git a/src/platform/Darwin/DnssdContexts.cpp b/src/platform/Darwin/DnssdContexts.cpp index 4e88df40ee..ff869911e9 100644 --- a/src/platform/Darwin/DnssdContexts.cpp +++ b/src/platform/Darwin/DnssdContexts.cpp @@ -247,6 +247,7 @@ void MdnsContexts::Delete(GenericContext * context) if (context->serviceRef != nullptr) { DNSServiceRefDeallocate(context->serviceRef); + context->serviceRef = nullptr; } chip::Platform::Delete(context); } From e9f64bb1836fd38dfb2799e769ed02abc499c4f4 Mon Sep 17 00:00:00 2001 From: Anu Biradar <104591549+abiradarti@users.noreply.github.com> Date: Mon, 19 Aug 2024 11:28:27 -0500 Subject: [PATCH 087/165] [TI] Switch Application for CC13x4_26x4 (#34916) * Switch Application for TI CC13x4_26x4 * Added light-switch to CI and restyled changes * OOB configs * CI fix * CI fix in all_targets_linux_x64.txt * revert CI changes for switch-app * updated args.gni comment for logging --- .github/workflows/examples-cc13xx_26xx.yaml | 2 +- examples/light-switch-app/cc13x4_26x4/.gn | 30 + .../light-switch-app/cc13x4_26x4/BUILD.gn | 117 +++ .../light-switch-app/cc13x4_26x4/README.md | 311 ++++++++ .../light-switch-app/cc13x4_26x4/args.gni | 74 ++ .../cc13x4_26x4/build_overrides | 1 + .../light-switch-app/cc13x4_26x4/chip.syscfg | 241 ++++++ .../cc13x4_26x4/include/CHIPProjectConfig.h | 119 +++ .../cc13x4_26x4/src/AppConfig.h | 35 + .../cc13x4_26x4/src/AppEvent.h | 86 +++ .../cc13x4_26x4/src/AppTask.cpp | 722 ++++++++++++++++++ .../cc13x4_26x4/src/AppTask.h | 99 +++ .../cc13x4_26x4/src/BindingHandler.cpp | 163 ++++ .../cc13x4_26x4/src/BindingHandler.h | 33 + .../cc13x4_26x4/src/LightSwitchManager.cpp | 193 +++++ .../cc13x4_26x4/src/LightSwitchManager.h | 87 +++ .../cc13x4_26x4/src/ZclCallbacks.cpp | 57 ++ .../light-switch-app/cc13x4_26x4/src/main.cpp | 96 +++ .../cc13x4_26x4/third_party/connectedhomeip | 1 + 19 files changed, 2466 insertions(+), 1 deletion(-) create mode 100644 examples/light-switch-app/cc13x4_26x4/.gn create mode 100644 examples/light-switch-app/cc13x4_26x4/BUILD.gn create mode 100644 examples/light-switch-app/cc13x4_26x4/README.md create mode 100644 examples/light-switch-app/cc13x4_26x4/args.gni create mode 120000 examples/light-switch-app/cc13x4_26x4/build_overrides create mode 100644 examples/light-switch-app/cc13x4_26x4/chip.syscfg create mode 100644 examples/light-switch-app/cc13x4_26x4/include/CHIPProjectConfig.h create mode 100644 examples/light-switch-app/cc13x4_26x4/src/AppConfig.h create mode 100644 examples/light-switch-app/cc13x4_26x4/src/AppEvent.h create mode 100644 examples/light-switch-app/cc13x4_26x4/src/AppTask.cpp create mode 100644 examples/light-switch-app/cc13x4_26x4/src/AppTask.h create mode 100644 examples/light-switch-app/cc13x4_26x4/src/BindingHandler.cpp create mode 100644 examples/light-switch-app/cc13x4_26x4/src/BindingHandler.h create mode 100644 examples/light-switch-app/cc13x4_26x4/src/LightSwitchManager.cpp create mode 100644 examples/light-switch-app/cc13x4_26x4/src/LightSwitchManager.h create mode 100644 examples/light-switch-app/cc13x4_26x4/src/ZclCallbacks.cpp create mode 100644 examples/light-switch-app/cc13x4_26x4/src/main.cpp create mode 120000 examples/light-switch-app/cc13x4_26x4/third_party/connectedhomeip diff --git a/.github/workflows/examples-cc13xx_26xx.yaml b/.github/workflows/examples-cc13xx_26xx.yaml index b486415dbc..53c813d0b4 100644 --- a/.github/workflows/examples-cc13xx_26xx.yaml +++ b/.github/workflows/examples-cc13xx_26xx.yaml @@ -105,7 +105,7 @@ jobs: run: | .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py \ cc13x4_26x4 LP_EM_CC1354P10_6 lighting-app \ - out/artifacts/ti-cc13x4_26x4-lighting-mtd/chip-LP_EM_CC1354P10_6-lighting-example.out \ + out/artifacts/ti-cc13x4_26x4-lighting-ftd/chip-LP_EM_CC1354P10_6-lighting-example.out \ /tmp/bloat_reports/ - name: Uploading Size Reports uses: ./.github/actions/upload-size-reports diff --git a/examples/light-switch-app/cc13x4_26x4/.gn b/examples/light-switch-app/cc13x4_26x4/.gn new file mode 100644 index 0000000000..cf974b2eb1 --- /dev/null +++ b/examples/light-switch-app/cc13x4_26x4/.gn @@ -0,0 +1,30 @@ +# 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. + +import("//build_overrides/build.gni") + +# The location of the build configuration file. +buildconfig = "${build_root}/config/BUILDCONFIG.gn" + +# CHIP uses angle bracket includes. +check_system_includes = true + +default_args = { + target_cpu = "arm" + target_os = "freertos" + + import("//args.gni") + pw_build_PIP_REQUIREMENTS += + [ "${chip_root}/scripts/setup/requirements.ti.txt" ] +} diff --git a/examples/light-switch-app/cc13x4_26x4/BUILD.gn b/examples/light-switch-app/cc13x4_26x4/BUILD.gn new file mode 100644 index 0000000000..2994ab5dcc --- /dev/null +++ b/examples/light-switch-app/cc13x4_26x4/BUILD.gn @@ -0,0 +1,117 @@ +# 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. + +import("//build_overrides/build.gni") +import("//build_overrides/chip.gni") +import("//build_overrides/openthread.gni") +import("//build_overrides/ti_simplelink_sdk.gni") + +import("${build_root}/config/defaults.gni") + +import("${chip_root}/src/platform/device.gni") + +import("${ti_simplelink_sdk_build_root}/ti_simplelink_executable.gni") +import("${ti_simplelink_sdk_build_root}/ti_simplelink_sdk.gni") + +assert(current_os == "freertos") + +project_dir = "${chip_root}/examples/light-switch-app/cc13x4_26x4" + +ti_simplelink_sdk("sdk") { + include_dirs = [ "${project_dir}/include" ] + public_configs = [ ":light-switch_app_config" ] +} + +ti_sysconfig("sysconfig") { + sources = [ "${project_dir}/chip.syscfg" ] + + outputs = [ + "ti_radio_config.c", + "ti_radio_config.h", + "ti_drivers_config.c", + "ti_drivers_config.h", + "ti_ble_config.c", + "ti_ble_config.h", + "ti_dmm_application_policy.c", + "ti_dmm_application_policy.h", + + # CCFG generation disabled for OTA-able application + #"ti_devices_config.c", + #"ti_devices_config.h", + ] + + public_configs = [ ":sdk_cc13x4_26x4_dmm_config" ] + + cflags = [ + "-Wno-comment", + "@" + rebase_path("${target_gen_dir}/sysconfig/ti_utils_build_compiler.opt", + root_build_dir), + ] +} + +ti_simplelink_executable("light-switch_app") { + output_name = "chip-${ti_simplelink_board}-light-switch-example.out" + + sources = [ + "${chip_root}/examples/providers/DeviceInfoProviderImpl.cpp", + "${chip_root}/src/app/clusters/general-diagnostics-server/GenericFaultTestEventTriggerHandler.cpp", + "${project_dir}/src/AppTask.cpp", + "${project_dir}/src/BindingHandler.cpp", + "${project_dir}/src/LightSwitchManager.cpp", + "${project_dir}/src/ZclCallbacks.cpp", + "${project_dir}/src/main.cpp", + ] + + public = [ + "${chip_root}/src/platform/cc13xx_26xx/DefaultTestEventTriggerDelegate.h", + ] + + deps = [ + ":sdk", + ":sysconfig", + "${chip_root}/examples/light-switch-app/light-switch-common", + "${chip_root}/examples/platform/cc13x4_26x4:cc13x4_26x4-attestation-credentials", + "${chip_root}/src/lib", + "${chip_root}/third_party/openthread:openthread", + ] + defines = [] + if (custom_factory_data) { + defines += [ "CC13XX_26XX_FACTORY_DATA" ] + } + + if (chip_enable_icd_server) { + defines += [ "TI_ICD_ENABLE_SERVER" ] + } + + include_dirs = [ + "${project_dir}", + "${chip_root}/examples/providers/", + ] + + cflags = [ + "-Wno-implicit-fallthrough", + "-Wno-sign-compare", + "-Wconversion", + ] + + output_dir = root_out_dir +} + +group("cc13x4_26x4") { + deps = [ ":light-switch_app" ] +} + +group("default") { + deps = [ ":cc13x4_26x4" ] +} diff --git a/examples/light-switch-app/cc13x4_26x4/README.md b/examples/light-switch-app/cc13x4_26x4/README.md new file mode 100644 index 0000000000..a27c702714 --- /dev/null +++ b/examples/light-switch-app/cc13x4_26x4/README.md @@ -0,0 +1,311 @@ +# Matter Light Switch Example Application + +An example application showing the use of [Matter][matter] on the Texas +Instruments CC13XX_26XX family of Wireless MCUs. + +--- + +- [Matter Light Switch Example Application](#matter-light-switch-example-application) + - [Introduction](#introduction) + - [Device UI](#device-ui) + - [Building](#building) + - [Preparation](#preparation) + - [Compilation](#compilation) + - [Programming](#programming) + - [Code Composer Studio](#code-composer-studio) + - [UniFlash](#uniflash) + - [Viewing Logging Output](#viewing-logging-output) + - [Running the Example](#running-the-example) + - [TI Support](#ti-support) + +--- + +## Introduction + +The CC13XX_26XX light-switch example application provides a working +demonstration of a connected light-switch device. This uses the open-source +Matter implementation and the Texas Instruments SimpleLink™ CC13XX and CC26XX +software development kit. + +This example is enabled to build for CC1354P10 devices. + +The light-switch example is intended to serve both as a means to explore the +workings of Matter, as well as a template for creating real products based on +the Texas Instruments devices. + +## Device UI + +| Action | Functionality | +| ------------------------------------------------ | ---------------------------------- | +| Left Button (`BTN-1`) Press (less than 1000 ms) | Turns connected bulb off | +| Left Button (`BTN-1`) Press (more than 1000 ms) | Factory Reset | +| Right Button (`BTN-2`) Press (less than 1000 ms) | Turns connected bulb on | +| Right Button (`BTN-2`) Press (more than 1000 ms) | BLE Advertisement (Enable/Disable) | + +## Building + +### Preparation + +Some initial setup is necessary for preparing the build environment. This +section will need to be done when migrating to new versions of the SDK. This +guide assumes that the environment is linux based, and recommends Ubuntu 20.04. + +- Download and install [SysConfig][sysconfig]. This can be done simply with + the following commands. + + ``` + $ cd ~ + $ wget https://dr-download.ti.com/software-development/ide-configuration-compiler-or-debugger/MD-nsUM6f7Vvb/1.18.1.3343/sysconfig-1.18.1_3343-setup.run + $ chmod +x sysconfig-1.18.1_3343-setup.run + $ ./sysconfig-1.18.1_3343-setup.run + ``` + +- Run the bootstrap script to setup the build environment. +- Note, a recursive submodule checkout is required to utilize TI's Openthread + reference commit. +- Note, in order to build the chip-tool and ota-provider examples, a recursive + submodule checkout is required for the linux platform as seen in the command + below. + + ``` + $ cd ~/connectedhomeip + $ source ./scripts/bootstrap.sh + $ ./scripts/checkout_submodules.py --shallow --platform cc13xx_26xx linux --recursive + + ``` + +### Compilation + +It is necessary to activate the environment in every new shell. Then run GN and +Ninja to build the executable. + +- Activate the build environment with the repository activate script. + + ``` + $ cd ~/connectedhomeip + $ source ./scripts/activate.sh + + ``` + +- Run the build to produce a default executable. By default on Linux both the + TI SimpleLink SDK and Sysconfig are located in a `ti` folder in the user's + home directory, and you must provide the absolute path to them. For example + `/home/username/ti/sysconfig_1.18.1`. On Windows the default directory is + `C:\ti`. Take note of this install path, as it will be used in the next + step. + + ``` + $ cd ~/connectedhomeip/examples/lock-app/cc13x4_26x4 + $ gn gen out/debug --args="ti_sysconfig_root=\"$HOME/ti/sysconfig_1.18.1\"" + $ ninja -C out/debug + + ``` + + If you would like to define arguments on the command line you may add them + to the GN call. + + ``` + gn gen out/debug --args="ti_sysconfig_root=\"$HOME/ti/sysconfig_1.18.1\" target_defines=[\"CC13X4_26X4_ATTESTATION_CREDENTIALS=1\"] chip_generate_link_map_file=true" + + ``` + +## Programming + +Loading the built image onto a LaunchPad is supported through two methods; +Uniflash and Code Composer Studio (CCS). UniFlash can be used to load the image. +Code Composer Studio can be used to load the image and debug the source code. + +### Code Composer Studio + +Programming with CCS will allow for a full debug environment within the IDE. +This is accomplished by creating a target connection to the XDS110 debugger and +starting a project-less debug session. The CCS IDE will attempt to find the +source files on the local machine based on the debug information embedded within +the ELF. CCS may prompt you to find the source code if the image was built on +another machine or the source code is located in a different location than is +recorded within the ELF. + +Download and install [Code Composer Studio][ccs]. + +First open CCS and create a new workspace. + +Create a target connection (sometimes called the CCXML) for your target SoC and +debugger as described in the [Manual Method][ccs_manual_method] section of the +CCS User's Guide. + +Next initiate a project-less debug session as described in the [Manual +Launch][ccs_manual_launch] section of the CCS User's Guide. + +CCS should switch to the debug view described in the [After +Launch][ccs_after_launch] section of the User's Guide. The SoC core will likely +be disconnected and symbols will not be loaded. Connect to the core as described +in the [Debug View][ccs_debug_view] section of the User's Guide. Once the core +is connected, use the `Load` button on the toolbar to load the ELF image. + +Note that the default configuration of the CCXML uses 2-wire cJTAG instead of +the full 4-wire JTAG connection to match the default jumper configuration of the +LaunchPad. + +### UniFlash + +Uniflash is Texas Instrument's uniform programming tool for embedded processors. +This will allow you to erase, flash, and inspect the SoC without setting up a +debugging environment. + +Download and install [UniFlash][uniflash]. + +First open UniFlash. Debug probes connected to the computer will usually be +displayed under the Detected Devices due to the automatic device detection +feature. If your device does not show up in this view it my be disconnected, or +you may have to create a New Configuration. If you already have a CCXML for your +SoC and debug connection you can use that in the section at the bottom. Once +your device is selected, click the `Start` button within the section to launch +the session. + +Select the ELF image to load on the device with the `Browse` button. This file +is placed in the `out/debug` folder by this guide and ends with the `*.out` file +extension. For OTA enabled applications, the standalone image will instead end +with the `*-mcuboot.hex` file extension. This this is a combined image with +application and `MCUBoot` included. The flag to enable or disable the OTA +feature is determined by "chip_enable_ota_requestor" in the application's +args.gni file. + +Finally click the `Load Image` button to load the executable image onto the +device. You should be able to see the log output over the XDS110 User UART. + +Note that programming the device through JTAG sets the Halt-in-Boot flag and may +cause issues when performing a software reset. This flag can be reset by +power-cycling the LaunchPad. + +## Viewing Logging Output + +By default the log output will be sent to the Application/User UART. Open a +terminal emulator to that port to see the output with the following options: + +| Parameter | Value | +| ------------ | -------- | +| Speed (baud) | `115200` | +| Data bits | `8` | +| Stop bits | `1` | +| Parity | `None` | +| Flow control | `None` | + +## Running the Example + +Once a device has been flashed with this example, it can now join and operate in +an existing Matter network. The following sections assume that a Matter network +is already active, and has at least one [OpenThread Border +Router][ot_border_router_setup]. + +For insight into what other components are needed to run this example, please +refer to our [Matter Getting Started Guide][matter-e2e-faq]. + +The steps below should be followed to commission the light-switch device onto +the network and control it once it has been commissioned. + +**Step 0** + +Set up the CHIP tool by following the instructions outlined in our [Matter +Getting Started Guide][matter-e2e-faq]. + +**Step 1** + +First, you will need to have a lighting app device setup and commissioned into +the Matter network. Look through the README.md file for lighting app for +building and commissioning instructions for the default lighting app. + +Commission the light-switch device onto the Matter network. Run the following +command on the CHIP tool: + +``` + +./chip-tool pairing ble-thread hex: 20202021 3840 + +``` + +Interacting with the application begins by enabling BLE advertisements and then +pairing the device into a Thread network. To provision this example onto a +Matter network, the device must be discoverable over Bluetooth LE. + +On the LaunchPad, press and hold the right button, labeled `BTN-2`, for more +than 1 second. Upon release, the Bluetooth LE advertising will begin. Once the +device is fully provisioned, BLE advertising will stop. + +Once the device has been successfully commissioned, you will see the following +message on the CHIP tool output: + +``` + +[1677648218.370754][39785:39790] CHIP:CTL: Received CommissioningComplete response, errorCode=0 +[1677648218.370821][39785:39790] CHIP:CTL: Successfully finished commissioning step 'SendComplete' + +``` + +An accompanying message will be seen from the device: + +``` + +Commissioning complete, notify platform driver to persist network credentials. + +``` + +You can check if the light-switch is able to receive commands from CHIP-TOOL by +using this command: + +``` +./chip-tool basicinformation read vendor-id 0 +``` + +**Step 2** + +Send commands to the light-switch app. + +Here is how you can bind the light-switch app to a lighting app device: + +Tell the lighting device to give the light-switch device access to it's onoff +cluster (replace <> with lighting/light-switch node IDs): + +``` +./chip-tool accesscontrol write acl '[{"fabricIndex": 1, "privilege": 5, "authMode": 2, "subjects": [112233], "targets": null}, {"fabricIndex": 1, "privilege": 3, "authMode": 2, "subjects": [], "targets": [{"cluster": 6, "endpoint": 1, "deviceType": null}]}]' 0 + +``` + +Tell the light-switch device to bind to the onoff cluster on the lighting device +(replace <> with lighting/light-switch node IDs): + +``` +./chip-tool binding write binding '[{"fabricIndex": 1, "node": , "endpoint": 1, "cluster": 6}]' 1 + +``` + +Now you can press the Right BTN on the light-switch device and it will turn ON +the RED LED on the lighting device. Press the Left BTN on the light-switch +device to turn OFF the RED LED on the lighting device. If the devices aren't +bound properly the light-switch will display on UART that the Switch On/Off +operation has been completed but the lighting device's LEDs will not turn on/off +accordingly. + +## TI Support + +For technical support, please consider creating a post on TI's [E2E forum][e2e]. +Additionally, we welcome any feedback. + +[matter]: https://csa-iot.org/all-solutions/matter/ +[ccs]: https://www.ti.com/tool/CCSTUDIO +[ccs_after_launch]: + https://software-dl.ti.com/ccs/esd/documents/users_guide/ccs_debug-main.html?configuration#after-launch +[ccs_debug_view]: + https://software-dl.ti.com/ccs/esd/documents/users_guide/ccs_debug-main.html?configuration#debug-view +[ccs_manual_launch]: + https://software-dl.ti.com/ccs/esd/documents/users_guide/ccs_debug-main.html?configuration#manual-launch +[ccs_manual_method]: + https://software-dl.ti.com/ccs/esd/documents/users_guide/ccs_debug-main.html?configuration#manual-method +[e2e]: + https://e2e.ti.com/support/wireless-connectivity/zigbee-thread-group/zigbee-and-thread/f/zigbee-thread-forum +[matter-e2e-faq]: + https://e2e.ti.com/support/wireless-connectivity/zigbee-thread-group/zigbee-and-thread/f/zigbee-thread-forum/1082428/faq-cc2652r7-matter----getting-started-guide +[sysconfig]: https://www.ti.com/tool/SYSCONFIG +[ti_thread_dnd]: + https://www.ti.com/wireless-connectivity/thread/design-development.html +[ot_border_router_setup]: https://openthread.io/guides/border-router/build +[uniflash]: https://www.ti.com/tool/download/UNIFLASH diff --git a/examples/light-switch-app/cc13x4_26x4/args.gni b/examples/light-switch-app/cc13x4_26x4/args.gni new file mode 100644 index 0000000000..1223bfef03 --- /dev/null +++ b/examples/light-switch-app/cc13x4_26x4/args.gni @@ -0,0 +1,74 @@ +# 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. + +import("//build_overrides/chip.gni") +import("//build_overrides/freertos.gni") +import("${chip_root}/config/standalone/args.gni") +import("${chip_root}/examples/platform/cc13x4_26x4/args.gni") + +ti_simplelink_sdk_target = get_label_info(":sdk", "label_no_toolchain") +ti_simplelink_sysconfig_target = + get_label_info(":sysconfig", "label_no_toolchain") + +ti_simplelink_board = "LP_EM_CC1354P10_6" + +# Size Optimizations +# use -Os instead of -Og, LWIP release build +optimize_debug_level = "s" +lwip_debug = false + +chip_enable_ota_requestor = true + +chip_openthread_ftd = true + +ot_ti_lib_dir = "" +openthread_external_platform = + "${chip_root}/third_party/openthread/platforms/ti:libopenthread-ti" + +# When using TI Certified Openthread libs set to ${chip_root}/third_party/openthread/platforms/ti:ot-ti-cert +# For source builds, set to empty string. +chip_openthread_target = + "${chip_root}/third_party/openthread/platforms/ti:ot-ti-cert" + +# Enable CHIP Logging +chip_progress_logging = true +chip_detail_logging = true +chip_automation_logging = true + +# BLE options +chip_config_network_layer_ble = true + +# Disable lock tracking, since our FreeRTOS configuration does not set +# INCLUDE_xSemaphoreGetMutexHolder +chip_stack_lock_tracking = "none" + +matter_device_vid = "0xFFF1" +matter_device_pid = "0x8004" +matter_software_ver = "0x0001" +matter_software_ver_str = "1.0.1+1" + +custom_factory_data = false + +# ICD Default configurations +# when enabled the device will be configured as a sleepy end device +chip_enable_icd_server = false +chip_persist_subscriptions = false +chip_subscription_timeout_resumption = false + +freertos_root = "//third_party/connectedhomeip/third_party/ti_simplelink_sdk/repo_cc13xx_cc26xx/source/third_party/freertos" + +if (chip_openthread_target != "") { + openthread_root = + "//third_party/connectedhomeip/third_party/openthread/ot-ti/openthread" +} diff --git a/examples/light-switch-app/cc13x4_26x4/build_overrides b/examples/light-switch-app/cc13x4_26x4/build_overrides new file mode 120000 index 0000000000..e578e73312 --- /dev/null +++ b/examples/light-switch-app/cc13x4_26x4/build_overrides @@ -0,0 +1 @@ +../../build_overrides \ No newline at end of file diff --git a/examples/light-switch-app/cc13x4_26x4/chip.syscfg b/examples/light-switch-app/cc13x4_26x4/chip.syscfg new file mode 100644 index 0000000000..e4ae2b6acf --- /dev/null +++ b/examples/light-switch-app/cc13x4_26x4/chip.syscfg @@ -0,0 +1,241 @@ +/* + * + * Copyright (c) 2020 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. + */ + + +/* Modules */ +var AESCCM = scripting.addModule("/ti/drivers/AESCCM"); +var AESECB = scripting.addModule("/ti/drivers/AESECB"); +var Button = scripting.addModule("/ti/drivers/apps/Button"); +var LED = scripting.addModule("/ti/drivers/apps/LED"); +var NVS = scripting.addModule("/ti/drivers/NVS"); +var RF = scripting.addModule("/ti/drivers/RF"); +var RFDesign = scripting.addModule("ti/devices/radioconfig/rfdesign"); +var RFCustom = scripting.addModule("/ti/devices/radioconfig/custom"); +var TRNG = scripting.addModule("/ti/drivers/TRNG"); +var SHA2 = scripting.addModule("/ti/drivers/SHA2"); +var UART2 = scripting.addModule("/ti/drivers/UART2"); +var ble = scripting.addModule("/ti/ble5stack/ble"); +var dmm = scripting.addModule("/ti/dmm/dmm"); +var AESCTRDRBG = scripting.addModule("/ti/drivers/AESCTRDRBG"); +var ECDH = scripting.addModule("/ti/drivers/ECDH"); + +/* Instances */ +var AESCCM1 = AESCCM.addInstance(); +var AESECB1 = AESECB.addInstance(); +var AESECB2 = AESECB.addInstance(); +var Button1 = Button.addInstance(); +var Button2 = Button.addInstance(); +var NVS1 = NVS.addInstance(); +var NVS2 = NVS.addInstance(); +var SHA21 = SHA2.addInstance(); +var LED1 = LED.addInstance(); +var LED2 = LED.addInstance(); +var TRNG1 = TRNG.addInstance(); +var TRNG2 = TRNG.addInstance(); +var TRNG3 = TRNG.addInstance(); +var UART2 = UART2.addInstance(); +var AESCTRDRBG1 = AESCTRDRBG.addInstance(); +var ECDH1 = ECDH.addInstance(); + +AESCTRDRBG1.$name = "CONFIG_AESCTRDRBG_0"; + +AESCCM1.$name = "CONFIG_AESCCM0"; + +AESECB1.$name = "CONFIG_AESECB0"; +AESECB2.$name = "CONFIG_AESECB_1"; + +ECDH1.$name = "CONFIG_ECDH0"; + +/* Left Button */ +Button1.$name = "CONFIG_BTN_LEFT"; +Button1.$hardware = system.deviceData.board.components["BTN-1"]; +Button1.gpioPin.$name = "CONFIG_GPIO_BTN1"; +Button1.gpioPin.pull = "Pull Up"; +Button1.gpioPin.interruptTrigger = "Falling Edge"; + +/* Left Button */ +Button2.$name = "CONFIG_BTN_RIGHT"; +Button2.$hardware = system.deviceData.board.components["BTN-2"]; +Button2.gpioPin.$name = "CONFIG_GPIO_BTN2"; +Button2.gpioPin.pull = "Pull Up"; +Button2.gpioPin.interruptTrigger = "Falling Edge"; + +/* ======== CCFG ======== */ +var CCFG = scripting.addModule("/ti/devices/CCFG"); +const ccfgSettings = system.getScript("/ti/common/lprf_ccfg_settings.js").ccfgSettings; +for(var setting in ccfgSettings) +{ + CCFG[setting] = ccfgSettings[setting]; +} + +/* disable CCFG for OTA-able application */ +CCFG.enableCodeGeneration = false; + + +/* NVS */ +NVS1.$name = "CONFIG_NVSINTERNAL"; +NVS1.internalFlash.regionBase = 0xFB800; +NVS1.internalFlash.regionSize = 0x2800; + + +NVS2.$name = "CONFIG_NVSEXTERNAL"; +NVS2.nvsType = "External"; // NVS Region Type +NVS2.$hardware = system.deviceData.board.components.MX25R8035F; + +/* RF */ +/* if an antenna component exists, assign it to the rf instance */ +if (system.deviceData.board && system.deviceData.board.components.RF) { + RF.$hardware = system.deviceData.board.components.RF; +} + +const rfDesignSettings = system.getScript("/ti/common/lprf_rf_design_settings.js").rfDesignSettings; +for(var setting in rfDesignSettings) +{ + RFDesign[setting] = rfDesignSettings[setting]; +} + + + +/* Handling for RF frontend characterization */ +if(RFDesign.rfDesign.match(/LP_CC2652PSIP/)) +{ + RFCustom.ieee = ["ieee154p10"]; + var rfCodeExportConfig = RFCustom.radioConfigieee154p10.codeExportConfig +} +else +{ + RFCustom.ieee = ["ieee154"]; + var rfCodeExportConfig = RFCustom.radioConfigieee154.codeExportConfig +} + +var cmdList = [ + "cmdIeeeTx", + "cmdIeeeRx", + "cmdIeeeCsma", + "cmdIeeeEdScan", + "cmdIeeeRxAck", + "cmdTxTest" +]; + +rfCodeExportConfig.useConst = true; +rfCodeExportConfig.useMulti = true; +rfCodeExportConfig.symGenMethod = "Custom"; + +const deviceId = system.deviceData.deviceId; + +// Add high PA options if present +if(deviceId.match(/CC(265[12]R|2674R|1352R1|1354R)/)) +{ + cmdList.push("cmdRadioSetup"); + rfCodeExportConfig.cmdRadioSetup = "RF_cmdIeeeRadioSetup"; +} +else if(deviceId.match(/CC(265[12]P|2674P|1352P)/)) +{ + cmdList.push("cmdRadioSetupPa"); + rfCodeExportConfig.cmdRadioSetupPa = "RF_cmdIeeeRadioSetup"; + rfCodeExportConfig.paExport = "combined"; +} +else if(deviceId.match(/CC(265[34]|1354)P/)) +{ + cmdList.push("cmdRadioSetupPa"); + rfCodeExportConfig.cmdRadioSetupPa = "RF_cmdIeeeRadioSetup"; + // currently not characterized for high PA +} +else +{ + throw new Error("Could not match platform to any known platform types"); +} + +rfCodeExportConfig.cmdList_ieee_15_4 = cmdList; + +/* Red LED */ +LED1.$name = "CONFIG_LED_RED"; +LED1.$hardware = system.deviceData.board.components.LED_RED; +LED1.gpioPin.$name = "CONFIG_GPIO_RLED"; +LED1.gpioPin.mode = "Output"; + +/* Green LED */ +LED2.$name = "CONFIG_LED_GREEN"; +LED2.$hardware = system.deviceData.board.components.LED_GREEN; +LED2.gpioPin.$name = "CONFIG_GPIO_GLED"; +LED2.gpioPin.mode = "Output"; + +/* Debug UART */ +UART2.$hardware = system.deviceData.board.components.XDS110UART; +UART2.$name = "CONFIG_UART2_DEBUG"; + +/* TRNG */ +TRNG1.$name = "CONFIG_TRNG_0"; +TRNG2.$name = "CONFIG_TRNG_THREAD"; +TRNG3.$name = "CONFIG_TRNG_APP"; + +/* BLE */ +ble.addressMode = "ADDRMODE_RP_WITH_PUBLIC_ID"; +ble.maxConnNum = 1; +ble.numOfAdvSets = 1; +ble.lockProject = true; +ble.oneLibSizeOpt = true; +ble.maxPDUSize = 255; +ble.radioConfig.codeExportConfig.$name = "ti_devices_radioconfig_code_export_param1"; +ble.connUpdateParamsPeripheral.$name = "ti_ble5stack_general_ble_conn_update_params0"; +ble.connUpdateParamsPeripheral.reqMinConnInt = 30; +ble.connUpdateParamsPeripheral.reqMaxConnInt = 50; + +ble.advSet1.$name = "ti_ble5stack_broadcaster_advertisement_set0"; +ble.advSet1.advParam1.$name = "ti_ble5stack_broadcaster_advertisement_params0"; + +ble.rfDesign = "LP_EM_CC1354P10_6"; + +ble.thorPg = 2; +/* DMM */ +dmm.project = "ti_thread_thermostat_remote_display"; +dmm.stackRoles = ["blePeripheral","threadFTD"]; +dmm.lockStackRoles = true; +dmm.numApplicationStates = 10; +dmm.applicationState0 = "ANY"; +dmm.applicationState1 = "DMMPOLICY_BLE_IDLE"; +dmm.applicationState2 = "DMMPOLICY_BLE_ADV"; +dmm.applicationState3 = "DMMPOLICY_BLE_CONNECTING"; +dmm.applicationState4 = "DMMPOLICY_BLE_HIGH_BANDWIDTH"; +dmm.applicationState5 = "DMMPOLICY_BLE_CONNECTED"; +dmm.applicationState6 = "DMMPOLICY_BLE_OAD"; +dmm.applicationState7 = "DMMPOLICY_THREAD_IDLE"; +dmm.applicationState8 = "DMMPOLICY_THREAD_LINK_EST"; +dmm.applicationState9 = "DMMPOLICY_THREAD_DATA"; +dmm.policyArray.create(4); +dmm.policyArray[0].$name = "ti_dmm_policy_dmm_policy0"; +dmm.policyArray[0].blePeripheral.$name = "ti_dmm_policy_stack_dmm_stack_ble0"; +dmm.policyArray[0].blePeripheral.applicationStates = ["applicationState6"]; +dmm.policyArray[0].threadFTD.$name = "ti_dmm_policy_stack_dmm_stack_thread0"; +dmm.policyArray[0].threadFTD.pause = "DMMPOLICY_PAUSED"; +dmm.policyArray[1].$name = "ti_dmm_policy_dmm_policy1"; +dmm.policyArray[1].blePeripheral.$name = "ti_dmm_policy_stack_dmm_stack_ble1"; +dmm.policyArray[1].blePeripheral.applicationStates = ["applicationState3","applicationState4"]; +dmm.policyArray[1].blePeripheral.weight = 25; +dmm.policyArray[1].blePeripheral.appliedActivity = ["DMMPOLICY_APPLIED_ACTIVITY_BLE_CONNECTION"]; +dmm.policyArray[1].threadFTD.$name = "ti_dmm_policy_stack_dmm_stack_thread1"; +dmm.policyArray[2].$name = "ti_dmm_policy_dmm_policy2"; +dmm.policyArray[2].blePeripheral.$name = "ti_dmm_policy_stack_dmm_stack_ble2"; +dmm.policyArray[2].threadFTD.$name = "ti_dmm_policy_stack_dmm_stack_thread2"; +dmm.policyArray[2].threadFTD.weight = 30; +dmm.policyArray[2].threadFTD.applicationStates = ["applicationState8"]; +dmm.policyArray[2].threadFTD.appliedActivity = ["DMMPOLICY_APPLIED_ACTIVITY_ALL"]; +dmm.policyArray[3].$name = "ti_dmm_policy_dmm_policy3"; +dmm.policyArray[3].blePeripheral.$name = "ti_dmm_policy_stack_dmm_stack_ble3"; +dmm.policyArray[3].threadFTD.$name = "ti_dmm_policy_stack_dmm_stack_thread3"; +dmm.policyArray[3].threadFTD.weight = 1; diff --git a/examples/light-switch-app/cc13x4_26x4/include/CHIPProjectConfig.h b/examples/light-switch-app/cc13x4_26x4/include/CHIPProjectConfig.h new file mode 100644 index 0000000000..88e08c6332 --- /dev/null +++ b/examples/light-switch-app/cc13x4_26x4/include/CHIPProjectConfig.h @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2019 Google LLC. + * 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 + * Example project configuration file for CHIP. + * + * This is a place to put application or project-specific overrides + * to the default configuration values for general CHIP features. + * + */ + +#ifndef CHIP_PROJECT_CONFIG_H +#define CHIP_PROJECT_CONFIG_H + +#if BUILD_RELEASE // release build +// Note: Default Pairing/PIN/Serial Numbers being used. These should not be enabled for production builds +#endif // BUILD_RELEASE + +// Use a default pairing code if one hasn't been provisioned in flash. +#define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE 20202021 +#define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR 0xF00 + +/** + * CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER + * + * Enables the use of a hard-coded default serial number if none + * is found in CHIP NV storage. + */ +#define CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER "TEST_SN" + +/** + * CHIP_DEVICE_CONFIG_DEVICE_HARDWARE_VERSION + * + * The hardware version number assigned to device or product by the device vendor. This + * number is scoped to the device product id, and typically corresponds to a revision of the + * physical device, a change to its packaging, and/or a change to its marketing presentation. + * This value is generally *not* incremented for device software versions. + */ +#ifndef CHIP_DEVICE_CONFIG_DEVICE_HARDWARE_VERSION +#define CHIP_DEVICE_CONFIG_DEVICE_HARDWARE_VERSION 1 +#endif + +/** + * Values set by args.gni: + * CHIP_DEVICE_CONFIG_DEVICE_VENDOR_ID + * CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_ID + * CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING + * CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION + */ + +/** + * CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE + * + * Enable support for CHIP-over-BLE (CHIPOBLE). + */ +#define CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE 1 + +/** + * CHIP_DEVICE_CONFIG_EVENT_LOGGING_DEBUG_BUFFER_SIZE + * + * A size, in bytes, of the individual debug event logging buffer. + */ +#define CHIP_DEVICE_CONFIG_EVENT_LOGGING_DEBUG_BUFFER_SIZE (512) + +#define MATTER_CC13XX_26XX_PLATFORM_LOG_ENABLED 1 + +/** + * CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT + * + * Enable the OpenThread SRP client to allow for CHIP device discovery. + */ +#define CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT 1 + +/** + * CHIP_CONFIG_EVENT_LOGGING_DEFAULT_IMPORTANCE + * + * For a development build, set the default importance of events to be logged as Debug. + * Since debug is the lowest importance level, this means all standard, critical, info and + * debug importance level vi events get logged. + */ +#if BUILD_RELEASE +#define CHIP_CONFIG_EVENT_LOGGING_DEFAULT_IMPORTANCE chip::Profiles::DataManagement::Production +#else +#define CHIP_CONFIG_EVENT_LOGGING_DEFAULT_IMPORTANCE chip::Profiles::DataManagement::Debug +#endif // BUILD_RELEASE + +#define CHIP_DEVICE_CONFIG_ENABLE_EXTENDED_DISCOVERY 1 + +/** + * @def CHIP_IM_MAX_NUM_COMMAND_HANDLER + * + * @brief Defines the maximum number of CommandHandler, limits the number of active commands transactions on server. + */ +#define CHIP_IM_MAX_NUM_COMMAND_HANDLER 2 + +/** + * @def CHIP_IM_MAX_NUM_WRITE_HANDLER + * + * @brief Defines the maximum number of WriteHandler, limits the number of active write transactions on server. + */ +#define CHIP_IM_MAX_NUM_WRITE_HANDLER 2 + +#endif // CHIP_PROJECT_CONFIG_H diff --git a/examples/light-switch-app/cc13x4_26x4/src/AppConfig.h b/examples/light-switch-app/cc13x4_26x4/src/AppConfig.h new file mode 100644 index 0000000000..a818b21d64 --- /dev/null +++ b/examples/light-switch-app/cc13x4_26x4/src/AppConfig.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2020 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. + */ + +#ifndef APP_CONFIG_H +#define APP_CONFIG_H + +// Logging +#ifdef __cplusplus +extern "C" { +#endif + +int cc13xx_26xxLogInit(void); +void cc13xx_26xxLog(const char * aFormat, ...); +#define PLAT_LOG(...) cc13xx_26xxLog(__VA_ARGS__); + +#define ACTUATOR_MOVEMENT_PERIOD_MS 1000 + +#ifdef __cplusplus +} +#endif +#endif // APP_CONFIG_H diff --git a/examples/light-switch-app/cc13x4_26x4/src/AppEvent.h b/examples/light-switch-app/cc13x4_26x4/src/AppEvent.h new file mode 100644 index 0000000000..07f414bd41 --- /dev/null +++ b/examples/light-switch-app/cc13x4_26x4/src/AppEvent.h @@ -0,0 +1,86 @@ +/* + * + * 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. + */ + +#ifndef APP_EVENT_H +#define APP_EVENT_H + +struct AppEvent; +typedef void (*EventHandler)(AppEvent *); + +struct AppEvent +{ + enum AppEventType + { + kEventType_None = 0, + kEventType_ButtonLeft, + kEventType_ButtonRight, + kEventType_AppEvent, + kEventType_IdentifyStart, + kEventType_IdentifyStop, + kEventType_Light, + kEventType_Timer, + kEventType_Identify, + }; + + enum AppEventButtonType + { + kAppEventButtonType_None = 0, + kAppEventButtonType_Clicked, + kAppEventButtonType_LongClicked, + }; + + enum AppEventIdentifyType + { + kAppEventIdentifyType_Blink = 0, + kAppEventIdentifyType_Breathe, + kAppEventIdentifyType_Okay, + kAppEventIdentifyType_Finish, + kAppEventIdentifyType_Stop, + }; + + enum AppEventType Type; + + union + { + struct + { + enum AppEventButtonType Type; + } ButtonEvent; + + struct + { + void * Context; + } TimerEvent; + + struct + { + uint8_t Action; + int32_t Actor; + void * Context; + } LightSwitchEvent; + + struct + { + enum AppEventIdentifyType Type; + } IdentifyEvent; + }; + + EventHandler Handler; +}; + +#endif // APP_EVENT_H diff --git a/examples/light-switch-app/cc13x4_26x4/src/AppTask.cpp b/examples/light-switch-app/cc13x4_26x4/src/AppTask.cpp new file mode 100644 index 0000000000..eec72be980 --- /dev/null +++ b/examples/light-switch-app/cc13x4_26x4/src/AppTask.cpp @@ -0,0 +1,722 @@ +/* + * + * Copyright (c) 2020 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 "AppTask.h" +#include "AppConfig.h" +#include "AppEvent.h" +#include +#include + +#include "FreeRTOS.h" + +#include +#include +#include + +#include +#include + +#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR +#include +#include +#include +#include +#include +#endif + +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include + +/* syscfg */ +#include + +#define APP_TASK_STACK_SIZE (4096) +#define APP_TASK_PRIORITY 4 +#define APP_EVENT_QUEUE_SIZE 10 + +#define IDENTIFY_TRIGGER_EFFECT_BLINK 0 +#define IDENTIFY_TRIGGER_EFFECT_BREATHE 1 +#define IDENTIFY_TRIGGER_EFFECT_OKAY 2 +#define IDENTIFY_TRIGGER_EFFECT_FINISH_STOP 3 + +static uint32_t identify_trigger_effect = IDENTIFY_TRIGGER_EFFECT_FINISH_STOP; + +#define SWITCH_APPLICATION_IDENTIFY_ENDPOINT 1 + +#if (CHIP_CONFIG_ENABLE_ICD_SERVER == 1) +#define LED_ENABLE 0 +#else +#define LED_ENABLE 1 +#endif +#define BUTTON_ENABLE 1 + +#define OTAREQUESTOR_INIT_TIMER_DELAY_MS 10000 + +using namespace ::chip; +using namespace ::chip::app; +using namespace ::chip::Credentials; +using namespace ::chip::DeviceLayer; + +static TaskHandle_t sAppTaskHandle; +static QueueHandle_t sAppEventQueue; + +#if (LED_ENABLE == 1) +static LED_Handle sAppRedHandle; +static LED_Handle sAppGreenHandle; +#endif +static Button_Handle sAppLeftHandle; +static Button_Handle sAppRightHandle; + +static DeviceInfoProviderImpl sExampleDeviceInfoProvider; + +AppTask AppTask::sAppTask; + +void uiSwitchOnStart(void); +void uiSwitchOnDone(void); +void uiSwitchOffStart(void); +void uiSwitchOffDone(void); + +#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR +void StartTimer(uint32_t aTimeoutMs); +void CancelTimer(void); +#endif + +uint8_t sTestEventTriggerEnableKey[TestEventTriggerDelegate::kEnableKeyLength] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, + 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff }; + +#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR +static DefaultOTARequestor sRequestorCore; +static DefaultOTARequestorStorage sRequestorStorage; +static DefaultOTARequestorDriver sRequestorUser; +static BDXDownloader sDownloader; +static OTAImageProcessorImpl sImageProcessor; + +void InitializeOTARequestor(void) +{ + // Initialize and interconnect the Requestor and Image Processor objects + SetRequestorInstance(&sRequestorCore); + + sRequestorStorage.Init(Server::GetInstance().GetPersistentStorage()); + sRequestorCore.Init(Server::GetInstance(), sRequestorStorage, sRequestorUser, sDownloader); + sImageProcessor.SetOTADownloader(&sDownloader); + sDownloader.SetImageProcessorDelegate(&sImageProcessor); + sRequestorUser.Init(&sRequestorCore, &sImageProcessor); +} + +TimerHandle_t sOTAInitTimer = 0; +#endif + +// The OTA Init Timer is only started upon the first Thread State Change +// detected if the device is already on a Thread Network, or during the AppTask +// Init sequence if the device is not yet on a Thread Network. Once the timer +// has been started once, it does not need to be started again so the flag will +// be set to false. +bool isAppStarting = true; + +::Identify stIdentify = { SWITCH_APPLICATION_IDENTIFY_ENDPOINT, AppTask::IdentifyStartHandler, AppTask::IdentifyStopHandler, + Clusters::Identify::IdentifyTypeEnum::kVisibleIndicator, AppTask::TriggerIdentifyEffectHandler }; + +int AppTask::StartAppTask() +{ + int ret = 0; + + sAppEventQueue = xQueueCreate(APP_EVENT_QUEUE_SIZE, sizeof(AppEvent)); + if (sAppEventQueue == NULL) + { + PLAT_LOG("Failed to allocate app event queue"); + while (1) + ; + } + + // Start App task. + if (xTaskCreate(AppTaskMain, "APP", APP_TASK_STACK_SIZE / sizeof(StackType_t), NULL, APP_TASK_PRIORITY, &sAppTaskHandle) != + pdPASS) + { + PLAT_LOG("Failed to create app task"); + while (1) + ; + } + return ret; +} + +// Identify take action +void identify_TakeAction(void) +{ +#if (LED_ENABLE == 1) + LED_setOn(sAppGreenHandle, LED_BRIGHTNESS_MAX); + LED_startBlinking(sAppGreenHandle, 1000, LED_BLINK_FOREVER); +#endif // LED_ENABLE +} + +// Identify stop action +void identify_StopAction(void) +{ +#if (LED_ENABLE == 1) + LED_stopBlinking(sAppGreenHandle); + LED_setOff(sAppGreenHandle); +#endif // LED_ENABLE +} + +void DeviceEventCallback(const ChipDeviceEvent * event, intptr_t arg) +{ + switch (event->Type) + { + case DeviceEventType::kCHIPoBLEConnectionEstablished: + PLAT_LOG("CHIPoBLE connection established"); + break; + + case DeviceEventType::kCHIPoBLEConnectionClosed: + PLAT_LOG("CHIPoBLE disconnected"); + break; + + case DeviceEventType::kCommissioningComplete: + PLAT_LOG("Commissioning complete"); + break; + case DeviceEventType::kThreadStateChange: + PLAT_LOG("Thread State Change"); + bool isThreadAttached = ThreadStackMgrImpl().IsThreadAttached(); + + if (isThreadAttached) + { + PLAT_LOG("Device is on the Thread Network"); +#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR + if (isAppStarting) + { + StartTimer(OTAREQUESTOR_INIT_TIMER_DELAY_MS); + isAppStarting = false; + } +#endif + } + break; + } +} + +#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR +void OTAInitTimerEventHandler(TimerHandle_t xTimer) +{ + InitializeOTARequestor(); +} +#endif + +int AppTask::Init() +{ + cc13xx_26xxLogInit(); + + // Init Chip memory management before the stack + Platform::MemoryInit(); + + PLAT_LOG("Software Version: %d", CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION); + PLAT_LOG("Software Version String: %s", CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING); + + CHIP_ERROR ret = PlatformMgr().InitChipStack(); + if (ret != CHIP_NO_ERROR) + { + PLAT_LOG("PlatformMgr().InitChipStack() failed"); + while (1) + ; + } +#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR + // Create FreeRTOS sw timer for OTA timer. + sOTAInitTimer = xTimerCreate("OTAInitTmr", // Just a text name, not used by the RTOS kernel + OTAREQUESTOR_INIT_TIMER_DELAY_MS, // timer period (mS) + false, // no timer reload (==one-shot) + (void *) this, // init timer id = light obj context + OTAInitTimerEventHandler // timer callback handler + ); + + if (sOTAInitTimer == NULL) + { + PLAT_LOG("sOTAInitTimer timer create failed"); + } + else + { + PLAT_LOG("sOTAInitTimer timer created successfully "); + } +#endif + + ret = ThreadStackMgr().InitThreadStack(); + if (ret != CHIP_NO_ERROR) + { + PLAT_LOG("ThreadStackMgr().InitThreadStack() failed"); + while (1) + ; + } +#if CHIP_DEVICE_CONFIG_THREAD_FTD + ret = ConnectivityMgr().SetThreadDeviceType(ConnectivityManager::kThreadDeviceType_Router); +#elif CHIP_CONFIG_ENABLE_ICD_SERVER + ret = ConnectivityMgr().SetThreadDeviceType(ConnectivityManager::kThreadDeviceType_SleepyEndDevice); +#else + ret = ConnectivityMgr().SetThreadDeviceType(ConnectivityManager::kThreadDeviceType_MinimalEndDevice); +#endif + + if (ret != CHIP_NO_ERROR) + { + PLAT_LOG("ConnectivityMgr().SetThreadDeviceType() failed"); + while (1) + ; + } + + ret = ThreadStackMgrImpl().StartThreadTask(); + if (ret != CHIP_NO_ERROR) + { + PLAT_LOG("ThreadStackMgr().StartThreadTask() failed"); + while (1) + ; + } + + // Initialize device attestation config +#ifdef CC13X4_26X4_ATTESTATION_CREDENTIALS +#ifdef CC13XX_26XX_FACTORY_DATA + SetDeviceInstanceInfoProvider(&mFactoryDataProvider); + SetDeviceAttestationCredentialsProvider(&mFactoryDataProvider); + SetCommissionableDataProvider(&mFactoryDataProvider); +#else + SetDeviceAttestationCredentialsProvider(CC13X4_26X4::GetCC13X4_26X4DacProvider()); +#endif +#else + SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); +#endif + + // Init ZCL Data Model and start server + PLAT_LOG("Initialize Server"); + static CommonCaseDeviceServerInitParams initParams; + static DefaultTestEventTriggerDelegate sTestEventTriggerDelegate{ ByteSpan(sTestEventTriggerEnableKey) }; + initParams.testEventTriggerDelegate = &sTestEventTriggerDelegate; + (void) initParams.InitializeStaticResourcesBeforeServerInit(); + + // Initialize info provider + sExampleDeviceInfoProvider.SetStorageDelegate(initParams.persistentStorageDelegate); + SetDeviceInfoProvider(&sExampleDeviceInfoProvider); + + Server::GetInstance().Init(initParams); + + ret = PlatformMgr().StartEventLoopTask(); + if (ret != CHIP_NO_ERROR) + { + PLAT_LOG("PlatformMgr().StartEventLoopTask() failed"); + while (1) + ; + } + + PlatformMgr().AddEventHandler(DeviceEventCallback, reinterpret_cast(nullptr)); + + uiInit(); + + PlatformMgr().LockChipStack(); + { + ret = LightSwitchMgr().Init(); + } + + PlatformMgr().UnlockChipStack(); + + if (ret != CHIP_NO_ERROR) + { + PLAT_LOG("LightSwitchMgr().Init() failed"); + while (1) + ; + } + + LightSwitchMgr().SetCallbacks(ActionInitiated, ActionCompleted); + + ConfigurationMgr().LogDeviceConfig(); + + bool isThreadEnabled = ThreadStackMgrImpl().IsThreadEnabled(); + if (!isThreadEnabled && isAppStarting) + { +#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR + PLAT_LOG("Thread is Disabled, enable OTA Requestor"); + StartTimer(OTAREQUESTOR_INIT_TIMER_DELAY_MS); + isAppStarting = false; +#endif + } + + // QR code will be used with CHIP Tool + PrintOnboardingCodes(RendezvousInformationFlags(RendezvousInformationFlag::kBLE)); + + return 0; +} + +void AppTask::AppTaskMain(void * pvParameter) +{ + AppEvent event; + + sAppTask.Init(); + + while (1) + { + /* Task pend until we have stuff to do */ + if (xQueueReceive(sAppEventQueue, &event, portMAX_DELAY) == pdTRUE) + { + sAppTask.DispatchEvent(&event); + } + } +} + +#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR +void StartTimer(uint32_t aTimeoutMs) +{ + PLAT_LOG("Start OTA Init Timer") + if (xTimerIsTimerActive(sOTAInitTimer)) + { + PLAT_LOG("app timer already started!"); + CancelTimer(); + } + + // timer is not active, change its period to required value (== restart). + // FreeRTOS- Block for a maximum of 100 ticks if the change period command + // cannot immediately be sent to the timer command queue. + if (xTimerChangePeriod(sOTAInitTimer, pdMS_TO_TICKS(aTimeoutMs), 100) != pdPASS) + { + PLAT_LOG("sOTAInitTimer timer start() failed"); + } +} + +void CancelTimer(void) +{ + if (xTimerStop(sOTAInitTimer, 0) == pdFAIL) + { + PLAT_LOG("sOTAInitTimer stop() failed"); + } +} +#endif +void AppTask::ActionInitiated(LightSwitchManager::Action_t aAction, int32_t aActor) +{ + if (aAction == LightSwitchManager::SWITCH_ON_ACTION) + { + uiSwitchOnStart(); + } + else if (aAction == LightSwitchManager::SWITCH_OFF_ACTION) + { + uiSwitchOffStart(); + } +} + +void AppTask::ActionCompleted(LightSwitchManager::Action_t aAction) +{ + if (aAction == LightSwitchManager::SWITCH_ON_ACTION) + { + uiSwitchOnDone(); + } + else if (aAction == LightSwitchManager::SWITCH_OFF_ACTION) + { + uiSwitchOffDone(); + } +} + +void AppTask::PostEvent(const AppEvent * aEvent) +{ + if (sAppEventQueue != NULL) + { + BaseType_t status; + if (xPortIsInsideInterrupt()) + { + BaseType_t higherPrioTaskWoken = pdFALSE; + status = xQueueSendFromISR(sAppEventQueue, aEvent, &higherPrioTaskWoken); + +#ifdef portYIELD_FROM_ISR + portYIELD_FROM_ISR(higherPrioTaskWoken); +#elif portEND_SWITCHING_ISR // portYIELD_FROM_ISR or portEND_SWITCHING_ISR + portEND_SWITCHING_ISR(higherPrioTaskWoken); +#else // portYIELD_FROM_ISR or portEND_SWITCHING_ISR +#error "Must have portYIELD_FROM_ISR or portEND_SWITCHING_ISR" +#endif // portYIELD_FROM_ISR or portEND_SWITCHING_ISR + } + else + { + status = xQueueSend(sAppEventQueue, aEvent, 1); + } + + if (status != pdTRUE) + { + PLAT_LOG("Failed to post event to app task event queue"); + } + } + else + { + PLAT_LOG("Event Queue is NULL should never happen"); + } +} + +void AppTask::DispatchEvent(AppEvent * aEvent) +{ + int32_t actor; + + switch (aEvent->Type) + { + case AppEvent::kEventType_ButtonLeft: + if (AppEvent::kAppEventButtonType_Clicked == aEvent->ButtonEvent.Type) + { + actor = AppEvent::kEventType_ButtonLeft; + LightSwitchMgr().InitiateAction(actor, LightSwitchManager::SWITCH_OFF_ACTION); + } + else if (AppEvent::kAppEventButtonType_LongClicked == aEvent->ButtonEvent.Type) + { + chip::Server::GetInstance().ScheduleFactoryReset(); + } + break; + + case AppEvent::kEventType_ButtonRight: + if (AppEvent::kAppEventButtonType_Clicked == aEvent->ButtonEvent.Type) + { + actor = AppEvent::kEventType_ButtonRight; + LightSwitchMgr().InitiateAction(actor, LightSwitchManager::SWITCH_ON_ACTION); + } + else if (AppEvent::kAppEventButtonType_LongClicked == aEvent->ButtonEvent.Type) + { + // Enable BLE advertisements + if (!ConnectivityMgr().IsBLEAdvertisingEnabled()) + { + if (Server::GetInstance().GetCommissioningWindowManager().OpenBasicCommissioningWindow() == CHIP_NO_ERROR) + { + PLAT_LOG("Enabled BLE Advertisements"); + } + else + { + PLAT_LOG("OpenBasicCommissioningWindow() failed"); + } + } + else + { + // Disable BLE advertisements + ConnectivityMgr().SetBLEAdvertisingEnabled(false); + PLAT_LOG("Disabled BLE Advertisements"); + } + } + break; + + case AppEvent::kEventType_IdentifyStart: + switch (identify_trigger_effect) + { + case IDENTIFY_TRIGGER_EFFECT_BLINK: + identify_TakeAction(); + break; + case IDENTIFY_TRIGGER_EFFECT_BREATHE: + identify_TakeAction(); + break; + case IDENTIFY_TRIGGER_EFFECT_OKAY: + identify_TakeAction(); + break; + default: + break; + } + PLAT_LOG("Identify started"); + break; + + case AppEvent::kEventType_Identify: + // blink LED + PLAT_LOG("Identify cmd received, will blink green led three times now"); +#if (LED_ENABLE == 1) + LED_startBlinking(sAppGreenHandle, 250, 3); +#endif + break; + + case AppEvent::kEventType_IdentifyStop: +#if (LED_ENABLE == 1) + LED_stopBlinking(sAppGreenHandle); + LED_setOff(sAppGreenHandle); +#endif + PLAT_LOG("Identify stopped"); + break; + + case AppEvent::kEventType_AppEvent: + if (NULL != aEvent->Handler) + { + aEvent->Handler(aEvent); + } + break; + + case AppEvent::kEventType_None: + default: + break; + } +} + +void AppTask::IdentifyStartHandler(::Identify *) +{ + AppEvent event; + event.Type = AppEvent::kEventType_IdentifyStart; + sAppTask.PostEvent(&event); +} + +void AppTask::IdentifyStopHandler(::Identify *) +{ + AppEvent event; + event.Type = AppEvent::kEventType_IdentifyStop; + sAppTask.PostEvent(&event); +} + +void AppTask::TriggerIdentifyEffectHandler(::Identify * identify) +{ + switch (identify->mCurrentEffectIdentifier) + { + case Clusters::Identify::EffectIdentifierEnum::kBlink: + PLAT_LOG("Starting blink identifier effect"); + identify_trigger_effect = IDENTIFY_TRIGGER_EFFECT_BLINK; + IdentifyStartHandler(identify); + break; + case Clusters::Identify::EffectIdentifierEnum::kBreathe: + PLAT_LOG("Starting breathe identifier effect"); + identify_trigger_effect = IDENTIFY_TRIGGER_EFFECT_BREATHE; + IdentifyStartHandler(identify); + break; + case Clusters::Identify::EffectIdentifierEnum::kOkay: + PLAT_LOG("Starting okay identifier effect"); + identify_trigger_effect = IDENTIFY_TRIGGER_EFFECT_OKAY; + IdentifyStartHandler(identify); + break; + case Clusters::Identify::EffectIdentifierEnum::kChannelChange: + PLAT_LOG("Channel Change identifier effect not implemented"); + break; + case Clusters::Identify::EffectIdentifierEnum::kFinishEffect: + PLAT_LOG("Finish identifier effect"); + identify_trigger_effect = IDENTIFY_TRIGGER_EFFECT_FINISH_STOP; + IdentifyStopHandler(identify); + break; + case Clusters::Identify::EffectIdentifierEnum::kStopEffect: + PLAT_LOG("Stop identifier effect"); + identify_trigger_effect = IDENTIFY_TRIGGER_EFFECT_FINISH_STOP; + IdentifyStopHandler(identify); + break; + default: + PLAT_LOG("No identifier effect"); + } +} + +#if (BUTTON_ENABLE == 1) +void AppTask::ButtonLeftEventHandler(Button_Handle handle, Button_EventMask events) +{ + AppEvent event; + event.Type = AppEvent::kEventType_ButtonLeft; + + if (events & Button_EV_CLICKED) + { + event.ButtonEvent.Type = AppEvent::kAppEventButtonType_Clicked; + } + else if (events & Button_EV_LONGCLICKED) + { + event.ButtonEvent.Type = AppEvent::kAppEventButtonType_LongClicked; + } + // button callbacks are in ISR context + if (xQueueSendFromISR(sAppEventQueue, &event, NULL) != pdPASS) + { + /* Failed to post the message */ + } +} + +void AppTask::ButtonRightEventHandler(Button_Handle handle, Button_EventMask events) +{ + AppEvent event; + event.Type = AppEvent::kEventType_ButtonRight; + + if (events & Button_EV_CLICKED) + { + event.ButtonEvent.Type = AppEvent::kAppEventButtonType_Clicked; + } + else if (events & Button_EV_LONGCLICKED) + { + event.ButtonEvent.Type = AppEvent::kAppEventButtonType_LongClicked; + } + // button callbacks are in ISR context + if (xQueueSendFromISR(sAppEventQueue, &event, NULL) != pdPASS) + { + /* Failed to post the message */ + } +} +#endif // BUTTON_ENABLE + +// Action initiated callback +void uiSwitchOnStart(void) +{ + PLAT_LOG("Switch On initiated"); +} + +// Action completed callback +void uiSwitchOnDone(void) +{ + PLAT_LOG("Switch On completed"); +} + +// Action initiated callback +void uiSwitchOffStart(void) +{ + PLAT_LOG("Switch Off initiated"); +} + +// Action completed callback +void uiSwitchOffDone(void) +{ + PLAT_LOG("Switch Off completed"); +} + +void AppTask::uiInit(void) +{ +#if (LED_ENABLE == 1) + + LED_Params ledParams; + + // Initialize LEDs + PLAT_LOG("Initialize LEDs"); + LED_init(); + + LED_Params_init(&ledParams); // default PWM LED + sAppRedHandle = LED_open(CONFIG_LED_RED, &ledParams); + LED_setOff(sAppRedHandle); + + LED_Params_init(&ledParams); // default PWM LED + sAppGreenHandle = LED_open(CONFIG_LED_GREEN, &ledParams); + LED_setOff(sAppGreenHandle); +#endif // LED ENABLE + +#if (BUTTON_ENABLE == 1) + Button_Params buttonParams; + + // Initialize buttons + PLAT_LOG("Initialize buttons"); + Button_init(); + + Button_Params_init(&buttonParams); + buttonParams.buttonEventMask = Button_EV_CLICKED | Button_EV_LONGCLICKED; + buttonParams.longPressDuration = 1000U; // ms + sAppLeftHandle = Button_open(CONFIG_BTN_LEFT, &buttonParams); + Button_setCallback(sAppLeftHandle, ButtonLeftEventHandler); + + Button_Params_init(&buttonParams); + buttonParams.buttonEventMask = Button_EV_CLICKED | Button_EV_LONGCLICKED; + buttonParams.longPressDuration = 1000U; // ms + sAppRightHandle = Button_open(CONFIG_BTN_RIGHT, &buttonParams); + Button_setCallback(sAppRightHandle, ButtonRightEventHandler); +#endif // BUTTON ENABLE +} diff --git a/examples/light-switch-app/cc13x4_26x4/src/AppTask.h b/examples/light-switch-app/cc13x4_26x4/src/AppTask.h new file mode 100644 index 0000000000..85eb6e5203 --- /dev/null +++ b/examples/light-switch-app/cc13x4_26x4/src/AppTask.h @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2019 Google LLC. + * 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 "FreeRTOS.h" +#include "semphr.h" +#include "task.h" + +#include "AppEvent.h" +#include "LightSwitchManager.h" + +#include + +#ifdef CC13XX_26XX_FACTORY_DATA +#include +#endif + +// Application-defined error codes in the CHIP_ERROR space. +#define APP_ERROR_EVENT_QUEUE_FAILED CHIP_APPLICATION_ERROR(0x01) +#define APP_ERROR_CREATE_TASK_FAILED CHIP_APPLICATION_ERROR(0x02) +#define APP_ERROR_UNHANDLED_EVENT CHIP_APPLICATION_ERROR(0x03) +#define APP_ERROR_CREATE_TIMER_FAILED CHIP_APPLICATION_ERROR(0x04) +#define APP_ERROR_START_TIMER_FAILED CHIP_APPLICATION_ERROR(0x05) +#define APP_ERROR_STOP_TIMER_FAILED CHIP_APPLICATION_ERROR(0x06) +#define APP_ERROR_ALLOCATION_FAILED CHIP_APPLICATION_ERROR(0x07) + +struct Identify; + +class AppTask +{ + +public: + int StartAppTask(); + static void AppTaskMain(void * pvParameter); + + static AppTask & GetAppTask() { return sAppTask; } + void PostEvent(const AppEvent * event); + + static void IdentifyStartHandler(::Identify *); + static void IdentifyStopHandler(::Identify *); + static void TriggerIdentifyEffectHandler(::Identify * identify); + +private: + friend AppTask & GetAppTask(void); + + int Init(); + + static void ActionInitiated(LightSwitchManager::Action_t aAction, int32_t aActor); + static void ActionCompleted(LightSwitchManager::Action_t aAction); + + void DispatchEvent(AppEvent * event); + void uiInit(void); + static void ButtonLeftEventHandler(Button_Handle handle, Button_EventMask events); + static void ButtonRightEventHandler(Button_Handle handle, Button_EventMask events); + static void TimerEventHandler(void * p_context); + + enum Function_t + { + kFunction_NoneSelected = 0, + kFunction_SoftwareUpdate = 0, + kFunction_FactoryReset, + + kFunction_Invalid + } Function; + + Function_t mFunction; + bool mFunctionTimerActive; + + static AppTask sAppTask; + + // bool mSyncClusterToButtonAction; +#ifdef CC13XX_26XX_FACTORY_DATA + chip::DeviceLayer::FactoryDataProvider mFactoryDataProvider; +#endif +}; + +inline AppTask & GetAppTask(void) +{ + return AppTask::sAppTask; +} diff --git a/examples/light-switch-app/cc13x4_26x4/src/BindingHandler.cpp b/examples/light-switch-app/cc13x4_26x4/src/BindingHandler.cpp new file mode 100644 index 0000000000..67fd1c9ed1 --- /dev/null +++ b/examples/light-switch-app/cc13x4_26x4/src/BindingHandler.cpp @@ -0,0 +1,163 @@ +/* + * + * 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. + */ + +#include "BindingHandler.h" + +#include "AppConfig.h" +#include "app/CommandSender.h" +#include "app/clusters/bindings/BindingManager.h" +#include "app/server/Server.h" +#include "controller/InvokeInteraction.h" +#include "platform/CHIPDeviceLayer.h" +#include +#include +#include + +using namespace chip; +using namespace chip::app; + +namespace { + +void ProcessOnOffUnicastBindingCommand(CommandId commandId, const EmberBindingTableEntry & binding, + Messaging::ExchangeManager * exchangeMgr, const SessionHandle & sessionHandle) +{ + auto onSuccess = [](const ConcreteCommandPath & commandPath, const StatusIB & status, const auto & dataResponse) { + ChipLogProgress(NotSpecified, "OnOff command succeeds"); + }; + auto onFailure = [](CHIP_ERROR error) { + ChipLogError(NotSpecified, "OnOff command failed: %" CHIP_ERROR_FORMAT, error.Format()); + }; + + switch (commandId) + { + case Clusters::OnOff::Commands::Toggle::Id: + Clusters::OnOff::Commands::Toggle::Type toggleCommand; + Controller::InvokeCommandRequest(exchangeMgr, sessionHandle, binding.remote, toggleCommand, onSuccess, onFailure); + break; + + case Clusters::OnOff::Commands::On::Id: + Clusters::OnOff::Commands::On::Type onCommand; + Controller::InvokeCommandRequest(exchangeMgr, sessionHandle, binding.remote, onCommand, onSuccess, onFailure); + break; + + case Clusters::OnOff::Commands::Off::Id: + Clusters::OnOff::Commands::Off::Type offCommand; + Controller::InvokeCommandRequest(exchangeMgr, sessionHandle, binding.remote, offCommand, onSuccess, onFailure); + break; + } +} + +void ProcessOnOffGroupBindingCommand(CommandId commandId, const EmberBindingTableEntry & binding) +{ + Messaging::ExchangeManager & exchangeMgr = Server::GetInstance().GetExchangeManager(); + switch (commandId) + { + case Clusters::OnOff::Commands::Toggle::Id: + Clusters::OnOff::Commands::Toggle::Type toggleCommand; + Controller::InvokeGroupCommandRequest(&exchangeMgr, binding.fabricIndex, binding.groupId, toggleCommand); + break; + + case Clusters::OnOff::Commands::On::Id: + Clusters::OnOff::Commands::On::Type onCommand; + Controller::InvokeGroupCommandRequest(&exchangeMgr, binding.fabricIndex, binding.groupId, onCommand); + + break; + + case Clusters::OnOff::Commands::Off::Id: + Clusters::OnOff::Commands::Off::Type offCommand; + Controller::InvokeGroupCommandRequest(&exchangeMgr, binding.fabricIndex, binding.groupId, offCommand); + break; + } +} + +void LightSwitchChangedHandler(const EmberBindingTableEntry & binding, OperationalDeviceProxy * peer_device, void * context) +{ + VerifyOrReturn(context != nullptr, ChipLogError(NotSpecified, "OnDeviceConnectedFn: context is null")); + BindingCommandData * data = static_cast(context); + if (binding.type == MATTER_MULTICAST_BINDING && data->isGroup) + { + switch (data->clusterId) + { + case Clusters::OnOff::Id: + + ProcessOnOffGroupBindingCommand(data->commandId, binding); + + break; + } + } + else if (binding.type == MATTER_UNICAST_BINDING && !data->isGroup) + { + switch (data->clusterId) + { + case Clusters::OnOff::Id: + VerifyOrDie(peer_device != nullptr && peer_device->ConnectionReady()); + ProcessOnOffUnicastBindingCommand(data->commandId, binding, peer_device->GetExchangeManager(), + peer_device->GetSecureSession().Value()); + break; + } + } +} + +void LightSwitchContextReleaseHandler(void * context) +{ + VerifyOrReturn(context != nullptr, ChipLogError(NotSpecified, "LightSwitchContextReleaseHandler: context is null")); + Platform::Delete(static_cast(context)); +} + +void InitBindingHandlerInternal(intptr_t arg) +{ + ChipLogProgress(NotSpecified, "Initializing Binding Handler"); + auto & server = chip::Server::GetInstance(); + if (CHIP_NO_ERROR != + BindingManager::GetInstance().Init( + { &server.GetFabricTable(), server.GetCASESessionManager(), &server.GetPersistentStorage() })) + { + ChipLogError(NotSpecified, "InitBindingHandlerInternal failed"); + } + chip::BindingManager::GetInstance().RegisterBoundDeviceChangedHandler(LightSwitchChangedHandler); + chip::BindingManager::GetInstance().RegisterBoundDeviceContextReleaseHandler(LightSwitchContextReleaseHandler); +} + +} // namespace + +/******************************************************** + * Switch functions + *********************************************************/ + +void SwitchWorkerFunction(intptr_t context) +{ + VerifyOrReturn(context != 0, ChipLogError(NotSpecified, "SwitchWorkerFunction - Invalid work data")); + BindingCommandData * data = reinterpret_cast(context); + BindingManager::GetInstance().NotifyBoundClusterChanged(data->localEndpointId, data->clusterId, static_cast(data)); +} + +void BindingWorkerFunction(intptr_t context) +{ + VerifyOrReturn(context != 0, ChipLogError(NotSpecified, "BindingWorkerFunction - Invalid work data")); + EmberBindingTableEntry * entry = reinterpret_cast(context); + AddBindingEntry(*entry); + Platform::Delete(entry); +} + +CHIP_ERROR InitBindingHandler() +{ + // The initialization of binding manager will try establishing connection with unicast peers + // so it requires the Server instance to be correctly initialized. Post the init function to + // the event queue so that everything is ready when initialization is conducted. + chip::DeviceLayer::PlatformMgr().ScheduleWork(InitBindingHandlerInternal); + return CHIP_NO_ERROR; +} diff --git a/examples/light-switch-app/cc13x4_26x4/src/BindingHandler.h b/examples/light-switch-app/cc13x4_26x4/src/BindingHandler.h new file mode 100644 index 0000000000..aed08be25e --- /dev/null +++ b/examples/light-switch-app/cc13x4_26x4/src/BindingHandler.h @@ -0,0 +1,33 @@ +/* + * + * 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. + */ +#pragma once + +#include "app-common/zap-generated/ids/Clusters.h" +#include "app-common/zap-generated/ids/Commands.h" +#include "lib/core/CHIPError.h" + +CHIP_ERROR InitBindingHandler(); +void SwitchWorkerFunction(intptr_t context); +void BindingWorkerFunction(intptr_t context); + +struct BindingCommandData +{ + chip::EndpointId localEndpointId = 1; + chip::CommandId commandId; + chip::ClusterId clusterId; + bool isGroup = false; +}; diff --git a/examples/light-switch-app/cc13x4_26x4/src/LightSwitchManager.cpp b/examples/light-switch-app/cc13x4_26x4/src/LightSwitchManager.cpp new file mode 100644 index 0000000000..020378f3e3 --- /dev/null +++ b/examples/light-switch-app/cc13x4_26x4/src/LightSwitchManager.cpp @@ -0,0 +1,193 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2019 Google LLC. + * 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 "LightSwitchManager.h" +#include "BindingHandler.h" + +#include "AppConfig.h" +#include "AppTask.h" +#include + +#include +#include +#include +#include +#include + +using namespace chip; +using namespace chip::app; +using namespace chip::app::Clusters; +using namespace ::chip::DeviceLayer; + +LightSwitchManager LightSwitchManager::sLightSwitch; + +TimerHandle_t sSwitchTimer; + +CHIP_ERROR LightSwitchManager::Init() +{ + // Create FreeRTOS sw timer for light timer. + sSwitchTimer = xTimerCreate("switchTmr", // Just a text name, not used by the RTOS kernel + 1, // == default timer period (mS) + false, // no timer reload (==one-shot) + (void *) this, // init timer id = light obj context + TimerEventHandler // timer callback handler + ); + + if (sSwitchTimer == NULL) + { + PLAT_LOG("sSwitchTimer timer create failed"); + return APP_ERROR_CREATE_TIMER_FAILED; + } + + // Configure Bindings + CHIP_ERROR error = InitBindingHandler(); + if (error != CHIP_NO_ERROR) + { + PLAT_LOG("InitBindingHandler() failed!"); + return APP_ERROR_CREATE_TIMER_FAILED; + } + + mState = kState_SwitchOffCompleted; + + return CHIP_NO_ERROR; +} + +void LightSwitchManager::SetCallbacks(Callback_fn_initiated aActionInitiated_CB, Callback_fn_completed aActionCompleted_CB) +{ + mActionInitiated_CB = aActionInitiated_CB; + mActionCompleted_CB = aActionCompleted_CB; +} + +bool LightSwitchManager::InitiateAction(int32_t aActor, Action_t aAction) +{ + bool action_initiated = false; + + State_t new_state; + + BindingCommandData * data = Platform::New(); + + data->clusterId = chip::app::Clusters::OnOff::Id; + + // need to create logic to separate this + data->isGroup = false; + + // Initiate Switch On/Off Action only when the previous one is complete. + if ((mState == kState_SwitchOffCompleted || mState == kState_SwitchOnCompleted) && aAction == SWITCH_ON_ACTION) + { + action_initiated = true; + new_state = kState_SwitchOnInitiated; + data->commandId = chip::app::Clusters::OnOff::Commands::On::Id; + } + else if ((mState == kState_SwitchOffCompleted || mState == kState_SwitchOnCompleted) && aAction == SWITCH_OFF_ACTION) + { + action_initiated = true; + new_state = kState_SwitchOffInitiated; + data->commandId = chip::app::Clusters::OnOff::Commands::Off::Id; + } + + if (action_initiated) + { + StartTimer(ACTUATOR_MOVEMENT_PERIOD_MS); + // Since the timer started successfully, update the state and trigger callback + mState = new_state; + + if (mActionInitiated_CB) + { + mActionInitiated_CB(aAction, aActor); + } + } + // Platform::Delete(data); + return action_initiated; +} + +void LightSwitchManager::StartTimer(uint32_t aTimeoutMs) +{ + if (xTimerIsTimerActive(sSwitchTimer)) + { + PLAT_LOG("app timer already started!"); + CancelTimer(); + } + // timer is not active, change its period to required value (== restart). + // FreeRTOS- Block for a maximum of 100 ticks if the change period command + // cannot immediately be sent to the timer command queue. + if (xTimerChangePeriod(sSwitchTimer, pdMS_TO_TICKS(aTimeoutMs), 100) != pdPASS) + { + PLAT_LOG("sSwitchTimer timer start() failed"); + } +} + +void LightSwitchManager::CancelTimer(void) +{ + if (xTimerStop(sSwitchTimer, 0) == pdFAIL) + { + PLAT_LOG("sSwitchTimer stop() failed"); + } +} + +void LightSwitchManager::TimerEventHandler(TimerHandle_t xTimer) +{ + // Get light obj context from timer id. + LightSwitchManager * lightswitch = static_cast(pvTimerGetTimerID(xTimer)); + // The timer event handler will be called in the context of the timer task + // once sLightTimer expires. Post an event to apptask queue with the actual handler + // so that the event can be handled in the context of the apptask. + AppEvent event; + event.Type = AppEvent::kEventType_AppEvent; + event.LightSwitchEvent.Context = lightswitch; + event.Handler = ActuatorMovementTimerEventHandler; + AppTask::GetAppTask().PostEvent(&event); +} + +void LightSwitchManager::ActuatorMovementTimerEventHandler(AppEvent * aEvent) +{ + Action_t actionCompleted = INVALID_ACTION; + BindingCommandData * data = Platform::New(); + data->clusterId = chip::app::Clusters::OnOff::Id; + + LightSwitchManager * lightswitch = static_cast(aEvent->LightSwitchEvent.Context); + if (lightswitch->mState == kState_SwitchOffInitiated) + { + lightswitch->mState = kState_SwitchOffCompleted; + actionCompleted = SWITCH_OFF_ACTION; + data->commandId = chip::app::Clusters::OnOff::Commands::Off::Id; + } + else if (lightswitch->mState == kState_SwitchOnInitiated) + { + lightswitch->mState = kState_SwitchOnCompleted; + actionCompleted = SWITCH_ON_ACTION; + data->commandId = chip::app::Clusters::OnOff::Commands::On::Id; + } + + if (actionCompleted != INVALID_ACTION) + { + DeviceLayer::PlatformMgr().ScheduleWork(SwitchWorkerFunction, reinterpret_cast(data)); + + if (lightswitch->mActionCompleted_CB) + { + lightswitch->mActionCompleted_CB(actionCompleted); + } + } +} + +void LightSwitchManager::IdentifyEventHandler() +{ + AppEvent event; + event.Type = AppEvent::kEventType_Identify; + AppTask::GetAppTask().PostEvent(&event); +} diff --git a/examples/light-switch-app/cc13x4_26x4/src/LightSwitchManager.h b/examples/light-switch-app/cc13x4_26x4/src/LightSwitchManager.h new file mode 100644 index 0000000000..05db8172df --- /dev/null +++ b/examples/light-switch-app/cc13x4_26x4/src/LightSwitchManager.h @@ -0,0 +1,87 @@ +/* + * + * Copyright (c) 2019 Google LLC. + * 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 "AppEvent.h" + +#include "FreeRTOS.h" +#include "timers.h" // provides FreeRTOS timer support +#include + +#include +#include + +using namespace ::chip; + +class LightSwitchManager +{ +public: + enum Action_t + { + SWITCH_ON_ACTION = 0, + SWITCH_OFF_ACTION, + INVALID_ACTION + } Action; + + enum State_t + { + kState_SwitchOffInitiated = 0, + kState_SwitchOffCompleted, + kState_SwitchOnInitiated, + kState_SwitchOnCompleted, + } State; + + CHIP_ERROR Init(); + + bool InitiateAction(int32_t aActor, Action_t aAction); + + typedef void (*Callback_fn_initiated)(Action_t, int32_t aActor); + typedef void (*Callback_fn_completed)(Action_t); + void SetCallbacks(Callback_fn_initiated aActionInitiated_CB, Callback_fn_completed aActionCompleted_CB); + + bool SwitchOn(chip::EndpointId endpointId); + bool SwitchOff(chip::EndpointId endpointId); + + void IdentifyEventHandler(); + +private: + friend LightSwitchManager & LightSwitchMgr(void); + State_t mState; + + Callback_fn_initiated mActionInitiated_CB; + Callback_fn_completed mActionCompleted_CB; + + void CancelTimer(void); + void StartTimer(uint32_t aTimeoutMs); + + static void TimerEventHandler(TimerHandle_t xTimer); + static void ActuatorMovementTimerEventHandler(AppEvent * aEvent); + + static LightSwitchManager sLightSwitch; +}; + +inline LightSwitchManager & LightSwitchMgr(void) +{ + return LightSwitchManager::sLightSwitch; +} diff --git a/examples/light-switch-app/cc13x4_26x4/src/ZclCallbacks.cpp b/examples/light-switch-app/cc13x4_26x4/src/ZclCallbacks.cpp new file mode 100644 index 0000000000..0ef772323f --- /dev/null +++ b/examples/light-switch-app/cc13x4_26x4/src/ZclCallbacks.cpp @@ -0,0 +1,57 @@ +/* + * + * 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 file implements the handler for data model messages. + */ + +#include "AppConfig.h" +#include "LightSwitchManager.h" + +#include +#include +#include +#include + +using namespace ::chip; +using namespace ::chip::app::Clusters; + +void MatterPostAttributeChangeCallback(const chip::app::ConcreteAttributePath & attributePath, uint8_t type, uint16_t size, + uint8_t * value) +{ + ClusterId clusterId = attributePath.mClusterId; + AttributeId attributeId = attributePath.mAttributeId; + (void) attributeId; + ChipLogProgress(Zcl, "Cluster callback: " ChipLogFormatMEI, ChipLogValueMEI(clusterId)); + + if (clusterId == OnOffSwitchConfiguration::Id) + { + ChipLogProgress(Zcl, "OnOffSwitchConfiguration attribute ID: " ChipLogFormatMEI " Type: %u Value: %u, length %u", + ChipLogValueMEI(attributeId), type, *value, size); + } + else if (clusterId == Identify::Id) + { + ChipLogProgress(Zcl, "Identify attribute ID: " ChipLogFormatMEI " Type: %u Value: %u, length %u", + ChipLogValueMEI(attributeId), type, *value, size); + } + else if (clusterId == Groups::Id) + { + ChipLogProgress(Zcl, "Groups attribute ID: " ChipLogFormatMEI " Type: %u Value: %u, length %u", + ChipLogValueMEI(attributeId), type, *value, size); + } +} diff --git a/examples/light-switch-app/cc13x4_26x4/src/main.cpp b/examples/light-switch-app/cc13x4_26x4/src/main.cpp new file mode 100644 index 0000000000..d2635ed96e --- /dev/null +++ b/examples/light-switch-app/cc13x4_26x4/src/main.cpp @@ -0,0 +1,96 @@ +/* + * + * 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. + */ + +#include +#include + +#include + +#include "AppConfig.h" +#include "AppTask.h" + +#include + +/* Driver Header files */ +#include +#include +#include + +#include +#include +#include +#include + +#include +#define TOTAL_ICALL_HEAP_SIZE (0xc600) + +using namespace ::chip; +using namespace ::chip::Inet; +using namespace ::chip::DeviceLayer; + +__attribute__((section(".heap"))) uint8_t GlobalHeapZoneBuffer[TOTAL_ICALL_HEAP_SIZE]; +uint32_t heapSize = TOTAL_ICALL_HEAP_SIZE; + +// ================================================================================ +// FreeRTOS Callbacks +// ================================================================================ +/* Wrapper functions for using the queue registry regardless of whether it is enabled or disabled */ +extern "C" void vQueueAddToRegistryWrapper(QueueHandle_t xQueue, const char * pcQueueName) +{ + /* This function is intentionally left empty as the Queue Registry is disabled */ +} + +extern "C" void vQueueUnregisterQueueWrapper(QueueHandle_t xQueue) +{ + /* This function is intentionally left empty as the Queue Registry is disabled */ +} + +// ================================================================================ +// Main Code +// ================================================================================ +int main(void) +{ + Board_init(); + bpool((void *) GlobalHeapZoneBuffer, TOTAL_ICALL_HEAP_SIZE); + + GPIO_init(); + + NVS_init(); + + ECDH_init(); + + ECDSA_init(); + + AESECB_init(); + + SHA2_init(); + + int ret = GetAppTask().StartAppTask(); + if (ret != 0) + { + // can't log until the kernel is started + // PLAT_LOG("GetAppTask().StartAppTask() failed"); + while (1) + ; + } + + vTaskStartScheduler(); + + // Should never get here. + while (1) + ; +} diff --git a/examples/light-switch-app/cc13x4_26x4/third_party/connectedhomeip b/examples/light-switch-app/cc13x4_26x4/third_party/connectedhomeip new file mode 120000 index 0000000000..c866b86874 --- /dev/null +++ b/examples/light-switch-app/cc13x4_26x4/third_party/connectedhomeip @@ -0,0 +1 @@ +../../../.. \ No newline at end of file From 7705be9b28c079f9d899b925d1bcf59e2d838e12 Mon Sep 17 00:00:00 2001 From: Yufeng Wang Date: Mon, 19 Aug 2024 09:37:08 -0700 Subject: [PATCH 088/165] [Fabric-Admin] Fix the new added device failed to get reported (#35058) * [Fabric-Admin] Fix the new added device failed to get reported * Restyled by prettier-markdown --------- Co-authored-by: Restyled.io --- docs/guides/fabric_synchronization_guide.md | 10 ++++++++-- examples/fabric-admin/device_manager/DeviceManager.cpp | 6 +++--- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/docs/guides/fabric_synchronization_guide.md b/docs/guides/fabric_synchronization_guide.md index 5944105512..50fa3202f8 100644 --- a/docs/guides/fabric_synchronization_guide.md +++ b/docs/guides/fabric_synchronization_guide.md @@ -98,6 +98,12 @@ Run the Fabric Synchronization script: In Ecosystem 1 Fabric-Admin console: +Pair the local bridge of Ecosystem 1 with node ID 1: + +``` +fabricsync add-local-bridge 1 +``` + Pair the Ecosystem 2 bridge to Ecosystem 1 with node ID 2: ``` @@ -130,8 +136,8 @@ Pair the Light Example with node ID 3 using its payload number: pairing already-discovered 3 20202021 5543 ``` -After the device is successfully added, you will observe the following on -Ecosystem 2 with the newly assigned Node ID: +After the device is successfully added, you will observe the following message +on Ecosystem 2 with the newly assigned Node ID: ``` >>> New device with Node ID: 0x3 has been successfully added. diff --git a/examples/fabric-admin/device_manager/DeviceManager.cpp b/examples/fabric-admin/device_manager/DeviceManager.cpp index fe0c8aea4d..56f8591ab5 100644 --- a/examples/fabric-admin/device_manager/DeviceManager.cpp +++ b/examples/fabric-admin/device_manager/DeviceManager.cpp @@ -215,8 +215,8 @@ void DeviceManager::SubscribeRemoteFabricBridge() // Prepare and push the commissioner control subscribe command commandBuilder.Add("commissionercontrol subscribe-event commissioning-request-result "); - commandBuilder.AddFormat("%d %d %lu %d --is-urgent true", kSubscribeMinInterval, kSubscribeMaxInterval, mRemoteBridgeNodeId, - kRootEndpointId); + commandBuilder.AddFormat("%d %d %lu %d --is-urgent true --keepSubscriptions true", kSubscribeMinInterval, kSubscribeMaxInterval, + mRemoteBridgeNodeId, kRootEndpointId); PushCommand(commandBuilder.c_str()); } @@ -413,7 +413,7 @@ void DeviceManager::HandleAttributeData(const app::ConcreteDataAttributePath & p for (const auto & endpoint : addedEndpoints) { // print to console - fprintf(stderr, "A new devie is added on Endpoint: %u\n", endpoint); + fprintf(stderr, "A new device is added on Endpoint: %u\n", endpoint); if (mAutoSyncEnabled) { From baba33d9ac6cce2508c86cb102504e62913a17ef Mon Sep 17 00:00:00 2001 From: Yufeng Wang Date: Mon, 19 Aug 2024 09:57:02 -0700 Subject: [PATCH 089/165] Fix failed to sync device when using dynamic setupPIN (#35061) --- examples/fabric-admin/device_manager/DeviceManager.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/examples/fabric-admin/device_manager/DeviceManager.cpp b/examples/fabric-admin/device_manager/DeviceManager.cpp index 56f8591ab5..849d557f0b 100644 --- a/examples/fabric-admin/device_manager/DeviceManager.cpp +++ b/examples/fabric-admin/device_manager/DeviceManager.cpp @@ -144,7 +144,6 @@ void DeviceManager::OpenRemoteDeviceCommissioningWindow(EndpointId remoteEndpoin commandBuilder.Add("pairing open-commissioning-window "); commandBuilder.AddFormat("%lu %d %d %d %d %d", mRemoteBridgeNodeId, remoteEndpointId, kEnhancedCommissioningMethod, kWindowTimeout, kIteration, discriminator); - commandBuilder.Add(" --setup-pin 20202021"); PushCommand(commandBuilder.c_str()); } From b7b67388b4da84182abef13f9bfe8421551a51e8 Mon Sep 17 00:00:00 2001 From: Kiel Oleson Date: Mon, 19 Aug 2024 10:08:13 -0700 Subject: [PATCH 090/165] improve `MTRDeviceController`/`_Concrete` (#35060) logging --- src/darwin/Framework/CHIP/MTRDeviceController.mm | 14 +++++++------- .../CHIP/MTRDeviceController_Concrete.mm | 16 ++++++++-------- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/src/darwin/Framework/CHIP/MTRDeviceController.mm b/src/darwin/Framework/CHIP/MTRDeviceController.mm index bfbb62fa2f..322593312c 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController.mm +++ b/src/darwin/Framework/CHIP/MTRDeviceController.mm @@ -306,7 +306,7 @@ - (instancetype)initWithFactory:(MTRDeviceControllerFactory *)factory - (NSString *)description { - return [NSString stringWithFormat:@"", self, _uniqueIdentifier]; + return [NSString stringWithFormat:@"<%@: %p uuid %@>", NSStringFromClass(self.class), self, _uniqueIdentifier]; } - (BOOL)isRunning @@ -322,7 +322,7 @@ - (void)shutdown return; } - MTR_LOG("Shutting down MTRDeviceController: %@", self); + MTR_LOG("Shutting down %@: %@", NSStringFromClass(self.class), self); [self cleanupAfterStartup]; } @@ -334,7 +334,7 @@ - (void)cleanupAfterStartup // do the secure session shutdowns. Since we don't want to hold the lock // while calling out into arbitrary invalidation code, snapshot the list of // devices before we start invalidating. - MTR_LOG("cleanupAfterStartup MTRDeviceController: %@", self); + MTR_LOG("%s: %@", __PRETTY_FUNCTION__, self); os_unfair_lock_lock(self.deviceMapLock); NSEnumerator * devices = [_nodeIDToDeviceMap objectEnumerator]; [_nodeIDToDeviceMap removeAllObjects]; @@ -352,7 +352,7 @@ - (void)cleanupAfterStartup // in a very specific way that only MTRDeviceControllerFactory knows about. - (void)shutDownCppController { - MTR_LOG("shutDownCppController MTRDeviceController: %p", self); + MTR_LOG("%s: %p", __PRETTY_FUNCTION__, self); assertChipStackLockedByCurrentThread(); // Shut down all our endpoints. @@ -659,7 +659,7 @@ - (BOOL)startup:(MTRDeviceControllerStartupParamsInternal *)startupParams }); }]; } - MTR_LOG("MTRDeviceController startup: %@", self); + MTR_LOG("%@ startup: %@", NSStringFromClass(self.class), self); return YES; } @@ -1174,7 +1174,7 @@ - (BOOL)addServerEndpoint:(MTRServerEndpoint *)endpoint } if (![endpoint associateWithController:self]) { - MTR_LOG_ERROR("%@ Failed to associate MTRServerEndpoint with MTRDeviceController", self); + MTR_LOG_ERROR("%@ Failed to associate MTRServerEndpoint with %@", self, NSStringFromClass(self.class)); [_factory removeServerEndpoint:endpoint]; return NO; } @@ -1294,7 +1294,7 @@ - (BOOL)checkIsRunning:(NSError * __autoreleasing *)error return YES; } - MTR_LOG_ERROR("MTRDeviceController: %@ Error: %s", self, [kErrorNotRunning UTF8String]); + MTR_LOG_ERROR("%@: %@ Error: %s", NSStringFromClass(self.class), self, [kErrorNotRunning UTF8String]); if (error) { *error = [MTRError errorForCHIPErrorCode:CHIP_ERROR_INCORRECT_STATE]; } diff --git a/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.mm b/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.mm index b3152a9e34..0ea7bf9232 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.mm +++ b/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.mm @@ -317,7 +317,7 @@ - (instancetype)initWithFactory:(MTRDeviceControllerFactory *)factory - (NSString *)description { - return [NSString stringWithFormat:@"", self, _uniqueIdentifier]; + return [NSString stringWithFormat:@"<%@: %p uuid %@>", NSStringFromClass(self.class), self, _uniqueIdentifier]; } - (BOOL)isRunning @@ -333,7 +333,7 @@ - (void)shutdown return; } - MTR_LOG("Shutting down MTRDeviceController: %@", self); + MTR_LOG("Shutting down %@: %@", NSStringFromClass(self.class), self); [self cleanupAfterStartup]; } @@ -345,7 +345,7 @@ - (void)cleanupAfterStartup // do the secure session shutdowns. Since we don't want to hold the lock // while calling out into arbitrary invalidation code, snapshot the list of // devices before we start invalidating. - MTR_LOG("cleanupAfterStartup MTRDeviceController: %@", self); + MTR_LOG("%s: %@", __PRETTY_FUNCTION__, self); os_unfair_lock_lock(self.deviceMapLock); NSEnumerator * devices = [self.nodeIDToDeviceMap objectEnumerator]; [self.nodeIDToDeviceMap removeAllObjects]; @@ -363,7 +363,7 @@ - (void)cleanupAfterStartup // in a very specific way that only MTRDeviceControllerFactory knows about. - (void)shutDownCppController { - MTR_LOG("shutDownCppController MTRDeviceController: %p", self); + MTR_LOG("%s: %p", __PRETTY_FUNCTION__, self); assertChipStackLockedByCurrentThread(); // Shut down all our endpoints. @@ -668,7 +668,7 @@ - (BOOL)startup:(MTRDeviceControllerStartupParamsInternal *)startupParams }); }]; } - MTR_LOG("MTRDeviceController startup: %@", self); + MTR_LOG("%s: startup: %@", __PRETTY_FUNCTION__, self); return YES; } @@ -1020,7 +1020,7 @@ - (MTRDevice *)_setupDeviceForNodeID:(NSNumber *)nodeID prefetchedClusterData:(N { os_unfair_lock_assert_owner(self.deviceMapLock); - MTRDevice * deviceToReturn = [[MTRDevice alloc] initWithNodeID:nodeID controller:self]; + MTRDevice * deviceToReturn = [[MTRDevice_Concrete alloc] initWithNodeID:nodeID controller:self]; // If we're not running, don't add the device to our map. That would // create a cycle that nothing would break. Just return the device, // which will be in exactly the state it would be in if it were created @@ -1183,7 +1183,7 @@ - (BOOL)addServerEndpoint:(MTRServerEndpoint *)endpoint } if (![endpoint associateWithController:self]) { - MTR_LOG_ERROR("%@ Failed to associate MTRServerEndpoint with MTRDeviceController", self); + MTR_LOG_ERROR("%@ Failed to associate MTRServerEndpoint with %@", self, NSStringFromClass(self.class)); [_factory removeServerEndpoint:endpoint]; return NO; } @@ -1303,7 +1303,7 @@ - (BOOL)checkIsRunning:(NSError * __autoreleasing *)error return YES; } - MTR_LOG_ERROR("MTRDeviceController: %@ Error: %s", self, [kDeviceControllerErrorNotRunning UTF8String]); + MTR_LOG_ERROR("%@: %@ Error: %s", NSStringFromClass(self.class), self, [kDeviceControllerErrorNotRunning UTF8String]); if (error) { *error = [MTRError errorForCHIPErrorCode:CHIP_ERROR_INCORRECT_STATE]; } From c4a5a95348c66f60a5a33e6ff0389e949589aaa6 Mon Sep 17 00:00:00 2001 From: Terence Hampson Date: Mon, 19 Aug 2024 13:59:11 -0400 Subject: [PATCH 091/165] Updates to BRBINFO_4_1 after issues discovered during TE2 (#35040) * Updates to BRBINFO_4_1 after issues discovered during TE2 * Update test step 3 text * Restyled by autopep8 --------- Co-authored-by: Restyled.io --- src/python_testing/TC_BRBINFO_4_1.py | 96 +++++++++++++++++----------- 1 file changed, 57 insertions(+), 39 deletions(-) diff --git a/src/python_testing/TC_BRBINFO_4_1.py b/src/python_testing/TC_BRBINFO_4_1.py index 8e920d8bc6..ea230150c2 100644 --- a/src/python_testing/TC_BRBINFO_4_1.py +++ b/src/python_testing/TC_BRBINFO_4_1.py @@ -15,10 +15,10 @@ # limitations under the License. # -# This test requires a TH_SERVER application. Please specify with --string-arg th_server_app_path: -# TH_SERVER must support following arguments: --secured-device-port --discriminator --passcode --KVS +# This test requires a TH_ICD_SERVER application. Please specify with --string-arg th_icd_server_app_path: +# TH_ICD_SERVER must support following arguments: --secured-device-port --discriminator --passcode --KVS # E.g: python3 src/python_testing/TC_BRBINFO_4_1.py --commissioning-method on-network --qr-code MT:-24J042C00KA0648G00 \ -# --string-arg th_server_app_path:out/linux-x64-lit-icd/lit-icd-app +# --string-arg th_icd_server_app_path:out/linux-x64-lit-icd/lit-icd-app import logging import os @@ -62,7 +62,8 @@ def steps_TC_BRBINFO_4_1(self) -> list[TestStep]: TestStep("1a", "TH reads from the ICD the A_IDLE_MODE_DURATION, A_ACTIVE_MODE_DURATION, and ACTIVE_MODE_THRESHOLD attributes"), TestStep("1b", "Simple KeepActive command w/ subscription. ActiveChanged event received by TH contains PromisedActiveDuration"), TestStep("2", "Sends 3x KeepActive commands w/ subscription. ActiveChanged event received ONCE and contains PromisedActiveDuration"), - TestStep("3", "KeepActive not returned after 60 minutes of offline ICD"), + TestStep("3", "TH waits for check-in from TH_ICD to confirm no additional ActiveChanged events are recieved"), + TestStep("4", "KeepActive not returned after 60 minutes of offline ICD"), ] return steps @@ -110,9 +111,10 @@ async def setup_class(self): super().setup_class() self.app_process = None - app = self.user_params.get("th_server_app_path", None) + self.app_process_paused = False + app = self.user_params.get("th_icd_server_app_path", None) if not app: - asserts.fail('This test requires a TH_SERVER app. Specify app path with --string-arg th_server_app_path:') + asserts.fail('This test requires a TH_ICD_SERVER app. Specify app path with --string-arg th_icd_server_app_path:') self.kvs = f'kvs_{str(uuid.uuid4())}' self.port = 5543 @@ -129,6 +131,7 @@ async def setup_class(self): logging.info("Commissioning of ICD to fabric one (TH)") self.icd_nodeid = 1111 + self.default_controller.EnableICDRegistration(self.default_controller.GenerateICDRegistrationParameters()) await self.default_controller.CommissionOnNetwork(nodeId=self.icd_nodeid, setupPinCode=passcode, filterType=ChipDeviceCtrl.DiscoveryFilterType.LONG_DISCRIMINATOR, filter=discriminator) logging.info("Commissioning of ICD to fabric two (DUT)") @@ -138,9 +141,10 @@ async def setup_class(self): params.commissioningParameters.setupManualCode, params.commissioningParameters.setupQRCode) def teardown_class(self): - # In case the th_server_app_path does not exist, then we failed the test + # In case the th_icd_server_app_path does not exist, then we failed the test # and there is nothing to remove if self.app_process is not None: + self.resume_th_icd_server(check_state=False) logging.warning("Stopping app with SIGTERM") self.app_process.send_signal(signal.SIGTERM.value) self.app_process.wait() @@ -150,6 +154,24 @@ def teardown_class(self): super().teardown_class() + def pause_th_icd_server(self, check_state): + if check_state: + asserts.assert_false(self.app_process_paused, "ICD TH Server unexpectedly is already paused") + if self.app_process_paused: + return + # stops (halts) the ICD server process by sending a SIGTOP signal + self.app_process.send_signal(signal.SIGSTOP.value) + self.app_process_paused = True + + def resume_th_icd_server(self, check_state): + if check_state: + asserts.assert_true(self.app_process_paused, "ICD TH Server unexpectedly is already running") + if not self.app_process_paused: + return + # resumes (continues) the ICD server process by sending a SIGCONT signal + self.app_process.send_signal(signal.SIGCONT.value) + self.app_process_paused = False + # # BRBINFO 4.1 Test Body # @@ -232,58 +254,54 @@ async def test_TC_BRBINFO_4_1(self): self.step("2") - stay_active_duration_ms = 1500 - logging.info(f"Sending KeepActiveCommand({stay_active_duration_ms}ms)") - await self._send_keep_active_command(stay_active_duration_ms, dynamic_endpoint_id) - - logging.info("Waiting for ActiveChanged from DUT...") - timeout_s = idle_mode_duration_s + max(active_mode_duration_ms, stay_active_duration_ms)/1000 - promised_active_duration_ms = await self._wait_for_active_changed_event(timeout_s) - - # wait for active time duration - sleep_time_s = max(stay_active_duration_ms, promised_active_duration_ms)/1000 - time.sleep(sleep_time_s) - # ICD now should be in idle mode - + # Prevent icd app from sending any check-in messages. + self.pause_th_icd_server(check_state=True) # sends 3x keep active commands - logging.info(f"Step3 Sending first KeepActiveCommand({stay_active_duration_ms})") + stay_active_duration_ms = 2000 + logging.info(f"Sending first KeepActiveCommand({stay_active_duration_ms})") await self._send_keep_active_command(stay_active_duration_ms, dynamic_endpoint_id) - time.sleep(0.1) - logging.info(f"Step3 Sending second KeepActiveCommand({stay_active_duration_ms})") + logging.info(f"Sending second KeepActiveCommand({stay_active_duration_ms})") await self._send_keep_active_command(stay_active_duration_ms, dynamic_endpoint_id) - time.sleep(0.1) - logging.info(f"Step3 Sending third KeepActiveCommand({stay_active_duration_ms})") + logging.info(f"Sending third KeepActiveCommand({stay_active_duration_ms})") await self._send_keep_active_command(stay_active_duration_ms, dynamic_endpoint_id) - time.sleep(0.1) + self.resume_th_icd_server(check_state=True) logging.info("Waiting for ActiveChanged from DUT...") promised_active_duration_ms = await self._wait_for_active_changed_event((idle_mode_duration_s + max(active_mode_duration_ms, stay_active_duration_ms))/1000) - - asserts.assert_equal(self.q.qSize(), 0, "More than one event received from DUT") + asserts.assert_equal(self.q.qsize(), 0, "More than one event received from DUT") self.step("3") + await self.default_controller.WaitForActive(self.icd_nodeid, stayActiveDurationMs=5000) + asserts.assert_equal(self.q.qsize(), 0, "More than one event received from DUT") + + self.step("4") + logging.info("TH waiting for checkin from TH_ICD...") + await self.default_controller.WaitForActive(self.icd_nodeid, stayActiveDurationMs=10000) stay_active_duration_ms = 10000 logging.info(f"Sending KeepActiveCommand({stay_active_duration_ms})") await self._send_keep_active_command(stay_active_duration_ms, dynamic_endpoint_id) - # stops (halts) the ICD server process by sending a SIGTOP signal - self.app_process.send_signal(signal.SIGSTOP.value) + self.pause_th_icd_server(check_state=True) + # If we are seeing assertion below fail test assumption is likely incorrect. + # Test assumes after TH waits for check-in from TH_ICD it has enough time to + # call the KeepActive command and pause the app to prevent it from checking in + # after DUT recieved the KeepActive command. Should this assumption be incorrect + # we could look into using existing ICDTestEventTriggerEvent, or adding test + # event trigger that will help suppress check-ins from the TH_ICD_SERVER. + asserts.assert_equal(self.q.qsize(), 0, "") if not self.is_ci: logging.info("Waiting for 60 minutes") - self._timeout time.sleep(60*60) - # resumes (continues) the ICD server process by sending a SIGCONT signal - self.app_process.send_signal(signal.SIGCONT.value) + self.resume_th_icd_server(check_state=True) - # wait for active changed event, expect no event will be sent - event_timeout = (idle_mode_duration_s + max(active_mode_duration_ms, stay_active_duration_ms))/1000 - try: - promised_active_duration_ms = self.q.get(block=True, timeout=event_timeout) - finally: - asserts.assert_true(queue.Empty(), "ActiveChanged event received when not expected") + logging.info("TH waiting for first checkin from TH_ICD...") + await self.default_controller.WaitForActive(self.icd_nodeid, stayActiveDurationMs=10000) + logging.info("TH waiting for second checkin from TH_ICD...") + await self.default_controller.WaitForActive(self.icd_nodeid, stayActiveDurationMs=10000) + asserts.assert_equal(self.q.qsize(), 0, "More than one event received from DUT") if __name__ == "__main__": From 96ee61efe249438fd01055736921dfa9520706db Mon Sep 17 00:00:00 2001 From: Terence Hampson Date: Mon, 19 Aug 2024 14:30:25 -0400 Subject: [PATCH 092/165] Add fabric scoping to ECOINFO cluster attributes (#35022) --------- Co-authored-by: Restyled.io Co-authored-by: Andrei Litvin --- .../ecosystem-information-server.cpp | 40 +++++++++++-------- .../ecosystem-information-server.h | 40 +++++++++++-------- 2 files changed, 47 insertions(+), 33 deletions(-) diff --git a/src/app/clusters/ecosystem-information-server/ecosystem-information-server.cpp b/src/app/clusters/ecosystem-information-server/ecosystem-information-server.cpp index c51a5165f3..2ce82394a5 100644 --- a/src/app/clusters/ecosystem-information-server/ecosystem-information-server.cpp +++ b/src/app/clusters/ecosystem-information-server/ecosystem-information-server.cpp @@ -128,6 +128,13 @@ EcosystemDeviceStruct::Builder & EcosystemDeviceStruct::Builder::AddUniqueLocati return *this; } +EcosystemDeviceStruct::Builder & EcosystemDeviceStruct::Builder::SetFabricIndex(FabricIndex aFabricIndex) +{ + VerifyOrDie(!mIsAlreadyBuilt); + mFabricIndex = aFabricIndex; + return *this; +} + std::unique_ptr EcosystemDeviceStruct::Builder::Build() { VerifyOrReturnValue(!mIsAlreadyBuilt, nullptr, ChipLogError(Zcl, "Build() already called")); @@ -136,6 +143,8 @@ std::unique_ptr EcosystemDeviceStruct::Builder::Build() VerifyOrReturnValue(!mDeviceTypes.empty(), nullptr, ChipLogError(Zcl, "No device types added")); VerifyOrReturnValue(mUniqueLocationIds.size() <= kUniqueLocationIdsListMaxSize, nullptr, ChipLogError(Zcl, "Too many location ids")); + VerifyOrReturnValue(mFabricIndex >= kMinValidFabricIndex, nullptr, ChipLogError(Zcl, "Fabric index is invalid")); + VerifyOrReturnValue(mFabricIndex <= kMaxValidFabricIndex, nullptr, ChipLogError(Zcl, "Fabric index is invalid")); for (auto & locationId : mUniqueLocationIds) { @@ -145,12 +154,12 @@ std::unique_ptr EcosystemDeviceStruct::Builder::Build() // std::make_unique does not have access to private constructor we workaround with using new std::unique_ptr ret{ new EcosystemDeviceStruct( std::move(mDeviceName), mDeviceNameLastEditEpochUs, mBridgedEndpoint, mOriginalEndpoint, std::move(mDeviceTypes), - std::move(mUniqueLocationIds), mUniqueLocationIdsLastEditEpochUs) }; + std::move(mUniqueLocationIds), mUniqueLocationIdsLastEditEpochUs, mFabricIndex) }; mIsAlreadyBuilt = true; return ret; } -CHIP_ERROR EcosystemDeviceStruct::Encode(const AttributeValueEncoder::ListEncodeHelper & aEncoder, const FabricIndex & aFabricIndex) +CHIP_ERROR EcosystemDeviceStruct::Encode(const AttributeValueEncoder::ListEncodeHelper & aEncoder) { Structs::EcosystemDeviceStruct::Type deviceStruct; if (!mDeviceName.empty()) @@ -172,9 +181,7 @@ CHIP_ERROR EcosystemDeviceStruct::Encode(const AttributeValueEncoder::ListEncode deviceStruct.uniqueLocationIDs = DataModel::List(locationIds.data(), locationIds.size()); deviceStruct.uniqueLocationIDsLastEdit = mUniqueLocationIdsLastEditEpochUs; - - // TODO(#33223) this is a hack, use mFabricIndex when it exists. - deviceStruct.SetFabricIndex(aFabricIndex); + deviceStruct.SetFabricIndex(mFabricIndex); return aEncoder.Encode(deviceStruct); } @@ -226,12 +233,9 @@ CHIP_ERROR EcosystemLocationStruct::Encode(const AttributeValueEncoder::ListEnco const std::string & aUniqueLocationId, const FabricIndex & aFabricIndex) { Structs::EcosystemLocationStruct::Type locationStruct; - VerifyOrDie(!aUniqueLocationId.empty()); locationStruct.uniqueLocationID = CharSpan(aUniqueLocationId.c_str(), aUniqueLocationId.size()); locationStruct.locationDescriptor = GetEncodableLocationDescriptorStruct(mLocationDescriptor); locationStruct.locationDescriptorLastEdit = mLocationDescriptorLastEditEpochUs; - - // TODO(#33223) this is a hack, use mFabricIndex when it exists. locationStruct.SetFabricIndex(aFabricIndex); return aEncoder.Encode(locationStruct); } @@ -266,16 +270,20 @@ CHIP_ERROR EcosystemInformationServer::AddDeviceInfo(EndpointId aEndpoint, std:: } CHIP_ERROR EcosystemInformationServer::AddLocationInfo(EndpointId aEndpoint, const std::string & aLocationId, - std::unique_ptr aLocation) + FabricIndex aFabricIndex, std::unique_ptr aLocation) { VerifyOrReturnError(aLocation, CHIP_ERROR_INVALID_ARGUMENT); VerifyOrReturnError((aEndpoint != kRootEndpointId && aEndpoint != kInvalidEndpointId), CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(!aLocationId.empty(), CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(aFabricIndex >= kMinValidFabricIndex, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(aFabricIndex <= kMaxValidFabricIndex, CHIP_ERROR_INVALID_ARGUMENT); - auto & deviceInfo = mDevicesMap[aEndpoint]; - VerifyOrReturnError((deviceInfo.mLocationDirectory.find(aLocationId) == deviceInfo.mLocationDirectory.end()), + auto & deviceInfo = mDevicesMap[aEndpoint]; + EcosystemLocationKey key = { .mUniqueLocationId = aLocationId, .mFabricIndex = aFabricIndex }; + VerifyOrReturnError((deviceInfo.mLocationDirectory.find(key) == deviceInfo.mLocationDirectory.end()), CHIP_ERROR_INVALID_ARGUMENT); VerifyOrReturnError((deviceInfo.mLocationDirectory.size() < kLocationDirectoryMaxSize), CHIP_ERROR_NO_MEMORY); - deviceInfo.mLocationDirectory[aLocationId] = std::move(aLocation); + deviceInfo.mLocationDirectory[key] = std::move(aLocation); return CHIP_NO_ERROR; } @@ -352,11 +360,10 @@ CHIP_ERROR EcosystemInformationServer::EncodeDeviceDirectoryAttribute(EndpointId return aEncoder.EncodeEmptyList(); } - FabricIndex fabricIndex = aEncoder.AccessingFabricIndex(); return aEncoder.EncodeList([&](const auto & encoder) -> CHIP_ERROR { for (auto & device : deviceInfo.mDeviceDirectory) { - ReturnErrorOnFailure(device->Encode(encoder, fabricIndex)); + ReturnErrorOnFailure(device->Encode(encoder)); } return CHIP_NO_ERROR; }); @@ -379,11 +386,10 @@ CHIP_ERROR EcosystemInformationServer::EncodeLocationStructAttribute(EndpointId return aEncoder.EncodeEmptyList(); } - FabricIndex fabricIndex = aEncoder.AccessingFabricIndex(); return aEncoder.EncodeList([&](const auto & encoder) -> CHIP_ERROR { - for (auto & [id, device] : deviceInfo.mLocationDirectory) + for (auto & [key, device] : deviceInfo.mLocationDirectory) { - ReturnErrorOnFailure(device->Encode(encoder, id, fabricIndex)); + ReturnErrorOnFailure(device->Encode(encoder, key.mUniqueLocationId, key.mFabricIndex)); } return CHIP_NO_ERROR; }); diff --git a/src/app/clusters/ecosystem-information-server/ecosystem-information-server.h b/src/app/clusters/ecosystem-information-server/ecosystem-information-server.h index dce12e745b..d4f4d7dc3a 100644 --- a/src/app/clusters/ecosystem-information-server/ecosystem-information-server.h +++ b/src/app/clusters/ecosystem-information-server/ecosystem-information-server.h @@ -49,6 +49,7 @@ class EcosystemDeviceStruct Builder & SetOriginalEndpoint(EndpointId aOriginalEndpoint); Builder & AddDeviceType(Structs::DeviceTypeStruct::Type aDeviceType); Builder & AddUniqueLocationId(std::string aUniqueLocationId, uint64_t aUniqueLocationIdsLastEditEpochUs); + Builder & SetFabricIndex(FabricIndex aFabricIndex); // Upon success this object will have moved all ownership of underlying // types to EcosystemDeviceStruct and should not be used afterwards. @@ -62,21 +63,25 @@ class EcosystemDeviceStruct std::vector mDeviceTypes; std::vector mUniqueLocationIds; uint64_t mUniqueLocationIdsLastEditEpochUs = 0; + FabricIndex mFabricIndex = kUndefinedFabricIndex; bool mIsAlreadyBuilt = false; }; - CHIP_ERROR Encode(const AttributeValueEncoder::ListEncodeHelper & aEncoder, const FabricIndex & aFabricIndex); + CHIP_ERROR Encode(const AttributeValueEncoder::ListEncodeHelper & aEncoder); private: // Constructor is intentionally private. This is to ensure that it is only constructed with // values that conform to the spec. explicit EcosystemDeviceStruct(std::string && aDeviceName, uint64_t aDeviceNameLastEditEpochUs, EndpointId aBridgedEndpoint, EndpointId aOriginalEndpoint, std::vector && aDeviceTypes, - std::vector && aUniqueLocationIds, uint64_t aUniqueLocationIdsLastEditEpochUs) : + std::vector && aUniqueLocationIds, uint64_t aUniqueLocationIdsLastEditEpochUs, + FabricIndex aFabricIndex) : mDeviceName(std::move(aDeviceName)), mDeviceNameLastEditEpochUs(aDeviceNameLastEditEpochUs), mBridgedEndpoint(aBridgedEndpoint), mOriginalEndpoint(aOriginalEndpoint), mDeviceTypes(std::move(aDeviceTypes)), - mUniqueLocationIds(std::move(aUniqueLocationIds)), mUniqueLocationIdsLastEditEpochUs(aUniqueLocationIdsLastEditEpochUs) + mUniqueLocationIds(std::move(aUniqueLocationIds)), mUniqueLocationIdsLastEditEpochUs(aUniqueLocationIdsLastEditEpochUs), + mFabricIndex(aFabricIndex) + {} const std::string mDeviceName; @@ -86,10 +91,7 @@ class EcosystemDeviceStruct std::vector mDeviceTypes; std::vector mUniqueLocationIds; uint64_t mUniqueLocationIdsLastEditEpochUs; - // TODO(#33223) This structure needs to contain fabric index to be spec compliant. - // To keep initial PR smaller, we are going to assume that all entries - // here are for any fabric. This will allow follow up PR introducing - // fabric scoped to be more throughly reviewed with focus on fabric scoping. + FabricIndex mFabricIndex; }; struct LocationDescriptorStruct @@ -134,15 +136,11 @@ class EcosystemLocationStruct mLocationDescriptor(aLocationDescriptor), mLocationDescriptorLastEditEpochUs(aLocationDescriptorLastEditEpochUs) {} // EcosystemLocationStruct is used as a value in a key-value map. - // Because UniqueLocationId is manditory when an entry exist, and - // it is unique, we use it as a key to the key-value pair and is why it is + // Because UniqueLocationId and FabricIndex are mandatory when an entry exist, + // and needs to be unique, we use it as a key to the key-value pair and is why it is // not explicitly in this struct. LocationDescriptorStruct mLocationDescriptor; uint64_t mLocationDescriptorLastEditEpochUs; - // TODO(#33223) This structure needs to contain fabric index to be spec compliant. - // To keep initial PR smaller, we are going to assume that all entries - // here are for any fabric. This will allow follow up PR introducing - // fabric scoped to be more throughly reviewed with focus on fabric scoping. }; class EcosystemInformationServer @@ -186,7 +184,7 @@ class EcosystemInformationServer * @return #CHIP_NO_ERROR on success. * @return Other CHIP_ERROR associated with issue. */ - CHIP_ERROR AddLocationInfo(EndpointId aEndpoint, const std::string & aLocationId, + CHIP_ERROR AddLocationInfo(EndpointId aEndpoint, const std::string & aLocationId, FabricIndex aFabricIndex, std::unique_ptr aLocation); /** @@ -203,12 +201,22 @@ class EcosystemInformationServer CHIP_ERROR ReadAttribute(const ConcreteReadAttributePath & aPath, AttributeValueEncoder & aEncoder); private: + struct EcosystemLocationKey + { + bool operator<(const EcosystemLocationKey & other) const + { + return mUniqueLocationId < other.mUniqueLocationId || + (mUniqueLocationId == other.mUniqueLocationId && mFabricIndex < other.mFabricIndex); + } + std::string mUniqueLocationId; + FabricIndex mFabricIndex; + }; + struct DeviceInfo { Optional mRemovedOn = NullOptional; std::vector> mDeviceDirectory; - // Map key is using the UniqueLocationId - std::map> mLocationDirectory; + std::map> mLocationDirectory; }; CHIP_ERROR EncodeRemovedOnAttribute(EndpointId aEndpoint, AttributeValueEncoder & aEncoder); From dec73c63e0c01d8ec9aeee7285ab86b1ba351214 Mon Sep 17 00:00:00 2001 From: Harshith-GRL <145322529+Harshith-GRL@users.noreply.github.com> Date: Tue, 20 Aug 2024 01:31:08 +0530 Subject: [PATCH 093/165] RVC DirectModeChange Feature Update for RVCCLEANM and RVCRUNM (#34994) * Python Scripts TC_RVCCLEANM_2_2.py and TC_RVCRUNM_2_2.py updated * Updated the python script TC_RVCCLEANM_2_2.py with two new steps '7a' For reading FeatureMap Attribute and '7b' for send ChangeToMode Command * Updated the python script TC_RVCRUNM_2_2.py with two new steps '6a' For reading FeatureMap Attribute and '6b' for send ChangeToMode Command * Updated TC_RVCOPSTATE_2_4.py with updated PICS as per Test Plan * Python Script TC_RVCOPSTATE_2_4.py * Updated TC_RVCOPSTATE_2_4.py with steps numbers update * Restyled by autopep8 * Python Scripts TC_RVCCLEANM_2_2.py and TC_RVCRUNM_2_2.py updated * Updated the python script TC_RVCCLEANM_2_2.py with two new steps '7a' For reading FeatureMap Attribute and '7b' for send ChangeToMode Command * Updated the python script TC_RVCRUNM_2_2.py with two new steps '6a' For reading FeatureMap Attribute and '6b' for send ChangeToMode Command * Updated TC_RVCOPSTATE_2_4.py with updated PICS as per Test Plan * Python Script TC_RVCOPSTATE_2_4.py * Updated TC_RVCOPSTATE_2_4.py with steps numbers update * Restyled by autopep8 * Python Script TC_RVCRUNM_2_2.py and TC_RVCCLEANM_2_2.py * Updated TC_RVCRUNM_2_2.py and TC_RVCCLEANM_2_2.py as per comments from ROB * Restyled by autopep8 * Updated CI PICS Value For TC_RVCOPSTATE_2_4.py * Updated PICS.yaml For TC_RVCOPSTATE_2_4.py * Updated CI PICS file by removing RVCOPSTATE.S.C128.Rsp * Updated RVC PICS value at location examples/rvc-app/rvc-common/pics/rvc-app-pics-values --------- Co-authored-by: Restyled.io --- .../rvc-common/pics/rvc-app-pics-values | 4 +- src/app/tests/suites/certification/PICS.yaml | 2 +- .../tests/suites/certification/ci-pics-values | 3 +- src/python_testing/TC_RVCCLEANM_2_2.py | 38 +++++++++++++++--- src/python_testing/TC_RVCOPSTATE_2_4.py | 8 ++-- src/python_testing/TC_RVCRUNM_2_2.py | 40 ++++++++++++++----- 6 files changed, 72 insertions(+), 23 deletions(-) diff --git a/examples/rvc-app/rvc-common/pics/rvc-app-pics-values b/examples/rvc-app/rvc-common/pics/rvc-app-pics-values index c38f0c1b7e..4ad084ec61 100644 --- a/examples/rvc-app/rvc-common/pics/rvc-app-pics-values +++ b/examples/rvc-app/rvc-common/pics/rvc-app-pics-values @@ -20,7 +20,7 @@ RVCOPSTATE.S.E01=1 RVCOPSTATE.S.C00.Rsp=1 RVCOPSTATE.S.C03.Rsp=1 RVCOPSTATE.S.C04.Tx=1 -RVCOPSTATE.S.C128.Rsp=1 +RVCOPSTATE.S.C80.Rsp=1 RVCOPSTATE.S.M.ST_STOPPED=1 RVCOPSTATE.S.M.ST_RUNNING=1 RVCOPSTATE.S.M.ST_PAUSED=1 @@ -77,4 +77,4 @@ SEAR.S.M.HAS_MANUAL_SKIP_STATE_CONTROL=1 SEAR.S.M.INVALID_STATE_FOR_SKIP=1 SEAR.S.M.NO_SELAREA_FOR_SKIP=1 SEAR.S.M.VALID_STATE_FOR_SKIP=1 -SEAR.S.M.HAS_MANUAL_OPERATING_STATE_CONTROL=1 \ No newline at end of file +SEAR.S.M.HAS_MANUAL_OPERATING_STATE_CONTROL=1 diff --git a/src/app/tests/suites/certification/PICS.yaml b/src/app/tests/suites/certification/PICS.yaml index 1fc182bd9b..c575bd348f 100644 --- a/src/app/tests/suites/certification/PICS.yaml +++ b/src/app/tests/suites/certification/PICS.yaml @@ -9740,7 +9740,7 @@ PICS: id: RVCOPSTATE.S.C03.Rsp - label: "Does the device implement receiving the GoHome command?" - id: RVCOPSTATE.S.C128.Rsp + id: RVCOPSTATE.S.C80.Rsp #Commands generated - label: diff --git a/src/app/tests/suites/certification/ci-pics-values b/src/app/tests/suites/certification/ci-pics-values index f64941bb68..9109f30bec 100644 --- a/src/app/tests/suites/certification/ci-pics-values +++ b/src/app/tests/suites/certification/ci-pics-values @@ -2532,7 +2532,7 @@ RVCOPSTATE.S.C01.Rsp=0 RVCOPSTATE.S.C02.Rsp=0 RVCOPSTATE.S.C03.Rsp=1 RVCOPSTATE.S.C04.Tx=1 -RVCOPSTATE.S.C128.Rsp=1 +RVCOPSTATE.S.C80.Rsp=1 RVCOPSTATE.S.M.ST_STOPPED=1 RVCOPSTATE.S.M.ST_RUNNING=1 RVCOPSTATE.S.M.ST_PAUSED=1 @@ -2618,6 +2618,7 @@ PIXIT.RVCRUNM.MODE_CHANGE_OK=0 # RVCOPSTATE.S.C02.Rsp=0 # RVCOPSTATE.S.C03.Rsp=1 # RVCOPSTATE.S.C04.Tx=1 +# RVCOPSTATE.S.C80.Rsp=1 # RVCOPSTATE.S.C128.Rsp=1 # RVCOPSTATE.C.C00.Tx=1 # RVCOPSTATE.C.C01.Tx=1 diff --git a/src/python_testing/TC_RVCCLEANM_2_2.py b/src/python_testing/TC_RVCCLEANM_2_2.py index 8aaae7ff78..e3a92033b3 100644 --- a/src/python_testing/TC_RVCCLEANM_2_2.py +++ b/src/python_testing/TC_RVCCLEANM_2_2.py @@ -27,13 +27,22 @@ # test-runner-run/run1/script-args: --storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --PICS examples/rvc-app/rvc-common/pics/rvc-app-pics-values --endpoint 1 --trace-to json:${TRACE_TEST_JSON}.json --trace-to perfetto:${TRACE_TEST_PERFETTO}.perfetto # === END CI TEST ARGUMENTS === +import enum from time import sleep import chip.clusters as Clusters -from matter_testing_support import MatterBaseTest, async_test_body, default_matter_test_main +from matter_testing_support import MatterBaseTest, async_test_body, default_matter_test_main, type_matches from mobly import asserts +class RvcStatusEnum(enum.IntEnum): + # TODO remove this class once InvalidInMode response code is implemented in python SDK + Success = 0x0 + UnsupportedMode = 0x1 + GenericFailure = 0x2 + InvalidInMode = 0x3 + + class TC_RVCCLEANM_2_2(MatterBaseTest): def __init__(self, *args): @@ -64,6 +73,11 @@ async def read_clean_supported_modes(self) -> Clusters.Objects.RvcCleanMode.Attr Clusters.RvcCleanMode.Attributes.SupportedModes) return ret + async def read_feature_map_attribute(self): + ret = await self.read_mod_attribute_expect_success(Clusters.RvcCleanMode, + Clusters.RvcCleanMode.Attributes.FeatureMap) + return ret + async def send_clean_change_to_mode_cmd(self, newMode) -> Clusters.Objects.RvcCleanMode.Commands.ChangeToModeResponse: ret = await self.send_single_cmd(cmd=Clusters.Objects.RvcCleanMode.Commands.ChangeToMode(newMode=newMode), endpoint=self.endpoint) return ret @@ -90,6 +104,9 @@ def write_to_app_pipe(self, command): @async_test_body async def test_TC_RVCCLEANM_2_2(self): + # TODO Replace 0x8000 with python object of RVCCLEAN FEATURE bit map when implemented + # 0x8000 corresponds to 16 bit DIRECTMODECH Feature map + self.directmodech_bit_mask = 0x8000 self.endpoint = self.matter_test_config.endpoint self.is_ci = self.check_pics("PICS_SDK_CI_ONLY") if self.is_ci: @@ -157,11 +174,22 @@ async def test_TC_RVCCLEANM_2_2(self): self.new_clean_mode_th = mode break - self.print_step(7, "Send ChangeToMode command") + self.print_step("7a", "Read FeatureMap Attribute") + feature_map = await self.read_feature_map_attribute() + directmode_enabled = feature_map & self.directmodech_bit_mask + + self.print_step("7b", "Send ChangeToMode command") response = await self.send_clean_change_to_mode_cmd(self.new_clean_mode_th) - asserts.assert_equal(response.status, 3, - "The response should contain a ChangeToModeResponse command " - "with the Status set to InvalidInMode(0x03).") + asserts.assert_true(type_matches(response, Clusters.RvcCleanMode.Commands.ChangeToModeResponse), + "The response should ChangeToModeResponse command") + if directmode_enabled: + asserts.assert_equal(response.status, RvcStatusEnum.Success, + "The response should contain a ChangeToModeResponse command " + "with the Status set to Success(0x0).") + else: + asserts.assert_equal(response.status, RvcStatusEnum.InvalidInMode, + "The response should contain a ChangeToModeResponse command " + "with the Status set to InvalidInMode(0x03).") if __name__ == "__main__": diff --git a/src/python_testing/TC_RVCOPSTATE_2_4.py b/src/python_testing/TC_RVCOPSTATE_2_4.py index b680453b06..7f03d33b19 100644 --- a/src/python_testing/TC_RVCOPSTATE_2_4.py +++ b/src/python_testing/TC_RVCOPSTATE_2_4.py @@ -114,7 +114,7 @@ async def test_TC_RVCOPSTATE_2_4(self): asserts.assert_true(self.check_pics("RVCOPSTATE.S.A0004"), "RVCOPSTATE.S.A0004 must be supported") asserts.assert_true(self.check_pics("RVCOPSTATE.S.C04.Tx"), "RVCOPSTATE.S.C04.Tx must be supported") - asserts.assert_true(self.check_pics("RVCOPSTATE.S.C128.Rsp"), "RVCOPSTATE.S.C128.Rsp must be supported") + asserts.assert_true(self.check_pics("RVCOPSTATE.S.C80.Rsp"), "RVCOPSTATE.S.C80.Rsp must be supported") op_states = Clusters.OperationalState.Enums.OperationalStateEnum rvc_op_states = Clusters.RvcOperationalState.Enums.OperationalStateEnum @@ -170,16 +170,16 @@ async def test_TC_RVCOPSTATE_2_4(self): if self.check_pics("PICS_M_ST_SEEKING_CHARGER"): step_name = "Manually put the device in the SEEKING CHARGER operational state" - self.print_step(8, step_name) + self.print_step(11, step_name) if self.is_ci: await self.send_run_change_to_mode_cmd(rvc_app_run_mode_cleaning) await self.send_run_change_to_mode_cmd(rvc_app_run_mode_idle) else: self.wait_for_user_input(prompt_msg=f"{step_name}, and press Enter when ready.") - await self.read_operational_state_with_check(9, rvc_op_states.kSeekingCharger) + await self.read_operational_state_with_check(12, rvc_op_states.kSeekingCharger) - await self.send_go_home_cmd_with_check(10, op_errors.kNoError) + await self.send_go_home_cmd_with_check(13, op_errors.kNoError) if __name__ == "__main__": diff --git a/src/python_testing/TC_RVCRUNM_2_2.py b/src/python_testing/TC_RVCRUNM_2_2.py index dca866adb9..b0d1233010 100644 --- a/src/python_testing/TC_RVCRUNM_2_2.py +++ b/src/python_testing/TC_RVCRUNM_2_2.py @@ -27,6 +27,7 @@ # test-runner-run/run1/script-args: --storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --PICS examples/rvc-app/rvc-common/pics/rvc-app-pics-values --endpoint 1 --trace-to json:${TRACE_TEST_JSON}.json --trace-to perfetto:${TRACE_TEST_PERFETTO}.perfetto --int-arg PIXIT.RVCRUNM.MODE_A:1 PIXIT.RVCRUNM.MODE_B:2 # === END CI TEST ARGUMENTS === +import enum from time import sleep import chip.clusters as Clusters @@ -38,17 +39,25 @@ # --int-arg PIXIT.RVCRUNM.MODE_A: PIXIT.RVCRUNM.MODE_B: +class RvcStatusEnum(enum.IntEnum): + # TODO remove this class once InvalidInMode response code is implemented in python SDK + Success = 0x0 + UnsupportedMode = 0x1 + GenericFailure = 0x2 + InvalidInMode = 0x3 + + def error_enum_to_text(error_enum): try: return f'{Clusters.RvcRunMode.Enums.ModeTag(error_enum).name} 0x{error_enum:02x}' except AttributeError: - if error_enum == 0: + if error_enum == RvcStatusEnum.Success: return "Success(0x00)" - elif error_enum == 0x1: + elif error_enum == RvcStatusEnum.UnsupportedMode: return "UnsupportedMode(0x01)" - elif error_enum == 0x2: + elif error_enum == RvcStatusEnum.GenericFailure: return "GenericFailure(0x02)" - elif error_enum == 0x3: + elif error_enum == RvcStatusEnum.InvalidInMode: return "InvalidInMode(0x03)" raise AttributeError("Unknown Enum value") @@ -122,6 +131,9 @@ async def test_TC_RVCRUNM_2_2(self): "PIXIT.RVCRUNM.MODE_A: \n" "PIXIT.RVCRUNM.MODE_B:") + # TODO Replace 0x8000 with python object of RVCRUN FEATURE bit when implemented + # 0x8000 corresponds to 16 bit DIRECTMODECH Feature map + self.directmodech_bit_mask = 0x8000 self.endpoint = self.matter_test_config.endpoint self.is_ci = self.check_pics("PICS_SDK_CI_ONLY") self.mode_a = self.matter_test_config.global_test_params['PIXIT.RVCRUNM.MODE_A'] @@ -193,15 +205,23 @@ async def test_TC_RVCRUNM_2_2(self): asserts.assert_true(idle_tag_present, "The device must be in a mode with the Idle (0x4000) mode tag.") self.print_step(5, "Send ChangeToMode MODE_A command") - await self.send_change_to_mode_with_check(self.mode_a, 0) + await self.send_change_to_mode_with_check(self.mode_a, RvcStatusEnum.Success) # This step is not described in the test plan, but it ought to be await self.read_current_mode_with_check(self.mode_a) - self.print_step(6, "Send ChangeToMode MODE_B command") - await self.send_change_to_mode_with_check(self.mode_b, 3) + self.print_step("6a", "Read Attribute FeatureMap") + feature_map = await self.read_mod_attribute_expect_success(cluster=Clusters.RvcRunMode, + attribute=Clusters.RvcRunMode.Attributes.FeatureMap) + directmode_enabled = feature_map & self.directmodech_bit_mask + + self.print_step('6b', "Send ChangeToMode MODE_B command") + if directmode_enabled: + await self.send_change_to_mode_with_check(self.mode_b, RvcStatusEnum.Success) + else: + await self.send_change_to_mode_with_check(self.mode_b, RvcStatusEnum.InvalidInMode) self.print_step(7, "Send ChangeToMode idle command") - await self.send_change_to_mode_with_check(self.idle_mode_dut, 0) + await self.send_change_to_mode_with_check(self.idle_mode_dut, RvcStatusEnum.Success) # This step is not described in the test plan, but it ought to be await self.read_current_mode_with_check(self.idle_mode_dut) @@ -228,12 +248,12 @@ async def test_TC_RVCRUNM_2_2(self): "Expected RVCOPSTATE's OperationalState attribute to be one of Stopped(0x00), Paused(0x02), Charging(0x41) or Docked(0x42)") self.print_step(11, "Send ChangeToMode MODE_B command") - await self.send_change_to_mode_with_check(self.mode_b, 0) + await self.send_change_to_mode_with_check(self.mode_b, RvcStatusEnum.Success) # This step is not described in the test plan, but it ought to be await self.read_current_mode_with_check(self.mode_b) self.print_step(12, "Send ChangeToMode idle command") - await self.send_change_to_mode_with_check(self.idle_mode_dut, 0) + await self.send_change_to_mode_with_check(self.idle_mode_dut, RvcStatusEnum.Success) # This step is not described in the test plan, but it ought to be await self.read_current_mode_with_check(self.idle_mode_dut) From b13f8ac59c964f50dbdf784e45a2d3d2392ec9a5 Mon Sep 17 00:00:00 2001 From: Yufeng Wang Date: Mon, 19 Aug 2024 13:15:56 -0700 Subject: [PATCH 094/165] [Fabric-Admin] We should only start the reverse commission process if the local fabric bridge is ready. (#35079) * [Fabric-Admin] We should only start the reverse commission process if the local fabric is ready. * Fix compile error --- .../commands/fabric-sync/FabricSyncCommand.cpp | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.cpp b/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.cpp index 704996d189..6a7b5be05b 100644 --- a/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.cpp +++ b/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.cpp @@ -64,13 +64,16 @@ void FabricSyncAddBridgeCommand::OnCommissioningComplete(NodeId deviceId, CHIP_E DeviceMgr().SubscribeRemoteFabricBridge(); - // After successful commissioning of the Commissionee, initiate Reverse Commissioning - // via the Commissioner Control Cluster. However, we must first verify that the - // remote Fabric-Bridge supports Fabric Synchronization. - // - // Note: The Fabric-Admin MUST NOT send the RequestCommissioningApproval command - // if the remote Fabric-Bridge lacks Fabric Synchronization support. - DeviceLayer::PlatformMgr().ScheduleWork(CheckFabricBridgeSynchronizationSupport, 0); + if (DeviceMgr().IsLocalBridgeReady()) + { + // After successful commissioning of the Commissionee, initiate Reverse Commissioning + // via the Commissioner Control Cluster. However, we must first verify that the + // remote Fabric-Bridge supports Fabric Synchronization. + // + // Note: The Fabric-Admin MUST NOT send the RequestCommissioningApproval command + // if the remote Fabric-Bridge lacks Fabric Synchronization support. + DeviceLayer::PlatformMgr().ScheduleWork(CheckFabricBridgeSynchronizationSupport, 0); + } } else { From 20caa91fea35cc5629aa0a6b9aa864eddceed15e Mon Sep 17 00:00:00 2001 From: mkardous-silabs <84793247+mkardous-silabs@users.noreply.github.com> Date: Mon, 19 Aug 2024 16:23:01 -0400 Subject: [PATCH 095/165] [ICD] Add ICDM 3.2 Python Certification Script (#34782) * Add ICDM 3.2 Python Certification Script * fix restyle * Restyled by prettier-json * Restyled by isort * restyle and linter fix * Add CI test arguments --------- Co-authored-by: Restyled.io --- .../certification/Test_TC_ICDM_3_2.yaml | 346 --------------- src/app/tests/suites/manualTests.json | 2 +- src/python_testing/TC_ICDM_3_2.py | 419 ++++++++++++++++++ 3 files changed, 420 insertions(+), 347 deletions(-) delete mode 100644 src/app/tests/suites/certification/Test_TC_ICDM_3_2.yaml create mode 100644 src/python_testing/TC_ICDM_3_2.py diff --git a/src/app/tests/suites/certification/Test_TC_ICDM_3_2.yaml b/src/app/tests/suites/certification/Test_TC_ICDM_3_2.yaml deleted file mode 100644 index f6104a53d4..0000000000 --- a/src/app/tests/suites/certification/Test_TC_ICDM_3_2.yaml +++ /dev/null @@ -1,346 +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. -# Auto-generated scripts for harness use only, please review before automation. The endpoints and cluster names are currently set to default - -name: 217.2.3. [TC-ICDM-3.2] Verify RegisterClient command with DUT as Server - -PICS: - - ICDM.S - - ICDM.S.C00.Rsp - - ICDM.S.C02.Rsp - -config: - nodeId: 0x12344321 - cluster: "Basic Information" - endpoint: 0 - -tests: - - label: "Preconditions" - verification: | - 1.Commission DUT to TH (can be skipped if done in a preceding test). - 2a.TH reads from the DUT the RegisteredClients attribute. - 2b.If list of registered clients is not empty, unregister existing client(s) - 2c.TH reads from the DUT the RegisteredClients attribute. Verify that the DUT response contains empty list of registered clients. - disabled: true - - - label: - "Step 1a: TH sends RegisterClient command. - CheckInNodeID: - registering clients node ID (CheckInNodeID1) - MonitoredSubject: - monitored subject ID (MonitorSubID1) - Key: shared secret between the - client and the ICD (Key1)" - PICS: ICDM.S.C00.Rsp - verification: | - ./chip-tool icdmanagement register-client 1 1 hex:1234567890abcdef1234567890abcdef 1 0 - - [1702418857.289325][1350:1352] CHIP:DMG: Received Command Response Data, Endpoint=0 Cluster=0x0000_0046 Command=0x0000_0001 - [1702418857.289426][1350:1352] CHIP:TOO: Endpoint: 0 Cluster: 0x0000_0046 Command 0x0000_0001 - [1702418857.289635][1350:1352] CHIP:TOO: RegisterClientResponse: { - [1702418857.289725][1350:1352] CHIP:TOO: ICDCounter: 1321491095 - [1702418857.289781][1350:1352] CHIP:TOO: } - disabled: true - - - label: "Step 1b: TH reads from the DUT the RegisteredClients attribute." - PICS: ICDM.S.A0003 - verification: | - ./chip-tool icdmanagement read registered-clients 1 0 - - [1702418868.283920][1353:1355] CHIP:TOO: Endpoint: 0 Cluster: 0x0000_0046 Attribute 0x0000_0003 DataVersion: 4124981277 - [1702418868.284152][1353:1355] CHIP:TOO: RegisteredClients: 2 entries - [1702418868.284338][1353:1355] CHIP:TOO: [1]: { - [1702418868.284396][1353:1355] CHIP:TOO: CheckInNodeID: 112233 - [1702418868.284449][1353:1355] CHIP:TOO: MonitoredSubject: 112233 - [1702418868.284525][1353:1355] CHIP:TOO: FabricIndex: 1 - [1702418868.284577][1353:1355] CHIP:TOO: } - [1702418868.284647][1353:1355] CHIP:TOO: [2]: { - [1702418868.284700][1353:1355] CHIP:TOO: CheckInNodeID: 1 - [1702418868.284751][1353:1355] CHIP:TOO: MonitoredSubject: 1 - [1702418868.284801][1353:1355] CHIP:TOO: FabricIndex: 1 - [1702418868.284849][1353:1355] CHIP:TOO: } - disabled: true - - - label: "Step 1c: Power cycle DUT" - verification: | - Power cycle DUT - disabled: true - - - label: "Step 1d: TH reads from the DUT the RegisteredClients attribute." - PICS: ICDM.S.A0003(RegisteredClients) - verification: | - ./chip-tool icdmanagement read registered-clients 1 0 - - [1702418876.828984][1356:1358] CHIP:TOO: Endpoint: 0 Cluster: 0x0000_0046 Attribute 0x0000_0003 DataVersion: 4124981277 - [1702418876.829201][1356:1358] CHIP:TOO: RegisteredClients: 2 entries - [1702418876.829372][1356:1358] CHIP:TOO: [1]: { - [1702418876.829426][1356:1358] CHIP:TOO: CheckInNodeID: 112233 - [1702418876.829535][1356:1358] CHIP:TOO: MonitoredSubject: 112233 - [1702418876.829609][1356:1358] CHIP:TOO: FabricIndex: 1 - [1702418876.829655][1356:1358] CHIP:TOO: } - [1702418876.829719][1356:1358] CHIP:TOO: [2]: { - [1702418876.829766][1356:1358] CHIP:TOO: CheckInNodeID: 1 - [1702418876.829867][1356:1358] CHIP:TOO: MonitoredSubject: 1 - [1702418876.829912][1356:1358] CHIP:TOO: FabricIndex: 1 - [1702418876.829955][1356:1358] CHIP:TOO: } - disabled: true - - - label: - "Step 2a: Setup the TH such that is has administrator privileges for - the ICDM cluster." - verification: | - chip-tool default with admin privilege. - disabled: true - - - label: - "Step 2b: TH sends RegisterClient command with same CheckInNodeID as - in Step 1a and different MonitoredSubject and Key. - CheckInNodeID: - registering clients node ID (CheckInNodeID1) - MonitoredSubject: - monitored subject ID (MonitorSubID2) - Key: shared secret between the - client and the ICD (Key2)" - PICS: ICDM.S.C00.Rsp - verification: | - ./chip-tool icdmanagement register-client 1 2 hex:abcdef1234567890abcdef1234567890 1 0 - - [1702418883.807797][1359:1361] CHIP:DMG: Received Command Response Data, Endpoint=0 Cluster=0x0000_0046 Command=0x0000_0001 - [1702418883.807919][1359:1361] CHIP:TOO: Endpoint: 0 Cluster: 0x0000_0046 Command 0x0000_0001 - [1702418883.808188][1359:1361] CHIP:TOO: RegisterClientResponse: { - [1702418883.808260][1359:1361] CHIP:TOO: ICDCounter: 1321491095 - [1702418883.808316][1359:1361] CHIP:TOO: } - disabled: true - - - label: "Step 2c: TH reads from the DUT the ICDCounter attribute." - PICS: ICDM.S.A0004 - verification: | - ./chip-tool icdmanagement read icdcounter 1 0 - - [1702418902.706877][1365:1367] CHIP:TOO: Endpoint: 0 Cluster: 0x0000_0046 Attribute 0x0000_0004 DataVersion: 4124981277 - [1702418902.706989][1365:1367] CHIP:TOO: ICDCounter: 1321491095 - disabled: true - - - label: "Step 2d: TH reads from the DUT the RegisteredClients attribute." - PICS: ICDM.S.A0003 - verification: | - ./chip-tool icdmanagement read registered-clients 1 0 - - [1702418891.793516][1362:1364] CHIP:TOO: Endpoint: 0 Cluster: 0x0000_0046 Attribute 0x0000_0003 DataVersion: 4124981277 - [1702418891.793737][1362:1364] CHIP:TOO: RegisteredClients: 2 entries - [1702418891.793959][1362:1364] CHIP:TOO: [1]: { - [1702418891.794016][1362:1364] CHIP:TOO: CheckInNodeID: 112233 - [1702418891.794065][1362:1364] CHIP:TOO: MonitoredSubject: 112233 - [1702418891.794133][1362:1364] CHIP:TOO: FabricIndex: 1 - [1702418891.794179][1362:1364] CHIP:TOO: } - [1702418891.794290][1362:1364] CHIP:TOO: [2]: { - [1702418891.794344][1362:1364] CHIP:TOO: CheckInNodeID: 1 - [1702418891.794390][1362:1364] CHIP:TOO: MonitoredSubject: 2 - [1702418891.794483][1362:1364] CHIP:TOO: FabricIndex: 1 - [1702418891.794531][1362:1364] CHIP:TOO: } - disabled: true - - - label: - "Step 2e: TH sends UnregisterClient command with the CheckInNodeID - (CheckInNodeID1)." - PICS: ICDM.S.C02.Rsp - verification: | - ./chip-tool icdmanagement unregister-client 1 1 0 - - [1702419153.281757][1380:1382] CHIP:DMG: InvokeResponseMessage = - [1702419153.281885][1380:1382] CHIP:DMG: { - [1702419153.282005][1380:1382] CHIP:DMG: suppressResponse = false, - [1702419153.282061][1380:1382] CHIP:DMG: InvokeResponseIBs = - [1702419153.282126][1380:1382] CHIP:DMG: [ - [1702419153.282177][1380:1382] CHIP:DMG: InvokeResponseIB = - [1702419153.282243][1380:1382] CHIP:DMG: { - [1702419153.282296][1380:1382] CHIP:DMG: CommandStatusIB = - [1702419153.282357][1380:1382] CHIP:DMG: { - [1702419153.282576][1380:1382] CHIP:DMG: CommandPathIB = - [1702419153.282650][1380:1382] CHIP:DMG: { - [1702419153.282725][1380:1382] CHIP:DMG: EndpointId = 0x0, - [1702419153.282812][1380:1382] CHIP:DMG: ClusterId = 0x46, - [1702419153.282895][1380:1382] CHIP:DMG: CommandId = 0x2, - [1702419153.282973][1380:1382] CHIP:DMG: }, - [1702419153.283183][1380:1382] CHIP:DMG: - [1702419153.283246][1380:1382] CHIP:DMG: StatusIB = - [1702419153.283327][1380:1382] CHIP:DMG: { - [1702419153.283409][1380:1382] CHIP:DMG: status = 0x00 (SUCCESS), - [1702419153.283490][1380:1382] CHIP:DMG: }, - [1702419153.283562][1380:1382] CHIP:DMG: - [1702419153.283626][1380:1382] CHIP:DMG: }, - [1702419153.283699][1380:1382] CHIP:DMG: - [1702419153.283751][1380:1382] CHIP:DMG: }, - [1702419153.283811][1380:1382] CHIP:DMG: - [1702419153.283859][1380:1382] CHIP:DMG: ], - [1702419153.283919][1380:1382] CHIP:DMG: - [1702419153.283966][1380:1382] CHIP:DMG: InteractionModelRevision = 11 - [1702419153.284013][1380:1382] CHIP:DMG: }, - [1702419153.284182][1380:1382] CHIP:DMG: Received Command Response Status for Endpoint=0 Cluster=0x0000_0046 Command=0x0000_0002 Status=0x0 - disabled: true - - - label: "Step 2f: TH reads from the DUT the RegisteredClients attribute." - PICS: ICDM.S.A0003 - verification: | - ./chip-tool icdmanagement read registered-clients 1 0 - - [1702419210.157158][1385:1387] CHIP:TOO: Endpoint: 0 Cluster: 0x0000_0046 Attribute 0x0000_0003 DataVersion: 4124981277 - [1702419210.157311][1385:1387] CHIP:TOO: RegisteredClients: 1 entries - [1702419210.157489][1385:1387] CHIP:TOO: [1]: { - [1702419210.157543][1385:1387] CHIP:TOO: CheckInNodeID: 112233 - [1702419210.157591][1385:1387] CHIP:TOO: MonitoredSubject: 112233 - [1702419210.157662][1385:1387] CHIP:TOO: FabricIndex: 1 - [1702419210.157730][1385:1387] CHIP:TOO: } - disabled: true - - - label: - "Step 2g: Clear the THs administrator privileges for the ICDM cluster." - verification: | - ./chip-tool accesscontrol write acl '[{"fabricIndex": 1, "privilege": 4, "authMode": 2, "subjects": [112233], "targets": null } ]' 1 0 - disabled: true - - - label: - "Step 3a: TH sends RegisterClient command. - CheckInNodeID: - registering clients node ID (CheckInNodeID3) - MonitoredSubject: - monitored subject ID (MonitorSubID3) - Key: shared secret between the - client and the ICD (Key3) - VerificationKey: verification key - (VerificationKey3)" - PICS: ICDM.S.C00.Rsp - verification: | - ./chip-tool icdmanagement register-client 3 3 hex:3334567890abcdef3334567890abcdef 1 0 --VerificationKey hex:abcdef1234567890abcdef1234567890 - - [1702433488.601132][2043:2045] CHIP:DMG: Received Command Response Data, Endpoint=0 Cluster=0x0000_0046 Command=0x0000_0001 - [1702433488.601231][2043:2045] CHIP:TOO: Endpoint: 0 Cluster: 0x0000_0046 Command 0x0000_0001 - [1702433488.601414][2043:2045] CHIP:TOO: RegisterClientResponse: { - [1702433488.601478][2043:2045] CHIP:TOO: ICDCounter: 228745926 - [1702433488.601531][2043:2045] CHIP:TOO: } - disabled: true - - - label: "Step 3b: TH reads from the DUT the RegisteredClients attribute." - PICS: ICDM.S.A0003 - verification: | - ./chip-tool icdmanagement read registered-clients 1 0 - - [1702433698.808800][2095:2097] CHIP:TOO: Endpoint: 0 Cluster: 0x0000_0046 Attribute 0x0000_0003 DataVersion: 2083795792 - [1702433698.808939][2095:2097] CHIP:TOO: RegisteredClients: 2 entries - [1702433698.809081][2095:2097] CHIP:TOO: [1]: { - [1702433698.809126][2095:2097] CHIP:TOO: CheckInNodeID: 112233 - [1702433698.809167][2095:2097] CHIP:TOO: MonitoredSubject: 112233 - [1702433698.809226][2095:2097] CHIP:TOO: FabricIndex: 1 - [1702433698.809266][2095:2097] CHIP:TOO: } - [1702433698.809319][2095:2097] CHIP:TOO: [2]: { - [1702433698.809359][2095:2097] CHIP:TOO: CheckInNodeID: 3 - [1702433698.809399][2095:2097] CHIP:TOO: MonitoredSubject: 3 - [1702433698.809514][2095:2097] CHIP:TOO: FabricIndex: 1 - [1702433698.809559][2095:2097] CHIP:TOO: } - disabled: true - - - label: - "Step 4: TH sends RegisterClient command with same CheckInNodeID as in - Step 3a and different MonitoredSubject and Key, and an invalid - VerificationKey - CheckInNodeID: registering clients node ID - (CheckInNodeID3) - MonitoredSubject: monitored subject ID - (MonitorSubID4) - Key: shared secret between the client and the ICD - (Key4) - VerificationKey: invalid verification key (VerificationKey4)" - PICS: ICDM.S.C00.Rsp - verification: | - ./chip-tool icdmanagement register-client 3 4 hex:3334567890abcdef3334567890abcdef 1 0 --VerificationKey hex:abcdef1234567890 - - [1703266655.434604][2378:2381] CHIP:DMG: Received Command Response Status for Endpoint=0 Cluster=0x0000_0046 Command=0x0000_0000 Status=0x1 - [1703266655.434688][2378:2381] CHIP:TOO: Error: IM Error 0x00000501: General error: 0x01 (FAILURE) - disabled: true - - - label: - "Step 5: TH sends RegisterClient command with same CheckInNodeID as in - Step 3a and different MonitoredSubject, Key, and VerificationKey - - CheckInNodeID: registering clients node ID (CheckInNodeID3) - - MonitoredSubject: monitored subject ID (MonitorSubID5) - Key: shared - secret between the client and the ICD (Key5) - VerificationKey: valid - verification key (VerificationKey5)" - PICS: ICDM.S.C00.Rsp - verification: | - ./chip-tool icdmanagement register-client 3 5 hex:3334567890abcdef3334567890abcdef 1 0 --VerificationKey hex:abcdef1234567890abcdef1234500000 - - [1703266705.829853][2551:2553] CHIP:DMG: Received Command Response Status for Endpoint=0 Cluster=0x0000_0046 Command=0x0000_0000 Status=0x1 - [1703266705.829994][2551:2553] CHIP:TOO: Error: IM Error 0x00000501: General error: 0x01 (FAILURE) - disabled: true - - - label: - "Step 6a: TH sends RegisterClient command with same CheckInNodeID and - VerificationKey as in Step 3a and different MonitoredSubject and Key - - CheckInNodeID: registering clients node ID (CheckInNodeID3) - - MonitoredSubject: monitored subject ID (MonitorSubID6) - Key: shared - secret between the client and the ICD (Key6) - VerificationKey: - verification key (VerificationKey3)" - PICS: ICDM.S.C00.Rsp - verification: | - ./chip-tool icdmanagement register-client 3 6 hex:3334567890abcdef3334567890abcdef 1 0 --VerificationKey hex:abcdef1234567890abcdef1234567890 - - [1703267703.849366][2694:2696] CHIP:TOO: Endpoint: 0 Cluster: 0x0000_0046 Command 0x0000_0001 - [1703267703.849532][2694:2696] CHIP:TOO: RegisterClientResponse: { - [1703267703.849587][2694:2696] CHIP:TOO: ICDCounter: 228745930 - [1703267703.849633][2694:2696] CHIP:TOO: } - disabled: true - - - label: "Step 6b: TH reads from the DUT the RegisteredClients attribute." - PICS: ICDM.S.A0003 - verification: | - ./chip-tool icdmanagement read registered-clients 1 0 - - [1702433698.808800][2095:2097] CHIP:TOO: Endpoint: 0 Cluster: 0x0000_0046 Attribute 0x0000_0003 DataVersion: 2083795792 - [1702433698.808939][2095:2097] CHIP:TOO: RegisteredClients: 2 entries - [1702433698.809081][2095:2097] CHIP:TOO: [1]: { - [1702433698.809126][2095:2097] CHIP:TOO: CheckInNodeID: 112233 - [1702433698.809167][2095:2097] CHIP:TOO: MonitoredSubject: 112233 - [1702433698.809226][2095:2097] CHIP:TOO: FabricIndex: 1 - [1702433698.809266][2095:2097] CHIP:TOO: } - [1702433698.809319][2095:2097] CHIP:TOO: [2]: { - [1702433698.809359][2095:2097] CHIP:TOO: CheckInNodeID: 3 - [1702433698.809399][2095:2097] CHIP:TOO: MonitoredSubject: 6 - [1702433698.809514][2095:2097] CHIP:TOO: FabricIndex: 1 - [1702433698.809559][2095:2097] CHIP:TOO: } - disabled: true - - - label: - "Step 6c: TH sends UnregisterClient command with the CheckInNodeID - (CheckInNodeID3) and VerificationKey (VerificationKey3)." - PICS: ICDM.S.C02.Rsp - verification: | - ./chip-tool icdmanagement unregister-client 3 3 0 - - [1702419153.281757][1380:1382] CHIP:DMG: InvokeResponseMessage = - [1702419153.281885][1380:1382] CHIP:DMG: { - [1702419153.282005][1380:1382] CHIP:DMG: suppressResponse = false, - [1702419153.282061][1380:1382] CHIP:DMG: InvokeResponseIBs = - [1702419153.282126][1380:1382] CHIP:DMG: [ - [1702419153.282177][1380:1382] CHIP:DMG: InvokeResponseIB = - [1702419153.282243][1380:1382] CHIP:DMG: { - [1702419153.282296][1380:1382] CHIP:DMG: CommandStatusIB = - [1702419153.282357][1380:1382] CHIP:DMG: { - [1702419153.282576][1380:1382] CHIP:DMG: CommandPathIB = - [1702419153.282650][1380:1382] CHIP:DMG: { - [1702419153.282725][1380:1382] CHIP:DMG: EndpointId = 0x0, - [1702419153.282812][1380:1382] CHIP:DMG: ClusterId = 0x46, - [1702419153.282895][1380:1382] CHIP:DMG: CommandId = 0x2, - [1702419153.282973][1380:1382] CHIP:DMG: }, - [1702419153.283183][1380:1382] CHIP:DMG: - [1702419153.283246][1380:1382] CHIP:DMG: StatusIB = - [1702419153.283327][1380:1382] CHIP:DMG: { - [1702419153.283409][1380:1382] CHIP:DMG: status = 0x00 (SUCCESS), - [1702419153.283490][1380:1382] CHIP:DMG: }, - [1702419153.283562][1380:1382] CHIP:DMG: - [1702419153.283626][1380:1382] CHIP:DMG: }, - [1702419153.283699][1380:1382] CHIP:DMG: - [1702419153.283751][1380:1382] CHIP:DMG: }, - [1702419153.283811][1380:1382] CHIP:DMG: - [1702419153.283859][1380:1382] CHIP:DMG: ], - [1702419153.283919][1380:1382] CHIP:DMG: - [1702419153.283966][1380:1382] CHIP:DMG: InteractionModelRevision = 11 - [1702419153.284013][1380:1382] CHIP:DMG: }, - [1702419153.284182][1380:1382] CHIP:DMG: Received Command Response Status for Endpoint=0 Cluster=0x0000_0046 Command=0x0000_0002 Status=0x0 - disabled: true diff --git a/src/app/tests/suites/manualTests.json b/src/app/tests/suites/manualTests.json index 5edf1cbe71..8048c7b3be 100644 --- a/src/app/tests/suites/manualTests.json +++ b/src/app/tests/suites/manualTests.json @@ -117,7 +117,7 @@ "GeneralCommissioning": ["Test_TC_CGEN_2_2"], "GeneralDiagnostics": ["Test_TC_DGGEN_2_2"], "Identify": ["Test_TC_I_3_2"], - "IcdManagement": ["Test_TC_ICDM_3_2", "Test_TC_ICDM_5_1"], + "IcdManagement": ["Test_TC_ICDM_4_1", "Test_TC_ICDM_5_1"], "IlluminanceMeasurement": [], "InteractionDataModel": [ "Test_TC_IDM_1_1", diff --git a/src/python_testing/TC_ICDM_3_2.py b/src/python_testing/TC_ICDM_3_2.py new file mode 100644 index 0000000000..5a194420c3 --- /dev/null +++ b/src/python_testing/TC_ICDM_3_2.py @@ -0,0 +1,419 @@ + +# +# Copyright (c) 2023 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. +# + +# See https://github.com/project-chip/connectedhomeip/blob/master/docs/testing/python.md#defining-the-ci-test-arguments +# for details about the block below. +# +# === BEGIN CI TEST ARGUMENTS === +# test-runner-runs: run1 +# test-runner-run/run1/app: ${LIT_ICD_APP} +# test-runner-run/run1/factoryreset: True +# test-runner-run/run1/quiet: True +# test-runner-run/run1/app-args: --discriminator 1234 --KVS kvs1 --trace-to json:${TRACE_APP}.json +# test-runner-run/run1/script-args: --storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --PICS src/app/tests/suites/certification/ci-pics-values --trace-to json:${TRACE_TEST_JSON}.json --trace-to perfetto:${TRACE_TEST_PERFETTO}.perfetto +# === END CI TEST ARGUMENTS === + +import logging +import time +from dataclasses import dataclass + +import chip.clusters as Clusters +from chip.interaction_model import InteractionModelError, Status +from matter_testing_support import MatterBaseTest, TestStep, async_test_body, default_matter_test_main +from mobly import asserts + +logger = logging.getLogger(__name__) + +# ========================== +# Constants +# ========================== + +kRootEndpointId = 0 + +cluster = Clusters.Objects.IcdManagement +commands = cluster.Commands +ClientTypeEnum = cluster.Enums.ClientTypeEnum +attributes = cluster.Attributes + + +@dataclass +class Client: + checkInNodeID: int + subjectId: int + key: bytes + clientType: ClientTypeEnum + + +# +# Test Input Data +# +kIncorrectKey = b"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1a" +kInvalidKey = b"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e1g" + +client1 = Client( + checkInNodeID=1, + subjectId=1, + key=b"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f", + clientType=ClientTypeEnum.kEphemeral +) + +client2 = Client( + checkInNodeID=1, + subjectId=2, + key=b"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1e", + clientType=ClientTypeEnum.kEphemeral +) + +client3 = Client( + checkInNodeID=1, + subjectId=3, + key=b"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1d", + clientType=ClientTypeEnum.kEphemeral +) + +client4 = Client( + checkInNodeID=1, + subjectId=4, + key=b"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1c", + clientType=ClientTypeEnum.kEphemeral +) + +client5 = Client( + checkInNodeID=5, + subjectId=5, + key=b"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1b", + clientType=ClientTypeEnum.kEphemeral +) + +client6 = Client( + checkInNodeID=5, + subjectId=6, + key=b"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1a", + clientType=ClientTypeEnum.kEphemeral +) + +client7 = Client( + checkInNodeID=5, + subjectId=7, + key=b"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x0f", + clientType=ClientTypeEnum.kEphemeral +) + +client8 = Client( + checkInNodeID=5, + subjectId=8, + key=b"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x0e", + clientType=ClientTypeEnum.kEphemeral +) + + +class TC_ICDM_3_2(MatterBaseTest): + + # + # Class Helper functions + # + async def _read_icdm_attribute_expect_success(self, attribute): + return await self.read_single_attribute_check_success(endpoint=kRootEndpointId, cluster=cluster, attribute=attribute) + + async def _send_single_icdm_command(self, command): + return await self.send_single_cmd(command, endpoint=kRootEndpointId) + # + # Test Harness Helpers + # + + def desc_TC_ICDM_3_2(self) -> str: + """Returns a description of this test""" + return "[TC-ICDM-3.2] Verify RegisterClient Command with DUT as Server" + + def steps_TC_ICDM_3_2(self) -> list[TestStep]: + steps = [ + TestStep(0, "Commissioning, already done", is_commissioning=True), + TestStep(1, "TH reads from the DUT the RegisteredClients attribute. RegisteredClients is empty."), + TestStep("2a", "TH sends RegisterClient command."), + TestStep("2b", "TH reads from the DUT the RegisteredClients attribute."), + TestStep("2c", "Power cycle DUT."), + TestStep("2d", "TH waits for {PIXIT.WAITTIME.REBOOT}"), + TestStep("2e", "TH reads from the DUT the RegisteredClients attribute."), + TestStep("3a", "TH sends RegisterClient command with same CheckInNodeID1 as in Step 1a and different MonitorSubID2 and Key2."), + TestStep("3b", "TH reads from the DUT the RegisteredClients attribute."), + TestStep("4a", "TH sends RegisterClient command with same CheckInNodeID1 as in Step 1a and different MonitorSubID3 and Key3, and an invalid VerificationKey3."), + TestStep("4b", "TH reads from the DUT the RegisteredClients attribute."), + TestStep("5a", "TH sends RegisterClient command with same CheckInNodeID1 as in Step 1a and different MonitorSubID4 and Key4, and a valid wrong VerificationKey4."), + TestStep("5b", "TH reads from the DUT the RegisteredClients attribute."), + TestStep("6a", "TH sends UnregisterClient command with CheckInNodeID1."), + TestStep("6b", "TH reads from the DUT the RegisteredClients attribute."), + TestStep(7, "Set the TH to Manage privilege for ICDM cluster."), + TestStep("8a", "TH sends RegisterClient command."), + TestStep("8b", "TH sends RegisterClient command with same CheckInNodeID5 as in Step 6a and different MonitorSubID6 and Key6, and an invalid VerificationKey6."), + TestStep("8c", "TH sends RegisterClient command with same CheckInNodeID5 as in Step 6a and different MonitorSubID7 and Key7, and an valid wrong VerificationKey7."), + TestStep("8d", "TH sends RegisterClient command with same CheckInNodeID5 and VerificationKey5 as in Step 6a and different MonitorSubID9 and Key9."), + TestStep(9, "TH sends UnregisterClient command with the CheckInNodeID5 and VerificationKey5."), + ] + return steps + + def pics_TC_ICDM_3_2(self) -> list[str]: + """ This function returns a list of PICS for this test case that must be True for the test to be run""" + pics = [ + "ICDM.S", + "ICDM.S.F00" + ] + return pics + + # + # ICDM 3.2 Test Body + # + + @ async_test_body + async def test_TC_ICDM_3_2(self): + is_ci = self.check_pics("PICS_SDK_CI_ONLY") + + if not is_ci: + asserts.assert_true('PIXIT.WAITTIME.REBOOT' in self.matter_test_config.global_test_params, + "PIXIT.WAITTIME.REBOOT must be included on the command line in " + "the --int-arg flag as PIXIT.WAITTIME.REBOOT:") + + wait_time_reboot = self.matter_test_config.global_test_params['PIXIT.WAITTIME.REBOOT'] + if wait_time_reboot == 0: + asserts.fail("PIXIT.WAITTIME.REBOOT shall be higher than 0.") + + # Pre-Condition: Commissioning + self.step(0) + + # Empty RegisteredClients attribute for all registrations + self.step(1) + registeredClients = await self._read_icdm_attribute_expect_success( + attributes.RegisteredClients) + + for client in registeredClients: + try: + await self._send_single_icdm_command(commands.UnregisterClient(checkInNodeID=client.checkInNodeID)) + except InteractionModelError as e: + asserts.assert_equal( + e.status, Status.Success, "Unexpected error returned") + + try: + self.step("2a") + try: + await self._send_single_icdm_command(commands.RegisterClient(checkInNodeID=client1.checkInNodeID, monitoredSubject=client1.subjectId, key=client1.key, clientType=client1.clientType)) + except InteractionModelError as e: + asserts.assert_equal( + e.status, Status.Success, "Unexpected error returned") + + self.step("2b") + registeredClients = await self._read_icdm_attribute_expect_success( + attributes.RegisteredClients) + # Validate list size + asserts.assert_equal(len(registeredClients), 1, + "The expected length of RegisteredClients is 1. List has the wrong size.") + + # Validate entry values + asserts.assert_equal( + registeredClients[0].checkInNodeID, client1.checkInNodeID, "The read attribute does not match the registered value.") + asserts.assert_equal( + registeredClients[0].monitoredSubject, client1.subjectId, "The read attribute does not match the registered value.") + asserts.assert_equal( + registeredClients[0].clientType, client1.clientType, "The read attribute does not match the registered value.") + + # Reboot + self.step("2c") + if not is_ci: + self.wait_for_user_input(prompt_msg="Restart DUT. Press Enter when restart has been initiated.") + + self.step("2d") + if not is_ci: + time.sleep(wait_time_reboot) + + self.step("2e") + registeredClients = await self._read_icdm_attribute_expect_success( + attributes.RegisteredClients) + # Validate list size + asserts.assert_equal(len(registeredClients), 1, + "The expected length of RegisteredClients is 1. List has the wrong size.") + + # Validate entry values + asserts.assert_equal( + registeredClients[0].checkInNodeID, client1.checkInNodeID, "The read attribute does not match the registered value.") + asserts.assert_equal( + registeredClients[0].monitoredSubject, client1.subjectId, "The read attribute does not match the registered value.") + asserts.assert_equal( + registeredClients[0].clientType, client1.clientType, "The read attribute does not match the registered value.") + + self.step("3a") + try: + await self._send_single_icdm_command(commands.RegisterClient(checkInNodeID=client2.checkInNodeID, monitoredSubject=client2.subjectId, key=client2.key, clientType=client2.clientType)) + except InteractionModelError as e: + asserts.assert_equal( + e.status, Status.Success, "Unexpected error returned") + + self.step("3b") + registeredClients = await self._read_icdm_attribute_expect_success( + attributes.RegisteredClients) + # Validate list size + asserts.assert_equal(len(registeredClients), 1, + "The expected length of RegisteredClients is 1. List has the wrong size.") + + # Validate entry values + asserts.assert_equal( + registeredClients[0].checkInNodeID, client2.checkInNodeID, "The read attribute does not match the registered value.") + asserts.assert_equal( + registeredClients[0].monitoredSubject, client2.subjectId, "The read attribute does not match the registered value.") + asserts.assert_equal( + registeredClients[0].clientType, client2.clientType, "The read attribute does not match the registered value.") + + self.step("4a") + try: + await self._send_single_icdm_command(commands.RegisterClient(checkInNodeID=client3.checkInNodeID, monitoredSubject=client3.subjectId, key=client3.key, clientType=client3.clientType, verificationKey=kInvalidKey)) + except InteractionModelError as e: + asserts.assert_equal( + e.status, Status.Success, "Unexpected error returned") + + self.step("4b") + registeredClients = await self._read_icdm_attribute_expect_success( + attributes.RegisteredClients) + # Validate list size + asserts.assert_equal(len(registeredClients), 1, + "The expected length of RegisteredClients is 1. List has the wrong size.") + + # Validate entry values + asserts.assert_equal( + registeredClients[0].checkInNodeID, client3.checkInNodeID, "The read attribute does not match the registered value.") + asserts.assert_equal( + registeredClients[0].monitoredSubject, client3.subjectId, "The read attribute does not match the registered value.") + asserts.assert_equal( + registeredClients[0].clientType, client3.clientType, "The read attribute does not match the registered value.") + + self.step("5a") + try: + await self._send_single_icdm_command(commands.RegisterClient(checkInNodeID=client4.checkInNodeID, monitoredSubject=client4.subjectId, key=client4.key, clientType=client4.clientType, verificationKey=kIncorrectKey)) + except InteractionModelError as e: + asserts.assert_equal( + e.status, Status.Success, "Unexpected error returned") + + self.step("5b") + registeredClients = await self._read_icdm_attribute_expect_success( + attributes.RegisteredClients) + # Validate list size + asserts.assert_equal(len(registeredClients), 1, + "The expected length of RegisteredClients is 1. List has the wrong size.") + + # Validate entry values + asserts.assert_equal( + registeredClients[0].checkInNodeID, client4.checkInNodeID, "The read attribute does not match the registered value.") + asserts.assert_equal( + registeredClients[0].monitoredSubject, client4.subjectId, "The read attribute does not match the registered value.") + asserts.assert_equal( + registeredClients[0].clientType, client4.clientType, "The read attribute does not match the registered value.") + + self.step("6a") + try: + await self._send_single_icdm_command(commands.UnregisterClient(checkInNodeID=client4.checkInNodeID)) + except InteractionModelError as e: + asserts.assert_equal( + e.status, Status.Success, "Unexpected error returned") + + self.step("6b") + registeredClients = await self._read_icdm_attribute_expect_success( + attributes.RegisteredClients) + asserts.assert_equal(len(registeredClients), 0, + "The RegisteredClients list must be empty. List has the wrong size.") + + self.step(7) + ac = Clusters.AccessControl + previousAcl = await self.read_single_attribute_check_success(cluster=ac, attribute=ac.Attributes.Acl) + newAcls = [] + + # Set Admin permissions on Access Control cluster + newAclEntry = ac.Structs.AccessControlEntryStruct(privilege=ac.Enums.AccessControlEntryPrivilegeEnum.kAdminister, + authMode=ac.Enums.AccessControlEntryAuthModeEnum.kCase, + subjects=previousAcl[0].subjects, targets=[ac.Structs.AccessControlTargetStruct( + cluster=Clusters.AccessControl.id)], fabricIndex=previousAcl[0].fabricIndex + ) + newAcls.append(newAclEntry) + + # Set Manage permissions on ICD Management cluster + newAclEntry = ac.Structs.AccessControlEntryStruct(privilege=ac.Enums.AccessControlEntryPrivilegeEnum.kManage, + authMode=ac.Enums.AccessControlEntryAuthModeEnum.kCase, + subjects=previousAcl[0].subjects, targets=[ac.Structs.AccessControlTargetStruct( + cluster=Clusters.IcdManagement.id)], fabricIndex=previousAcl[0].fabricIndex + ) + newAcls.append(newAclEntry) + + try: + await self.default_controller.WriteAttribute(nodeid=self.dut_node_id, attributes=[(0, ac.Attributes.Acl(newAcls))]) + except InteractionModelError as e: + asserts.assert_equal( + e.status, Status.Success, "Unexpected error returned") + + self.step("8a") + try: + await self._send_single_icdm_command(commands.RegisterClient(checkInNodeID=client5.checkInNodeID, monitoredSubject=client5.subjectId, key=client5.key, clientType=client5.clientType)) + except InteractionModelError as e: + asserts.assert_equal( + e.status, Status.Success, "Unexpected error returned") + + self.step("8b") + try: + await self._send_single_icdm_command(commands.RegisterClient(checkInNodeID=client6.checkInNodeID, monitoredSubject=client6.subjectId, key=client6.key, clientType=client6.clientType, verificationKey=kInvalidKey)) + except InteractionModelError as e: + asserts.assert_equal( + e.status, Status.Failure, "Unexpected error returned") + + self.step("8c") + try: + await self._send_single_icdm_command(commands.RegisterClient(checkInNodeID=client7.checkInNodeID, monitoredSubject=client7.subjectId, key=client7.key, clientType=client7.clientType, verificationKey=kIncorrectKey)) + except InteractionModelError as e: + asserts.assert_equal( + e.status, Status.Failure, "Unexpected error returned") + + self.step("8d") + try: + await self._send_single_icdm_command(commands.RegisterClient(checkInNodeID=client8.checkInNodeID, monitoredSubject=client8.subjectId, key=client8.key, clientType=client8.clientType, verificationKey=client5.key)) + except InteractionModelError as e: + asserts.assert_equal( + e.status, Status.Success, "Unexpected error returned") + + self.step(9) + try: + await self._send_single_icdm_command(commands.UnregisterClient(checkInNodeID=client8.checkInNodeID, verificationKey=client8.key)) + except InteractionModelError as e: + asserts.assert_equal( + e.status, Status.Success, "Unexpected error returned") + + # Post-Condition steps + finally: + # Reset ACLs + try: + await self.default_controller.WriteAttribute(nodeid=self.dut_node_id, attributes=[(0, ac.Attributes.Acl(previousAcl))]) + except InteractionModelError as e: + asserts.assert_equal( + e.status, Status.Success, "Unexpected error returned") + + # Clear all RegisteredClients + registeredClients = await self._read_icdm_attribute_expect_success( + attributes.RegisteredClients) + + for client in registeredClients: + try: + await self._send_single_icdm_command(commands.UnregisterClient(checkInNodeID=client.checkInNodeID)) + except InteractionModelError as e: + asserts.assert_equal( + e.status, Status.Success, "Unexpected error returned") + + +if __name__ == "__main__": + default_matter_test_main() From a902838bfe0f6185434859c681a0a22f953aa015 Mon Sep 17 00:00:00 2001 From: Yufeng Wang Date: Mon, 19 Aug 2024 16:09:30 -0700 Subject: [PATCH 096/165] [FabricAdmin] Refactor FS specific attribute handlings out of general HandleAttributeData function (#35080) * [FabricAdmin] Refactor attribute Data handling * Use reference to pass chip::TLV::TLVReader * Update examples/fabric-admin/device_manager/DeviceManager.h Co-authored-by: Terence Hampson * Update function name --------- Co-authored-by: Terence Hampson --- .../commands/clusters/ClusterCommand.h | 2 +- .../commands/clusters/ReportCommand.cpp | 4 +- .../device_manager/DeviceManager.cpp | 159 +++++++++--------- .../device_manager/DeviceManager.h | 14 +- 4 files changed, 94 insertions(+), 85 deletions(-) diff --git a/examples/fabric-admin/commands/clusters/ClusterCommand.h b/examples/fabric-admin/commands/clusters/ClusterCommand.h index ab2a535da4..edf2302219 100644 --- a/examples/fabric-admin/commands/clusters/ClusterCommand.h +++ b/examples/fabric-admin/commands/clusters/ClusterCommand.h @@ -84,7 +84,7 @@ class ClusterCommand : public InteractionModelCommands, public ModelCommand, pub if (data != nullptr) { LogErrorOnFailure(RemoteDataModelLogger::LogCommandAsJSON(path, data)); - DeviceMgr().HandleCommandResponse(path, data); + DeviceMgr().HandleCommandResponse(path, *data); } } diff --git a/examples/fabric-admin/commands/clusters/ReportCommand.cpp b/examples/fabric-admin/commands/clusters/ReportCommand.cpp index ff52a30e66..2fdb965ddc 100644 --- a/examples/fabric-admin/commands/clusters/ReportCommand.cpp +++ b/examples/fabric-admin/commands/clusters/ReportCommand.cpp @@ -46,7 +46,7 @@ void ReportCommand::OnAttributeData(const app::ConcreteDataAttributePath & path, LogErrorOnFailure(RemoteDataModelLogger::LogAttributeAsJSON(path, data)); - DeviceMgr().HandleAttributeData(path, data); + DeviceMgr().HandleAttributeData(path, *data); } void ReportCommand::OnEventData(const app::EventHeader & eventHeader, TLV::TLVReader * data, const app::StatusIB * status) @@ -73,5 +73,5 @@ void ReportCommand::OnEventData(const app::EventHeader & eventHeader, TLV::TLVRe LogErrorOnFailure(RemoteDataModelLogger::LogEventAsJSON(eventHeader, data)); - DeviceMgr().HandleEventData(eventHeader, data); + DeviceMgr().HandleEventData(eventHeader, *data); } diff --git a/examples/fabric-admin/device_manager/DeviceManager.cpp b/examples/fabric-admin/device_manager/DeviceManager.cpp index 849d557f0b..ad8def646a 100644 --- a/examples/fabric-admin/device_manager/DeviceManager.cpp +++ b/examples/fabric-admin/device_manager/DeviceManager.cpp @@ -237,6 +237,25 @@ void DeviceManager::ReadSupportedDeviceCategories() PushCommand(commandBuilder.c_str()); } +void DeviceManager::HandleReadSupportedDeviceCategories(chip::TLV::TLVReader & data) +{ + ChipLogProgress(NotSpecified, "Attribute SupportedDeviceCategories detected."); + + BitMask value; + CHIP_ERROR error = app::DataModel::Decode(data, value); + if (error != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to decode attribute value. Error: %" CHIP_ERROR_FORMAT, error.Format()); + return; + } + + if (value.Has(CommissionerControl::SupportedDeviceCategoryBitmap::kFabricSynchronization)) + { + ChipLogProgress(NotSpecified, "Remote Fabric-Bridge supports Fabric Synchronization, start reverse commissioning."); + RequestCommissioningApproval(); + } +} + void DeviceManager::RequestCommissioningApproval() { ChipLogProgress(NotSpecified, "Starting reverse commissioning for bridge device: NodeId: " ChipLogFormatX64, @@ -254,12 +273,12 @@ void DeviceManager::RequestCommissioningApproval() PushCommand(commandBuilder.c_str()); } -void DeviceManager::HandleCommissioningRequestResult(TLV::TLVReader * data) +void DeviceManager::HandleCommissioningRequestResult(TLV::TLVReader & data) { ChipLogProgress(NotSpecified, "CommissioningRequestResult event received."); CommissionerControl::Events::CommissioningRequestResult::DecodableType value; - CHIP_ERROR error = app::DataModel::Decode(*data, value); + CHIP_ERROR error = app::DataModel::Decode(data, value); if (error != CHIP_NO_ERROR) { ChipLogError(NotSpecified, "Failed to decode event value. Error: %" CHIP_ERROR_FORMAT, error.Format()); @@ -283,82 +302,12 @@ void DeviceManager::HandleCommissioningRequestResult(TLV::TLVReader * data) SendCommissionNodeRequest(value.requestId, kResponseTimeoutSeconds); } -void DeviceManager::SendCommissionNodeRequest(uint64_t requestId, uint16_t responseTimeoutSeconds) -{ - ChipLogProgress(NotSpecified, "Request the Commissioner Control Server to begin commissioning a previously approved request."); - - StringBuilder commandBuilder; - commandBuilder.Add("commissionercontrol commission-node "); - commandBuilder.AddFormat("%lu %u %lu %d", requestId, responseTimeoutSeconds, mRemoteBridgeNodeId, kRootEndpointId); - - PushCommand(commandBuilder.c_str()); -} - -void DeviceManager::HandleReverseOpenCommissioningWindow(TLV::TLVReader * data) +void DeviceManager::HandleAttributePartsListUpdate(chip::TLV::TLVReader & data) { - CommissionerControl::Commands::ReverseOpenCommissioningWindow::DecodableType value; - CHIP_ERROR error = app::DataModel::Decode(*data, value); - if (error != CHIP_NO_ERROR) - { - ChipLogError(NotSpecified, "Failed to decode command response value. Error: %" CHIP_ERROR_FORMAT, error.Format()); - return; - } - - // Log all fields - ChipLogProgress(NotSpecified, "DecodableType fields:"); - ChipLogProgress(NotSpecified, " commissioningTimeout: %u", value.commissioningTimeout); - ChipLogProgress(NotSpecified, " discriminator: %u", value.discriminator); - ChipLogProgress(NotSpecified, " iterations: %u", value.iterations); - - char verifierHex[Crypto::kSpake2p_VerifierSerialized_Length * 2 + 1]; - Encoding::BytesToHex(value.PAKEPasscodeVerifier.data(), value.PAKEPasscodeVerifier.size(), verifierHex, sizeof(verifierHex), - Encoding::HexFlags::kNullTerminate); - ChipLogProgress(NotSpecified, " PAKEPasscodeVerifier: %s", verifierHex); - - char saltHex[Crypto::kSpake2p_Max_PBKDF_Salt_Length * 2 + 1]; - Encoding::BytesToHex(value.salt.data(), value.salt.size(), saltHex, sizeof(saltHex), Encoding::HexFlags::kNullTerminate); - ChipLogProgress(NotSpecified, " salt: %s", saltHex); - - OpenDeviceCommissioningWindow(mLocalBridgeNodeId, value.commissioningTimeout, value.iterations, value.discriminator, saltHex, - verifierHex); -} - -void DeviceManager::HandleAttributeData(const app::ConcreteDataAttributePath & path, TLV::TLVReader * data) -{ - if (path.mClusterId == CommissionerControl::Id && - path.mAttributeId == CommissionerControl::Attributes::SupportedDeviceCategories::Id) - { - ChipLogProgress(NotSpecified, "Attribute SupportedDeviceCategories detected."); - - BitMask value; - CHIP_ERROR error = app::DataModel::Decode(*data, value); - if (error != CHIP_NO_ERROR) - { - ChipLogError(NotSpecified, "Failed to decode attribute value. Error: %" CHIP_ERROR_FORMAT, error.Format()); - return; - } - - if (value.Has(CommissionerControl::SupportedDeviceCategoryBitmap::kFabricSynchronization)) - { - ChipLogProgress(NotSpecified, "Remote Fabric-Bridge supports Fabric Synchronization, start reverse commissioning."); - RequestCommissioningApproval(); - } - - return; - } - - if (path.mClusterId != Descriptor::Id || path.mAttributeId != Descriptor::Attributes::PartsList::Id) - { - return; - } - - ChipLogProgress(NotSpecified, "Attribute change detected:"); - ChipLogProgress( - NotSpecified, "Endpoint: %u, Cluster: " ChipLogFormatMEI ", Attribute: " ChipLogFormatMEI ", DataVersion: %" PRIu32, - path.mEndpointId, ChipLogValueMEI(path.mClusterId), ChipLogValueMEI(path.mAttributeId), path.mDataVersion.ValueOr(0)); + ChipLogProgress(NotSpecified, "Attribute PartsList change detected:"); app::DataModel::DecodableList value; - CHIP_ERROR error = app::DataModel::Decode(*data, value); + CHIP_ERROR error = app::DataModel::Decode(data, value); if (error != CHIP_NO_ERROR) { ChipLogError(NotSpecified, "Failed to decode attribute value. Error: %" CHIP_ERROR_FORMAT, error.Format()); @@ -456,7 +405,63 @@ void DeviceManager::HandleAttributeData(const app::ConcreteDataAttributePath & p } } -void DeviceManager::HandleEventData(const app::EventHeader & header, TLV::TLVReader * data) +void DeviceManager::SendCommissionNodeRequest(uint64_t requestId, uint16_t responseTimeoutSeconds) +{ + ChipLogProgress(NotSpecified, "Request the Commissioner Control Server to begin commissioning a previously approved request."); + + StringBuilder commandBuilder; + commandBuilder.Add("commissionercontrol commission-node "); + commandBuilder.AddFormat("%lu %u %lu %d", requestId, responseTimeoutSeconds, mRemoteBridgeNodeId, kRootEndpointId); + + PushCommand(commandBuilder.c_str()); +} + +void DeviceManager::HandleReverseOpenCommissioningWindow(TLV::TLVReader & data) +{ + CommissionerControl::Commands::ReverseOpenCommissioningWindow::DecodableType value; + CHIP_ERROR error = app::DataModel::Decode(data, value); + if (error != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to decode command response value. Error: %" CHIP_ERROR_FORMAT, error.Format()); + return; + } + + // Log all fields + ChipLogProgress(NotSpecified, "DecodableType fields:"); + ChipLogProgress(NotSpecified, " commissioningTimeout: %u", value.commissioningTimeout); + ChipLogProgress(NotSpecified, " discriminator: %u", value.discriminator); + ChipLogProgress(NotSpecified, " iterations: %u", value.iterations); + + char verifierHex[Crypto::kSpake2p_VerifierSerialized_Length * 2 + 1]; + Encoding::BytesToHex(value.PAKEPasscodeVerifier.data(), value.PAKEPasscodeVerifier.size(), verifierHex, sizeof(verifierHex), + Encoding::HexFlags::kNullTerminate); + ChipLogProgress(NotSpecified, " PAKEPasscodeVerifier: %s", verifierHex); + + char saltHex[Crypto::kSpake2p_Max_PBKDF_Salt_Length * 2 + 1]; + Encoding::BytesToHex(value.salt.data(), value.salt.size(), saltHex, sizeof(saltHex), Encoding::HexFlags::kNullTerminate); + ChipLogProgress(NotSpecified, " salt: %s", saltHex); + + OpenDeviceCommissioningWindow(mLocalBridgeNodeId, value.commissioningTimeout, value.iterations, value.discriminator, saltHex, + verifierHex); +} + +void DeviceManager::HandleAttributeData(const app::ConcreteDataAttributePath & path, TLV::TLVReader & data) +{ + if (path.mClusterId == CommissionerControl::Id && + path.mAttributeId == CommissionerControl::Attributes::SupportedDeviceCategories::Id) + { + HandleReadSupportedDeviceCategories(data); + return; + } + + if (path.mClusterId == Descriptor::Id && path.mAttributeId == Descriptor::Attributes::PartsList::Id) + { + HandleAttributePartsListUpdate(data); + return; + } +} + +void DeviceManager::HandleEventData(const app::EventHeader & header, TLV::TLVReader & data) { if (header.mPath.mClusterId == CommissionerControl::Id && header.mPath.mEventId == CommissionerControl::Events::CommissioningRequestResult::Id) @@ -465,7 +470,7 @@ void DeviceManager::HandleEventData(const app::EventHeader & header, TLV::TLVRea } } -void DeviceManager::HandleCommandResponse(const app::ConcreteCommandPath & path, TLV::TLVReader * data) +void DeviceManager::HandleCommandResponse(const app::ConcreteCommandPath & path, TLV::TLVReader & data) { ChipLogProgress(NotSpecified, "Command Response received."); diff --git a/examples/fabric-admin/device_manager/DeviceManager.h b/examples/fabric-admin/device_manager/DeviceManager.h index b6c7dc0e65..d3b47c4b33 100644 --- a/examples/fabric-admin/device_manager/DeviceManager.h +++ b/examples/fabric-admin/device_manager/DeviceManager.h @@ -150,11 +150,11 @@ class DeviceManager : public PairingDelegate void ReadSupportedDeviceCategories(); - void HandleAttributeData(const chip::app::ConcreteDataAttributePath & path, chip::TLV::TLVReader * data); + void HandleAttributeData(const chip::app::ConcreteDataAttributePath & path, chip::TLV::TLVReader & data); - void HandleEventData(const chip::app::EventHeader & header, chip::TLV::TLVReader * data); + void HandleEventData(const chip::app::EventHeader & header, chip::TLV::TLVReader & data); - void HandleCommandResponse(const chip::app::ConcreteCommandPath & path, chip::TLV::TLVReader * data); + void HandleCommandResponse(const chip::app::ConcreteCommandPath & path, chip::TLV::TLVReader & data); void OnDeviceRemoved(chip::NodeId deviceId, CHIP_ERROR err) override; @@ -163,11 +163,15 @@ class DeviceManager : public PairingDelegate void RequestCommissioningApproval(); - void HandleCommissioningRequestResult(chip::TLV::TLVReader * data); + void HandleReadSupportedDeviceCategories(chip::TLV::TLVReader & data); + + void HandleCommissioningRequestResult(chip::TLV::TLVReader & data); + + void HandleAttributePartsListUpdate(chip::TLV::TLVReader & data); void SendCommissionNodeRequest(uint64_t requestId, uint16_t responseTimeoutSeconds); - void HandleReverseOpenCommissioningWindow(chip::TLV::TLVReader * data); + void HandleReverseOpenCommissioningWindow(chip::TLV::TLVReader & data); static DeviceManager sInstance; From 9c79da28a732aad0ced375fed69d4ea1b0e3c3ec Mon Sep 17 00:00:00 2001 From: Rob Bultman Date: Tue, 20 Aug 2024 07:37:27 -0400 Subject: [PATCH 097/165] Move step (#35070) --- src/python_testing/TC_OpstateCommon.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/python_testing/TC_OpstateCommon.py b/src/python_testing/TC_OpstateCommon.py index edc72f253e..45d5b0918a 100644 --- a/src/python_testing/TC_OpstateCommon.py +++ b/src/python_testing/TC_OpstateCommon.py @@ -1264,8 +1264,8 @@ async def TEST_TC_OPSTATE_BASE_2_6(self, endpoint=1): sub_handler = ClusterAttributeChangeAccumulator(cluster) await sub_handler.start(self.default_controller, self.dut_node_id, endpoint) - self.step(3) if self.pics_guard(self.check_pics(f"{self.test_info.pics_code}.S.M.ST_RUNNING")): + self.step(3) self.send_manual_or_pipe_command(name="OperationalStateChange", device=self.device, operation="Start") From 15ad51003f789c263eba84a1aa881c682bada3ee Mon Sep 17 00:00:00 2001 From: Rohit Jadhav <69809379+jadhavrohit924@users.noreply.github.com> Date: Tue, 20 Aug 2024 18:21:19 +0530 Subject: [PATCH 098/165] Use PRIu32 instead of %u to print unsigned integer (#35069) --- .../service-area-server.cpp | 67 ++++++++++--------- 1 file changed, 35 insertions(+), 32 deletions(-) diff --git a/src/app/clusters/service-area-server/service-area-server.cpp b/src/app/clusters/service-area-server/service-area-server.cpp index a7e8127883..a4c132df8a 100644 --- a/src/app/clusters/service-area-server/service-area-server.cpp +++ b/src/app/clusters/service-area-server/service-area-server.cpp @@ -373,7 +373,7 @@ void Instance::HandleSkipAreaCmd(HandlerContext & ctx, const Commands::SkipArea: // If the Status field is set to InvalidAreaList, the StatusText field SHALL be an empty string. if (!IsSupportedArea(req.skippedArea)) { - ChipLogError(Zcl, "SkippedArea (%u) is not in the SupportedAreas attribute.", req.skippedArea); + ChipLogError(Zcl, "SkippedArea (%" PRIu32 ") is not in the SupportedAreas attribute.", req.skippedArea); exitResponse(SkipAreaStatus::kInvalidAreaList, ""_span); return; } @@ -453,7 +453,7 @@ bool Instance::IsValidSupportedArea(const AreaStructureWrapper & aArea) // If the LandmarkInfo field is null, the LocationInfo field SHALL NOT be null. if (aArea.areaDesc.locationInfo.IsNull() && aArea.areaDesc.landmarkInfo.IsNull()) { - ChipLogDetail(Zcl, "IsValidAsSupportedArea %u - must have locationInfo and/or LandmarkInfo", aArea.areaID); + ChipLogDetail(Zcl, "IsValidAsSupportedArea %" PRIu32 " - must have locationInfo and/or LandmarkInfo", aArea.areaID); return false; } @@ -464,8 +464,9 @@ bool Instance::IsValidSupportedArea(const AreaStructureWrapper & aArea) if (aArea.areaDesc.locationInfo.Value().locationName.empty() && aArea.areaDesc.locationInfo.Value().floorNumber.IsNull() && aArea.areaDesc.locationInfo.Value().areaType.IsNull() && aArea.areaDesc.landmarkInfo.IsNull()) { - ChipLogDetail(Zcl, "IsValidAsSupportedArea %u - AreaName is empty string, FloorNumber, AreaType, LandmarkInfo are null", - aArea.areaID); + ChipLogDetail( + Zcl, "IsValidAsSupportedArea %" PRIu32 " - AreaName is empty string, FloorNumber, AreaType, LandmarkInfo are null", + aArea.areaID); return false; } } @@ -475,14 +476,15 @@ bool Instance::IsValidSupportedArea(const AreaStructureWrapper & aArea) { if (aArea.mapID.IsNull()) { - ChipLogDetail(Zcl, "IsValidSupportedArea %u - map Id should not be null when there are supported maps", aArea.areaID); + ChipLogDetail(Zcl, "IsValidSupportedArea %" PRIu32 " - map Id should not be null when there are supported maps", + aArea.areaID); return false; } // If the SupportedMaps attribute is not null, mapID SHALL be the ID of an entry from the SupportedMaps attribute. if (!IsSupportedMap(aArea.mapID.Value())) { - ChipLogError(Zcl, "IsValidSupportedArea %u - map Id %u is not in supported map list", aArea.areaID, + ChipLogError(Zcl, "IsValidSupportedArea %" PRIu32 " - map Id %" PRIu32 " is not in supported map list", aArea.areaID, aArea.mapID.Value()); return false; } @@ -491,8 +493,8 @@ bool Instance::IsValidSupportedArea(const AreaStructureWrapper & aArea) { if (!aArea.mapID.IsNull()) { - ChipLogDetail(Zcl, "IsValidSupportedArea %u - map Id %u is not in empty supported map list", aArea.areaID, - aArea.mapID.Value()); + ChipLogDetail(Zcl, "IsValidSupportedArea %" PRIu32 " - map Id %" PRIu32 " is not in empty supported map list", + aArea.areaID, aArea.mapID.Value()); return false; } } @@ -578,14 +580,14 @@ bool Instance::AddSupportedArea(AreaStructureWrapper & aNewArea) // Check there is space for the entry. if (mDelegate->GetNumberOfSupportedAreas() >= kMaxNumSupportedAreas) { - ChipLogError(Zcl, "AddSupportedArea %u - too many entries", aNewArea.areaID); + ChipLogError(Zcl, "AddSupportedArea %" PRIu32 " - too many entries", aNewArea.areaID); return false; } // Verify cluster requirements concerning valid fields and field relationships. if (!IsValidSupportedArea(aNewArea)) { - ChipLogError(Zcl, "AddSupportedArea %u - not a valid location object", aNewArea.areaID); + ChipLogError(Zcl, "AddSupportedArea %" PRIu32 " - not a valid location object", aNewArea.areaID); return false; } @@ -595,7 +597,7 @@ bool Instance::AddSupportedArea(AreaStructureWrapper & aNewArea) // the AreaInfo field. if (!IsUniqueSupportedArea(aNewArea, false)) { - ChipLogError(Zcl, "AddSupportedArea %u - not a unique location object", aNewArea.areaID); + ChipLogError(Zcl, "AddSupportedArea %" PRIu32 " - not a unique location object", aNewArea.areaID); return false; } @@ -619,7 +621,7 @@ bool Instance::ModifySupportedArea(AreaStructureWrapper & aNewArea) AreaStructureWrapper supportedArea; if (!mDelegate->GetSupportedAreaById(aNewArea.areaID, listIndex, supportedArea)) { - ChipLogError(Zcl, "ModifySupportedArea %u - not a supported areaID", aNewArea.areaID); + ChipLogError(Zcl, "ModifySupportedArea %" PRIu32 " - not a supported areaID", aNewArea.areaID); return false; } @@ -639,7 +641,7 @@ bool Instance::ModifySupportedArea(AreaStructureWrapper & aNewArea) // verify cluster requirements concerning valid fields and field relationships if (!IsValidSupportedArea(aNewArea)) { - ChipLogError(Zcl, "ModifySupportedArea %u - not a valid location object", aNewArea.areaID); + ChipLogError(Zcl, "ModifySupportedArea %" PRIu32 " - not a valid location object", aNewArea.areaID); return false; } @@ -647,7 +649,7 @@ bool Instance::ModifySupportedArea(AreaStructureWrapper & aNewArea) // We ignore comparing the area ID as one of the locations will match this one. if (!IsUniqueSupportedArea(aNewArea, true)) { - ChipLogError(Zcl, "ModifySupportedArea %u - not a unique location object", aNewArea.areaID); + ChipLogError(Zcl, "ModifySupportedArea %" PRIu32 " - not a unique location object", aNewArea.areaID); return false; } @@ -701,14 +703,14 @@ bool Instance::AddSupportedMap(uint32_t aMapId, const CharSpan & aMapName) // check max# of list entries if (mDelegate->GetNumberOfSupportedMaps() >= kMaxNumSupportedMaps) { - ChipLogError(Zcl, "AddSupportedMap %u - maximum number of entries", aMapId); + ChipLogError(Zcl, "AddSupportedMap %" PRIu32 " - maximum number of entries", aMapId); return false; } // Map name SHALL include readable text that describes the map name (cannot be empty string). if (aMapName.empty()) { - ChipLogError(Zcl, "AddSupportedMap %u - Name must not be empty string", aMapId); + ChipLogError(Zcl, "AddSupportedMap %" PRIu32 " - Name must not be empty string", aMapId); return false; } @@ -721,7 +723,7 @@ bool Instance::AddSupportedMap(uint32_t aMapId, const CharSpan & aMapName) // the name cannot be the same as an existing map if (entry.IsNameEqual(aMapName)) { - ChipLogError(Zcl, "AddSupportedMap %u - A map already exists with same name '%.*s'", aMapId, + ChipLogError(Zcl, "AddSupportedMap %" PRIu32 " - A map already exists with same name '%.*s'", aMapId, static_cast(entry.GetName().size()), entry.GetName().data()); return false; } @@ -729,7 +731,7 @@ bool Instance::AddSupportedMap(uint32_t aMapId, const CharSpan & aMapName) // Each entry in this list SHALL have a unique value for the MapID field. if (aMapId == entry.mapID) { - ChipLogError(Zcl, "AddSupportedMap - non-unique Id %u", aMapId); + ChipLogError(Zcl, "AddSupportedMap - non-unique Id %" PRIu32 "", aMapId); return false; } } @@ -757,14 +759,14 @@ bool Instance::RenameSupportedMap(uint32_t aMapId, const CharSpan & newMapName) // get existing entry if (!mDelegate->GetSupportedMapById(aMapId, modifiedIndex, modifiedMap)) { - ChipLogError(Zcl, "RenameSupportedMap Id %u - map does not exist", aMapId); + ChipLogError(Zcl, "RenameSupportedMap Id %" PRIu32 " - map does not exist", aMapId); return false; } // Map name SHALL include readable text that describes the map's name. It cannot be empty string. if (newMapName.empty()) { - ChipLogError(Zcl, "RenameSupportedMap %u - Name must not be empty string", aMapId); + ChipLogError(Zcl, "RenameSupportedMap %" PRIu32 " - Name must not be empty string", aMapId); return false; } @@ -784,7 +786,7 @@ bool Instance::RenameSupportedMap(uint32_t aMapId, const CharSpan & newMapName) if (entry.IsNameEqual(newMapName)) { - ChipLogError(Zcl, "RenameSupportedMap %u - map already exists with same name '%.*s'", aMapId, + ChipLogError(Zcl, "RenameSupportedMap %" PRIu32 " - map already exists with same name '%.*s'", aMapId, static_cast(entry.GetName().size()), entry.GetName().data()); return false; } @@ -828,21 +830,21 @@ bool Instance::AddSelectedArea(uint32_t & aSelectedArea) // check max# of list entries if (mDelegate->GetNumberOfSelectedAreas() >= kMaxNumSelectedAreas) { - ChipLogError(Zcl, "AddSelectedArea %u - maximum number of entries", aSelectedArea); + ChipLogError(Zcl, "AddSelectedArea %" PRIu32 " - maximum number of entries", aSelectedArea); return false; } // each item in this list SHALL match the AreaID field of an entry on the SupportedAreas attribute's list if (!IsSupportedArea(aSelectedArea)) { - ChipLogError(Zcl, "AddSelectedArea %u - not a supported location", aSelectedArea); + ChipLogError(Zcl, "AddSelectedArea %" PRIu32 " - not a supported location", aSelectedArea); return false; } // each entry in this list SHALL have a unique value if (mDelegate->IsSelectedArea(aSelectedArea)) { - ChipLogError(Zcl, "AddSelectedArea %u - duplicated location", aSelectedArea); + ChipLogError(Zcl, "AddSelectedArea %" PRIu32 " - duplicated location", aSelectedArea); return false; } @@ -852,7 +854,7 @@ bool Instance::AddSelectedArea(uint32_t & aSelectedArea) if (!mDelegate->IsSetSelectedAreasAllowed(locationStatusText)) { - ChipLogError(Zcl, "AddSelectedArea %u - %.*s", aSelectedArea, static_cast(locationStatusText.size()), + ChipLogError(Zcl, "AddSelectedArea %" PRIu32 " - %.*s", aSelectedArea, static_cast(locationStatusText.size()), locationStatusText.data()); return false; } @@ -886,7 +888,7 @@ bool Instance::SetCurrentArea(const DataModel::Nullable & aCurrentArea // list. if ((!aCurrentArea.IsNull()) && (!IsSupportedArea(aCurrentArea.Value()))) { - ChipLogError(Zcl, "SetCurrentArea %u - location is not supported", aCurrentArea.Value()); + ChipLogError(Zcl, "SetCurrentArea %" PRIu32 " - location is not supported", aCurrentArea.Value()); return false; } @@ -955,14 +957,14 @@ bool Instance::AddPendingProgressElement(uint32_t aAreaId) // For each entry in this list, the AreaID field SHALL match an entry on the SupportedAreas attribute's list. if (!IsSupportedArea(aAreaId)) { - ChipLogError(Zcl, "AddPendingProgressElement - not a supported location %u", aAreaId); + ChipLogError(Zcl, "AddPendingProgressElement - not a supported location %" PRIu32 "", aAreaId); return false; } // Each entry in this list SHALL have a unique value for the AreaID field. if (mDelegate->IsProgressElement(aAreaId)) { - ChipLogError(Zcl, "AddPendingProgressElement - progress element already exists for location %u", aAreaId); + ChipLogError(Zcl, "AddPendingProgressElement - progress element already exists for location %" PRIu32 "", aAreaId); return false; } @@ -984,7 +986,7 @@ bool Instance::SetProgressStatus(uint32_t aAreaId, OperationalStatusEnum opStatu if (!mDelegate->GetProgressElementById(aAreaId, listIndex, progressElement)) { - ChipLogError(Zcl, "SetProgressStatus - progress element does not exist for location %u", aAreaId); + ChipLogError(Zcl, "SetProgressStatus - progress element does not exist for location %" PRIu32 "", aAreaId); return false; } @@ -1020,7 +1022,7 @@ bool Instance::SetProgressTotalOperationalTime(uint32_t aAreaId, const DataModel if (!mDelegate->GetProgressElementById(aAreaId, listIndex, progressElement)) { - ChipLogError(Zcl, "SetProgressTotalOperationalTime - progress element does not exist for location %u", aAreaId); + ChipLogError(Zcl, "SetProgressTotalOperationalTime - progress element does not exist for location %" PRIu32 "", aAreaId); return false; } @@ -1036,7 +1038,8 @@ bool Instance::SetProgressTotalOperationalTime(uint32_t aAreaId, const DataModel !aTotalOperationalTime.IsNull()) { ChipLogError(Zcl, - "SetProgressTotalOperationalTime - location %u opStatus value %u - can be non-null only if opStatus is " + "SetProgressTotalOperationalTime - location %" PRIu32 + " opStatus value %u - can be non-null only if opStatus is " "Completed or Skipped", aAreaId, to_underlying(progressElement.status)); return false; @@ -1062,7 +1065,7 @@ bool Instance::SetProgressEstimatedTime(uint32_t aAreaId, const DataModel::Nulla if (!mDelegate->GetProgressElementById(aAreaId, listIndex, progressElement)) { - ChipLogError(Zcl, "SetProgressEstimatedTime - progress element does not exist for location %u", aAreaId); + ChipLogError(Zcl, "SetProgressEstimatedTime - progress element does not exist for location %" PRIu32 "", aAreaId); return false; } From c3ac7658f4063ab2cd8ab3c7a367b0783c5eab3f Mon Sep 17 00:00:00 2001 From: Borys Nykytiuk <165832970+BorysNykytiuk@users.noreply.github.com> Date: Tue, 20 Aug 2024 15:53:26 +0300 Subject: [PATCH 099/165] soc: riscv: telink_b9x, telink_w91: Auto calculation of SETTINGS_NVS_SECTOR_COUNT (#34958) - Remove sector count of NVS from metter kconfig - Sector count of NVS now calculates on Zephyr side as the storage partition size divided by the sector size (4 KB) Signed-off-by: Borys Nykytiuk --- config/telink/chip-module/Kconfig.defaults | 5 ----- 1 file changed, 5 deletions(-) diff --git a/config/telink/chip-module/Kconfig.defaults b/config/telink/chip-module/Kconfig.defaults index 45c8894722..80d07150f2 100644 --- a/config/telink/chip-module/Kconfig.defaults +++ b/config/telink/chip-module/Kconfig.defaults @@ -219,12 +219,7 @@ config NVS_LOOKUP_CACHE_SIZE config SETTINGS_NVS_SECTOR_SIZE_MULT default 1 -# Set sector counter of NVS -config SETTINGS_NVS_SECTOR_COUNT - default 12 - # Enable OpenThread - config NET_L2_OPENTHREAD default y if !WIFI From 9a90d8ba03837e19d9cd07af5bf6169579bfd9f3 Mon Sep 17 00:00:00 2001 From: Alex Tsitsiura Date: Tue, 20 Aug 2024 15:53:49 +0300 Subject: [PATCH 100/165] riscv: telink: tlsr9528a_4m_flash.overlay (#34945) - follow telink flash rules . Signed-off-by: Haiwen Xia Co-authored-by: Haiwen Xia --- .../telink/tlsr9528a_4m_flash.overlay | 38 ++++++++++--------- 1 file changed, 21 insertions(+), 17 deletions(-) diff --git a/src/platform/telink/tlsr9528a_4m_flash.overlay b/src/platform/telink/tlsr9528a_4m_flash.overlay index 0005da2a59..ec88c5742a 100644 --- a/src/platform/telink/tlsr9528a_4m_flash.overlay +++ b/src/platform/telink/tlsr9528a_4m_flash.overlay @@ -14,31 +14,35 @@ }; slot0_partition: partition@13000 { label = "image-0"; - reg = <0x13000 0x1ec000>; + reg = <0x13000 0x1ea000>; }; - factory_partition: partition@1ff000 { - label = "factory-data"; - reg = <0x1ff000 0x1000>; + slot1_partition: partition@1fd000 { + label = "image-1"; + reg = <0x1fd000 0x1ea000>; }; - dac_keypair_partition: partition@200000 { - label = "dac-keypair"; - reg = <0x200000 0x1000>; //store dac and key pair. + storage_partition: partition@3e7000 { + label = "storage"; + reg = <0x3e7000 0xf000>; // matter nvs part }; - descriptor_partition: partition@201000 { - label = "sboot-descriptor"; - reg = <0x201000 0x2000>; + dac_keypair_partition: partition@3f6000 { + label = "dac-keypair"; + reg = <0x3f6000 0x1000>; //store dac and key pair. }; - storage_partition: partition@203000 { - label = "storage"; - reg = <0x203000 0xf000>; + factory_partition: partition@3f7000 { + label = "factory-data"; + reg = <0x3f7000 0x1000>; // factory data info }; - slot1_partition: partition@212000 { - label = "image-1"; - reg = <0x212000 0x1ec000>; + secure_partition: partition@3f8000 { + label = "secure"; + reg = <0x3f8000 0x4000>; //secure info ,reserved for secure boot .if not use , can be used by other way . + }; + vendor_rfu_partition: partition@3fc000 { + label = "vendor-rfu"; + reg = <0x3fc000 0x2000>;// reserved for chip extend. }; vendor_partition: partition@3fe000 { label = "vendor-data"; - reg = <0x3fe000 0x2000>; + reg = <0x3fe000 0x2000>;// mac and adc info. }; }; }; From 7b7fe914f0dedf999f1c1e27f4c877baa345e411 Mon Sep 17 00:00:00 2001 From: Junior Martinez <67972863+jmartinez-silabs@users.noreply.github.com> Date: Tue, 20 Aug 2024 10:25:50 -0400 Subject: [PATCH 101/165] [Silabs] Update Silabs sdks version and related enablement (#35083) * Update all sdks to new verions * 9116 changes to support sdk update * 917 changes to support sdk update * Update to provision storage for configurable address * bump matter_support submodule * Bump docker image version used for silabs ci * Restyled by clang-format * Fix wifi ncp builds --------- Co-authored-by: Mathieu Kardous Co-authored-by: Restyled.io --- .github/workflows/examples-efr32.yaml | 2 +- .gitmodules | 6 +- examples/platform/silabs/FreeRTOSConfig.h | 2 +- .../silabs/SiWx917/SiWx917/sl_wifi_if.cpp | 95 ++++++------------- examples/platform/silabs/display/demo-ui.c | 14 ++- .../platform/silabs/efr32/rs911x/rsi_if.c | 6 +- .../provision/ProvisionStorageDefault.cpp | 21 ++-- .../provision/ProvisionStorageFlash.cpp | 18 ++-- examples/platform/silabs/wfx_rsi.h | 1 - .../silabs/provision/ProvisionStorage.h | 5 +- src/platform/silabs/rs911x/ble_config.h | 19 +++- src/platform/silabs/rs911x/rsi_ble_config.h | 6 +- third_party/silabs/SiWx917_sdk.gni | 20 ---- third_party/silabs/efr32_sdk.gni | 2 + third_party/silabs/matter_support | 2 +- third_party/silabs/simplicity_sdk | 2 +- third_party/silabs/wifi_sdk | 2 +- third_party/silabs/wiseconnect-wifi-bt-sdk | 2 +- 18 files changed, 104 insertions(+), 121 deletions(-) mode change 120000 => 100644 src/platform/silabs/rs911x/ble_config.h diff --git a/.github/workflows/examples-efr32.yaml b/.github/workflows/examples-efr32.yaml index ed6f5b45fa..c236b4ca3d 100644 --- a/.github/workflows/examples-efr32.yaml +++ b/.github/workflows/examples-efr32.yaml @@ -40,7 +40,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-efr32:73 + image: ghcr.io/project-chip/chip-build-efr32:74 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" steps: diff --git a/.gitmodules b/.gitmodules index 0b015f8d14..78a6cabb94 100644 --- a/.gitmodules +++ b/.gitmodules @@ -213,17 +213,17 @@ [submodule "third_party/silabs/simplicity_sdk"] path = third_party/silabs/simplicity_sdk url = https://github.com/SiliconLabs/simplicity_sdk.git - branch = v2024.6.0 + branch = v2024.6.1-0 platforms = silabs [submodule "third_party/silabs/wiseconnect-wifi-bt-sdk"] path = third_party/silabs/wiseconnect-wifi-bt-sdk url = https://github.com/SiliconLabs/wiseconnect-wifi-bt-sdk.git - branch = 2.8.2 + branch = 2.10.0 platforms = silabs [submodule "third_party/silabs/wifi_sdk"] path = third_party/silabs/wifi_sdk url = https://github.com/SiliconLabs/wiseconnect.git - branch = v3.3.0 + branch = v3.3.1 platforms = silabs [submodule "editline"] path = third_party/editline/repo diff --git a/examples/platform/silabs/FreeRTOSConfig.h b/examples/platform/silabs/FreeRTOSConfig.h index d2805c4065..b27c775d9b 100644 --- a/examples/platform/silabs/FreeRTOSConfig.h +++ b/examples/platform/silabs/FreeRTOSConfig.h @@ -150,7 +150,7 @@ extern uint32_t SystemCoreClock; #define configEXPECTED_IDLE_TIME_BEFORE_SLEEP 70 #define configPRE_SLEEP_PROCESSING(x) #define configPOST_SLEEP_PROCESSING(x) -#define configPRE_SUPPRESS_TICKS_AND_SLEEP_PROCESSING(x) sl_si91x_pre_supress_ticks_and_sleep(&x) +#define configPRE_SUPPRESS_TICKS_AND_SLEEP_PROCESSING(x) #else #define configUSE_TICKLESS_IDLE 0 #endif // SL_CATALOG_POWER_MANAGER_PRESENT diff --git a/examples/platform/silabs/SiWx917/SiWx917/sl_wifi_if.cpp b/examples/platform/silabs/SiWx917/SiWx917/sl_wifi_if.cpp index bfdedbfe82..03b51540cf 100644 --- a/examples/platform/silabs/SiWx917/SiWx917/sl_wifi_if.cpp +++ b/examples/platform/silabs/SiWx917/SiWx917/sl_wifi_if.cpp @@ -15,6 +15,10 @@ * limitations under the License. */ +/* + * This file implements the interface to the wifi sdk + */ + #include #include #include @@ -23,38 +27,44 @@ #include "sl_matter_wifi_config.h" #endif // SL_MATTER_GN_BUILD +#include "FreeRTOS.h" +#include "ble_config.h" +#include "dhcp_client.h" +#include "event_groups.h" +#include "sl_board_configuration.h" #include "sl_status.h" +#include "task.h" +#include "wfx_host_events.h" +#include "wfx_rsi.h" #include #include #include -#include "FreeRTOS.h" -#include "event_groups.h" -#include "sl_board_configuration.h" extern "C" { +#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" #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 "task.h" #if (EXP_BOARD) #include "rsi_bt_common_apis.h" #endif -#include "ble_config.h" - #if CHIP_CONFIG_ENABLE_ICD_SERVER && SLI_SI91X_MCU_INTERFACE #include "rsi_rom_power_save.h" #include "sl_si91x_button_pin_config.h" -#if DISPLAY_ENABLED -#include "sl_memlcd.h" -#endif // DISPLAY_ENABLED -extern "C" { -#include "sl_si91x_driver.h" -#include "sl_si91x_m4_ps.h" -} +#include "sl_si91x_power_manager.h" namespace { // TODO: should be removed once we are getting the press interrupt for button 0 with sleep @@ -67,9 +77,6 @@ bool ps_requirement_added = false; } // namespace #endif // CHIP_CONFIG_ENABLE_ICD_SERVER && SLI_SI91X_MCU_INTERFACE -#include "dhcp_client.h" -#include "wfx_host_events.h" -#include "wfx_rsi.h" #define ADV_SCAN_THRESHOLD -40 #define ADV_RSSI_TOLERANCE_THRESHOLD 5 #define ADV_ACTIVE_SCAN_DURATION 15 @@ -79,17 +86,9 @@ bool ps_requirement_added = false; // TODO: Confirm that this value works for size and timing #define WFX_QUEUE_SIZE 10 -extern "C" { -#include "sl_net.h" -#include "sl_si91x_host_interface.h" -#include "sl_wifi.h" -#include "sl_wifi_callback_framework.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 -} + +// TODO: Figure out why we actually need this, we are already handling failure and retries somewhere else. +#define WIFI_SCAN_TIMEOUT_TICK 10000 WfxRsi_t wfx_rsi; @@ -109,20 +108,9 @@ bool is_wifi_disconnection_event = false; uint32_t retryInterval = WLAN_MIN_RETRY_TIMER_MS; volatile bool scan_results_complete = false; volatile bool bg_scan_results_complete = false; - -// TODO: Figure out why we actually need this, we are already handling failure and retries somewhere else. -#define WIFI_SCAN_TIMEOUT_TICK 10000 - extern osSemaphoreId_t sl_rs_ble_init_sem; - -/* - * This file implements the interface to the wifi sdk - */ - 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 @@ -319,28 +307,6 @@ void sl_si91x_invoke_btn_press_event() } #endif // ENABLE_CHIP_SHELL } - -/****************************************************************** - * @fn sl_app_sleep_ready() - * @brief - * Called from the supress ticks from tickless to check if it - * is ok to go to sleep - * @param[in] None - * @return - * None - *********************************************************************/ -uint32_t sl_app_sleep_ready() -{ - if (wfx_rsi.dev_state & WFX_RSI_ST_SLEEP_READY) - { -#if DISPLAY_ENABLED - // Powering down the LCD - sl_memlcd_power_on(NULL, false); -#endif /* DISPLAY_ENABLED */ - return true; - } - return false; -} #endif // SLI_SI91X_MCU_INTERFACE /****************************************************************** @@ -370,14 +336,7 @@ int32_t wfx_rsi_power_save(rsi_power_save_profile_mode_t sl_si91x_ble_state, sl_ ChipLogError(DeviceLayer, "sl_wifi_set_performance_profile failed: 0x%lx", static_cast(status)); return status; } - if (sl_si91x_wifi_state == HIGH_PERFORMANCE) - { - wfx_rsi.dev_state &= ~(WFX_RSI_ST_SLEEP_READY); - } - else - { - wfx_rsi.dev_state |= WFX_RSI_ST_SLEEP_READY; - } + return status; } #endif /* CHIP_CONFIG_ENABLE_ICD_SERVER */ diff --git a/examples/platform/silabs/display/demo-ui.c b/examples/platform/silabs/display/demo-ui.c index 479af92fd5..e0fe37ec9c 100644 --- a/examples/platform/silabs/display/demo-ui.c +++ b/examples/platform/silabs/display/demo-ui.c @@ -25,6 +25,7 @@ #include "glib.h" #include "sl_component_catalog.h" #include "sl_memlcd.h" +#include #if SL_WIFI && !SLI_SI91X_MCU_INTERFACE #include "spi_multiplex.h" #endif // SL_WIFI && !SLI_SI91X_MCU_INTERFACE @@ -106,9 +107,12 @@ void demoUIInit(GLIB_Context_t * context) sl_status_t updateDisplay(void) { sl_status_t status = SL_STATUS_OK; -#if SLI_SI91X_MCU_INTERFACE && SL_ICD_ENABLED && DISPLAY_ENABLED + +#if SLI_SI91X_MCU_INTERFACE && CHIP_CONFIG_ENABLE_ICD_SERVER + // In sleep, memlcd will not be retained so re-initialize MEMLCD interface after sleep wakeup sl_memlcd_post_wakeup_init(); -#endif // SLI_SI91X_MCU_INTERFACE && SL_ICD_ENABLED && DISPLAY_ENABLED +#endif // SLI_SI91X_MCU_INTERFACE && SL_ICD_ENABLED && CHIP_CONFIG_ENABLE_ICD_SERVER + #if SL_LCDCTRL_MUX status = sl_wfx_host_pre_lcd_spi_transfer(); if (status != SL_STATUS_OK) @@ -123,6 +127,12 @@ sl_status_t updateDisplay(void) return status; #endif // SL_LCDCTRL_MUX +#if SLI_SI91X_MCU_INTERFACE && CHIP_CONFIG_ENABLE_ICD_SERVER + // MEMLCD is not a UULP component and not available in sleep so powering down before sleep and need to be re-initialized after + // sleep-wakeup + sl_memlcd_power_on(NULL, false); +#endif // SLI_SI91X_MCU_INTERFACE && CHIP_CONFIG_ENABLE_ICD_SERVER + return SL_STATUS_OK; } diff --git a/examples/platform/silabs/efr32/rs911x/rsi_if.c b/examples/platform/silabs/efr32/rs911x/rsi_if.c index a08e2a2f29..e4d6f51bf0 100644 --- a/examples/platform/silabs/efr32/rs911x/rsi_if.c +++ b/examples/platform/silabs/efr32/rs911x/rsi_if.c @@ -511,9 +511,9 @@ static void wfx_rsi_save_ap_info() // translation case SME_WEP: wfx_rsi.sec.security = WFX_SEC_WEP; break; - case SME_WPA3_TRANSITION: + case SME_WPA3_PERSONAL_TRANSITION: #if WIFI_ENABLE_SECURITY_WPA3_TRANSITION - case SME_WPA3: + case SME_WPA3_PERSONAL: wfx_rsi.sec.security = WFX_SEC_WPA3; #else wfx_rsi.sec.security = WFX_SEC_WPA2; @@ -557,7 +557,7 @@ static void wfx_rsi_do_join(void) break; #if WIFI_ENABLE_SECURITY_WPA3_TRANSITION case WFX_SEC_WPA3: - connect_security_mode = RSI_WPA3_TRANSITION; + connect_security_mode = RSI_WPA3_PERSONAL_TRANSITION; break; #endif // WIFI_ENABLE_SECURITY_WPA3_TRANSITION case WFX_SEC_NONE: diff --git a/examples/platform/silabs/provision/ProvisionStorageDefault.cpp b/examples/platform/silabs/provision/ProvisionStorageDefault.cpp index 1162323cda..801eb9e0b7 100644 --- a/examples/platform/silabs/provision/ProvisionStorageDefault.cpp +++ b/examples/platform/silabs/provision/ProvisionStorageDefault.cpp @@ -90,7 +90,7 @@ size_t RoundNearest(size_t n, size_t multiple) CHIP_ERROR WriteFile(Storage & store, SilabsConfig::Key offset_key, SilabsConfig::Key size_key, const ByteSpan & value) { uint32_t base_addr = 0; - ReturnErrorOnFailure(store.GetBaseAddress(base_addr)); + ReturnErrorOnFailure(store.GetCredentialsBaseAddress(base_addr)); if (0 == sCredentialsOffset) { ReturnErrorOnFailure(ErasePage(base_addr)); @@ -120,7 +120,7 @@ CHIP_ERROR WriteFile(Storage & store, SilabsConfig::Key offset_key, SilabsConfig CHIP_ERROR ReadFileByOffset(Storage & store, const char * description, uint32_t offset, uint32_t size, MutableByteSpan & value) { uint32_t base_addr = 0; - ReturnErrorOnFailure(store.GetBaseAddress(base_addr)); + ReturnErrorOnFailure(store.GetCredentialsBaseAddress(base_addr)); uint8_t * address = (uint8_t *) (base_addr + offset); ByteSpan span(address, size); @@ -167,12 +167,7 @@ CHIP_ERROR Storage::Initialize(uint32_t flash_addr, uint32_t flash_size) setNvm3End(base_addr); #endif } - return SilabsConfig::WriteConfigValue(SilabsConfig::kConfigKey_Creds_Base_Addr, base_addr); -} - -CHIP_ERROR Storage::GetBaseAddress(uint32_t & value) -{ - return SilabsConfig::ReadConfigValue(SilabsConfig::kConfigKey_Creds_Base_Addr, value); + return SetCredentialsBaseAddress(base_addr); } CHIP_ERROR Storage::Commit() @@ -625,6 +620,16 @@ CHIP_ERROR Storage::SignWithDeviceAttestationKey(const ByteSpan & message, Mutab // Other // +CHIP_ERROR Storage::SetCredentialsBaseAddress(uint32_t addr) +{ + return SilabsConfig::WriteConfigValue(SilabsConfig::kConfigKey_Creds_Base_Addr, addr); +} + +CHIP_ERROR Storage::GetCredentialsBaseAddress(uint32_t & addr) +{ + return SilabsConfig::ReadConfigValue(SilabsConfig::kConfigKey_Creds_Base_Addr, addr); +} + CHIP_ERROR Storage::SetProvisionVersion(const char * value, size_t size) { return SilabsConfig::WriteConfigValueStr(SilabsConfig::kConfigKey_Provision_Version, value, size); diff --git a/examples/platform/silabs/provision/ProvisionStorageFlash.cpp b/examples/platform/silabs/provision/ProvisionStorageFlash.cpp index 35a32d6af8..af59d6560c 100644 --- a/examples/platform/silabs/provision/ProvisionStorageFlash.cpp +++ b/examples/platform/silabs/provision/ProvisionStorageFlash.cpp @@ -296,12 +296,6 @@ CHIP_ERROR Storage::Commit() return CHIP_NO_ERROR; } -CHIP_ERROR Storage::GetBaseAddress(uint32_t & value) -{ - value = (uint32_t) Flash::sReadOnlyPage; - return CHIP_NO_ERROR; -} - // // DeviceInstanceInfoProvider // @@ -675,6 +669,18 @@ CHIP_ERROR Storage::SignWithDeviceAttestationKey(const ByteSpan & message, Mutab // Other // +CHIP_ERROR Storage::SetCredentialsBaseAddress(uint32_t addr) +{ + Flash::sReadOnlyPage = (uint8_t *) addr; + return CHIP_NO_ERROR; +} + +CHIP_ERROR Storage::GetCredentialsBaseAddress(uint32_t & addr) +{ + addr = (uint32_t) Flash::sReadOnlyPage; + return CHIP_NO_ERROR; +} + CHIP_ERROR Storage::SetProvisionVersion(const char * value, size_t size) { return Flash::Set(Parameters::ID::kVersion, value, size); diff --git a/examples/platform/silabs/wfx_rsi.h b/examples/platform/silabs/wfx_rsi.h index c47a4ee0af..c559e1e761 100644 --- a/examples/platform/silabs/wfx_rsi.h +++ b/examples/platform/silabs/wfx_rsi.h @@ -62,7 +62,6 @@ typedef enum 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 */ - WFX_RSI_ST_SLEEP_READY = (1 << 11) /* Notify the M4 to go to sleep*/ } WfxStateType_e; typedef struct WfxEvent_s diff --git a/src/platform/silabs/provision/ProvisionStorage.h b/src/platform/silabs/provision/ProvisionStorage.h index 3dbc780764..ff012491ae 100644 --- a/src/platform/silabs/provision/ProvisionStorage.h +++ b/src/platform/silabs/provision/ProvisionStorage.h @@ -42,7 +42,7 @@ enum ID : uint16_t kFlashAddress = 0x0101, kFlashSize = 0x0102, kFlashPageSize = 0x0103, - kBaseAddress = 0x0104, + kCredsAddress = 0x0104, kCsrFile = 0x0105, // Options, kVersion = 0x0111, @@ -175,7 +175,6 @@ struct Storage : public GenericStorage, CHIP_ERROR Initialize(uint32_t flash_addr = 0, uint32_t flash_size = 0); CHIP_ERROR Commit(); - CHIP_ERROR GetBaseAddress(uint32_t & value); // // Generic Interface @@ -233,6 +232,8 @@ struct Storage : public GenericStorage, // Other // + CHIP_ERROR SetCredentialsBaseAddress(uint32_t addr); + CHIP_ERROR GetCredentialsBaseAddress(uint32_t & addr); CHIP_ERROR GetSetupPayload(chip::MutableCharSpan & value); CHIP_ERROR SetProvisionRequest(bool value); CHIP_ERROR GetProvisionRequest(bool & value); diff --git a/src/platform/silabs/rs911x/ble_config.h b/src/platform/silabs/rs911x/ble_config.h deleted file mode 120000 index 48a308dc91..0000000000 --- a/src/platform/silabs/rs911x/ble_config.h +++ /dev/null @@ -1 +0,0 @@ -rsi_ble_config.h \ No newline at end of file diff --git a/src/platform/silabs/rs911x/ble_config.h b/src/platform/silabs/rs911x/ble_config.h new file mode 100644 index 0000000000..0b8c951b4f --- /dev/null +++ b/src/platform/silabs/rs911x/ble_config.h @@ -0,0 +1,18 @@ +/******************************************************************************* + * @file ble_config.h + * @brief + ******************************************************************************* + * # License + * Copyright 2020 Silicon Laboratories Inc. www.silabs.com + ******************************************************************************* + * + * The licensor of this software is Silicon Laboratories Inc. Your use of this + * software is governed by the terms of Silicon Labs Master Software License + * Agreement (MSLA) available at + * www.silabs.com/about-us/legal/master-software-license-agreement. This + * software is distributed to you in Source Code format and is governed by the + * sections of the MSLA applicable to Source Code. + * + ******************************************************************************/ + +#include diff --git a/src/platform/silabs/rs911x/rsi_ble_config.h b/src/platform/silabs/rs911x/rsi_ble_config.h index f5442578e5..781ad80a29 100644 --- a/src/platform/silabs/rs911x/rsi_ble_config.h +++ b/src/platform/silabs/rs911x/rsi_ble_config.h @@ -24,6 +24,10 @@ #include #endif +#if SL_MATTER_GN_BUILD == 0 +#include "sl_matter_wifi_config.h" +#endif // SL_MATTER_GN_BUILD + /****************************************************** * * Macros * ******************************************************/ @@ -107,7 +111,7 @@ #else #define RSI_BLE_MAX_NBR_ATT_REC (80) -#if (SLI_SI91X_MCU_INTERFACE | EXP_BOARD) +#if (EXP_BOARD) #define RSI_BLE_MAX_NBR_PERIPHERALS (3) #else #define RSI_BLE_MAX_NBR_SLAVES (3) diff --git a/third_party/silabs/SiWx917_sdk.gni b/third_party/silabs/SiWx917_sdk.gni index 8c7635ad92..1163cd28c9 100644 --- a/third_party/silabs/SiWx917_sdk.gni +++ b/third_party/silabs/SiWx917_sdk.gni @@ -27,17 +27,8 @@ import("silabs_board.gni") examples_plat_dir = "${chip_root}/examples/platform/silabs/SiWx917" declare_args() { - # Enable the Alarm Based Wakeup for 917 SoC when sleep is enabled - si91x_alarm_based_periodic_wakeup = false - - # Periodic time at which the 917 SoC should wakeup - si91x_alarm_periodic_time = 30 - # option to select the crypto library sl_si91x_crypto_flavor = "tinycrypt" - - # enable 917 SoC M4 sleep wakeup - si917_m4_sleep_enabled = false } # Defines an siwx917 SDK build target. @@ -325,17 +316,6 @@ template("siwx917_sdk") { "SL_SI91X_POWER_MANAGER_UC_AVAILABLE=1", "SL_SI91X_TICKLESS_MODE=1", ] - - if (si91x_alarm_based_periodic_wakeup) { - defines += [ "ALARM_PERIODIC_TIME=${si91x_alarm_periodic_time}" ] - } - - if (si917_m4_sleep_enabled) { - defines += [ - "SI917_M4_SLEEP_ENABLED=1", - "XTAL_OFF", - ] - } } if (sl_uart_log_output) { diff --git a/third_party/silabs/efr32_sdk.gni b/third_party/silabs/efr32_sdk.gni index c9126d02e4..617dfd10fa 100644 --- a/third_party/silabs/efr32_sdk.gni +++ b/third_party/silabs/efr32_sdk.gni @@ -485,6 +485,8 @@ template("efr32_sdk") { "RSI_LITTLE_ENDIAN=1", "SLI_SI91X_ENABLE_BLE=1", "SL_SI91X_ENABLE_LITTLE_ENDIAN=1", + "RSI_BLE_MAX_NBR_PERIPHERALS=1", + "RSI_BLE_MAX_NBR_CENTRALS=1", ] } diff --git a/third_party/silabs/matter_support b/third_party/silabs/matter_support index 8f476b30f9..e313f2dc96 160000 --- a/third_party/silabs/matter_support +++ b/third_party/silabs/matter_support @@ -1 +1 @@ -Subproject commit 8f476b30f9c6041de334abadcdb6852ade77790e +Subproject commit e313f2dc9663da1ee4488eceba17dbff038f6a63 diff --git a/third_party/silabs/simplicity_sdk b/third_party/silabs/simplicity_sdk index a1a37fa7dd..aa5ce2e835 160000 --- a/third_party/silabs/simplicity_sdk +++ b/third_party/silabs/simplicity_sdk @@ -1 +1 @@ -Subproject commit a1a37fa7dda1f76ea70229aa4ffe2e47cb066edc +Subproject commit aa5ce2e835dfdce8c20fb828f27d3a261946f946 diff --git a/third_party/silabs/wifi_sdk b/third_party/silabs/wifi_sdk index e97a0ed00d..841ea3f7e0 160000 --- a/third_party/silabs/wifi_sdk +++ b/third_party/silabs/wifi_sdk @@ -1 +1 @@ -Subproject commit e97a0ed00ddda347a8a39e8276f470e1c5fea469 +Subproject commit 841ea3f7e0e8ce64a160ae2354e747260a61b1e9 diff --git a/third_party/silabs/wiseconnect-wifi-bt-sdk b/third_party/silabs/wiseconnect-wifi-bt-sdk index c3843e95e6..f94b83d050 160000 --- a/third_party/silabs/wiseconnect-wifi-bt-sdk +++ b/third_party/silabs/wiseconnect-wifi-bt-sdk @@ -1 +1 @@ -Subproject commit c3843e95e63f84e301a2727f7b3c26125818b53a +Subproject commit f94b83d050fe6200c5ec2dacfafa2edc92ad5ef3 From 88b66443a240cd2b181ab8c02b630fe3806b414e Mon Sep 17 00:00:00 2001 From: fesseha-eve <88329315+fessehaeve@users.noreply.github.com> Date: Tue, 20 Aug 2024 17:05:27 +0200 Subject: [PATCH 102/165] In TC-ICDM-3.4 make sure that a new session will be used after DUT reboots (#35092) * after DUT reboots make sure that a new session will be used fixes #34985 * updated comment to reflect closing the session than expiring it * re-establish session only when not in CI --- src/python_testing/TC_ICDM_3_4.py | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/python_testing/TC_ICDM_3_4.py b/src/python_testing/TC_ICDM_3_4.py index 6123053217..b062da0845 100644 --- a/src/python_testing/TC_ICDM_3_4.py +++ b/src/python_testing/TC_ICDM_3_4.py @@ -32,7 +32,8 @@ import time import chip.clusters as Clusters -from matter_testing_support import MatterBaseTest, TestStep, async_test_body, default_matter_test_main +from matter_testing_support import (MatterBaseTest, MatterStackState, MatterTestConfig, TestStep, async_test_body, + default_matter_test_main) from mobly import asserts logger = logging.getLogger(__name__) @@ -110,6 +111,16 @@ async def test_TC_ICDM_3_4(self): time.sleep(wait_time_reboot) self.step(3) + if not is_ci: + # since device has rebooted, force establishing a new CASE session by closing it + self.config = MatterTestConfig() + self.stack = MatterStackState(self.config) + devCtrl = self.stack.certificate_authorities[0].adminList[0].NewController( + nodeId=self.config.controller_node_id, + paaTrustStorePath=str(self.config.paa_trust_store_path), + catTags=self.config.controller_cat_tags + ) + devCtrl.CloseSession(self.dut_node_id) icdCounter2 = await self._read_icdm_attribute_expect_success(attribute=attributes.ICDCounter) asserts.assert_greater_equal(icdCounter2, icdCounter1, "ICDCounter have reboot is not greater or equal to the ICDCounter read before the reboot.") From 7f84a48ed903e51875d7418cb2da3537173c2ebc Mon Sep 17 00:00:00 2001 From: Jeff Tung <100387939+jtung-apple@users.noreply.github.com> Date: Tue, 20 Aug 2024 09:33:35 -0700 Subject: [PATCH 103/165] [Darwin] MTRDeviceController_XPC client protocol xpc interface fix (#35087) --- .../Framework/CHIP/MTRDeviceController_XPC.mm | 22 ++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm b/src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm index 157a38199f..49fd7c32f9 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm +++ b/src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm @@ -43,6 +43,26 @@ @implementation MTRDeviceController_XPC @synthesize uniqueIdentifier = _uniqueIdentifier; +- (NSXPCInterface *)_interfaceForClientProtocol +{ + NSXPCInterface * interface = [NSXPCInterface interfaceWithProtocol:@protocol(MTRXPCClientProtocol)]; + NSSet * allowedClasses = [NSSet setWithArray:@[ + [NSString class], [NSNumber class], [NSData class], [NSArray class], [NSDictionary class], [NSError class], [MTRAttributePath class] + ]]; + [interface setClasses:allowedClasses + forSelector:@selector(device:receivedAttributeReport:) + argumentIndex:1 + ofReply:NO]; + allowedClasses = [NSSet setWithArray:@[ + [NSString class], [NSNumber class], [NSData class], [NSArray class], [NSDictionary class], [NSError class], [MTREventPath class] + ]]; + [interface setClasses:allowedClasses + forSelector:@selector(device:receivedEventReport:) + argumentIndex:1 + ofReply:NO]; + return interface; +} + - (id)initWithUniqueIdentifier:(NSUUID *)UUID xpConnectionBlock:(NSXPCConnection * (^)(void) )connectionBlock { if (self = [super initForSubclasses]) { @@ -64,7 +84,7 @@ - (id)initWithUniqueIdentifier:(NSUUID *)UUID xpConnectionBlock:(NSXPCConnection if (self.xpcConnection) { self.xpcConnection.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(MTRXPCServerProtocol)]; - self.xpcConnection.exportedInterface = [NSXPCInterface interfaceWithProtocol:@protocol(MTRXPCClientProtocol)]; + self.xpcConnection.exportedInterface = [self _interfaceForClientProtocol]; self.xpcConnection.exportedObject = self; self.xpcConnection.interruptionHandler = ^{ From b367512f519e5e109346e81a0d84fd85cd9192f7 Mon Sep 17 00:00:00 2001 From: William Date: Tue, 20 Aug 2024 18:26:53 +0100 Subject: [PATCH 104/165] Fix SkipArea logic and removed the use of memcpy (#35075) * Updated the SkipArea serever handle to not error if the CurrentArea is null, according to the spec updates. * Replaced the use of memcpy with CopyCharSpanToMutableCharSpan. * Restyled by clang-format --------- Co-authored-by: Restyled.io --- .../service-area-cluster-objects.h | 28 +++++-------------- .../service-area-server.cpp | 9 ------ 2 files changed, 7 insertions(+), 30 deletions(-) diff --git a/src/app/clusters/service-area-server/service-area-cluster-objects.h b/src/app/clusters/service-area-server/service-area-cluster-objects.h index 1b040c53cd..66f2072070 100644 --- a/src/app/clusters/service-area-server/service-area-cluster-objects.h +++ b/src/app/clusters/service-area-server/service-area-cluster-objects.h @@ -110,9 +110,9 @@ struct AreaStructureWrapper : public chip::app::Clusters::ServiceArea::Structs:: { areaDesc.locationInfo.SetNonNull(); // Copy the name - auto sizeToCopy = std::min(sizeof(mAreaNameBuffer), locationName.size()); - memcpy(mAreaNameBuffer, locationName.data(), sizeToCopy); - areaDesc.locationInfo.Value().locationName = CharSpan(mAreaNameBuffer, sizeToCopy); + auto areaNameSpan = MutableCharSpan(mAreaNameBuffer, kAreaNameMaxSize); + CopyCharSpanToMutableCharSpan(locationName, areaNameSpan); + areaDesc.locationInfo.Value().locationName = CharSpan(areaNameSpan.data(), areaNameSpan.size()); areaDesc.locationInfo.Value().floorNumber = floorNumber; areaDesc.locationInfo.Value().areaType = areaType; @@ -320,24 +320,10 @@ struct MapStructureWrapper : public chip::app::Clusters::ServiceArea::Structs::M */ void Set(uint32_t aMapId, const CharSpan & aMapName) { - mapID = aMapId; - - if (aMapName.empty()) - { - name = CharSpan(mMapNameBuffer, 0); - } - else if (aMapName.size() > sizeof(mMapNameBuffer)) - { - // Save the truncated name that fits into available size. - memcpy(mMapNameBuffer, aMapName.data(), sizeof(mMapNameBuffer)); - name = CharSpan(mMapNameBuffer, sizeof(mMapNameBuffer)); - } - else - { - // Save full name. - memcpy(mMapNameBuffer, aMapName.data(), aMapName.size()); - name = CharSpan(mMapNameBuffer, aMapName.size()); - } + mapID = aMapId; + auto mapNameSpan = MutableCharSpan(mMapNameBuffer, kMapNameMaxSize); + CopyCharSpanToMutableCharSpan(aMapName, mapNameSpan); + name = CharSpan(mapNameSpan.data(), mapNameSpan.size()); } /** diff --git a/src/app/clusters/service-area-server/service-area-server.cpp b/src/app/clusters/service-area-server/service-area-server.cpp index a4c132df8a..baf56cd4fc 100644 --- a/src/app/clusters/service-area-server/service-area-server.cpp +++ b/src/app/clusters/service-area-server/service-area-server.cpp @@ -378,15 +378,6 @@ void Instance::HandleSkipAreaCmd(HandlerContext & ctx, const Commands::SkipArea: return; } - // If the CurrentArea attribute is null, the status should be set to InvalidInMode. - // If the Status field is not set to Success, or InvalidAreaList, the StatusText field SHALL include a vendor defined error - // description. - if (mCurrentArea.IsNull()) - { - exitResponse(SkipAreaStatus::kInvalidInMode, "Current Area attribute is null"_span); - return; - } - // have the device attempt to skip // If the Status field is not set to Success, or InvalidAreaList, the StatusText field SHALL include a vendor defined error // description. InvalidInMode | The received request cannot be handled due to the current mode of the device. (skipStatusText to From 1866812d8ad73c90652ddd70d98de9d8670c9953 Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Tue, 20 Aug 2024 15:17:05 -0400 Subject: [PATCH 105/165] Move delegate management into shared MTRDevice super-class. (#35084) * Move delegate management into shared MTRDevice super-class. MTRDevice_XPC and MTRDevice_Concrete can then share that code. * Address review comments, fix TAPI build. --- src/darwin/Framework/CHIP/MTRDevice.mm | 130 ++------- .../Framework/CHIP/MTRDevice_Concrete.mm | 246 +----------------- .../Framework/CHIP/MTRDevice_Internal.h | 78 +++++- src/darwin/Framework/CHIP/MTRDevice_XPC.mm | 11 + 4 files changed, 114 insertions(+), 351 deletions(-) diff --git a/src/darwin/Framework/CHIP/MTRDevice.mm b/src/darwin/Framework/CHIP/MTRDevice.mm index d8fc52b1a2..b2fc853fb9 100644 --- a/src/darwin/Framework/CHIP/MTRDevice.mm +++ b/src/darwin/Framework/CHIP/MTRDevice.mm @@ -64,43 +64,6 @@ // Disabling pending crashes #define ENABLE_CONNECTIVITY_MONITORING 0 -// Consider moving utility classes to their own file -#pragma mark - Utility Classes - -// container of MTRDevice delegate weak reference, its queue, and its interested paths for attribute reports -MTR_DIRECT_MEMBERS -@interface MTRDeviceDelegateInfo : NSObject { -@private - void * _delegatePointerValue; - __weak id _delegate; - dispatch_queue_t _queue; - NSArray * _Nullable _interestedPathsForAttributes; - NSArray * _Nullable _interestedPathsForEvents; -} - -// Array of interested cluster paths, attribute paths, or endpointID, for attribute report filtering. -@property (readonly, nullable) NSArray * interestedPathsForAttributes; - -// Array of interested cluster paths, attribute paths, or endpointID, for event report filtering. -@property (readonly, nullable) NSArray * interestedPathsForEvents; - -// Expose delegate -@property (readonly) id delegate; - -// Pointer value for logging purpose only -@property (readonly) void * delegatePointerValue; - -- (instancetype)initWithDelegate:(id)delegate queue:(dispatch_queue_t)queue interestedPathsForAttributes:(NSArray * _Nullable)interestedPathsForAttributes interestedPathsForEvents:(NSArray * _Nullable)interestedPathsForEvents; - -// Returns YES if delegate and queue are both non-null, and the block is scheduled to run. -- (BOOL)callDelegateWithBlock:(void (^)(id))block; - -#ifdef DEBUG -// Only used for unit test purposes - normal delegate should not expect or handle being called back synchronously. -- (BOOL)callDelegateSynchronouslyWithBlock:(void (^)(id))block; -#endif -@end - @implementation MTRDeviceDelegateInfo - (instancetype)initWithDelegate:(id)delegate queue:(dispatch_queue_t)queue interestedPathsForAttributes:(NSArray * _Nullable)interestedPathsForAttributes interestedPathsForEvents:(NSArray * _Nullable)interestedPathsForEvents { @@ -371,7 +334,6 @@ - (BOOL)isEqual:(id)object #define MTRDEVICE_SUBSCRIPTION_LATENCY_NEW_VALUE_WEIGHT (1.0 / 3.0) @interface MTRDevice () -@property (nonatomic, readonly) os_unfair_lock lock; // protects the caches and device state // protects against concurrent time updates by guarding timeUpdateScheduled flag which manages time updates scheduling, // and protects device calls to setUTCTime and setDSTOffset. This can't just be replaced with "lock", because the time // update code calls public APIs like readAttributeWithEndpointID:.. (which attempt to take "lock") while holding @@ -502,8 +464,6 @@ @implementation MTRDevice { // System time change observer reference id _systemTimeChangeObserverToken; - NSMutableSet * _delegates; - // Protects mutable state used by our description getter. This is a separate lock from "lock" // so that we don't need to worry about getting our description while holding "lock" (e.g due to // logging self). This lock _must_ be held narrowly, with no other lock acquisitions allowed @@ -526,10 +486,11 @@ @implementation MTRDevice { NSDate * _Nullable _lastSubscriptionFailureTimeForDescription; } -- (instancetype)initForSubclasses +- (instancetype)initForSubclassesWithNodeID:(NSNumber *)nodeID controller:(MTRDeviceController *)controller { if (self = [super init]) { - // nothing, as superclass of MTRDevice is NSObject + _lock = OS_UNFAIR_LOCK_INIT; + _delegates = [NSMutableSet set]; } return self; @@ -875,6 +836,8 @@ - (BOOL)_subscriptionsAllowed { os_unfair_lock_assert_owner(&self->_lock); + // TODO: XPC: This function and all its callsites should go away from this class. + // We should not allow a subscription for device controllers over XPC. return ![_deviceController isKindOfClass:MTRDeviceControllerOverXPC.class]; } @@ -923,34 +886,14 @@ - (void)_addDelegate:(id)delegate queue:(dispatch_queue_t)que [_delegates addObject:newDelegateInfo]; MTR_LOG("%@ added delegate info %@", self, newDelegateInfo); - __block BOOL shouldSetUpSubscription = [self _subscriptionsAllowed]; - - // For unit testing only. If this ever changes to not being for unit testing purposes, - // we would need to move the code outside of where we acquire the lock above. -#ifdef DEBUG - [self _callFirstDelegateSynchronouslyWithBlock:^(id testDelegate) { - if ([testDelegate respondsToSelector:@selector(unitTestShouldSetUpSubscriptionForDevice:)]) { - shouldSetUpSubscription = [testDelegate unitTestShouldSetUpSubscriptionForDevice:self]; - } - }]; -#endif + // Call hook to allow subclasses to act on delegate addition. + [self _delegateAdded]; +} - if (shouldSetUpSubscription) { - MTR_LOG("%@ - starting subscription setup", self); - // Record the time of first addDelegate call that triggers initial subscribe, and do not reset this value on subsequent addDelegate calls - if (!_initialSubscribeStart) { - _initialSubscribeStart = [NSDate now]; - } - if ([self _deviceUsesThread]) { - MTR_LOG(" => %@ - device is a thread device, scheduling in pool", self); - [self _scheduleSubscriptionPoolWork:^{ - std::lock_guard lock(self->_lock); - [self _setupSubscriptionWithReason:@"delegate is set and scheduled subscription is happening"]; - } inNanoseconds:0 description:@"MTRDevice setDelegate first subscription"]; - } else { - [self _setupSubscriptionWithReason:@"delegate is set and subscription is needed"]; - } - } +- (void)_delegateAdded +{ + // Nothing to do; this is a hook for subclasses. If that ever changes for + // some reason, subclasses need to start calling this hook on their super. } - (void)removeDelegate:(id)delegate @@ -962,7 +905,10 @@ - (void)removeDelegate:(id)delegate NSMutableSet * delegatesToRemove = [NSMutableSet set]; [self _iterateDelegatesWithBlock:^(MTRDeviceDelegateInfo * delegateInfo) { id strongDelegate = delegateInfo.delegate; - if (strongDelegate == delegate) { + if (!strongDelegate) { + [delegatesToRemove addObject:delegateInfo]; + MTR_LOG("%@ removing delegate info for nil delegate %p", self, delegateInfo.delegatePointerValue); + } else if (strongDelegate == delegate) { [delegatesToRemove addObject:delegateInfo]; MTR_LOG("%@ removing delegate info %@ for %p", self, delegateInfo, delegate); } @@ -976,45 +922,9 @@ - (void)removeDelegate:(id)delegate - (void)invalidate { - MTR_LOG("%@ invalidate", self); - - [_asyncWorkQueue invalidate]; - - os_unfair_lock_lock(&self->_timeSyncLock); - _timeUpdateScheduled = NO; - os_unfair_lock_unlock(&self->_timeSyncLock); - - os_unfair_lock_lock(&self->_lock); - - _state = MTRDeviceStateUnknown; + std::lock_guard lock(_lock); [_delegates removeAllObjects]; - - // Make sure we don't try to resubscribe if we have a pending resubscribe - // attempt, since we now have no delegate. - _reattemptingSubscription = NO; - - [_deviceController asyncDispatchToMatterQueue:^{ - MTR_LOG("%@ invalidate disconnecting ReadClient and SubscriptionCallback", self); - - // Destroy the read client and callback (has to happen on the Matter - // queue, to avoid deleting objects that are being referenced), to - // tear down the subscription. We will get no more callbacks from - // the subscription after this point. - std::lock_guard lock(self->_lock); - self->_currentReadClient = nullptr; - if (self->_currentSubscriptionCallback) { - delete self->_currentSubscriptionCallback; - } - self->_currentSubscriptionCallback = nullptr; - - [self _changeInternalState:MTRInternalDeviceStateUnsubscribed]; - } - errorHandler:nil]; - - [self _stopConnectivityMonitoring]; - - os_unfair_lock_unlock(&self->_lock); } - (void)nodeMayBeAdvertisingOperational @@ -1145,8 +1055,7 @@ - (BOOL)_delegateExists return [self _iterateDelegatesWithBlock:nil]; } -// Returns YES if any non-null delegates were found -- (BOOL)_iterateDelegatesWithBlock:(void(NS_NOESCAPE ^)(MTRDeviceDelegateInfo * delegateInfo)_Nullable)block +- (BOOL)_iterateDelegatesWithBlock:(void(NS_NOESCAPE ^ _Nullable)(MTRDeviceDelegateInfo * delegateInfo))block { os_unfair_lock_assert_owner(&self->_lock); @@ -1198,7 +1107,6 @@ - (BOOL)_callDelegatesWithBlock:(void (^)(id delegate))block #ifdef DEBUG // Only used for unit test purposes - normal delegate should not expect or handle being called back synchronously -// Returns YES if a delegate is called - (void)_callFirstDelegateSynchronouslyWithBlock:(void (^)(id delegate))block { os_unfair_lock_assert_owner(&self->_lock); @@ -2496,6 +2404,8 @@ - (void)unitTestResetSubscription // assume lock is held - (void)_setupSubscriptionWithReason:(NSString *)reason { + // TODO: XPC: This is not really called anymore in this class. Should + // remove this function and anything only reachable from it. os_unfair_lock_assert_owner(&self->_lock); if (![self _subscriptionsAllowed]) { diff --git a/src/darwin/Framework/CHIP/MTRDevice_Concrete.mm b/src/darwin/Framework/CHIP/MTRDevice_Concrete.mm index e22b0b8edf..c9f4b7f07d 100644 --- a/src/darwin/Framework/CHIP/MTRDevice_Concrete.mm +++ b/src/darwin/Framework/CHIP/MTRDevice_Concrete.mm @@ -74,84 +74,6 @@ @interface MTRDevice_Concrete () // Disabling pending crashes #define ENABLE_CONNECTIVITY_MONITORING 0 -// Consider moving utility classes to their own file -#pragma mark - Utility Classes - -// container of MTRDevice delegate weak reference, its queue, and its interested paths for attribute reports -MTR_DIRECT_MEMBERS -@interface MTRDeviceDelegateInfo_ConcreteCopy : NSObject { -@private - void * _delegatePointerValue; - __weak id _delegate; - dispatch_queue_t _queue; - NSArray * _Nullable _interestedPathsForAttributes; - NSArray * _Nullable _interestedPathsForEvents; -} - -// Array of interested cluster paths, attribute paths, or endpointID, for attribute report filtering. -@property (readonly, nullable) NSArray * interestedPathsForAttributes; - -// Array of interested cluster paths, attribute paths, or endpointID, for event report filtering. -@property (readonly, nullable) NSArray * interestedPathsForEvents; - -// Expose delegate -@property (readonly) id delegate; - -// Pointer value for logging purpose only -@property (readonly) void * delegatePointerValue; - -- (instancetype)initWithDelegate:(id)delegate queue:(dispatch_queue_t)queue interestedPathsForAttributes:(NSArray * _Nullable)interestedPathsForAttributes interestedPathsForEvents:(NSArray * _Nullable)interestedPathsForEvents; - -// Returns YES if delegate and queue are both non-null, and the block is scheduled to run. -- (BOOL)callDelegateWithBlock:(void (^)(id))block; - -#ifdef DEBUG -// Only used for unit test purposes - normal delegate should not expect or handle being called back synchronously. -- (BOOL)callDelegateSynchronouslyWithBlock:(void (^)(id))block; -#endif -@end - -@implementation MTRDeviceDelegateInfo_ConcreteCopy -- (instancetype)initWithDelegate:(id)delegate queue:(dispatch_queue_t)queue interestedPathsForAttributes:(NSArray * _Nullable)interestedPathsForAttributes interestedPathsForEvents:(NSArray * _Nullable)interestedPathsForEvents -{ - if (self = [super init]) { - _delegate = delegate; - _delegatePointerValue = (__bridge void *) delegate; - _queue = queue; - _interestedPathsForAttributes = [interestedPathsForAttributes copy]; - _interestedPathsForEvents = [interestedPathsForEvents copy]; - } - return self; -} - -- (NSString *)description -{ - return [NSString stringWithFormat:@"", self, _delegatePointerValue, static_cast(_interestedPathsForAttributes.count), static_cast(_interestedPathsForEvents.count)]; -} - -- (BOOL)callDelegateWithBlock:(void (^)(id))block -{ - id strongDelegate = _delegate; - VerifyOrReturnValue(strongDelegate, NO); - dispatch_async(_queue, ^{ - block(strongDelegate); - }); - return YES; -} - -#ifdef DEBUG -- (BOOL)callDelegateSynchronouslyWithBlock:(void (^)(id))block -{ - id strongDelegate = _delegate; - VerifyOrReturnValue(strongDelegate, NO); - - block(strongDelegate); - - return YES; -} -#endif -@end - /* BEGIN DRAGONS: Note methods here cannot be renamed, and are used by private callers, do not rename, remove or modify behavior here */ @interface NSObject (MatterPrivateForInternalDragonsDoNotFeed) @@ -281,7 +203,6 @@ typedef NS_ENUM(NSUInteger, MTRDeviceWorkItemDuplicateTypeID) { #define MTRDEVICE_SUBSCRIPTION_LATENCY_NEW_VALUE_WEIGHT (1.0 / 3.0) @interface MTRDevice_Concrete () -@property (nonatomic, readonly) os_unfair_lock lock; // protects the caches and device state // protects against concurrent time updates by guarding timeUpdateScheduled flag which manages time updates scheduling, // and protects device calls to setUTCTime and setDSTOffset. This can't just be replaced with "lock", because the time // update code calls public APIs like readAttributeWithEndpointID:.. (which attempt to take "lock") while holding @@ -412,8 +333,6 @@ @implementation MTRDevice_Concrete { // System time change observer reference id _systemTimeChangeObserverToken; - NSMutableSet * _delegates; - // Protects mutable state used by our description getter. This is a separate lock from "lock" // so that we don't need to worry about getting our description while holding "lock" (e.g due to // logging self). This lock _must_ be held narrowly, with no other lock acquisitions allowed @@ -450,8 +369,7 @@ @implementation MTRDevice_Concrete { - (instancetype)initWithNodeID:(NSNumber *)nodeID controller:(MTRDeviceController *)controller { // `super` was NSObject, is now MTRDevice. MTRDevice hides its `init` - if (self = [super initForSubclasses]) { - _lock = OS_UNFAIR_LOCK_INIT; + if (self = [super initForSubclassesWithNodeID:nodeID controller:controller]) { _timeSyncLock = OS_UNFAIR_LOCK_INIT; _descriptionLock = OS_UNFAIR_LOCK_INIT; _nodeID = [nodeID copy]; @@ -483,8 +401,6 @@ - (instancetype)initWithNodeID:(NSNumber *)nodeID controller:(MTRDeviceControlle }]; } - _delegates = [NSMutableSet set]; - MTR_LOG_DEBUG("%@ init with hex nodeID 0x%016llX", self, _nodeID.unsignedLongLongValue); } return self; @@ -792,49 +708,9 @@ - (BOOL)_subscriptionsAllowed return ![_deviceController isKindOfClass:MTRDeviceControllerOverXPC.class]; } -- (void)setDelegate:(id)delegate queue:(dispatch_queue_t)queue -{ - MTR_LOG("%@ setDelegate %@", self, delegate); - [self _addDelegate:delegate queue:queue interestedPathsForAttributes:nil interestedPathsForEvents:nil]; -} - -- (void)addDelegate:(id)delegate queue:(dispatch_queue_t)queue -{ - MTR_LOG("%@ addDelegate %@", self, delegate); - [self _addDelegate:delegate queue:queue interestedPathsForAttributes:nil interestedPathsForEvents:nil]; -} - -- (void)addDelegate:(id)delegate queue:(dispatch_queue_t)queue interestedPathsForAttributes:(NSArray * _Nullable)interestedPathsForAttributes interestedPathsForEvents:(NSArray * _Nullable)interestedPathsForEvents +- (void)_delegateAdded { - MTR_LOG("%@ addDelegate %@ with interested attribute paths %@ event paths %@", self, delegate, interestedPathsForAttributes, interestedPathsForEvents); - [self _addDelegate:delegate queue:queue interestedPathsForAttributes:interestedPathsForAttributes interestedPathsForEvents:interestedPathsForEvents]; -} - -- (void)_addDelegate:(id)delegate queue:(dispatch_queue_t)queue interestedPathsForAttributes:(NSArray * _Nullable)interestedPathsForAttributes interestedPathsForEvents:(NSArray * _Nullable)interestedPathsForEvents -{ - std::lock_guard lock(_lock); - - // Replace delegate info with the same delegate object, and opportunistically remove defunct delegate references - NSMutableSet * delegatesToRemove = [NSMutableSet set]; - for (MTRDeviceDelegateInfo_ConcreteCopy * delegateInfo in _delegates) { - id strongDelegate = delegateInfo.delegate; - if (!strongDelegate) { - [delegatesToRemove addObject:delegateInfo]; - MTR_LOG("%@ removing delegate info for nil delegate %p", self, delegateInfo.delegatePointerValue); - } else if (strongDelegate == delegate) { - [delegatesToRemove addObject:delegateInfo]; - MTR_LOG("%@ replacing delegate info for %p", self, delegate); - } - } - if (delegatesToRemove.count) { - NSUInteger oldDelegatesCount = _delegates.count; - [_delegates minusSet:delegatesToRemove]; - MTR_LOG("%@ addDelegate: removed %lu", self, static_cast(_delegates.count - oldDelegatesCount)); - } - - MTRDeviceDelegateInfo_ConcreteCopy * newDelegateInfo = [[MTRDeviceDelegateInfo_ConcreteCopy alloc] initWithDelegate:delegate queue:queue interestedPathsForAttributes:interestedPathsForAttributes interestedPathsForEvents:interestedPathsForEvents]; - [_delegates addObject:newDelegateInfo]; - MTR_LOG("%@ added delegate info %@", self, newDelegateInfo); + os_unfair_lock_assert_owner(&self->_lock); __block BOOL shouldSetUpSubscription = [self _subscriptionsAllowed]; @@ -866,27 +742,6 @@ - (void)_addDelegate:(id)delegate queue:(dispatch_queue_t)que } } -- (void)removeDelegate:(id)delegate -{ - MTR_LOG("%@ removeDelegate %@", self, delegate); - - std::lock_guard lock(_lock); - - NSMutableSet * delegatesToRemove = [NSMutableSet set]; - [self _iterateDelegatesWithBlock:^(MTRDeviceDelegateInfo_ConcreteCopy * delegateInfo) { - id strongDelegate = delegateInfo.delegate; - if (strongDelegate == delegate) { - [delegatesToRemove addObject:delegateInfo]; - MTR_LOG("%@ removing delegate info %@ for %p", self, delegateInfo, delegate); - } - }]; - if (delegatesToRemove.count) { - NSUInteger oldDelegatesCount = _delegates.count; - [_delegates minusSet:delegatesToRemove]; - MTR_LOG("%@ removeDelegate: removed %lu", self, static_cast(_delegates.count - oldDelegatesCount)); - } -} - - (void)invalidate { MTR_LOG("%@ invalidate", self); @@ -901,8 +756,6 @@ - (void)invalidate _state = MTRDeviceStateUnknown; - [_delegates removeAllObjects]; - // Make sure we don't try to resubscribe if we have a pending resubscribe // attempt, since we now have no delegate. _reattemptingSubscription = NO; @@ -928,6 +781,8 @@ - (void)invalidate [self _stopConnectivityMonitoring]; os_unfair_lock_unlock(&self->_lock); + + [super invalidate]; } - (void)nodeMayBeAdvertisingOperational @@ -1052,79 +907,6 @@ - (void)_readThroughSkipped errorHandler:nil]; } -- (BOOL)_delegateExists -{ - os_unfair_lock_assert_owner(&self->_lock); - return [self _iterateDelegatesWithBlock:nil]; -} - -// Returns YES if any non-null delegates were found -- (BOOL)_iterateDelegatesWithBlock:(void(NS_NOESCAPE ^)(MTRDeviceDelegateInfo_ConcreteCopy * delegateInfo)_Nullable)block -{ - os_unfair_lock_assert_owner(&self->_lock); - - if (!_delegates.count) { - MTR_LOG_DEBUG("%@ no delegates to iterate", self); - return NO; - } - - // Opportunistically remove defunct delegate references on every iteration - NSMutableSet * delegatesToRemove = nil; - for (MTRDeviceDelegateInfo_ConcreteCopy * delegateInfo in _delegates) { - id strongDelegate = delegateInfo.delegate; - if (strongDelegate) { - if (block) { - @autoreleasepool { - block(delegateInfo); - } - } - (void) strongDelegate; // ensure it stays alive - } else { - if (!delegatesToRemove) { - delegatesToRemove = [NSMutableSet set]; - } - [delegatesToRemove addObject:delegateInfo]; - } - } - - if (delegatesToRemove.count) { - [_delegates minusSet:delegatesToRemove]; - MTR_LOG("%@ _iterateDelegatesWithBlock: removed %lu remaining %lu", self, static_cast(delegatesToRemove.count), (unsigned long) static_cast(_delegates.count)); - } - - return (_delegates.count > 0); -} - -- (BOOL)_callDelegatesWithBlock:(void (^)(id delegate))block -{ - os_unfair_lock_assert_owner(&self->_lock); - - __block NSUInteger delegatesCalled = 0; - [self _iterateDelegatesWithBlock:^(MTRDeviceDelegateInfo_ConcreteCopy * delegateInfo) { - if ([delegateInfo callDelegateWithBlock:block]) { - delegatesCalled++; - } - }]; - - return (delegatesCalled > 0); -} - -#ifdef DEBUG -// Only used for unit test purposes - normal delegate should not expect or handle being called back synchronously -// Returns YES if a delegate is called -- (void)_callFirstDelegateSynchronouslyWithBlock:(void (^)(id delegate))block -{ - os_unfair_lock_assert_owner(&self->_lock); - - for (MTRDeviceDelegateInfo_ConcreteCopy * delegateInfo in _delegates) { - if ([delegateInfo callDelegateSynchronouslyWithBlock:block]) { - MTR_LOG("%@ _callFirstDelegateSynchronouslyWithBlock: successfully called %@", self, delegateInfo); - return; - } - } -} -#endif - - (void)_callDelegateDeviceCachePrimed { os_unfair_lock_assert_owner(&self->_lock); @@ -1944,7 +1726,7 @@ - (void)_reportAttributes:(NSArray *> *)attributes { os_unfair_lock_assert_owner(&self->_lock); if (attributes.count) { - [self _iterateDelegatesWithBlock:^(MTRDeviceDelegateInfo_ConcreteCopy * delegateInfo) { + [self _iterateDelegatesWithBlock:^(MTRDeviceDelegateInfo * delegateInfo) { // _iterateDelegatesWithBlock calls this with an autorelease pool, and so temporary filtered attributes reports don't bloat memory NSArray *> * filteredAttributes = [self _filteredAttributes:attributes forInterestedPaths:delegateInfo.interestedPathsForAttributes]; if (filteredAttributes.count) { @@ -2123,7 +1905,7 @@ - (void)_handleEventReport:(NSArray *> *)eventRepor } __block BOOL delegatesCalled = NO; - [self _iterateDelegatesWithBlock:^(MTRDeviceDelegateInfo_ConcreteCopy * delegateInfo) { + [self _iterateDelegatesWithBlock:^(MTRDeviceDelegateInfo * delegateInfo) { // _iterateDelegatesWithBlock calls this with an autorelease pool, and so temporary filtered event reports don't bloat memory NSArray *> * filteredEvents = [self _filteredEvents:reportToReturn forInterestedPaths:delegateInfo.interestedPathsForEvents]; if (filteredEvents.count) { @@ -2658,20 +2440,6 @@ - (NSUInteger)unitTestAttributesReportedSinceLastCheck _unitTestAttributesReportedSinceLastCheck = 0; return attributesReportedSinceLastCheck; } - -- (NSUInteger)unitTestNonnullDelegateCount -{ - std::lock_guard lock(self->_lock); - - NSUInteger nonnullDelegateCount = 0; - for (MTRDeviceDelegateInfo_ConcreteCopy * delegateInfo in _delegates) { - if (delegateInfo.delegate) { - nonnullDelegateCount++; - } - } - - return nonnullDelegateCount; -} #endif #pragma mark Device Interactions diff --git a/src/darwin/Framework/CHIP/MTRDevice_Internal.h b/src/darwin/Framework/CHIP/MTRDevice_Internal.h index 4c1b51f51c..b0cc25d11f 100644 --- a/src/darwin/Framework/CHIP/MTRDevice_Internal.h +++ b/src/darwin/Framework/CHIP/MTRDevice_Internal.h @@ -18,6 +18,7 @@ #import #import #import +#import #import "MTRAsyncWorkQueue.h" #import "MTRDefines_Internal.h" @@ -65,8 +66,68 @@ MTR_TESTABLE - (nullable instancetype)initWithDataVersion:(NSNumber * _Nullable)dataVersion attributes:(NSDictionary * _Nullable)attributes; @end -@interface MTRDevice () -- (instancetype)initForSubclasses; +// Consider moving utility classes to their own file +#pragma mark - Utility Classes + +/** + * container of MTRDevice delegate weak reference, its queue, and its interested + * paths for attribute reports. + */ +MTR_DIRECT_MEMBERS +@interface MTRDeviceDelegateInfo : NSObject { +@private + void * _delegatePointerValue; + __weak id _delegate; + dispatch_queue_t _queue; +} + +// Array of interested cluster paths, attribute paths, or endpointID, for attribute report filtering. +@property (readonly, nullable) NSArray * interestedPathsForAttributes; + +// Array of interested cluster paths, attribute paths, or endpointID, for event report filtering. +@property (readonly, nullable) NSArray * interestedPathsForEvents; + +// Expose delegate +@property (readonly) id delegate; + +// Pointer value for logging purpose only +@property (readonly) void * delegatePointerValue; + +- (instancetype)initWithDelegate:(id)delegate queue:(dispatch_queue_t)queue interestedPathsForAttributes:(NSArray * _Nullable)interestedPathsForAttributes interestedPathsForEvents:(NSArray * _Nullable)interestedPathsForEvents; + +// Returns YES if delegate and queue are both non-null, and the block is scheduled to run. +- (BOOL)callDelegateWithBlock:(void (^)(id))block; + +#ifdef DEBUG +// Only used for unit test purposes - normal delegate should not expect or handle being called back synchronously. +- (BOOL)callDelegateSynchronouslyWithBlock:(void (^)(id))block; +#endif +@end + +#pragma mark - MTRDevice internal extensions + +@interface MTRDevice () { + // Ivars needed to implement shared MTRDevice functionality. + // + // Unfortunately, we can't use @protected here, because that exports the + // symbols (so that subclasses that are not part of the framework can see + // them), but TAPI does not see these declarations, because they are in a + // project header. + // + // Using @package means that the symbols do not need to be exported, but + // unfortunately gets treated as @public from inside our framework, which + // means random other framework code can access these ivars. Hopefully the + // naming with leading '_' will make it clearer that random other code + // should not touch these. + // + // TODO: Figure out some way of doing @protected but still not exporting the symbol. +@package + // Lock that protects overall device state, including delegate storage. + os_unfair_lock _lock; + NSMutableSet * _delegates; +} + +- (instancetype)initForSubclassesWithNodeID:(NSNumber *)nodeID controller:(MTRDeviceController *)controller; - (instancetype)initWithNodeID:(NSNumber *)nodeID controller:(MTRDeviceController *)controller; // Called from MTRClusters for writes and commands @@ -123,6 +184,19 @@ MTR_TESTABLE // Returns whether this MTRDevice uses Thread for communication - (BOOL)deviceUsesThread; +#pragma mark - MTRDevice functionality to deal with delegates. + +// Returns YES if any non-null delegates were found +- (BOOL)_iterateDelegatesWithBlock:(void(NS_NOESCAPE ^ _Nullable)(MTRDeviceDelegateInfo * delegateInfo))block; + +- (BOOL)_delegateExists; + +#ifdef DEBUG +// Only used for unit test purposes - normal delegate should not expect or handle being called back synchronously +// Returns YES if a delegate is called +- (void)_callFirstDelegateSynchronouslyWithBlock:(void (^)(id delegate))block; +#endif + @end #pragma mark - Constants diff --git a/src/darwin/Framework/CHIP/MTRDevice_XPC.mm b/src/darwin/Framework/CHIP/MTRDevice_XPC.mm index 69eba5bc6f..b3c9e75f6a 100644 --- a/src/darwin/Framework/CHIP/MTRDevice_XPC.mm +++ b/src/darwin/Framework/CHIP/MTRDevice_XPC.mm @@ -82,6 +82,17 @@ @implementation MTRDevice_XPC +- (instancetype)initWithNodeID:(NSNumber *)nodeID controller:(MTRDeviceController *)controller +{ + // TODO: Verify that this is a valid MTRDeviceController_XPC? + + if (self = [super initForSubclassesWithNodeID:nodeID controller:controller]) { + // Nothing else to do, all set. + } + + return self; +} + #pragma mark - Client Callbacks (MTRDeviceDelegate) // required methods for MTRDeviceDelegates From 56ed10aca41af05c20632017a4d2dda9f318cdc7 Mon Sep 17 00:00:00 2001 From: Jeff Tung <100387939+jtung-apple@users.noreply.github.com> Date: Tue, 20 Aug 2024 12:53:27 -0700 Subject: [PATCH 106/165] [Darwin] MTRDevice_XPC delegate callbacks need to hold lock before _callDelegatesWithBlock (#35095) * [Darwin] MTRDevice_XPC delegate callbacks need to hold lock before _callDelegatesWithBlock * Add back _callDelegatesWithBlock to avoid conflict --- src/darwin/Framework/CHIP/MTRDevice.mm | 6 ++++++ src/darwin/Framework/CHIP/MTRDevice_Internal.h | 3 +++ src/darwin/Framework/CHIP/MTRDevice_XPC.mm | 12 ++++++------ 3 files changed, 15 insertions(+), 6 deletions(-) diff --git a/src/darwin/Framework/CHIP/MTRDevice.mm b/src/darwin/Framework/CHIP/MTRDevice.mm index b2fc853fb9..ff4a76147d 100644 --- a/src/darwin/Framework/CHIP/MTRDevice.mm +++ b/src/darwin/Framework/CHIP/MTRDevice.mm @@ -1105,6 +1105,12 @@ - (BOOL)_callDelegatesWithBlock:(void (^)(id delegate))block return (delegatesCalled > 0); } +- (BOOL)_lockAndCallDelegatesWithBlock:(void (^)(id delegate))block +{ + std::lock_guard lock(self->_lock); + return [self _callDelegatesWithBlock:block]; +} + #ifdef DEBUG // Only used for unit test purposes - normal delegate should not expect or handle being called back synchronously - (void)_callFirstDelegateSynchronouslyWithBlock:(void (^)(id delegate))block diff --git a/src/darwin/Framework/CHIP/MTRDevice_Internal.h b/src/darwin/Framework/CHIP/MTRDevice_Internal.h index b0cc25d11f..5a826dc987 100644 --- a/src/darwin/Framework/CHIP/MTRDevice_Internal.h +++ b/src/darwin/Framework/CHIP/MTRDevice_Internal.h @@ -144,6 +144,9 @@ MTR_DIRECT_MEMBERS - (BOOL)_callDelegatesWithBlock:(void (^)(id delegate))block; +// Called by MTRDevice_XPC to forward delegate callbacks +- (BOOL)_lockAndCallDelegatesWithBlock:(void (^)(id delegate))block; + /** * Like the public invokeCommandWithEndpointID but: * diff --git a/src/darwin/Framework/CHIP/MTRDevice_XPC.mm b/src/darwin/Framework/CHIP/MTRDevice_XPC.mm index b3c9e75f6a..7dfb8da370 100644 --- a/src/darwin/Framework/CHIP/MTRDevice_XPC.mm +++ b/src/darwin/Framework/CHIP/MTRDevice_XPC.mm @@ -99,7 +99,7 @@ - (instancetype)initWithNodeID:(NSNumber *)nodeID controller:(MTRDeviceControlle - (oneway void)device:(NSNumber *)nodeID stateChanged:(MTRDeviceState)state { MTR_LOG("%s", __PRETTY_FUNCTION__); - [self _callDelegatesWithBlock:^(id delegate) { + [self _lockAndCallDelegatesWithBlock:^(id delegate) { [delegate device:self stateChanged:state]; }]; } @@ -107,7 +107,7 @@ - (oneway void)device:(NSNumber *)nodeID stateChanged:(MTRDeviceState)state - (oneway void)device:(NSNumber *)nodeID receivedAttributeReport:(NSArray *> *)attributeReport { MTR_LOG("%s", __PRETTY_FUNCTION__); - [self _callDelegatesWithBlock:^(id delegate) { + [self _lockAndCallDelegatesWithBlock:^(id delegate) { [delegate device:self receivedAttributeReport:attributeReport]; }]; } @@ -115,7 +115,7 @@ - (oneway void)device:(NSNumber *)nodeID receivedAttributeReport:(NSArray *> *)eventReport { MTR_LOG("%s", __PRETTY_FUNCTION__); - [self _callDelegatesWithBlock:^(id delegate) { + [self _lockAndCallDelegatesWithBlock:^(id delegate) { [delegate device:self receivedEventReport:eventReport]; }]; } @@ -124,7 +124,7 @@ - (oneway void)device:(NSNumber *)nodeID receivedEventReport:(NSArray delegate) { + [self _lockAndCallDelegatesWithBlock:^(id delegate) { if ([delegate respondsToSelector:@selector(deviceBecameActive:)]) { [delegate deviceBecameActive:self]; } @@ -133,7 +133,7 @@ - (oneway void)deviceBecameActive:(NSNumber *)nodeID - (oneway void)deviceCachePrimed:(NSNumber *)nodeID { - [self _callDelegatesWithBlock:^(id delegate) { + [self _lockAndCallDelegatesWithBlock:^(id delegate) { if ([delegate respondsToSelector:@selector(deviceCachePrimed:)]) { [delegate deviceCachePrimed:self]; } @@ -142,7 +142,7 @@ - (oneway void)deviceCachePrimed:(NSNumber *)nodeID - (oneway void)deviceConfigurationChanged:(NSNumber *)nodeID { - [self _callDelegatesWithBlock:^(id delegate) { + [self _lockAndCallDelegatesWithBlock:^(id delegate) { if ([delegate respondsToSelector:@selector(deviceConfigurationChanged:)]) { [delegate deviceConfigurationChanged:self]; } From 068da6143c28c2235c35f03e68c6c8a6a47db532 Mon Sep 17 00:00:00 2001 From: Terence Hampson Date: Tue, 20 Aug 2024 16:20:45 -0400 Subject: [PATCH 107/165] Add plumbing that allows fabric-bridge endpoints to report CADMIN attr (#35076) --- .../fabric-bridge-common/BUILD.gn | 2 + .../BridgedAdministratorCommissioning.h | 58 +++++++++++++ .../include/BridgedDevice.h | 12 +++ .../src/BridgedAdministratorCommissioning.cpp | 81 +++++++++++++++++++ examples/fabric-bridge-app/linux/main.cpp | 3 + 5 files changed, 156 insertions(+) create mode 100644 examples/fabric-bridge-app/fabric-bridge-common/include/BridgedAdministratorCommissioning.h create mode 100644 examples/fabric-bridge-app/fabric-bridge-common/src/BridgedAdministratorCommissioning.cpp diff --git a/examples/fabric-bridge-app/fabric-bridge-common/BUILD.gn b/examples/fabric-bridge-app/fabric-bridge-common/BUILD.gn index 7f2fbcbbfe..157032f8f9 100644 --- a/examples/fabric-bridge-app/fabric-bridge-common/BUILD.gn +++ b/examples/fabric-bridge-app/fabric-bridge-common/BUILD.gn @@ -41,10 +41,12 @@ source_set("fabric-bridge-lib") { public_configs = [ ":config" ] sources = [ + "include/BridgedAdministratorCommissioning.h", "include/BridgedDevice.h", "include/BridgedDeviceBasicInformationImpl.h", "include/BridgedDeviceManager.h", "include/CHIPProjectAppConfig.h", + "src/BridgedAdministratorCommissioning.cpp", "src/BridgedDevice.cpp", "src/BridgedDeviceBasicInformationImpl.cpp", "src/BridgedDeviceManager.cpp", diff --git a/examples/fabric-bridge-app/fabric-bridge-common/include/BridgedAdministratorCommissioning.h b/examples/fabric-bridge-app/fabric-bridge-common/include/BridgedAdministratorCommissioning.h new file mode 100644 index 0000000000..06fd9026d4 --- /dev/null +++ b/examples/fabric-bridge-app/fabric-bridge-common/include/BridgedAdministratorCommissioning.h @@ -0,0 +1,58 @@ +/* + * 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 + +/** + * @brief CADMIN cluster implementation for handling attribute interactions of bridged device endpoints. + * + * The current Administrator Commissioning Cluster server's zap generated code will automatically + * register an Attribute Access Interface for the root node endpoint implementation. In order to + * properly respond to a read attribute for bridged devices we are representing, we override the + * currently registered Attribute Interface such that we are first to receive any read attribute + * request on Administrator Commissioning Cluster, and if it is not an endpoint for a device we + * are a bridge for we redirect to the default cluster server implementation of Administrator + * Commissioning Cluster. + */ +class BridgedAdministratorCommissioning : public chip::app::AttributeAccessInterface +{ +public: + // Register for the AdministratorCommissioning cluster on all endpoints. + BridgedAdministratorCommissioning() : + AttributeAccessInterface(chip::NullOptional, chip::app::Clusters::AdministratorCommissioning::Id) + {} + + CHIP_ERROR Init(); + + CHIP_ERROR Read(const chip::app::ConcreteReadAttributePath & aPath, chip::app::AttributeValueEncoder & aEncoder) override; + + // We do not allow writing to CADMIN attributes of a bridged device endpoint. We simply redirect + // write requests to the original attribute interface. + CHIP_ERROR Write(const chip::app::ConcreteDataAttributePath & aPath, chip::app::AttributeValueDecoder & aDecoder) override + { + VerifyOrDie(mOriginalAttributeInterface); + return mOriginalAttributeInterface->Write(aPath, aDecoder); + } + +private: + // If mOriginalAttributeInterface is removed from here, the class description needs to be updated + // to reflect this change. + chip::app::AttributeAccessInterface * mOriginalAttributeInterface = nullptr; +}; 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 3dab8d3b16..7081278f4d 100644 --- a/examples/fabric-bridge-app/fabric-bridge-common/include/BridgedDevice.h +++ b/examples/fabric-bridge-app/fabric-bridge-common/include/BridgedDevice.h @@ -18,6 +18,7 @@ #pragma once +#include #include #include @@ -40,6 +41,14 @@ class BridgedDevice std::string softwareVersionString; }; + struct AdminCommissioningAttributes + { + chip::app::Clusters::AdministratorCommissioning::CommissioningWindowStatusEnum commissioningWindowStatus = + chip::app::Clusters::AdministratorCommissioning::CommissioningWindowStatusEnum::kWindowNotOpen; + std::optional openerFabricIndex = std::nullopt; + std::optional openerVendorId = std::nullopt; + }; + BridgedDevice(chip::NodeId nodeId); virtual ~BridgedDevice() = default; @@ -59,6 +68,8 @@ class BridgedDevice [[nodiscard]] const BridgedAttributes & GetBridgedAttributes() const { return mAttributes; } void SetBridgedAttributes(const BridgedAttributes & value) { mAttributes = value; } + // TODO(#35077): Need to allow mAdminCommissioningAttributes to be set from fabric-admin. + const AdminCommissioningAttributes & GetAdminCommissioningAttributes() const { return mAdminCommissioningAttributes; } /// Convenience method to set just the unique id of a bridged device as it /// is one of the few attributes that is not always bulk-set @@ -73,4 +84,5 @@ class BridgedDevice chip::EndpointId mParentEndpointId = 0; BridgedAttributes mAttributes; + AdminCommissioningAttributes mAdminCommissioningAttributes; }; diff --git a/examples/fabric-bridge-app/fabric-bridge-common/src/BridgedAdministratorCommissioning.cpp b/examples/fabric-bridge-app/fabric-bridge-common/src/BridgedAdministratorCommissioning.cpp new file mode 100644 index 0000000000..c7bca223d9 --- /dev/null +++ b/examples/fabric-bridge-app/fabric-bridge-common/src/BridgedAdministratorCommissioning.cpp @@ -0,0 +1,81 @@ +/* + * 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 "BridgedAdministratorCommissioning.h" + +#include "BridgedDevice.h" +#include "BridgedDeviceManager.h" +#include + +using namespace chip; +using namespace chip::app; +using namespace chip::app::Clusters; +using namespace chip::app::Clusters::AdministratorCommissioning; + +CHIP_ERROR BridgedAdministratorCommissioning::Init() +{ + // We expect initialization after all embr plugin clusters initialization. This allows us to unregister + // the existing AccessAttributeInterface for AdministratorCommissioning and register ourselves, ensuring + // we get the callback for reading attribute. If the read is not intended for a bridged device we will + // forward it to the original attribute interface that we are unregistering. + mOriginalAttributeInterface = AttributeAccessInterfaceRegistry::Instance().Get(kRootEndpointId, AdministratorCommissioning::Id); + VerifyOrReturnError(mOriginalAttributeInterface, CHIP_ERROR_INTERNAL); + AttributeAccessInterfaceRegistry::Instance().Unregister(mOriginalAttributeInterface); + VerifyOrDie(AttributeAccessInterfaceRegistry::Instance().Register(this)); + return CHIP_NO_ERROR; +} + +CHIP_ERROR BridgedAdministratorCommissioning::Read(const ConcreteReadAttributePath & aPath, AttributeValueEncoder & aEncoder) +{ + VerifyOrDie(aPath.mClusterId == Clusters::AdministratorCommissioning::Id); + EndpointId endpointId = aPath.mEndpointId; + BridgedDevice * device = BridgeDeviceMgr().GetDevice(endpointId); + + if (!device) + { + VerifyOrDie(mOriginalAttributeInterface); + return mOriginalAttributeInterface->Read(aPath, aEncoder); + } + auto attr = device->GetAdminCommissioningAttributes(); + + switch (aPath.mAttributeId) + { + case Attributes::WindowStatus::Id: { + return aEncoder.Encode(attr.commissioningWindowStatus); + } + case Attributes::AdminFabricIndex::Id: { + DataModel::Nullable encodeableFabricIndex = DataModel::NullNullable; + if (attr.openerFabricIndex.has_value()) + { + encodeableFabricIndex.SetNonNull(attr.openerFabricIndex.value()); + } + return aEncoder.Encode(encodeableFabricIndex); + } + case Attributes::AdminVendorId::Id: { + DataModel::Nullable encodeableVendorId = DataModel::NullNullable; + if (attr.openerVendorId.has_value()) + { + encodeableVendorId.SetNonNull(attr.openerVendorId.value()); + } + return aEncoder.Encode(encodeableVendorId); + } + default: + break; + } + + return CHIP_NO_ERROR; +} diff --git a/examples/fabric-bridge-app/linux/main.cpp b/examples/fabric-bridge-app/linux/main.cpp index 3b65024210..eeb290210c 100644 --- a/examples/fabric-bridge-app/linux/main.cpp +++ b/examples/fabric-bridge-app/linux/main.cpp @@ -18,6 +18,7 @@ #include +#include "BridgedAdministratorCommissioning.h" #include "BridgedDevice.h" #include "BridgedDeviceBasicInformationImpl.h" #include "BridgedDeviceManager.h" @@ -234,6 +235,7 @@ void BridgedDeviceInformationCommandHandler::InvokeCommand(HandlerContext & hand handlerContext.mCommandHandler.AddStatus(handlerContext.mRequestPath, status); } +BridgedAdministratorCommissioning gBridgedAdministratorCommissioning; AdministratorCommissioningCommandHandler gAdministratorCommissioningCommandHandler; BridgedDeviceInformationCommandHandler gBridgedDeviceInformationCommandHandler; @@ -258,6 +260,7 @@ void ApplicationInit() pollingThread.detach(); BridgeDeviceMgr().Init(); + VerifyOrDie(gBridgedAdministratorCommissioning.Init() == CHIP_NO_ERROR); VerifyOrDieWithMsg(CommissionerControlInit() == CHIP_NO_ERROR, NotSpecified, "Failed to initialize Commissioner Control Server"); From 23903bdffc806788c1f5484ac9acecd8a298183c Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Tue, 20 Aug 2024 18:51:02 -0400 Subject: [PATCH 108/165] Make the MTRDevice ivars protected. (#35101) It seems like by default we have the following visibility options here: @private - subclasses can't touch, not workable. @public - anyone can touch, not desirable. @package - @public inside Matter.framework, @private ouside it. Does not export the symbols, but anyone inside Matter.framework can touch. @protected - only subclasses can touch, but exports the symbols in case we have out-of-framework subclasses who want to touch it. Since the declarations are in a project header that TAPI does not know about in release builds, we get complaints about mismatches between what's declared public and what's exported. What we would really want here is "@protected inside Matter.framework, @private ouside it", but that does not exist. So this switches to @protected, and uses linker arguments to not export the symbols in release builds. Since the header itself is not public, this accomplishes the same goal. In debug builds, we do expose project headers to TAPI, hence there we want to keep exporting the symbols. The linker arguments just prevent exporting all ivar symbols, since we shouldn't be exporting any of those anyway. --- src/darwin/Framework/CHIP/MTRDevice_Internal.h | 15 +-------------- .../Framework/Matter.xcodeproj/project.pbxproj | 2 ++ 2 files changed, 3 insertions(+), 14 deletions(-) diff --git a/src/darwin/Framework/CHIP/MTRDevice_Internal.h b/src/darwin/Framework/CHIP/MTRDevice_Internal.h index 5a826dc987..bce5abfdfe 100644 --- a/src/darwin/Framework/CHIP/MTRDevice_Internal.h +++ b/src/darwin/Framework/CHIP/MTRDevice_Internal.h @@ -108,20 +108,7 @@ MTR_DIRECT_MEMBERS @interface MTRDevice () { // Ivars needed to implement shared MTRDevice functionality. - // - // Unfortunately, we can't use @protected here, because that exports the - // symbols (so that subclasses that are not part of the framework can see - // them), but TAPI does not see these declarations, because they are in a - // project header. - // - // Using @package means that the symbols do not need to be exported, but - // unfortunately gets treated as @public from inside our framework, which - // means random other framework code can access these ivars. Hopefully the - // naming with leading '_' will make it clearer that random other code - // should not touch these. - // - // TODO: Figure out some way of doing @protected but still not exporting the symbol. -@package +@protected // Lock that protects overall device state, including delegate storage. os_unfair_lock _lock; NSMutableSet * _delegates; diff --git a/src/darwin/Framework/Matter.xcodeproj/project.pbxproj b/src/darwin/Framework/Matter.xcodeproj/project.pbxproj index 3a5968072d..efafd27d28 100644 --- a/src/darwin/Framework/Matter.xcodeproj/project.pbxproj +++ b/src/darwin/Framework/Matter.xcodeproj/project.pbxproj @@ -2565,6 +2565,7 @@ "-Wl,-unexported_symbol,\"___*\"", "-Wl,-unexported_symbol,\"__Unwind_*\"", "-Wl,-unexported_symbol,\"_unw_*\"", + "-Wl,-unexported_symbol,\"_OBJC_IVAR_*\"", "-Wl,-hidden-lCHIP", ); "OTHER_LDFLAGS[sdk=macosx*]" = ( @@ -2583,6 +2584,7 @@ "-Wl,-unexported_symbol,\"___*\"", "-Wl,-unexported_symbol,\"__Unwind_*\"", "-Wl,-unexported_symbol,\"_unw_*\"", + "-Wl,-unexported_symbol,\"_OBJC_IVAR_*\"", "-Wl,-hidden-lCHIP", ); PRODUCT_BUNDLE_IDENTIFIER = com.csa.matter; From bb26a589c7184eeb137ba93a73e212424e1f0b4d Mon Sep 17 00:00:00 2001 From: C Freeman Date: Tue, 20 Aug 2024 19:28:44 -0400 Subject: [PATCH 109/165] IDM-12.1: Also dump to log (#35098) * IDM-12.1: Also dump to log * simplify print command --- src/python_testing/TC_DeviceBasicComposition.py | 13 ++++++++++++- src/python_testing/basic_composition_support.py | 11 ++++++++--- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/src/python_testing/TC_DeviceBasicComposition.py b/src/python_testing/TC_DeviceBasicComposition.py index 7af7b86554..72e6e3e241 100644 --- a/src/python_testing/TC_DeviceBasicComposition.py +++ b/src/python_testing/TC_DeviceBasicComposition.py @@ -775,7 +775,18 @@ def test_TC_IDM_12_1(self): software_version = self.endpoints[0][Clusters.BasicInformation][Clusters.BasicInformation.Attributes.SoftwareVersion] filename = f'device_dump_0x{vid:04X}_0x{pid:04X}_{software_version}.json' dump_device_composition_path = self.user_params.get("dump_device_composition_path", filename) - self.dump_wildcard(dump_device_composition_path) + json_str, txt_str = self.dump_wildcard(dump_device_composition_path) + + # Structured dump so we can pull these back out of the logs + def log_structured_data(start_tag: str, dump_string): + lines = dump_string.splitlines() + logging.info(f'{start_tag}BEGIN ({len(lines)} lines)====') + for line in lines: + logging.info(f'{start_tag}{line}') + logging.info(f'{start_tag}END ====') + + log_structured_data('==== json: ', json_str) + log_structured_data('==== txt: ', txt_str) if __name__ == "__main__": diff --git a/src/python_testing/basic_composition_support.py b/src/python_testing/basic_composition_support.py index 678c249d0a..e25de55c04 100644 --- a/src/python_testing/basic_composition_support.py +++ b/src/python_testing/basic_composition_support.py @@ -23,7 +23,7 @@ import pathlib import sys import typing -from pprint import pprint +from pprint import pformat, pprint from typing import Any, Optional import chip.clusters.ClusterObjects @@ -105,15 +105,20 @@ async def connect_over_pase(self, dev_ctrl): asserts.assert_equal(len(setupCode), 1, "Require one of either --qr-code or --manual-code.") await dev_ctrl.FindOrEstablishPASESession(setupCode[0], self.dut_node_id) - def dump_wildcard(self, dump_device_composition_path: typing.Optional[str]): + def dump_wildcard(self, dump_device_composition_path: typing.Optional[str]) -> tuple[str, str]: + """ Dumps a json and a txt file of the attribute wildcard for this device if the dump_device_composition_path is supplied. + Returns the json and txt as strings. + """ node_dump_dict = {endpoint_id: MatterTlvToJson(self.endpoints_tlv[endpoint_id]) for endpoint_id in self.endpoints_tlv} - logging.debug(f"Raw TLV contents of Node: {json.dumps(node_dump_dict, indent=2)}") + json_dump_string = json.dumps(node_dump_dict, indent=2) + logging.debug(f"Raw TLV contents of Node: {json_dump_string}") if dump_device_composition_path is not None: with open(pathlib.Path(dump_device_composition_path).with_suffix(".json"), "wt+") as outfile: json.dump(node_dump_dict, outfile, indent=2) with open(pathlib.Path(dump_device_composition_path).with_suffix(".txt"), "wt+") as outfile: pprint(self.endpoints, outfile, indent=1, width=200, compact=True) + return (json_dump_string, pformat(self.endpoints, indent=1, width=200, compact=True)) async def setup_class_helper(self, default_to_pase: bool = True): dev_ctrl = self.default_controller From c84593f2de5e4c90ac6e256b2424dc3e14dd7a1e Mon Sep 17 00:00:00 2001 From: Terence Hampson Date: Tue, 20 Aug 2024 19:57:05 -0400 Subject: [PATCH 110/165] Address post merge comment (#35103) * Address post merge comment * Quick fix --- .../src/BridgedAdministratorCommissioning.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) 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 c7bca223d9..a0d87cbb3b 100644 --- a/examples/fabric-bridge-app/fabric-bridge-common/src/BridgedAdministratorCommissioning.cpp +++ b/examples/fabric-bridge-app/fabric-bridge-common/src/BridgedAdministratorCommissioning.cpp @@ -28,9 +28,9 @@ using namespace chip::app::Clusters::AdministratorCommissioning; CHIP_ERROR BridgedAdministratorCommissioning::Init() { - // We expect initialization after all embr plugin clusters initialization. This allows us to unregister - // the existing AccessAttributeInterface for AdministratorCommissioning and register ourselves, ensuring - // we get the callback for reading attribute. If the read is not intended for a bridged device we will + // We expect initialization after emberAfInit(). This allows us to unregister the existing + // AccessAttributeInterface for AdministratorCommissioning and register ourselves, ensuring we + // get the callback for reading attribute. If the read is not intended for a bridged device we will // forward it to the original attribute interface that we are unregistering. mOriginalAttributeInterface = AttributeAccessInterfaceRegistry::Instance().Get(kRootEndpointId, AdministratorCommissioning::Id); VerifyOrReturnError(mOriginalAttributeInterface, CHIP_ERROR_INTERNAL); From 17cb1d9a557dba1d7434630bfc1a9a5c87c825da Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Tue, 20 Aug 2024 21:03:34 -0400 Subject: [PATCH 111/165] Update default file header for Matter.framework files. (#35106) Removes blank line at the top, makes copyright year be saner. --- .../Darwin.xcworkspace/xcshareddata/IDETemplateMacros.plist | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/darwin/Darwin.xcworkspace/xcshareddata/IDETemplateMacros.plist b/src/darwin/Darwin.xcworkspace/xcshareddata/IDETemplateMacros.plist index 861a74eaf6..03de09ad22 100644 --- a/src/darwin/Darwin.xcworkspace/xcshareddata/IDETemplateMacros.plist +++ b/src/darwin/Darwin.xcworkspace/xcshareddata/IDETemplateMacros.plist @@ -3,9 +3,8 @@ FILEHEADER - -/** - * Copyright (c) 2023 Project CHIP Authors + /** + * 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. From ec029c1e37d3d8d0133a4f08d3cbbfd60dfb7a8a Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Tue, 20 Aug 2024 21:05:40 -0400 Subject: [PATCH 112/165] Add availability annotations to new XPC protocols. (#35107) --- .../Framework/CHIP/XPC Protocol/MTRXPCClientProtocol.h | 7 +++++-- .../Framework/CHIP/XPC Protocol/MTRXPCServerProtocol.h | 8 ++++++-- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/src/darwin/Framework/CHIP/XPC Protocol/MTRXPCClientProtocol.h b/src/darwin/Framework/CHIP/XPC Protocol/MTRXPCClientProtocol.h index a571ebc07a..3e276eb25f 100644 --- a/src/darwin/Framework/CHIP/XPC Protocol/MTRXPCClientProtocol.h +++ b/src/darwin/Framework/CHIP/XPC Protocol/MTRXPCClientProtocol.h @@ -1,6 +1,5 @@ -// /** - * Copyright (c) 2023 Project CHIP Authors + * 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. @@ -15,10 +14,12 @@ * limitations under the License. */ +#import #import // for MTRDeviceState NS_ASSUME_NONNULL_BEGIN +MTR_NEWLY_AVAILABLE @protocol MTRXPCClientProtocol_MTRDevice - (oneway void)device:(NSNumber *)nodeID stateChanged:(MTRDeviceState)state; - (oneway void)device:(NSNumber *)nodeID receivedAttributeReport:(NSArray *> *)attributeReport; @@ -28,6 +29,7 @@ NS_ASSUME_NONNULL_BEGIN - (oneway void)deviceConfigurationChanged:(NSNumber *)nodeID; @end +MTR_NEWLY_AVAILABLE @protocol MTRXPCClientProtocol_MTRDeviceController // Not Supported via XPC //- (oneway void)controller:(NSUUID *)controller statusUpdate:(MTRCommissioningStatus)status; @@ -36,6 +38,7 @@ NS_ASSUME_NONNULL_BEGIN //- (oneway void)controller:(NSUUID *)controller readCommissioningInfo:(MTRProductIdentity *)info; @end +MTR_NEWLY_AVAILABLE @protocol MTRXPCClientProtocol @end diff --git a/src/darwin/Framework/CHIP/XPC Protocol/MTRXPCServerProtocol.h b/src/darwin/Framework/CHIP/XPC Protocol/MTRXPCServerProtocol.h index 5d619453b5..1eebb03965 100644 --- a/src/darwin/Framework/CHIP/XPC Protocol/MTRXPCServerProtocol.h +++ b/src/darwin/Framework/CHIP/XPC Protocol/MTRXPCServerProtocol.h @@ -1,6 +1,5 @@ -// /** - * Copyright (c) 2023 Project CHIP Authors + * 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. @@ -15,8 +14,11 @@ * limitations under the License. */ +#import + NS_ASSUME_NONNULL_BEGIN +MTR_NEWLY_AVAILABLE @protocol MTRXPCServerProtocol_MTRDevice - (oneway void)deviceController:(NSUUID *)controller nodeID:(NSNumber *)nodeID getStateWithReply:(void (^)(MTRDeviceState state))reply; @@ -45,6 +47,7 @@ NS_ASSUME_NONNULL_BEGIN // - (oneway void)downloadLogOfType:(MTRDiagnosticLogType)type nodeID:(NSNumber *)nodeID timeout:(NSTimeInterval)timeout completion:(void (^)(NSURL * _Nullable url, NSError * _Nullable error))completion; @end +MTR_NEWLY_AVAILABLE @protocol MTRXPCServerProtocol_MTRDeviceController - (oneway void)deviceController:(NSUUID *)controller getIsRunningWithReply:(void (^)(BOOL response))reply; @@ -69,6 +72,7 @@ NS_ASSUME_NONNULL_BEGIN @end +MTR_NEWLY_AVAILABLE @protocol MTRXPCServerProtocol - (oneway void)deviceController:(NSUUID *)controller checkInWithContext:(NSDictionary *)context; @end From 927c81857ae9288ffab4ffbd529979412f8cc5f1 Mon Sep 17 00:00:00 2001 From: C Freeman Date: Tue, 20 Aug 2024 21:31:40 -0400 Subject: [PATCH 113/165] TC-IDM-10.2: Add check for MACL (#35086) * TC-IDM-10.2: Add check for MACL Test: unit tests. Note this has not been tested against the example app as it is still under development. * Update src/python_testing/TC_DeviceConformance.py Co-authored-by: Tennessee Carmel-Veilleux * Update src/python_testing/TestConformanceTest.py --------- Co-authored-by: Tennessee Carmel-Veilleux --- .github/workflows/tests.yaml | 1 + src/python_testing/TC_DeviceConformance.py | 23 ++++ src/python_testing/TestConformanceTest.py | 131 +++++++++++++++++++++ src/python_testing/execute_python_tests.py | 1 + 4 files changed, 156 insertions(+) create mode 100644 src/python_testing/TestConformanceTest.py diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml index dbbda0aa36..d60ffb185d 100644 --- a/.github/workflows/tests.yaml +++ b/.github/workflows/tests.yaml @@ -514,6 +514,7 @@ jobs: 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' + scripts/run_in_python_env.sh out/venv 'python3 ./src/python_testing/TestConformanceTest.py' scripts/run_in_python_env.sh out/venv 'python3 ./src/python_testing/TestChoiceConformanceSupport.py' scripts/run_in_python_env.sh out/venv 'python3 ./src/python_testing/test_testing/test_IDM_10_4.py' scripts/run_in_python_env.sh out/venv 'python3 ./src/python_testing/test_testing/test_TC_SC_7_1.py' diff --git a/src/python_testing/TC_DeviceConformance.py b/src/python_testing/TC_DeviceConformance.py index 3cc57e2b01..611d7f54a8 100644 --- a/src/python_testing/TC_DeviceConformance.py +++ b/src/python_testing/TC_DeviceConformance.py @@ -50,6 +50,22 @@ async def setup_class_helper(self): self.xml_device_types, problems = build_xml_device_types() self.problems.extend(problems) + def _get_device_type_id(self, device_type_name: str) -> int: + id = [id for id, dt in self.xml_device_types.items() if dt.name.lower() == device_type_name.lower()] + if len(id) != 1: + self.fail_current_test(f"Unable to find {device_type_name} device type") + return id[0] + + def _has_nim(self): + nim_id = self._get_device_type_id('network infrastructure manager') + for endpoint in self.endpoints_tlv.values(): + desc = Clusters.Descriptor + device_types = [dt.deviceType for dt in endpoint[desc.id][desc.Attributes.DeviceTypeList.attribute_id]] + if nim_id in device_types: + # TODO: it's unclear if this needs to be present on every endpoint. Right now, this assumes one is sufficient. + return True + return False + def check_conformance(self, ignore_in_progress: bool, is_ci: bool): problems = [] success = True @@ -125,6 +141,13 @@ def record_warning(location, problem): for f in feature_masks: location = AttributePathLocation(endpoint_id=endpoint_id, cluster_id=cluster_id, attribute_id=GlobalAttributeIds.FEATURE_MAP_ID) + if cluster_id == Clusters.AccessControl.id and f == Clusters.AccessControl.Bitmaps.Feature.kManagedDevice: + # Managed ACL is treated as a special case because it is only allowed if other endpoints support NIM and disallowed otherwise. + if not self._has_nim(): + record_error( + location=location, problem="MACL feature is disallowed if the Network Infrastructure Manager device type is not present") + continue + if f not in self.xml_clusters[cluster_id].features.keys(): record_error(location=location, problem=f'Unknown feature with mask 0x{f:02x}') continue diff --git a/src/python_testing/TestConformanceTest.py b/src/python_testing/TestConformanceTest.py new file mode 100644 index 0000000000..a656e228bf --- /dev/null +++ b/src/python_testing/TestConformanceTest.py @@ -0,0 +1,131 @@ +# +# 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. +# + +from typing import Any + +import chip.clusters as Clusters +from conformance_support import ConformanceDecision +from global_attribute_ids import GlobalAttributeIds +from matter_testing_support import MatterBaseTest, async_test_body, default_matter_test_main +from mobly import asserts +from spec_parsing_support import build_xml_clusters, build_xml_device_types +from TC_DeviceConformance import DeviceConformanceTests + + +def is_mandatory(conformance): + return conformance(0, [], []).decision == ConformanceDecision.MANDATORY + + +class TestConformanceSupport(MatterBaseTest, DeviceConformanceTests): + def setup_class(self): + self.xml_clusters, self.problems = build_xml_clusters() + self.xml_device_types, problems = build_xml_device_types() + self.problems.extend(problems) + + def _create_minimal_cluster(self, cluster_id: int) -> dict[int, Any]: + attrs = {} + attrs[GlobalAttributeIds.FEATURE_MAP_ID] = 0 + + mandatory_attributes = [id for id, a in self.xml_clusters[cluster_id].attributes.items() if is_mandatory(a.conformance)] + for m in mandatory_attributes: + # dummy versions - we're not using the values in this test + attrs[m] = 0 + attrs[GlobalAttributeIds.ATTRIBUTE_LIST_ID] = mandatory_attributes + mandatory_accepted_commands = [id for id, a in self.xml_clusters[cluster_id].accepted_commands.items() + if is_mandatory(a.conformance)] + attrs[GlobalAttributeIds.ACCEPTED_COMMAND_LIST_ID] = mandatory_accepted_commands + mandatory_generated_commands = [id for id, a in self.xml_clusters[cluster_id].generated_commands.items() + if is_mandatory(a.conformance)] + attrs[GlobalAttributeIds.GENERATED_COMMAND_LIST_ID] = mandatory_generated_commands + attrs[GlobalAttributeIds.CLUSTER_REVISION_ID] = self.xml_clusters[cluster_id].revision + return attrs + + def _create_minimal_dt(self, device_type_id: int) -> dict[int, dict[int, Any]]: + ''' Creates the internals of an endpoint_tlv with the minimal set of clusters, with the minimal set of attributes and commands. Global attributes only. + Does NOT take into account overrides yet. + ''' + endpoint_tlv = {} + required_servers = [id for id, c in self.xml_device_types[device_type_id].server_clusters.items() + if is_mandatory(c.conformance)] + required_clients = [id for id, c in self.xml_device_types[device_type_id].client_clusters.items() + if is_mandatory(c.conformance)] + device_type_revision = self.xml_device_types[device_type_id].revision + + for s in required_servers: + endpoint_tlv[s] = self._create_minimal_cluster(s) + + # Descriptor + attr = Clusters.Descriptor.Attributes + attrs = {} + attrs[attr.FeatureMap.attribute_id] = 0 + attrs[attr.AcceptedCommandList.attribute_id] = [] + attrs[attr.GeneratedCommandList.attribute_id] = [] + attrs[attr.ClusterRevision.attribute_id] = self.xml_clusters[Clusters.Descriptor.id].revision + attrs[attr.DeviceTypeList.attribute_id] = [ + Clusters.Descriptor.Structs.DeviceTypeStruct(deviceType=device_type_id, revision=device_type_revision)] + attrs[attr.ServerList.attribute_id] = required_servers + attrs[attr.ClientList.attribute_id] = required_clients + attrs[attr.PartsList.attribute_id] = [] + attrs[attr.AttributeList.attribute_id] = [] + attrs[attr.AttributeList.attribute_id] = list(attrs.keys()) + + endpoint_tlv[Clusters.Descriptor.id] = attrs + return endpoint_tlv + + def add_macl(self, root_endpoint: dict[int, dict[int, Any]]): + ac = Clusters.AccessControl + root_endpoint[ac.id][ac.Attributes.FeatureMap.attribute_id] = ac.Bitmaps.Feature.kManagedDevice + root_endpoint[ac.id][ac.Attributes.Arl.attribute_id] = [] + root_endpoint[ac.id][ac.Attributes.CommissioningARL.attribute_id] = [] + root_endpoint[ac.id][ac.Attributes.AttributeList.attribute_id].extend([ + ac.Attributes.Arl.attribute_id, ac.Attributes.CommissioningARL.attribute_id]) + root_endpoint[ac.id][ac.Attributes.AcceptedCommandList.attribute_id].append(ac.Commands.ReviewFabricRestrictions.command_id) + root_endpoint[ac.id][ac.Attributes.GeneratedCommandList.attribute_id].append( + ac.Commands.ReviewFabricRestrictionsResponse.command_id) + + @async_test_body + async def test_macl_handling(self): + nim_id = self._get_device_type_id('network infrastructure manager') + root_node_id = self._get_device_type_id('root node') + on_off_id = self._get_device_type_id('On/Off Light') + + root = self._create_minimal_dt(device_type_id=root_node_id) + nim = self._create_minimal_dt(device_type_id=nim_id) + self.endpoints_tlv = {0: root, 1: nim} + asserts.assert_true(self._has_nim(), "Did not find NIM in generated device") + + success, problems = self.check_conformance(ignore_in_progress=False, is_ci=False) + self.problems.extend(problems) + asserts.assert_true(success, "Unexpected failure parsing minimal dt") + + self.add_macl(root) + # A MACL is allowed when there is a NIM, so this should succeed as well + success, problems = self.check_conformance(ignore_in_progress=False, is_ci=False) + self.problems.extend(problems) + asserts.assert_true(success, "Unexpected failure with NIM and MACL") + + # A MACL is not allowed when there is no NIM + self.endpoints_tlv[1] = self._create_minimal_dt(device_type_id=on_off_id) + success, problems = self.check_conformance(ignore_in_progress=False, is_ci=False) + self.problems.extend(problems) + asserts.assert_false(success, "Unexpected success with On/Off and MACL") + + # TODO: what happens if there is a NIM and a non-NIM endpoint? + + +if __name__ == "__main__": + default_matter_test_main() diff --git a/src/python_testing/execute_python_tests.py b/src/python_testing/execute_python_tests.py index ad3fc83c91..86d88e5aa1 100644 --- a/src/python_testing/execute_python_tests.py +++ b/src/python_testing/execute_python_tests.py @@ -87,6 +87,7 @@ def main(search_directory, env_file): "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", From ff6863ed127fb1a8a6f134ed15b2ed98ed75e418 Mon Sep 17 00:00:00 2001 From: Jeff Tung <100387939+jtung-apple@users.noreply.github.com> Date: Tue, 20 Aug 2024 20:57:05 -0700 Subject: [PATCH 114/165] [Darwin] New XPC bits need to initialize properly (#35110) --- src/darwin/Framework/CHIP/MTRDevice.mm | 2 ++ src/darwin/Framework/CHIP/MTRDeviceController.mm | 3 --- src/darwin/Framework/CHIP/MTRDeviceController_Internal.h | 4 ++++ src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm | 2 ++ 4 files changed, 8 insertions(+), 3 deletions(-) diff --git a/src/darwin/Framework/CHIP/MTRDevice.mm b/src/darwin/Framework/CHIP/MTRDevice.mm index ff4a76147d..4fc30b90b3 100644 --- a/src/darwin/Framework/CHIP/MTRDevice.mm +++ b/src/darwin/Framework/CHIP/MTRDevice.mm @@ -491,6 +491,8 @@ - (instancetype)initForSubclassesWithNodeID:(NSNumber *)nodeID controller:(MTRDe if (self = [super init]) { _lock = OS_UNFAIR_LOCK_INIT; _delegates = [NSMutableSet set]; + _deviceController = controller; + _nodeID = nodeID; } return self; diff --git a/src/darwin/Framework/CHIP/MTRDeviceController.mm b/src/darwin/Framework/CHIP/MTRDeviceController.mm index 322593312c..11fd481b48 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController.mm +++ b/src/darwin/Framework/CHIP/MTRDeviceController.mm @@ -109,9 +109,6 @@ using namespace chip::Tracing::DarwinFramework; @implementation MTRDeviceController { - // queue used to serialize all work performed by the MTRDeviceController - dispatch_queue_t _chipWorkQueue; - chip::Controller::DeviceCommissioner * _cppCommissioner; chip::Credentials::PartialDACVerifier * _partialDACVerifier; chip::Credentials::DefaultDACVerifier * _defaultDACVerifier; diff --git a/src/darwin/Framework/CHIP/MTRDeviceController_Internal.h b/src/darwin/Framework/CHIP/MTRDeviceController_Internal.h index 85d2c2e069..54d5cfd8d3 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController_Internal.h +++ b/src/darwin/Framework/CHIP/MTRDeviceController_Internal.h @@ -68,6 +68,10 @@ NS_ASSUME_NONNULL_BEGIN @property (nonatomic, readwrite, nullable) NSMapTable * nodeIDToDeviceMap; @property (readonly, assign) os_unfair_lock_t deviceMapLock; +// 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; #pragma mark - MTRDeviceControllerFactory methods diff --git a/src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm b/src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm index 49fd7c32f9..31acadcce5 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm +++ b/src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm @@ -79,6 +79,8 @@ - (id)initWithUniqueIdentifier:(NSUUID *)UUID xpConnectionBlock:(NSXPCConnection self.xpcConnection = connectionBlock(); self.uniqueIdentifier = UUID; + self.chipWorkQueue = dispatch_queue_create("MTRDeviceController_XPC_queue", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); + self.nodeIDToDeviceMap = [NSMapTable strongToWeakObjectsMapTable]; MTR_LOG("Set up XPC Connection: %@", self.xpcConnection); if (self.xpcConnection) { From 8b97b28e184bcb17d3376aae3b03fabb3dd5371d Mon Sep 17 00:00:00 2001 From: Karsten Sperling <113487422+ksperling-apple@users.noreply.github.com> Date: Wed, 21 Aug 2024 20:05:27 +1200 Subject: [PATCH 115/165] Revert "Enabling this for macOS Catalyst apps (#34956)" (#35117) This reverts commit 1d2ddd4131f3b6a10092d93a74ea58f0fe09510b. --- src/darwin/Framework/Matter.xcodeproj/project.pbxproj | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/darwin/Framework/Matter.xcodeproj/project.pbxproj b/src/darwin/Framework/Matter.xcodeproj/project.pbxproj index efafd27d28..7d0ab045b6 100644 --- a/src/darwin/Framework/Matter.xcodeproj/project.pbxproj +++ b/src/darwin/Framework/Matter.xcodeproj/project.pbxproj @@ -2373,7 +2373,6 @@ INSTALLHDRS_SCRIPT_PHASE = YES; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; IPHONEOS_DEPLOYMENT_TARGET = 14.0; - IS_ZIPPERED = YES; LIBRARY_SEARCH_PATHS = "$(TEMP_DIR)/out/lib"; OTHER_CFLAGS = "-fmacro-prefix-map=$(SRCROOT)/CHIP/="; OTHER_CPLUSPLUSFLAGS = ( @@ -2544,7 +2543,6 @@ INSTALLHDRS_SCRIPT_PHASE = YES; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; IPHONEOS_DEPLOYMENT_TARGET = 14.0; - IS_ZIPPERED = YES; LIBRARY_SEARCH_PATHS = "$(TEMP_DIR)/out/lib"; OTHER_CFLAGS = "-fmacro-prefix-map=$(SRCROOT)/CHIP/="; OTHER_CPLUSPLUSFLAGS = ( From b88eafac8bb91f6f1e3df887585a9c179591e5bf Mon Sep 17 00:00:00 2001 From: Yufeng Wang Date: Wed, 21 Aug 2024 06:32:50 -0700 Subject: [PATCH 116/165] [Fabric-Sync] Update the FS setup guide to wait for reverse commissioning complete (#35115) * [Fabric-Sync] Update the FS setup guide to wait for reverse commissing * Restyled by prettier-markdown --------- Co-authored-by: Restyled.io --- docs/guides/fabric_synchronization_guide.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/docs/guides/fabric_synchronization_guide.md b/docs/guides/fabric_synchronization_guide.md index 50fa3202f8..22d616211f 100644 --- a/docs/guides/fabric_synchronization_guide.md +++ b/docs/guides/fabric_synchronization_guide.md @@ -110,6 +110,14 @@ Pair the Ecosystem 2 bridge to Ecosystem 1 with node ID 2: fabricsync add-bridge 2 ``` +This command will initiate the reverse commissioning process. After a few +seconds, you should see the following message, indicating that the local bridge +of Ecosystem 1 has successfully paired with Ecosystem 2 on Endpoint 2: + +``` +>>> A new device is added on Endpoint 2. +``` + ### Pair Light Example to Ecosystem 2 Since Fabric-Bridge also functions as a Matter server, running it alongside the From 9e057a3af5e331902c3e6317b723ae0a3447c49e Mon Sep 17 00:00:00 2001 From: Yufeng Wang Date: Wed, 21 Aug 2024 08:02:39 -0700 Subject: [PATCH 117/165] [Fabric-Sync] Add VID/PID fields to IPC method CommissionNode (#35116) * Add VID/PID field to IPC methode CommissionNode * Use QRCodeSetupPayloadGenerator to generate pairing code --- .../pigweed/protos/fabric_admin_service.proto | 4 +++- .../fabric-admin/device_manager/DeviceManager.h | 4 ++-- examples/fabric-admin/rpc/RpcServer.cpp | 14 ++++++++------ .../linux/CommissionerControl.cpp | 3 ++- examples/fabric-bridge-app/linux/RpcClient.cpp | 4 +++- .../fabric-bridge-app/linux/include/RpcClient.h | 16 ++++++++++++---- 6 files changed, 30 insertions(+), 15 deletions(-) diff --git a/examples/common/pigweed/protos/fabric_admin_service.proto b/examples/common/pigweed/protos/fabric_admin_service.proto index 3c311493d1..3df3e2a7aa 100644 --- a/examples/common/pigweed/protos/fabric_admin_service.proto +++ b/examples/common/pigweed/protos/fabric_admin_service.proto @@ -19,7 +19,9 @@ message DeviceCommissioningInfo { uint32 discriminator = 1; uint32 iterations = 2; uint32 setup_pin = 3; - bytes salt = 4; + uint32 vendor_id = 4; + uint32 product_id = 5; + bytes salt = 6; } message KeepActiveParameters { diff --git a/examples/fabric-admin/device_manager/DeviceManager.h b/examples/fabric-admin/device_manager/DeviceManager.h index d3b47c4b33..1fb2ad5224 100644 --- a/examples/fabric-admin/device_manager/DeviceManager.h +++ b/examples/fabric-admin/device_manager/DeviceManager.h @@ -156,11 +156,11 @@ class DeviceManager : public PairingDelegate void HandleCommandResponse(const chip::app::ConcreteCommandPath & path, chip::TLV::TLVReader & data); - void OnDeviceRemoved(chip::NodeId deviceId, CHIP_ERROR err) override; - 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/rpc/RpcServer.cpp b/examples/fabric-admin/rpc/RpcServer.cpp index f240feda22..d56399514a 100644 --- a/examples/fabric-admin/rpc/RpcServer.cpp +++ b/examples/fabric-admin/rpc/RpcServer.cpp @@ -29,7 +29,7 @@ #include #include #include -#include +#include #include #if defined(PW_RPC_FABRIC_ADMIN_SERVICE) && PW_RPC_FABRIC_ADMIN_SERVICE @@ -103,16 +103,18 @@ class FabricAdmin final : public rpc::FabricAdmin, public IcdManager::Delegate setupPayload.setUpPINCode = request.setup_pin; setupPayload.version = 0; + setupPayload.vendorID = request.vendor_id; + setupPayload.productID = request.product_id; setupPayload.rendezvousInformation.SetValue(RendezvousInformationFlag::kOnNetwork); SetupDiscriminator discriminator{}; discriminator.SetLongValue(request.discriminator); setupPayload.discriminator = discriminator; - char payloadBuffer[kMaxManualCodeLength + 1]; - MutableCharSpan manualCode(payloadBuffer); + QRCodeSetupPayloadGenerator generator(setupPayload); + std::string code; + CHIP_ERROR error = generator.payloadBase38RepresentationWithAutoTLVBuffer(code); - CHIP_ERROR error = ManualSetupPayloadGenerator(setupPayload).payloadDecimalStringRepresentation(manualCode); if (error == CHIP_NO_ERROR) { NodeId nodeId = DeviceMgr().GetNextAvailableNodeId(); @@ -121,11 +123,11 @@ class FabricAdmin final : public rpc::FabricAdmin, public IcdManager::Delegate // RequestCommissioningApproval, you need to wait for it to open a commissioning window on its bridge. usleep(kCommissionPrepareTimeMs * 1000); - DeviceMgr().PairRemoteDevice(nodeId, payloadBuffer); + DeviceMgr().PairRemoteDevice(nodeId, code.c_str()); } else { - ChipLogError(NotSpecified, "Unable to generate manual code for setup payload: %" CHIP_ERROR_FORMAT, error.Format()); + ChipLogError(NotSpecified, "Unable to generate pairing code for setup payload: %" CHIP_ERROR_FORMAT, error.Format()); } return pw::OkStatus(); diff --git a/examples/fabric-bridge-app/linux/CommissionerControl.cpp b/examples/fabric-bridge-app/linux/CommissionerControl.cpp index 9f3180668d..3613aeec93 100644 --- a/examples/fabric-bridge-app/linux/CommissionerControl.cpp +++ b/examples/fabric-bridge-app/linux/CommissionerControl.cpp @@ -137,7 +137,8 @@ CHIP_ERROR CommissionerControlDelegate::HandleCommissionNode(const Commissioning .SetTimeout(params.commissioningTimeout) .SetDiscriminator(params.discriminator) .SetIteration(params.iterations) - .SetSalt(params.salt)); + .SetSalt(params.salt), + mVendorId, mProductId); #else ChipLogProgress(NotSpecified, "Failed to reverse commission bridge: PW_RPC_FABRIC_BRIDGE_SERVICE not defined"); return CHIP_ERROR_NOT_IMPLEMENTED; diff --git a/examples/fabric-bridge-app/linux/RpcClient.cpp b/examples/fabric-bridge-app/linux/RpcClient.cpp index b3c82303be..817479d848 100644 --- a/examples/fabric-bridge-app/linux/RpcClient.cpp +++ b/examples/fabric-bridge-app/linux/RpcClient.cpp @@ -163,12 +163,14 @@ OpenCommissioningWindow(chip::Controller::CommissioningWindowVerifierParams para } CHIP_ERROR -CommissionNode(chip::Controller::CommissioningWindowPasscodeParams params) +CommissionNode(chip::Controller::CommissioningWindowPasscodeParams params, VendorId vendorId, uint16_t productId) { chip_rpc_DeviceCommissioningInfo device; device.setup_pin = params.GetSetupPIN(); device.discriminator = params.GetDiscriminator(); device.iterations = params.GetIteration(); + device.vendor_id = vendorId; + device.product_id = productId; VerifyOrReturnError(params.GetSalt().size() <= sizeof(device.salt.bytes), CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(device.salt.bytes, params.GetSalt().data(), params.GetSalt().size()); diff --git a/examples/fabric-bridge-app/linux/include/RpcClient.h b/examples/fabric-bridge-app/linux/include/RpcClient.h index 87ccba24f6..c7628a8c3b 100644 --- a/examples/fabric-bridge-app/linux/include/RpcClient.h +++ b/examples/fabric-bridge-app/linux/include/RpcClient.h @@ -60,12 +60,20 @@ OpenCommissioningWindow(chip::Controller::CommissioningWindowVerifierParams para /** * Commission a node using the specified parameters. * - * @param params Params for commissioning the device using passcode. + * This function initiates the commissioning process for a node, utilizing + * the provided passcode parameters, vendor ID, and product ID. + * + * @param params Parameters required for commissioning the device using passcode. + * @param vendorId The Vendor ID (VID) of the device being commissioned. This identifies + * the manufacturer of the device. + * @param productId The Product ID (PID) of the device being commissioned. This identifies + * the specific product within the vendor's lineup. + * * @return CHIP_ERROR An error code indicating the success or failure of the operation. - * - CHIP_NO_ERROR: The RPC command was successfully sent. - * - CHIP_ERROR_INTERNAL: An internal error occurred. + * - CHIP_NO_ERROR: The RPC command was successfully sent and the commissioning process was initiated. + * - CHIP_ERROR_INTERNAL: An internal error occurred during the preparation or sending of the command. */ CHIP_ERROR -CommissionNode(chip::Controller::CommissioningWindowPasscodeParams params); +CommissionNode(chip::Controller::CommissioningWindowPasscodeParams params, chip::VendorId vendorId, uint16_t productId); CHIP_ERROR KeepActive(chip::NodeId nodeId, uint32_t stayActiveDurationMs); From 796394ffadb6d0322a16eb5eabfb28950c8e6116 Mon Sep 17 00:00:00 2001 From: C Freeman Date: Wed, 21 Aug 2024 13:01:59 -0400 Subject: [PATCH 118/165] Revert "TC-IDM-10.2: Add check for MACL (#35086)" (#35111) This reverts commit 927c81857ae9288ffab4ffbd529979412f8cc5f1. --- .github/workflows/tests.yaml | 1 - src/python_testing/TC_DeviceConformance.py | 23 ---- src/python_testing/TestConformanceTest.py | 131 --------------------- src/python_testing/execute_python_tests.py | 1 - 4 files changed, 156 deletions(-) delete mode 100644 src/python_testing/TestConformanceTest.py diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml index d60ffb185d..dbbda0aa36 100644 --- a/.github/workflows/tests.yaml +++ b/.github/workflows/tests.yaml @@ -514,7 +514,6 @@ jobs: 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' - scripts/run_in_python_env.sh out/venv 'python3 ./src/python_testing/TestConformanceTest.py' scripts/run_in_python_env.sh out/venv 'python3 ./src/python_testing/TestChoiceConformanceSupport.py' scripts/run_in_python_env.sh out/venv 'python3 ./src/python_testing/test_testing/test_IDM_10_4.py' scripts/run_in_python_env.sh out/venv 'python3 ./src/python_testing/test_testing/test_TC_SC_7_1.py' diff --git a/src/python_testing/TC_DeviceConformance.py b/src/python_testing/TC_DeviceConformance.py index 611d7f54a8..3cc57e2b01 100644 --- a/src/python_testing/TC_DeviceConformance.py +++ b/src/python_testing/TC_DeviceConformance.py @@ -50,22 +50,6 @@ async def setup_class_helper(self): self.xml_device_types, problems = build_xml_device_types() self.problems.extend(problems) - def _get_device_type_id(self, device_type_name: str) -> int: - id = [id for id, dt in self.xml_device_types.items() if dt.name.lower() == device_type_name.lower()] - if len(id) != 1: - self.fail_current_test(f"Unable to find {device_type_name} device type") - return id[0] - - def _has_nim(self): - nim_id = self._get_device_type_id('network infrastructure manager') - for endpoint in self.endpoints_tlv.values(): - desc = Clusters.Descriptor - device_types = [dt.deviceType for dt in endpoint[desc.id][desc.Attributes.DeviceTypeList.attribute_id]] - if nim_id in device_types: - # TODO: it's unclear if this needs to be present on every endpoint. Right now, this assumes one is sufficient. - return True - return False - def check_conformance(self, ignore_in_progress: bool, is_ci: bool): problems = [] success = True @@ -141,13 +125,6 @@ def record_warning(location, problem): for f in feature_masks: location = AttributePathLocation(endpoint_id=endpoint_id, cluster_id=cluster_id, attribute_id=GlobalAttributeIds.FEATURE_MAP_ID) - if cluster_id == Clusters.AccessControl.id and f == Clusters.AccessControl.Bitmaps.Feature.kManagedDevice: - # Managed ACL is treated as a special case because it is only allowed if other endpoints support NIM and disallowed otherwise. - if not self._has_nim(): - record_error( - location=location, problem="MACL feature is disallowed if the Network Infrastructure Manager device type is not present") - continue - if f not in self.xml_clusters[cluster_id].features.keys(): record_error(location=location, problem=f'Unknown feature with mask 0x{f:02x}') continue diff --git a/src/python_testing/TestConformanceTest.py b/src/python_testing/TestConformanceTest.py deleted file mode 100644 index a656e228bf..0000000000 --- a/src/python_testing/TestConformanceTest.py +++ /dev/null @@ -1,131 +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. -# - -from typing import Any - -import chip.clusters as Clusters -from conformance_support import ConformanceDecision -from global_attribute_ids import GlobalAttributeIds -from matter_testing_support import MatterBaseTest, async_test_body, default_matter_test_main -from mobly import asserts -from spec_parsing_support import build_xml_clusters, build_xml_device_types -from TC_DeviceConformance import DeviceConformanceTests - - -def is_mandatory(conformance): - return conformance(0, [], []).decision == ConformanceDecision.MANDATORY - - -class TestConformanceSupport(MatterBaseTest, DeviceConformanceTests): - def setup_class(self): - self.xml_clusters, self.problems = build_xml_clusters() - self.xml_device_types, problems = build_xml_device_types() - self.problems.extend(problems) - - def _create_minimal_cluster(self, cluster_id: int) -> dict[int, Any]: - attrs = {} - attrs[GlobalAttributeIds.FEATURE_MAP_ID] = 0 - - mandatory_attributes = [id for id, a in self.xml_clusters[cluster_id].attributes.items() if is_mandatory(a.conformance)] - for m in mandatory_attributes: - # dummy versions - we're not using the values in this test - attrs[m] = 0 - attrs[GlobalAttributeIds.ATTRIBUTE_LIST_ID] = mandatory_attributes - mandatory_accepted_commands = [id for id, a in self.xml_clusters[cluster_id].accepted_commands.items() - if is_mandatory(a.conformance)] - attrs[GlobalAttributeIds.ACCEPTED_COMMAND_LIST_ID] = mandatory_accepted_commands - mandatory_generated_commands = [id for id, a in self.xml_clusters[cluster_id].generated_commands.items() - if is_mandatory(a.conformance)] - attrs[GlobalAttributeIds.GENERATED_COMMAND_LIST_ID] = mandatory_generated_commands - attrs[GlobalAttributeIds.CLUSTER_REVISION_ID] = self.xml_clusters[cluster_id].revision - return attrs - - def _create_minimal_dt(self, device_type_id: int) -> dict[int, dict[int, Any]]: - ''' Creates the internals of an endpoint_tlv with the minimal set of clusters, with the minimal set of attributes and commands. Global attributes only. - Does NOT take into account overrides yet. - ''' - endpoint_tlv = {} - required_servers = [id for id, c in self.xml_device_types[device_type_id].server_clusters.items() - if is_mandatory(c.conformance)] - required_clients = [id for id, c in self.xml_device_types[device_type_id].client_clusters.items() - if is_mandatory(c.conformance)] - device_type_revision = self.xml_device_types[device_type_id].revision - - for s in required_servers: - endpoint_tlv[s] = self._create_minimal_cluster(s) - - # Descriptor - attr = Clusters.Descriptor.Attributes - attrs = {} - attrs[attr.FeatureMap.attribute_id] = 0 - attrs[attr.AcceptedCommandList.attribute_id] = [] - attrs[attr.GeneratedCommandList.attribute_id] = [] - attrs[attr.ClusterRevision.attribute_id] = self.xml_clusters[Clusters.Descriptor.id].revision - attrs[attr.DeviceTypeList.attribute_id] = [ - Clusters.Descriptor.Structs.DeviceTypeStruct(deviceType=device_type_id, revision=device_type_revision)] - attrs[attr.ServerList.attribute_id] = required_servers - attrs[attr.ClientList.attribute_id] = required_clients - attrs[attr.PartsList.attribute_id] = [] - attrs[attr.AttributeList.attribute_id] = [] - attrs[attr.AttributeList.attribute_id] = list(attrs.keys()) - - endpoint_tlv[Clusters.Descriptor.id] = attrs - return endpoint_tlv - - def add_macl(self, root_endpoint: dict[int, dict[int, Any]]): - ac = Clusters.AccessControl - root_endpoint[ac.id][ac.Attributes.FeatureMap.attribute_id] = ac.Bitmaps.Feature.kManagedDevice - root_endpoint[ac.id][ac.Attributes.Arl.attribute_id] = [] - root_endpoint[ac.id][ac.Attributes.CommissioningARL.attribute_id] = [] - root_endpoint[ac.id][ac.Attributes.AttributeList.attribute_id].extend([ - ac.Attributes.Arl.attribute_id, ac.Attributes.CommissioningARL.attribute_id]) - root_endpoint[ac.id][ac.Attributes.AcceptedCommandList.attribute_id].append(ac.Commands.ReviewFabricRestrictions.command_id) - root_endpoint[ac.id][ac.Attributes.GeneratedCommandList.attribute_id].append( - ac.Commands.ReviewFabricRestrictionsResponse.command_id) - - @async_test_body - async def test_macl_handling(self): - nim_id = self._get_device_type_id('network infrastructure manager') - root_node_id = self._get_device_type_id('root node') - on_off_id = self._get_device_type_id('On/Off Light') - - root = self._create_minimal_dt(device_type_id=root_node_id) - nim = self._create_minimal_dt(device_type_id=nim_id) - self.endpoints_tlv = {0: root, 1: nim} - asserts.assert_true(self._has_nim(), "Did not find NIM in generated device") - - success, problems = self.check_conformance(ignore_in_progress=False, is_ci=False) - self.problems.extend(problems) - asserts.assert_true(success, "Unexpected failure parsing minimal dt") - - self.add_macl(root) - # A MACL is allowed when there is a NIM, so this should succeed as well - success, problems = self.check_conformance(ignore_in_progress=False, is_ci=False) - self.problems.extend(problems) - asserts.assert_true(success, "Unexpected failure with NIM and MACL") - - # A MACL is not allowed when there is no NIM - self.endpoints_tlv[1] = self._create_minimal_dt(device_type_id=on_off_id) - success, problems = self.check_conformance(ignore_in_progress=False, is_ci=False) - self.problems.extend(problems) - asserts.assert_false(success, "Unexpected success with On/Off and MACL") - - # TODO: what happens if there is a NIM and a non-NIM endpoint? - - -if __name__ == "__main__": - default_matter_test_main() diff --git a/src/python_testing/execute_python_tests.py b/src/python_testing/execute_python_tests.py index 86d88e5aa1..ad3fc83c91 100644 --- a/src/python_testing/execute_python_tests.py +++ b/src/python_testing/execute_python_tests.py @@ -87,7 +87,6 @@ def main(search_directory, env_file): "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", From ddf8b8fbb76a02ef610b3c701b0528d70ba22e9e Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Wed, 21 Aug 2024 13:03:02 -0400 Subject: [PATCH 119/165] Fix UnregisterAllCommandHandlersForEndpoint to work correctly. (#35100) Fixes https://github.com/project-chip/connectedhomeip/issues/34953 --- src/app/CommandHandlerInterfaceRegistry.cpp | 7 +- src/app/tests/BUILD.gn | 1 + .../TestCommandHandlerInterfaceRegistry.cpp | 103 ++++++++++++++++++ 3 files changed, 110 insertions(+), 1 deletion(-) create mode 100644 src/app/tests/TestCommandHandlerInterfaceRegistry.cpp diff --git a/src/app/CommandHandlerInterfaceRegistry.cpp b/src/app/CommandHandlerInterfaceRegistry.cpp index 01436853dd..8345be5dcc 100644 --- a/src/app/CommandHandlerInterfaceRegistry.cpp +++ b/src/app/CommandHandlerInterfaceRegistry.cpp @@ -68,8 +68,11 @@ void CommandHandlerInterfaceRegistry::UnregisterAllCommandHandlersForEndpoint(En { CommandHandlerInterface * prev = nullptr; - for (auto * cur = mCommandHandlerList; cur; cur = cur->GetNext()) + for (auto * cur = mCommandHandlerList; cur;) { + // Fetch next node in the list before we remove this one. + auto * next = cur->GetNext(); + if (cur->MatchesEndpoint(endpointId)) { if (prev == nullptr) @@ -87,6 +90,8 @@ void CommandHandlerInterfaceRegistry::UnregisterAllCommandHandlersForEndpoint(En { prev = cur; } + + cur = next; } } diff --git a/src/app/tests/BUILD.gn b/src/app/tests/BUILD.gn index 1bce08d55e..104a57a2fc 100644 --- a/src/app/tests/BUILD.gn +++ b/src/app/tests/BUILD.gn @@ -194,6 +194,7 @@ chip_test_suite("tests") { "TestBasicCommandPathRegistry.cpp", "TestBindingTable.cpp", "TestBuilderParser.cpp", + "TestCommandHandlerInterfaceRegistry.cpp", "TestCommandInteraction.cpp", "TestCommandPathParams.cpp", "TestConcreteAttributePath.cpp", diff --git a/src/app/tests/TestCommandHandlerInterfaceRegistry.cpp b/src/app/tests/TestCommandHandlerInterfaceRegistry.cpp new file mode 100644 index 0000000000..aed017362c --- /dev/null +++ b/src/app/tests/TestCommandHandlerInterfaceRegistry.cpp @@ -0,0 +1,103 @@ +/* + * + * 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 + +namespace chip { +namespace app { + +namespace { + +class TestCommandHandlerInterface : public CommandHandlerInterface +{ +public: + TestCommandHandlerInterface(Optional endpointId, ClusterId clusterId) : + CommandHandlerInterface(endpointId, clusterId) + {} + + // Just need this to compile + void InvokeCommand(HandlerContext & handlerContext) override {} +}; + +} // anonymous namespace + +TEST(TestCommandHandlerInterfaceRegistry, TestRegisterUnregister) +{ + TestCommandHandlerInterface a(Optional(1), 1); + TestCommandHandlerInterface b(Optional(1), 2); + TestCommandHandlerInterface c(Optional(2), 1); + TestCommandHandlerInterface d(NullOptional, 3); + + CommandHandlerInterfaceRegistry registry; + EXPECT_EQ(registry.RegisterCommandHandler(&a), CHIP_NO_ERROR); + EXPECT_EQ(registry.RegisterCommandHandler(&b), CHIP_NO_ERROR); + EXPECT_EQ(registry.RegisterCommandHandler(&c), CHIP_NO_ERROR); + EXPECT_EQ(registry.RegisterCommandHandler(&d), CHIP_NO_ERROR); + + EXPECT_EQ(registry.GetCommandHandler(1, 1), &a); + EXPECT_EQ(registry.GetCommandHandler(1, 2), &b); + EXPECT_EQ(registry.GetCommandHandler(2, 1), &c); + EXPECT_EQ(registry.GetCommandHandler(1, 3), &d); + EXPECT_EQ(registry.GetCommandHandler(5, 3), &d); + + EXPECT_EQ(registry.UnregisterCommandHandler(&b), CHIP_NO_ERROR); + + EXPECT_EQ(registry.GetCommandHandler(1, 1), &a); + EXPECT_EQ(registry.GetCommandHandler(1, 2), nullptr); + EXPECT_EQ(registry.GetCommandHandler(2, 1), &c); + EXPECT_EQ(registry.GetCommandHandler(1, 3), &d); + EXPECT_EQ(registry.GetCommandHandler(5, 3), &d); + + EXPECT_EQ(registry.UnregisterCommandHandler(&b), CHIP_ERROR_KEY_NOT_FOUND); +} + +TEST(TestCommandHandlerInterfaceRegistry, TestUnregisterAll) +{ + TestCommandHandlerInterface a(Optional(1), 1); + TestCommandHandlerInterface b(Optional(1), 2); + TestCommandHandlerInterface c(Optional(2), 1); + TestCommandHandlerInterface d(NullOptional, 3); + + CommandHandlerInterfaceRegistry registry; + EXPECT_EQ(registry.RegisterCommandHandler(&a), CHIP_NO_ERROR); + EXPECT_EQ(registry.RegisterCommandHandler(&b), CHIP_NO_ERROR); + EXPECT_EQ(registry.RegisterCommandHandler(&c), CHIP_NO_ERROR); + EXPECT_EQ(registry.RegisterCommandHandler(&d), CHIP_NO_ERROR); + + EXPECT_EQ(registry.GetCommandHandler(1, 1), &a); + EXPECT_EQ(registry.GetCommandHandler(1, 2), &b); + EXPECT_EQ(registry.GetCommandHandler(2, 1), &c); + EXPECT_EQ(registry.GetCommandHandler(1, 3), &d); + EXPECT_EQ(registry.GetCommandHandler(5, 3), &d); + + registry.UnregisterAllCommandHandlersForEndpoint(1); + + EXPECT_EQ(registry.GetCommandHandler(1, 1), nullptr); + EXPECT_EQ(registry.GetCommandHandler(1, 2), nullptr); + EXPECT_EQ(registry.GetCommandHandler(2, 1), &c); + EXPECT_EQ(registry.GetCommandHandler(1, 3), &d); + EXPECT_EQ(registry.GetCommandHandler(5, 3), &d); +} + +} // namespace app +} // namespace chip From fd9dfe26964b5f77e08782ce7ed1ff8b259a69b8 Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Wed, 21 Aug 2024 13:03:39 -0400 Subject: [PATCH 120/165] Add missing CFLAGS to instrument things for fuzzers. (#35082) -fno-sanitize-coverage=pc-table is added since we are already using inline-8bit-counters and trace-cmp to provide instrumentation for the fuzzers. It also helps reduce memory usage and improve fuzzer performance. --- build/config/compiler/BUILD.gn | 2 ++ 1 file changed, 2 insertions(+) diff --git a/build/config/compiler/BUILD.gn b/build/config/compiler/BUILD.gn index fee0d745f6..2e2ebe606f 100644 --- a/build/config/compiler/BUILD.gn +++ b/build/config/compiler/BUILD.gn @@ -415,6 +415,8 @@ declare_args() { config("sanitize_address") { defines = [] cflags = [ + "-fsanitize-coverage=inline-8bit-counters,trace-cmp", + "-fno-sanitize-coverage=pc-table", "-fsanitize=address", "-fno-omit-frame-pointer", ] From 150aad355231832c220b5d4e9da0ba00e81b0b8d Mon Sep 17 00:00:00 2001 From: Paul Regan <64710345+paulr34@users.noreply.github.com> Date: Wed, 21 Aug 2024 13:27:19 -0400 Subject: [PATCH 121/165] adding mandatory endpointComposition data to XML for ZAP to consume (#34818) * adding endpointComposition data to XML for ZAP to consume * explicitly adding constraint as defined by the spec and defining compositions types * fix composition type tag * changing back to prevent both types being true which is not allowed * explciitly setting conformance and contraint to account for all scenarios --- .../zap-templates/zcl/data-model/chip/matter-devices.xml | 6 ++++++ 1 file changed, 6 insertions(+) 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 14f4b9edf3..ea18e98562 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 @@ -2209,6 +2209,12 @@ limitations under the License. 0x0070 Simple Endpoint + + tree + + 0x0071 + + From 849634bdb00ad1083ff3e615f3eac1448a21a0bc Mon Sep 17 00:00:00 2001 From: Thirupathi S <108743108+Thirsrin@users.noreply.github.com> Date: Wed, 21 Aug 2024 23:27:17 +0530 Subject: [PATCH 122/165] Colorcontrol xml file sync with specs (#33612) * doorlock xml file sync with specs and colorcontrol xml type changes * build error resolved * Restyled by clang-format * build error resolved * addressed review comments * Restyled by clang-format * Addressed review comments * Restyled by clang-format * build error solved * build error solved * build error solved * build error solved * build issue resolved * Restyled by clang-format * resolved build errors * removed doorlock xml changes * Restyled by clang-format * resolved build errors * Restyled by clang-format * resolved build errors * addressed review comments * addressed review comments * resolved build errors * resolved build errors * zap generated changes * Restyled by clang-format * Revert colorloopdirection type change * build error resolved * Restyled by clang-format * rebased and zap generated * color control xml file updated * build error solved * ameba build error resolved * Restyled by clang-format * ameba build error resolved * doorlock changes removed * ameba build error resolved * ameba build error resolved * addressed review comments * addressed review comments * Restyled by clang-format * Addressed review comments * Addressed review comments * Restyled by clang-format * build error resolved * build error resolved * addressed reviews comments and build error resolved * Restyled by clang-format * ZAP issue resolved * scripts updated * scripts updated * added enum values in compatenum.h file * Restyled by whitespace * Restyled by clang-format * added enum values in compatenum.h file * Restyled by whitespace * Restyled by clang-format * added enum values in compatenum.h file * added header file for to_underlying * build error resolved * build error resolved --------- Co-authored-by: Restyled.io --- .../all-clusters-app.matter | 182 ++++---- .../ameba/main/include/ColorControlCommands.h | 204 ++++----- .../all-clusters-minimal-app.matter | 182 ++++---- ...de_colortemperaturelight_hbUnzYVeyn.matter | 182 ++++---- ...tnode_extendedcolorlight_8lcaaYJVAa.matter | 182 ++++---- examples/common/imgui_ui/windows/light.cpp | 14 +- examples/common/imgui_ui/windows/light.h | 3 +- .../light-switch-app.matter | 182 ++++---- .../light-switch-app/qpg/zap/switch.matter | 182 ++++---- .../data_model/lighting-app-ethernet.matter | 182 ++++---- .../data_model/lighting-app-thread.matter | 182 ++++---- .../data_model/lighting-app-wifi.matter | 182 ++++---- .../lighting-common/lighting-app.matter | 182 ++++---- examples/lighting-app/qpg/zap/light.matter | 182 ++++---- .../data_model/lighting-thread-app.matter | 182 ++++---- .../data_model/lighting-wifi-app.matter | 182 ++++---- .../lighting-app/tizen/src/DBusInterface.cpp | 6 +- examples/lighting-app/tizen/src/main.cpp | 2 +- .../placeholder/linux/apps/app1/config.matter | 364 ++++++++-------- .../placeholder/linux/apps/app2/config.matter | 364 ++++++++-------- .../virtual-device-app.matter | 182 ++++---- .../color-control-server.cpp | 301 ++++++------- .../color-control-server.h | 44 +- src/app/common/CompatEnumNames.h | 46 ++ .../data-model/chip/color-control-cluster.xml | 187 ++++---- .../data_model/controller-clusters.matter | 182 ++++---- .../CHIPAttributeTLVValueDecoder.cpp | 4 +- .../python/chip/clusters/Objects.py | 143 +++--- .../MTRAttributeTLVValueDecoder.mm | 10 +- .../CHIP/zap-generated/MTRBaseClusters.h | 106 ++--- .../CHIP/zap-generated/MTRBaseClusters.mm | 2 +- .../zap-generated/MTRCommandPayloadsObjc.mm | 76 ++-- src/python_testing/TC_CC_2_2.py | 8 +- .../zap-generated/attributes/Accessors.cpp | 70 +-- .../zap-generated/attributes/Accessors.h | 44 +- .../zap-generated/cluster-enums-check.h | 56 +-- .../app-common/zap-generated/cluster-enums.h | 102 +++-- .../zap-generated/cluster-objects.h | 410 +++++++++--------- .../zap-generated/cluster/Commands.h | 23 +- .../cluster/logging/DataModelLogger.cpp | 10 +- .../zap-generated/cluster/Commands.h | 76 ++-- 41 files changed, 2825 insertions(+), 2580 deletions(-) diff --git a/examples/all-clusters-app/all-clusters-common/all-clusters-app.matter b/examples/all-clusters-app/all-clusters-common/all-clusters-app.matter index 46debb8a6c..c18c6164c5 100644 --- a/examples/all-clusters-app/all-clusters-common/all-clusters-app.matter +++ b/examples/all-clusters-app/all-clusters-common/all-clusters-app.matter @@ -5847,65 +5847,62 @@ cluster ThermostatUserInterfaceConfiguration = 516 { cluster ColorControl = 768 { revision 7; - enum ColorLoopAction : enum8 { + enum ColorLoopActionEnum : enum8 { kDeactivate = 0; kActivateFromColorLoopStartEnhancedHue = 1; kActivateFromEnhancedCurrentHue = 2; } - enum ColorLoopDirection : enum8 { - kDecrementHue = 0; - kIncrementHue = 1; + enum ColorLoopDirectionEnum : enum8 { + kDecrement = 0; + kIncrement = 1; } - enum ColorMode : enum8 { + enum ColorModeEnum : enum8 { kCurrentHueAndCurrentSaturation = 0; kCurrentXAndCurrentY = 1; - kColorTemperature = 2; + kColorTemperatureMireds = 2; } - enum HueDirection : enum8 { - kShortestDistance = 0; - kLongestDistance = 1; + enum DirectionEnum : enum8 { + kShortest = 0; + kLongest = 1; kUp = 2; kDown = 3; } - enum HueMoveMode : enum8 { - kStop = 0; - kUp = 1; - kDown = 3; + enum DriftCompensationEnum : enum8 { + kNone = 0; + kOtherOrUnknown = 1; + kTemperatureMonitoring = 2; + kOpticalLuminanceMonitoringAndFeedback = 3; + kOpticalColorMonitoringAndFeedback = 4; } - enum HueStepMode : enum8 { - kUp = 1; - kDown = 3; + enum EnhancedColorModeEnum : enum8 { + kCurrentHueAndCurrentSaturation = 0; + kCurrentXAndCurrentY = 1; + kColorTemperatureMireds = 2; + kEnhancedCurrentHueAndCurrentSaturation = 3; } - enum SaturationMoveMode : enum8 { + enum MoveModeEnum : enum8 { kStop = 0; kUp = 1; kDown = 3; } - enum SaturationStepMode : enum8 { + enum StepModeEnum : enum8 { kUp = 1; kDown = 3; } - bitmap ColorCapabilities : bitmap16 { - kHueSaturationSupported = 0x1; - kEnhancedHueSupported = 0x2; - kColorLoopSupported = 0x4; - kXYAttributesSupported = 0x8; - kColorTemperatureSupported = 0x10; - } - - bitmap ColorLoopUpdateFlags : bitmap8 { - kUpdateAction = 0x1; - kUpdateDirection = 0x2; - kUpdateTime = 0x4; - kUpdateStartHue = 0x8; + bitmap ColorCapabilitiesBitmap : bitmap16 { + kHueSaturation = 0x1; + kEnhancedHue = 0x2; + kColorLoop = 0x4; + kXY = 0x8; + kColorTemperature = 0x10; } bitmap Feature : bitmap32 { @@ -5916,16 +5913,27 @@ cluster ColorControl = 768 { kColorTemperature = 0x10; } + bitmap OptionsBitmap : bitmap8 { + kExecuteIfOff = 0x1; + } + + bitmap UpdateFlagsBitmap : bitmap8 { + kUpdateAction = 0x1; + kUpdateDirection = 0x2; + kUpdateTime = 0x4; + kUpdateStartHue = 0x8; + } + readonly attribute optional int8u currentHue = 0; readonly attribute optional int8u currentSaturation = 1; readonly attribute optional int16u remainingTime = 2; readonly attribute optional int16u currentX = 3; readonly attribute optional int16u currentY = 4; - readonly attribute optional enum8 driftCompensation = 5; + readonly attribute optional DriftCompensationEnum driftCompensation = 5; readonly attribute optional char_string<254> compensationText = 6; readonly attribute optional int16u colorTemperatureMireds = 7; - readonly attribute enum8 colorMode = 8; - attribute bitmap8 options = 15; + readonly attribute ColorModeEnum colorMode = 8; + attribute OptionsBitmap options = 15; readonly attribute nullable int8u numberOfPrimaries = 16; readonly attribute optional int16u primary1X = 17; readonly attribute optional int16u primary1Y = 18; @@ -5957,13 +5965,13 @@ cluster ColorControl = 768 { attribute access(write: manage) optional int16u colorPointBY = 59; attribute access(write: manage) optional nullable int8u colorPointBIntensity = 60; readonly attribute optional int16u enhancedCurrentHue = 16384; - readonly attribute enum8 enhancedColorMode = 16385; + readonly attribute EnhancedColorModeEnum enhancedColorMode = 16385; readonly attribute optional int8u colorLoopActive = 16386; readonly attribute optional int8u colorLoopDirection = 16387; readonly attribute optional int16u colorLoopTime = 16388; readonly attribute optional int16u colorLoopStartEnhancedHue = 16389; readonly attribute optional int16u colorLoopStoredEnhancedHue = 16390; - readonly attribute bitmap16 colorCapabilities = 16394; + readonly attribute ColorCapabilitiesBitmap colorCapabilities = 16394; readonly attribute optional int16u colorTempPhysicalMinMireds = 16395; readonly attribute optional int16u colorTempPhysicalMaxMireds = 16396; readonly attribute optional int16u coupleColorTempToLevelMinMireds = 16397; @@ -5977,150 +5985,150 @@ cluster ColorControl = 768 { request struct MoveToHueRequest { int8u hue = 0; - HueDirection direction = 1; + DirectionEnum direction = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveHueRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int8u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepHueRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int8u stepSize = 1; int8u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToSaturationRequest { int8u saturation = 0; int16u transitionTime = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct MoveSaturationRequest { - SaturationMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int8u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepSaturationRequest { - SaturationStepMode stepMode = 0; + StepModeEnum stepMode = 0; int8u stepSize = 1; int8u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToHueAndSaturationRequest { int8u hue = 0; int8u saturation = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToColorRequest { int16u colorX = 0; int16u colorY = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveColorRequest { int16s rateX = 0; int16s rateY = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepColorRequest { int16s stepX = 0; int16s stepY = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToColorTemperatureRequest { int16u colorTemperatureMireds = 0; int16u transitionTime = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct EnhancedMoveToHueRequest { int16u enhancedHue = 0; - HueDirection direction = 1; + DirectionEnum direction = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct EnhancedMoveHueRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int16u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct EnhancedStepHueRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int16u stepSize = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct EnhancedMoveToHueAndSaturationRequest { int16u enhancedHue = 0; int8u saturation = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct ColorLoopSetRequest { - ColorLoopUpdateFlags updateFlags = 0; - ColorLoopAction action = 1; - ColorLoopDirection direction = 2; + UpdateFlagsBitmap updateFlags = 0; + ColorLoopActionEnum action = 1; + ColorLoopDirectionEnum direction = 2; int16u time = 3; int16u startHue = 4; - bitmap8 optionsMask = 5; - bitmap8 optionsOverride = 6; + OptionsBitmap optionsMask = 5; + OptionsBitmap optionsOverride = 6; } request struct StopMoveStepRequest { - bitmap8 optionsMask = 0; - bitmap8 optionsOverride = 1; + OptionsBitmap optionsMask = 0; + OptionsBitmap optionsOverride = 1; } request struct MoveColorTemperatureRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int16u rate = 1; int16u colorTemperatureMinimumMireds = 2; int16u colorTemperatureMaximumMireds = 3; - bitmap8 optionsMask = 4; - bitmap8 optionsOverride = 5; + OptionsBitmap optionsMask = 4; + OptionsBitmap optionsOverride = 5; } request struct StepColorTemperatureRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int16u stepSize = 1; int16u transitionTime = 2; int16u colorTemperatureMinimumMireds = 3; int16u colorTemperatureMaximumMireds = 4; - bitmap8 optionsMask = 5; - bitmap8 optionsOverride = 6; + OptionsBitmap optionsMask = 5; + OptionsBitmap optionsOverride = 6; } /** Move to specified hue. */ diff --git a/examples/all-clusters-app/ameba/main/include/ColorControlCommands.h b/examples/all-clusters-app/ameba/main/include/ColorControlCommands.h index a80b5fe02d..73241be444 100644 --- a/examples/all-clusters-app/ameba/main/include/ColorControlCommands.h +++ b/examples/all-clusters-app/ameba/main/include/ColorControlCommands.h @@ -360,29 +360,29 @@ void ProcessColorControlUnicastBindingCommand(BindingCommandData * data, const E { case Clusters::ColorControl::Commands::MoveToHue::Id: moveToHueCommand.hue = static_cast(data->args[0]); - moveToHueCommand.direction = static_cast(data->args[1]); + moveToHueCommand.direction = static_cast(data->args[1]); moveToHueCommand.transitionTime = static_cast(data->args[2]); - moveToHueCommand.optionsMask = static_cast(data->args[3]); - moveToHueCommand.optionsOverride = static_cast(data->args[4]); + moveToHueCommand.optionsMask = static_cast(data->args[3]); + moveToHueCommand.optionsOverride = static_cast(data->args[4]); Controller::InvokeCommandRequest(peer_device->GetExchangeManager(), peer_device->GetSecureSession().Value(), binding.remote, moveToHueCommand, onSuccess, onFailure); break; case Clusters::ColorControl::Commands::MoveHue::Id: - moveHueCommand.moveMode = static_cast(data->args[0]); + moveHueCommand.moveMode = static_cast(data->args[0]); moveHueCommand.rate = static_cast(data->args[1]); - moveHueCommand.optionsMask = static_cast(data->args[2]); - moveHueCommand.optionsOverride = static_cast(data->args[3]); + moveHueCommand.optionsMask = static_cast(data->args[2]); + moveHueCommand.optionsOverride = static_cast(data->args[3]); Controller::InvokeCommandRequest(peer_device->GetExchangeManager(), peer_device->GetSecureSession().Value(), binding.remote, moveHueCommand, onSuccess, onFailure); break; case Clusters::ColorControl::Commands::StepHue::Id: - stepHueCommand.stepMode = static_cast(data->args[0]); + stepHueCommand.stepMode = static_cast(data->args[0]); stepHueCommand.stepSize = static_cast(data->args[1]); stepHueCommand.transitionTime = static_cast(data->args[2]); - stepHueCommand.optionsMask = static_cast(data->args[3]); - stepHueCommand.optionsOverride = static_cast(data->args[4]); + stepHueCommand.optionsMask = static_cast(data->args[3]); + stepHueCommand.optionsOverride = static_cast(data->args[4]); Controller::InvokeCommandRequest(peer_device->GetExchangeManager(), peer_device->GetSecureSession().Value(), binding.remote, stepHueCommand, onSuccess, onFailure); break; @@ -390,27 +390,27 @@ void ProcessColorControlUnicastBindingCommand(BindingCommandData * data, const E case Clusters::ColorControl::Commands::MoveToSaturation::Id: moveToSaturationCommand.saturation = static_cast(data->args[0]); moveToSaturationCommand.transitionTime = static_cast(data->args[1]); - moveToSaturationCommand.optionsMask = static_cast(data->args[2]); - moveToSaturationCommand.optionsOverride = static_cast(data->args[3]); + moveToSaturationCommand.optionsMask = static_cast(data->args[2]); + moveToSaturationCommand.optionsOverride = static_cast(data->args[3]); Controller::InvokeCommandRequest(peer_device->GetExchangeManager(), peer_device->GetSecureSession().Value(), binding.remote, moveToSaturationCommand, onSuccess, onFailure); break; case Clusters::ColorControl::Commands::MoveSaturation::Id: - moveSaturationCommand.moveMode = static_cast(data->args[0]); + moveSaturationCommand.moveMode = static_cast(data->args[0]); moveSaturationCommand.rate = static_cast(data->args[1]); - moveSaturationCommand.optionsMask = static_cast(data->args[2]); - moveSaturationCommand.optionsOverride = static_cast(data->args[3]); + moveSaturationCommand.optionsMask = static_cast(data->args[2]); + moveSaturationCommand.optionsOverride = static_cast(data->args[3]); Controller::InvokeCommandRequest(peer_device->GetExchangeManager(), peer_device->GetSecureSession().Value(), binding.remote, moveSaturationCommand, onSuccess, onFailure); break; case Clusters::ColorControl::Commands::StepSaturation::Id: - stepSaturationCommand.stepMode = static_cast(data->args[0]); + stepSaturationCommand.stepMode = static_cast(data->args[0]); stepSaturationCommand.stepSize = static_cast(data->args[1]); stepSaturationCommand.transitionTime = static_cast(data->args[2]); - stepSaturationCommand.optionsMask = static_cast(data->args[3]); - stepSaturationCommand.optionsOverride = static_cast(data->args[4]); + stepSaturationCommand.optionsMask = static_cast(data->args[3]); + stepSaturationCommand.optionsOverride = static_cast(data->args[4]); Controller::InvokeCommandRequest(peer_device->GetExchangeManager(), peer_device->GetSecureSession().Value(), binding.remote, stepSaturationCommand, onSuccess, onFailure); break; @@ -419,8 +419,8 @@ void ProcessColorControlUnicastBindingCommand(BindingCommandData * data, const E moveToHueAndSaturationCommand.hue = static_cast(data->args[0]); moveToHueAndSaturationCommand.saturation = static_cast(data->args[1]); moveToHueAndSaturationCommand.transitionTime = static_cast(data->args[2]); - moveToHueAndSaturationCommand.optionsMask = static_cast(data->args[3]); - moveToHueAndSaturationCommand.optionsOverride = static_cast(data->args[4]); + moveToHueAndSaturationCommand.optionsMask = static_cast(data->args[3]); + moveToHueAndSaturationCommand.optionsOverride = static_cast(data->args[4]); Controller::InvokeCommandRequest(peer_device->GetExchangeManager(), peer_device->GetSecureSession().Value(), binding.remote, moveToHueAndSaturationCommand, onSuccess, onFailure); break; @@ -429,8 +429,8 @@ void ProcessColorControlUnicastBindingCommand(BindingCommandData * data, const E moveToColorCommand.colorX = static_cast(data->args[0]); moveToColorCommand.colorY = static_cast(data->args[1]); moveToColorCommand.transitionTime = static_cast(data->args[2]); - moveToColorCommand.optionsMask = static_cast(data->args[3]); - moveToColorCommand.optionsOverride = static_cast(data->args[4]); + moveToColorCommand.optionsMask = static_cast(data->args[3]); + moveToColorCommand.optionsOverride = static_cast(data->args[4]); Controller::InvokeCommandRequest(peer_device->GetExchangeManager(), peer_device->GetSecureSession().Value(), binding.remote, moveToColorCommand, onSuccess, onFailure); break; @@ -438,8 +438,8 @@ void ProcessColorControlUnicastBindingCommand(BindingCommandData * data, const E case Clusters::ColorControl::Commands::MoveColor::Id: moveColorCommand.rateX = static_cast(data->args[0]); moveColorCommand.rateY = static_cast(data->args[1]); - moveColorCommand.optionsMask = static_cast(data->args[2]); - moveColorCommand.optionsOverride = static_cast(data->args[3]); + moveColorCommand.optionsMask = static_cast(data->args[2]); + moveColorCommand.optionsOverride = static_cast(data->args[3]); Controller::InvokeCommandRequest(peer_device->GetExchangeManager(), peer_device->GetSecureSession().Value(), binding.remote, moveColorCommand, onSuccess, onFailure); break; @@ -448,8 +448,8 @@ void ProcessColorControlUnicastBindingCommand(BindingCommandData * data, const E stepColorCommand.stepX = static_cast(data->args[0]); stepColorCommand.stepY = static_cast(data->args[1]); stepColorCommand.transitionTime = static_cast(data->args[2]); - stepColorCommand.optionsMask = static_cast(data->args[3]); - stepColorCommand.optionsOverride = static_cast(data->args[4]); + stepColorCommand.optionsMask = static_cast(data->args[3]); + stepColorCommand.optionsOverride = static_cast(data->args[4]); Controller::InvokeCommandRequest(peer_device->GetExchangeManager(), peer_device->GetSecureSession().Value(), binding.remote, stepColorCommand, onSuccess, onFailure); break; @@ -457,37 +457,37 @@ void ProcessColorControlUnicastBindingCommand(BindingCommandData * data, const E case Clusters::ColorControl::Commands::MoveToColorTemperature::Id: moveToColorTemperatureCommand.colorTemperatureMireds = static_cast(data->args[0]); moveToColorTemperatureCommand.transitionTime = static_cast(data->args[1]); - moveToColorTemperatureCommand.optionsMask = static_cast(data->args[2]); - moveToColorTemperatureCommand.optionsOverride = static_cast(data->args[3]); + moveToColorTemperatureCommand.optionsMask = static_cast(data->args[2]); + moveToColorTemperatureCommand.optionsOverride = static_cast(data->args[3]); Controller::InvokeCommandRequest(peer_device->GetExchangeManager(), peer_device->GetSecureSession().Value(), binding.remote, moveToColorTemperatureCommand, onSuccess, onFailure); break; case Clusters::ColorControl::Commands::EnhancedMoveToHue::Id: enhancedMoveToHueCommand.enhancedHue = static_cast(data->args[0]); - enhancedMoveToHueCommand.direction = static_cast(data->args[1]); + enhancedMoveToHueCommand.direction = static_cast(data->args[1]); enhancedMoveToHueCommand.transitionTime = static_cast(data->args[2]); - enhancedMoveToHueCommand.optionsMask = static_cast(data->args[3]); - enhancedMoveToHueCommand.optionsOverride = static_cast(data->args[4]); + enhancedMoveToHueCommand.optionsMask = static_cast(data->args[3]); + enhancedMoveToHueCommand.optionsOverride = static_cast(data->args[4]); Controller::InvokeCommandRequest(peer_device->GetExchangeManager(), peer_device->GetSecureSession().Value(), binding.remote, enhancedMoveToHueCommand, onSuccess, onFailure); break; case Clusters::ColorControl::Commands::EnhancedMoveHue::Id: - enhancedMoveHueCommand.moveMode = static_cast(data->args[0]); + enhancedMoveHueCommand.moveMode = static_cast(data->args[0]); enhancedMoveHueCommand.rate = static_cast(data->args[1]); - enhancedMoveHueCommand.optionsMask = static_cast(data->args[2]); - enhancedMoveHueCommand.optionsOverride = static_cast(data->args[3]); + enhancedMoveHueCommand.optionsMask = static_cast(data->args[2]); + enhancedMoveHueCommand.optionsOverride = static_cast(data->args[3]); Controller::InvokeCommandRequest(peer_device->GetExchangeManager(), peer_device->GetSecureSession().Value(), binding.remote, enhancedMoveHueCommand, onSuccess, onFailure); break; case Clusters::ColorControl::Commands::EnhancedStepHue::Id: - enhancedStepHueCommand.stepMode = static_cast(data->args[0]); + enhancedStepHueCommand.stepMode = static_cast(data->args[0]); enhancedStepHueCommand.stepSize = static_cast(data->args[1]); enhancedStepHueCommand.transitionTime = static_cast(data->args[2]); - enhancedStepHueCommand.optionsMask = static_cast(data->args[3]); - enhancedStepHueCommand.optionsOverride = static_cast(data->args[4]); + enhancedStepHueCommand.optionsMask = static_cast(data->args[3]); + enhancedStepHueCommand.optionsOverride = static_cast(data->args[4]); Controller::InvokeCommandRequest(peer_device->GetExchangeManager(), peer_device->GetSecureSession().Value(), binding.remote, enhancedStepHueCommand, onSuccess, onFailure); break; @@ -496,51 +496,51 @@ void ProcessColorControlUnicastBindingCommand(BindingCommandData * data, const E enhancedMoveToHueAndSaturationCommand.enhancedHue = static_cast(data->args[0]); enhancedMoveToHueAndSaturationCommand.saturation = static_cast(data->args[1]); enhancedMoveToHueAndSaturationCommand.transitionTime = static_cast(data->args[2]); - enhancedMoveToHueAndSaturationCommand.optionsMask = static_cast(data->args[3]); - enhancedMoveToHueAndSaturationCommand.optionsOverride = static_cast(data->args[4]); + enhancedMoveToHueAndSaturationCommand.optionsMask = static_cast(data->args[3]); + enhancedMoveToHueAndSaturationCommand.optionsOverride = static_cast(data->args[4]); Controller::InvokeCommandRequest(peer_device->GetExchangeManager(), peer_device->GetSecureSession().Value(), binding.remote, enhancedMoveToHueAndSaturationCommand, onSuccess, onFailure); break; case Clusters::ColorControl::Commands::ColorLoopSet::Id: colorLoopSetCommand.updateFlags = - static_cast>(data->args[0]); - colorLoopSetCommand.action = static_cast(data->args[1]); - colorLoopSetCommand.direction = static_cast(data->args[2]); + static_cast>(data->args[0]); + colorLoopSetCommand.action = static_cast(data->args[1]); + colorLoopSetCommand.direction = static_cast(data->args[2]); colorLoopSetCommand.time = static_cast(data->args[3]); colorLoopSetCommand.startHue = static_cast(data->args[4]); - colorLoopSetCommand.optionsMask = static_cast(data->args[5]); - colorLoopSetCommand.optionsOverride = static_cast(data->args[6]); + colorLoopSetCommand.optionsMask = static_cast(data->args[5]); + colorLoopSetCommand.optionsOverride = static_cast(data->args[6]); Controller::InvokeCommandRequest(peer_device->GetExchangeManager(), peer_device->GetSecureSession().Value(), binding.remote, colorLoopSetCommand, onSuccess, onFailure); break; case Clusters::ColorControl::Commands::StopMoveStep::Id: - stopMoveStepCommand.optionsMask = static_cast(data->args[0]); - stopMoveStepCommand.optionsOverride = static_cast(data->args[1]); + stopMoveStepCommand.optionsMask = static_cast(data->args[0]); + stopMoveStepCommand.optionsOverride = static_cast(data->args[1]); Controller::InvokeCommandRequest(peer_device->GetExchangeManager(), peer_device->GetSecureSession().Value(), binding.remote, stopMoveStepCommand, onSuccess, onFailure); break; case Clusters::ColorControl::Commands::MoveColorTemperature::Id: - moveColorTemperatureCommand.moveMode = static_cast(data->args[0]); + moveColorTemperatureCommand.moveMode = static_cast(data->args[0]); moveColorTemperatureCommand.rate = static_cast(data->args[1]); moveColorTemperatureCommand.colorTemperatureMinimumMireds = static_cast(data->args[2]); moveColorTemperatureCommand.colorTemperatureMaximumMireds = static_cast(data->args[3]); - moveColorTemperatureCommand.optionsMask = static_cast(data->args[4]); - moveColorTemperatureCommand.optionsOverride = static_cast(data->args[5]); + moveColorTemperatureCommand.optionsMask = static_cast(data->args[4]); + moveColorTemperatureCommand.optionsOverride = static_cast(data->args[5]); Controller::InvokeCommandRequest(peer_device->GetExchangeManager(), peer_device->GetSecureSession().Value(), binding.remote, moveColorTemperatureCommand, onSuccess, onFailure); break; case Clusters::ColorControl::Commands::StepColorTemperature::Id: - stepColorTemperatureCommand.stepMode = static_cast(data->args[0]); + stepColorTemperatureCommand.stepMode = static_cast(data->args[0]); stepColorTemperatureCommand.stepSize = static_cast(data->args[1]); stepColorTemperatureCommand.transitionTime = static_cast(data->args[2]); stepColorTemperatureCommand.colorTemperatureMinimumMireds = static_cast(data->args[3]); stepColorTemperatureCommand.colorTemperatureMaximumMireds = static_cast(data->args[4]); - stepColorTemperatureCommand.optionsMask = static_cast(data->args[5]); - stepColorTemperatureCommand.optionsOverride = static_cast(data->args[6]); + stepColorTemperatureCommand.optionsMask = static_cast(data->args[5]); + stepColorTemperatureCommand.optionsOverride = static_cast(data->args[6]); Controller::InvokeCommandRequest(peer_device->GetExchangeManager(), peer_device->GetSecureSession().Value(), binding.remote, stepColorTemperatureCommand, onSuccess, onFailure); break; @@ -577,52 +577,52 @@ void ProcessColorControlGroupBindingCommand(BindingCommandData * data, const Emb { case Clusters::ColorControl::Commands::MoveToHue::Id: moveToHueCommand.hue = static_cast(data->args[0]); - moveToHueCommand.direction = static_cast(data->args[1]); + moveToHueCommand.direction = static_cast(data->args[1]); moveToHueCommand.transitionTime = static_cast(data->args[2]); - moveToHueCommand.optionsMask = static_cast(data->args[3]); - moveToHueCommand.optionsOverride = static_cast(data->args[4]); + moveToHueCommand.optionsMask = static_cast(data->args[3]); + moveToHueCommand.optionsOverride = static_cast(data->args[4]); Controller::InvokeGroupCommandRequest(&exchangeMgr, binding.fabricIndex, binding.groupId, moveToHueCommand); break; case Clusters::ColorControl::Commands::MoveHue::Id: - moveHueCommand.moveMode = static_cast(data->args[0]); + moveHueCommand.moveMode = static_cast(data->args[0]); moveHueCommand.rate = static_cast(data->args[1]); - moveHueCommand.optionsMask = static_cast(data->args[2]); - moveHueCommand.optionsOverride = static_cast(data->args[3]); + moveHueCommand.optionsMask = static_cast(data->args[2]); + moveHueCommand.optionsOverride = static_cast(data->args[3]); Controller::InvokeGroupCommandRequest(&exchangeMgr, binding.fabricIndex, binding.groupId, moveHueCommand); break; case Clusters::ColorControl::Commands::StepHue::Id: - stepHueCommand.stepMode = static_cast(data->args[0]); + stepHueCommand.stepMode = static_cast(data->args[0]); stepHueCommand.stepSize = static_cast(data->args[1]); stepHueCommand.transitionTime = static_cast(data->args[2]); - stepHueCommand.optionsMask = static_cast(data->args[3]); - stepHueCommand.optionsOverride = static_cast(data->args[4]); + stepHueCommand.optionsMask = static_cast(data->args[3]); + stepHueCommand.optionsOverride = static_cast(data->args[4]); Controller::InvokeGroupCommandRequest(&exchangeMgr, binding.fabricIndex, binding.groupId, stepHueCommand); break; case Clusters::ColorControl::Commands::MoveToSaturation::Id: moveToSaturationCommand.saturation = static_cast(data->args[0]); moveToSaturationCommand.transitionTime = static_cast(data->args[1]); - moveToSaturationCommand.optionsMask = static_cast(data->args[2]); - moveToSaturationCommand.optionsOverride = static_cast(data->args[3]); + moveToSaturationCommand.optionsMask = static_cast(data->args[2]); + moveToSaturationCommand.optionsOverride = static_cast(data->args[3]); Controller::InvokeGroupCommandRequest(&exchangeMgr, binding.fabricIndex, binding.groupId, moveToSaturationCommand); break; case Clusters::ColorControl::Commands::MoveSaturation::Id: - moveSaturationCommand.moveMode = static_cast(data->args[0]); + moveSaturationCommand.moveMode = static_cast(data->args[0]); moveSaturationCommand.rate = static_cast(data->args[1]); - moveSaturationCommand.optionsMask = static_cast(data->args[2]); - moveSaturationCommand.optionsOverride = static_cast(data->args[3]); + moveSaturationCommand.optionsMask = static_cast(data->args[2]); + moveSaturationCommand.optionsOverride = static_cast(data->args[3]); Controller::InvokeGroupCommandRequest(&exchangeMgr, binding.fabricIndex, binding.groupId, moveSaturationCommand); break; case Clusters::ColorControl::Commands::StepSaturation::Id: - stepSaturationCommand.stepMode = static_cast(data->args[0]); + stepSaturationCommand.stepMode = static_cast(data->args[0]); stepSaturationCommand.stepSize = static_cast(data->args[1]); stepSaturationCommand.transitionTime = static_cast(data->args[2]); - stepSaturationCommand.optionsMask = static_cast(data->args[3]); - stepSaturationCommand.optionsOverride = static_cast(data->args[4]); + stepSaturationCommand.optionsMask = static_cast(data->args[3]); + stepSaturationCommand.optionsOverride = static_cast(data->args[4]); Controller::InvokeGroupCommandRequest(&exchangeMgr, binding.fabricIndex, binding.groupId, stepSaturationCommand); break; @@ -630,8 +630,8 @@ void ProcessColorControlGroupBindingCommand(BindingCommandData * data, const Emb moveToHueAndSaturationCommand.hue = static_cast(data->args[0]); moveToHueAndSaturationCommand.saturation = static_cast(data->args[1]); moveToHueAndSaturationCommand.transitionTime = static_cast(data->args[2]); - moveToHueAndSaturationCommand.optionsMask = static_cast(data->args[3]); - moveToHueAndSaturationCommand.optionsOverride = static_cast(data->args[4]); + moveToHueAndSaturationCommand.optionsMask = static_cast(data->args[3]); + moveToHueAndSaturationCommand.optionsOverride = static_cast(data->args[4]); Controller::InvokeGroupCommandRequest(&exchangeMgr, binding.fabricIndex, binding.groupId, moveToHueAndSaturationCommand); break; @@ -639,16 +639,16 @@ void ProcessColorControlGroupBindingCommand(BindingCommandData * data, const Emb moveToColorCommand.colorX = static_cast(data->args[0]); moveToColorCommand.colorY = static_cast(data->args[1]); moveToColorCommand.transitionTime = static_cast(data->args[2]); - moveToColorCommand.optionsMask = static_cast(data->args[3]); - moveToColorCommand.optionsOverride = static_cast(data->args[4]); + moveToColorCommand.optionsMask = static_cast(data->args[3]); + moveToColorCommand.optionsOverride = static_cast(data->args[4]); Controller::InvokeGroupCommandRequest(&exchangeMgr, binding.fabricIndex, binding.groupId, moveToColorCommand); break; case Clusters::ColorControl::Commands::MoveColor::Id: moveColorCommand.rateX = static_cast(data->args[0]); moveColorCommand.rateY = static_cast(data->args[1]); - moveColorCommand.optionsMask = static_cast(data->args[2]); - moveColorCommand.optionsOverride = static_cast(data->args[3]); + moveColorCommand.optionsMask = static_cast(data->args[2]); + moveColorCommand.optionsOverride = static_cast(data->args[3]); Controller::InvokeGroupCommandRequest(&exchangeMgr, binding.fabricIndex, binding.groupId, moveColorCommand); break; @@ -656,42 +656,42 @@ void ProcessColorControlGroupBindingCommand(BindingCommandData * data, const Emb stepColorCommand.stepX = static_cast(data->args[0]); stepColorCommand.stepY = static_cast(data->args[1]); stepColorCommand.transitionTime = static_cast(data->args[2]); - stepColorCommand.optionsMask = static_cast(data->args[3]); - stepColorCommand.optionsOverride = static_cast(data->args[4]); + stepColorCommand.optionsMask = static_cast(data->args[3]); + stepColorCommand.optionsOverride = static_cast(data->args[4]); Controller::InvokeGroupCommandRequest(&exchangeMgr, binding.fabricIndex, binding.groupId, stepColorCommand); break; case Clusters::ColorControl::Commands::MoveToColorTemperature::Id: moveToColorTemperatureCommand.colorTemperatureMireds = static_cast(data->args[0]); moveToColorTemperatureCommand.transitionTime = static_cast(data->args[1]); - moveToColorTemperatureCommand.optionsMask = static_cast(data->args[2]); - moveToColorTemperatureCommand.optionsOverride = static_cast(data->args[3]); + moveToColorTemperatureCommand.optionsMask = static_cast(data->args[2]); + moveToColorTemperatureCommand.optionsOverride = static_cast(data->args[3]); Controller::InvokeGroupCommandRequest(&exchangeMgr, binding.fabricIndex, binding.groupId, moveToColorTemperatureCommand); break; case Clusters::ColorControl::Commands::EnhancedMoveToHue::Id: enhancedMoveToHueCommand.enhancedHue = static_cast(data->args[0]); - enhancedMoveToHueCommand.direction = static_cast(data->args[1]); + enhancedMoveToHueCommand.direction = static_cast(data->args[1]); enhancedMoveToHueCommand.transitionTime = static_cast(data->args[2]); - enhancedMoveToHueCommand.optionsMask = static_cast(data->args[3]); - enhancedMoveToHueCommand.optionsOverride = static_cast(data->args[4]); + enhancedMoveToHueCommand.optionsMask = static_cast(data->args[3]); + enhancedMoveToHueCommand.optionsOverride = static_cast(data->args[4]); Controller::InvokeGroupCommandRequest(&exchangeMgr, binding.fabricIndex, binding.groupId, enhancedMoveToHueCommand); break; case Clusters::ColorControl::Commands::EnhancedMoveHue::Id: - enhancedMoveHueCommand.moveMode = static_cast(data->args[0]); + enhancedMoveHueCommand.moveMode = static_cast(data->args[0]); enhancedMoveHueCommand.rate = static_cast(data->args[1]); - enhancedMoveHueCommand.optionsMask = static_cast(data->args[2]); - enhancedMoveHueCommand.optionsOverride = static_cast(data->args[3]); + enhancedMoveHueCommand.optionsMask = static_cast(data->args[2]); + enhancedMoveHueCommand.optionsOverride = static_cast(data->args[3]); Controller::InvokeGroupCommandRequest(&exchangeMgr, binding.fabricIndex, binding.groupId, enhancedMoveHueCommand); break; case Clusters::ColorControl::Commands::EnhancedStepHue::Id: - enhancedStepHueCommand.stepMode = static_cast(data->args[0]); + enhancedStepHueCommand.stepMode = static_cast(data->args[0]); enhancedStepHueCommand.stepSize = static_cast(data->args[1]); enhancedStepHueCommand.transitionTime = static_cast(data->args[2]); - enhancedStepHueCommand.optionsMask = static_cast(data->args[3]); - enhancedStepHueCommand.optionsOverride = static_cast(data->args[4]); + enhancedStepHueCommand.optionsMask = static_cast(data->args[3]); + enhancedStepHueCommand.optionsOverride = static_cast(data->args[4]); Controller::InvokeGroupCommandRequest(&exchangeMgr, binding.fabricIndex, binding.groupId, enhancedStepHueCommand); break; @@ -699,48 +699,48 @@ void ProcessColorControlGroupBindingCommand(BindingCommandData * data, const Emb enhancedMoveToHueAndSaturationCommand.enhancedHue = static_cast(data->args[0]); enhancedMoveToHueAndSaturationCommand.saturation = static_cast(data->args[1]); enhancedMoveToHueAndSaturationCommand.transitionTime = static_cast(data->args[2]); - enhancedMoveToHueAndSaturationCommand.optionsMask = static_cast(data->args[3]); - enhancedMoveToHueAndSaturationCommand.optionsOverride = static_cast(data->args[4]); + enhancedMoveToHueAndSaturationCommand.optionsMask = static_cast(data->args[3]); + enhancedMoveToHueAndSaturationCommand.optionsOverride = static_cast(data->args[4]); Controller::InvokeGroupCommandRequest(&exchangeMgr, binding.fabricIndex, binding.groupId, enhancedMoveToHueAndSaturationCommand); break; case Clusters::ColorControl::Commands::ColorLoopSet::Id: colorLoopSetCommand.updateFlags = - static_cast>(data->args[0]); - colorLoopSetCommand.action = static_cast(data->args[1]); - colorLoopSetCommand.direction = static_cast(data->args[2]); + static_cast>(data->args[0]); + colorLoopSetCommand.action = static_cast(data->args[1]); + colorLoopSetCommand.direction = static_cast(data->args[2]); colorLoopSetCommand.time = static_cast(data->args[3]); colorLoopSetCommand.startHue = static_cast(data->args[4]); - colorLoopSetCommand.optionsMask = static_cast(data->args[5]); - colorLoopSetCommand.optionsOverride = static_cast(data->args[6]); + colorLoopSetCommand.optionsMask = static_cast(data->args[5]); + colorLoopSetCommand.optionsOverride = static_cast(data->args[6]); Controller::InvokeGroupCommandRequest(&exchangeMgr, binding.fabricIndex, binding.groupId, colorLoopSetCommand); break; case Clusters::ColorControl::Commands::StopMoveStep::Id: - stopMoveStepCommand.optionsMask = static_cast(data->args[0]); - stopMoveStepCommand.optionsOverride = static_cast(data->args[1]); + stopMoveStepCommand.optionsMask = static_cast(data->args[0]); + stopMoveStepCommand.optionsOverride = static_cast(data->args[1]); Controller::InvokeGroupCommandRequest(&exchangeMgr, binding.fabricIndex, binding.groupId, stopMoveStepCommand); break; case Clusters::ColorControl::Commands::MoveColorTemperature::Id: - moveColorTemperatureCommand.moveMode = static_cast(data->args[0]); + moveColorTemperatureCommand.moveMode = static_cast(data->args[0]); moveColorTemperatureCommand.rate = static_cast(data->args[1]); moveColorTemperatureCommand.colorTemperatureMinimumMireds = static_cast(data->args[2]); moveColorTemperatureCommand.colorTemperatureMaximumMireds = static_cast(data->args[3]); - moveColorTemperatureCommand.optionsMask = static_cast(data->args[4]); - moveColorTemperatureCommand.optionsOverride = static_cast(data->args[5]); + moveColorTemperatureCommand.optionsMask = static_cast(data->args[4]); + moveColorTemperatureCommand.optionsOverride = static_cast(data->args[5]); Controller::InvokeGroupCommandRequest(&exchangeMgr, binding.fabricIndex, binding.groupId, moveColorTemperatureCommand); break; case Clusters::ColorControl::Commands::StepColorTemperature::Id: - stepColorTemperatureCommand.stepMode = static_cast(data->args[0]); + stepColorTemperatureCommand.stepMode = static_cast(data->args[0]); stepColorTemperatureCommand.stepSize = static_cast(data->args[1]); stepColorTemperatureCommand.transitionTime = static_cast(data->args[2]); stepColorTemperatureCommand.colorTemperatureMinimumMireds = static_cast(data->args[3]); stepColorTemperatureCommand.colorTemperatureMaximumMireds = static_cast(data->args[4]); - stepColorTemperatureCommand.optionsMask = static_cast(data->args[5]); - stepColorTemperatureCommand.optionsOverride = static_cast(data->args[6]); + stepColorTemperatureCommand.optionsMask = static_cast(data->args[5]); + stepColorTemperatureCommand.optionsOverride = static_cast(data->args[6]); Controller::InvokeGroupCommandRequest(&exchangeMgr, binding.fabricIndex, binding.groupId, stepColorTemperatureCommand); break; } diff --git a/examples/all-clusters-minimal-app/all-clusters-common/all-clusters-minimal-app.matter b/examples/all-clusters-minimal-app/all-clusters-common/all-clusters-minimal-app.matter index 1444915c36..16f170c137 100644 --- a/examples/all-clusters-minimal-app/all-clusters-common/all-clusters-minimal-app.matter +++ b/examples/all-clusters-minimal-app/all-clusters-common/all-clusters-minimal-app.matter @@ -4281,65 +4281,62 @@ cluster ThermostatUserInterfaceConfiguration = 516 { cluster ColorControl = 768 { revision 7; - enum ColorLoopAction : enum8 { + enum ColorLoopActionEnum : enum8 { kDeactivate = 0; kActivateFromColorLoopStartEnhancedHue = 1; kActivateFromEnhancedCurrentHue = 2; } - enum ColorLoopDirection : enum8 { - kDecrementHue = 0; - kIncrementHue = 1; + enum ColorLoopDirectionEnum : enum8 { + kDecrement = 0; + kIncrement = 1; } - enum ColorMode : enum8 { + enum ColorModeEnum : enum8 { kCurrentHueAndCurrentSaturation = 0; kCurrentXAndCurrentY = 1; - kColorTemperature = 2; + kColorTemperatureMireds = 2; } - enum HueDirection : enum8 { - kShortestDistance = 0; - kLongestDistance = 1; + enum DirectionEnum : enum8 { + kShortest = 0; + kLongest = 1; kUp = 2; kDown = 3; } - enum HueMoveMode : enum8 { - kStop = 0; - kUp = 1; - kDown = 3; + enum DriftCompensationEnum : enum8 { + kNone = 0; + kOtherOrUnknown = 1; + kTemperatureMonitoring = 2; + kOpticalLuminanceMonitoringAndFeedback = 3; + kOpticalColorMonitoringAndFeedback = 4; } - enum HueStepMode : enum8 { - kUp = 1; - kDown = 3; + enum EnhancedColorModeEnum : enum8 { + kCurrentHueAndCurrentSaturation = 0; + kCurrentXAndCurrentY = 1; + kColorTemperatureMireds = 2; + kEnhancedCurrentHueAndCurrentSaturation = 3; } - enum SaturationMoveMode : enum8 { + enum MoveModeEnum : enum8 { kStop = 0; kUp = 1; kDown = 3; } - enum SaturationStepMode : enum8 { + enum StepModeEnum : enum8 { kUp = 1; kDown = 3; } - bitmap ColorCapabilities : bitmap16 { - kHueSaturationSupported = 0x1; - kEnhancedHueSupported = 0x2; - kColorLoopSupported = 0x4; - kXYAttributesSupported = 0x8; - kColorTemperatureSupported = 0x10; - } - - bitmap ColorLoopUpdateFlags : bitmap8 { - kUpdateAction = 0x1; - kUpdateDirection = 0x2; - kUpdateTime = 0x4; - kUpdateStartHue = 0x8; + bitmap ColorCapabilitiesBitmap : bitmap16 { + kHueSaturation = 0x1; + kEnhancedHue = 0x2; + kColorLoop = 0x4; + kXY = 0x8; + kColorTemperature = 0x10; } bitmap Feature : bitmap32 { @@ -4350,16 +4347,27 @@ cluster ColorControl = 768 { kColorTemperature = 0x10; } + bitmap OptionsBitmap : bitmap8 { + kExecuteIfOff = 0x1; + } + + bitmap UpdateFlagsBitmap : bitmap8 { + kUpdateAction = 0x1; + kUpdateDirection = 0x2; + kUpdateTime = 0x4; + kUpdateStartHue = 0x8; + } + readonly attribute optional int8u currentHue = 0; readonly attribute optional int8u currentSaturation = 1; readonly attribute optional int16u remainingTime = 2; readonly attribute optional int16u currentX = 3; readonly attribute optional int16u currentY = 4; - readonly attribute optional enum8 driftCompensation = 5; + readonly attribute optional DriftCompensationEnum driftCompensation = 5; readonly attribute optional char_string<254> compensationText = 6; readonly attribute optional int16u colorTemperatureMireds = 7; - readonly attribute enum8 colorMode = 8; - attribute bitmap8 options = 15; + readonly attribute ColorModeEnum colorMode = 8; + attribute OptionsBitmap options = 15; readonly attribute nullable int8u numberOfPrimaries = 16; readonly attribute optional int16u primary1X = 17; readonly attribute optional int16u primary1Y = 18; @@ -4391,13 +4399,13 @@ cluster ColorControl = 768 { attribute access(write: manage) optional int16u colorPointBY = 59; attribute access(write: manage) optional nullable int8u colorPointBIntensity = 60; readonly attribute optional int16u enhancedCurrentHue = 16384; - readonly attribute enum8 enhancedColorMode = 16385; + readonly attribute EnhancedColorModeEnum enhancedColorMode = 16385; readonly attribute optional int8u colorLoopActive = 16386; readonly attribute optional int8u colorLoopDirection = 16387; readonly attribute optional int16u colorLoopTime = 16388; readonly attribute optional int16u colorLoopStartEnhancedHue = 16389; readonly attribute optional int16u colorLoopStoredEnhancedHue = 16390; - readonly attribute bitmap16 colorCapabilities = 16394; + readonly attribute ColorCapabilitiesBitmap colorCapabilities = 16394; readonly attribute optional int16u colorTempPhysicalMinMireds = 16395; readonly attribute optional int16u colorTempPhysicalMaxMireds = 16396; readonly attribute optional int16u coupleColorTempToLevelMinMireds = 16397; @@ -4411,150 +4419,150 @@ cluster ColorControl = 768 { request struct MoveToHueRequest { int8u hue = 0; - HueDirection direction = 1; + DirectionEnum direction = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveHueRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int8u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepHueRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int8u stepSize = 1; int8u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToSaturationRequest { int8u saturation = 0; int16u transitionTime = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct MoveSaturationRequest { - SaturationMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int8u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepSaturationRequest { - SaturationStepMode stepMode = 0; + StepModeEnum stepMode = 0; int8u stepSize = 1; int8u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToHueAndSaturationRequest { int8u hue = 0; int8u saturation = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToColorRequest { int16u colorX = 0; int16u colorY = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveColorRequest { int16s rateX = 0; int16s rateY = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepColorRequest { int16s stepX = 0; int16s stepY = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToColorTemperatureRequest { int16u colorTemperatureMireds = 0; int16u transitionTime = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct EnhancedMoveToHueRequest { int16u enhancedHue = 0; - HueDirection direction = 1; + DirectionEnum direction = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct EnhancedMoveHueRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int16u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct EnhancedStepHueRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int16u stepSize = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct EnhancedMoveToHueAndSaturationRequest { int16u enhancedHue = 0; int8u saturation = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct ColorLoopSetRequest { - ColorLoopUpdateFlags updateFlags = 0; - ColorLoopAction action = 1; - ColorLoopDirection direction = 2; + UpdateFlagsBitmap updateFlags = 0; + ColorLoopActionEnum action = 1; + ColorLoopDirectionEnum direction = 2; int16u time = 3; int16u startHue = 4; - bitmap8 optionsMask = 5; - bitmap8 optionsOverride = 6; + OptionsBitmap optionsMask = 5; + OptionsBitmap optionsOverride = 6; } request struct StopMoveStepRequest { - bitmap8 optionsMask = 0; - bitmap8 optionsOverride = 1; + OptionsBitmap optionsMask = 0; + OptionsBitmap optionsOverride = 1; } request struct MoveColorTemperatureRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int16u rate = 1; int16u colorTemperatureMinimumMireds = 2; int16u colorTemperatureMaximumMireds = 3; - bitmap8 optionsMask = 4; - bitmap8 optionsOverride = 5; + OptionsBitmap optionsMask = 4; + OptionsBitmap optionsOverride = 5; } request struct StepColorTemperatureRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int16u stepSize = 1; int16u transitionTime = 2; int16u colorTemperatureMinimumMireds = 3; int16u colorTemperatureMaximumMireds = 4; - bitmap8 optionsMask = 5; - bitmap8 optionsOverride = 6; + OptionsBitmap optionsMask = 5; + OptionsBitmap optionsOverride = 6; } /** Move to specified hue. */ diff --git a/examples/chef/devices/rootnode_colortemperaturelight_hbUnzYVeyn.matter b/examples/chef/devices/rootnode_colortemperaturelight_hbUnzYVeyn.matter index 961f40352b..d8758b3043 100644 --- a/examples/chef/devices/rootnode_colortemperaturelight_hbUnzYVeyn.matter +++ b/examples/chef/devices/rootnode_colortemperaturelight_hbUnzYVeyn.matter @@ -1715,65 +1715,62 @@ cluster GroupKeyManagement = 63 { cluster ColorControl = 768 { revision 7; - enum ColorLoopAction : enum8 { + enum ColorLoopActionEnum : enum8 { kDeactivate = 0; kActivateFromColorLoopStartEnhancedHue = 1; kActivateFromEnhancedCurrentHue = 2; } - enum ColorLoopDirection : enum8 { - kDecrementHue = 0; - kIncrementHue = 1; + enum ColorLoopDirectionEnum : enum8 { + kDecrement = 0; + kIncrement = 1; } - enum ColorMode : enum8 { + enum ColorModeEnum : enum8 { kCurrentHueAndCurrentSaturation = 0; kCurrentXAndCurrentY = 1; - kColorTemperature = 2; + kColorTemperatureMireds = 2; } - enum HueDirection : enum8 { - kShortestDistance = 0; - kLongestDistance = 1; + enum DirectionEnum : enum8 { + kShortest = 0; + kLongest = 1; kUp = 2; kDown = 3; } - enum HueMoveMode : enum8 { - kStop = 0; - kUp = 1; - kDown = 3; + enum DriftCompensationEnum : enum8 { + kNone = 0; + kOtherOrUnknown = 1; + kTemperatureMonitoring = 2; + kOpticalLuminanceMonitoringAndFeedback = 3; + kOpticalColorMonitoringAndFeedback = 4; } - enum HueStepMode : enum8 { - kUp = 1; - kDown = 3; + enum EnhancedColorModeEnum : enum8 { + kCurrentHueAndCurrentSaturation = 0; + kCurrentXAndCurrentY = 1; + kColorTemperatureMireds = 2; + kEnhancedCurrentHueAndCurrentSaturation = 3; } - enum SaturationMoveMode : enum8 { + enum MoveModeEnum : enum8 { kStop = 0; kUp = 1; kDown = 3; } - enum SaturationStepMode : enum8 { + enum StepModeEnum : enum8 { kUp = 1; kDown = 3; } - bitmap ColorCapabilities : bitmap16 { - kHueSaturationSupported = 0x1; - kEnhancedHueSupported = 0x2; - kColorLoopSupported = 0x4; - kXYAttributesSupported = 0x8; - kColorTemperatureSupported = 0x10; - } - - bitmap ColorLoopUpdateFlags : bitmap8 { - kUpdateAction = 0x1; - kUpdateDirection = 0x2; - kUpdateTime = 0x4; - kUpdateStartHue = 0x8; + bitmap ColorCapabilitiesBitmap : bitmap16 { + kHueSaturation = 0x1; + kEnhancedHue = 0x2; + kColorLoop = 0x4; + kXY = 0x8; + kColorTemperature = 0x10; } bitmap Feature : bitmap32 { @@ -1784,16 +1781,27 @@ cluster ColorControl = 768 { kColorTemperature = 0x10; } + bitmap OptionsBitmap : bitmap8 { + kExecuteIfOff = 0x1; + } + + bitmap UpdateFlagsBitmap : bitmap8 { + kUpdateAction = 0x1; + kUpdateDirection = 0x2; + kUpdateTime = 0x4; + kUpdateStartHue = 0x8; + } + readonly attribute optional int8u currentHue = 0; readonly attribute optional int8u currentSaturation = 1; readonly attribute optional int16u remainingTime = 2; readonly attribute optional int16u currentX = 3; readonly attribute optional int16u currentY = 4; - readonly attribute optional enum8 driftCompensation = 5; + readonly attribute optional DriftCompensationEnum driftCompensation = 5; readonly attribute optional char_string<254> compensationText = 6; readonly attribute optional int16u colorTemperatureMireds = 7; - readonly attribute enum8 colorMode = 8; - attribute bitmap8 options = 15; + readonly attribute ColorModeEnum colorMode = 8; + attribute OptionsBitmap options = 15; readonly attribute nullable int8u numberOfPrimaries = 16; readonly attribute optional int16u primary1X = 17; readonly attribute optional int16u primary1Y = 18; @@ -1825,13 +1833,13 @@ cluster ColorControl = 768 { attribute access(write: manage) optional int16u colorPointBY = 59; attribute access(write: manage) optional nullable int8u colorPointBIntensity = 60; readonly attribute optional int16u enhancedCurrentHue = 16384; - readonly attribute enum8 enhancedColorMode = 16385; + readonly attribute EnhancedColorModeEnum enhancedColorMode = 16385; readonly attribute optional int8u colorLoopActive = 16386; readonly attribute optional int8u colorLoopDirection = 16387; readonly attribute optional int16u colorLoopTime = 16388; readonly attribute optional int16u colorLoopStartEnhancedHue = 16389; readonly attribute optional int16u colorLoopStoredEnhancedHue = 16390; - readonly attribute bitmap16 colorCapabilities = 16394; + readonly attribute ColorCapabilitiesBitmap colorCapabilities = 16394; readonly attribute optional int16u colorTempPhysicalMinMireds = 16395; readonly attribute optional int16u colorTempPhysicalMaxMireds = 16396; readonly attribute optional int16u coupleColorTempToLevelMinMireds = 16397; @@ -1845,150 +1853,150 @@ cluster ColorControl = 768 { request struct MoveToHueRequest { int8u hue = 0; - HueDirection direction = 1; + DirectionEnum direction = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveHueRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int8u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepHueRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int8u stepSize = 1; int8u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToSaturationRequest { int8u saturation = 0; int16u transitionTime = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct MoveSaturationRequest { - SaturationMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int8u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepSaturationRequest { - SaturationStepMode stepMode = 0; + StepModeEnum stepMode = 0; int8u stepSize = 1; int8u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToHueAndSaturationRequest { int8u hue = 0; int8u saturation = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToColorRequest { int16u colorX = 0; int16u colorY = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveColorRequest { int16s rateX = 0; int16s rateY = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepColorRequest { int16s stepX = 0; int16s stepY = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToColorTemperatureRequest { int16u colorTemperatureMireds = 0; int16u transitionTime = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct EnhancedMoveToHueRequest { int16u enhancedHue = 0; - HueDirection direction = 1; + DirectionEnum direction = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct EnhancedMoveHueRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int16u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct EnhancedStepHueRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int16u stepSize = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct EnhancedMoveToHueAndSaturationRequest { int16u enhancedHue = 0; int8u saturation = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct ColorLoopSetRequest { - ColorLoopUpdateFlags updateFlags = 0; - ColorLoopAction action = 1; - ColorLoopDirection direction = 2; + UpdateFlagsBitmap updateFlags = 0; + ColorLoopActionEnum action = 1; + ColorLoopDirectionEnum direction = 2; int16u time = 3; int16u startHue = 4; - bitmap8 optionsMask = 5; - bitmap8 optionsOverride = 6; + OptionsBitmap optionsMask = 5; + OptionsBitmap optionsOverride = 6; } request struct StopMoveStepRequest { - bitmap8 optionsMask = 0; - bitmap8 optionsOverride = 1; + OptionsBitmap optionsMask = 0; + OptionsBitmap optionsOverride = 1; } request struct MoveColorTemperatureRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int16u rate = 1; int16u colorTemperatureMinimumMireds = 2; int16u colorTemperatureMaximumMireds = 3; - bitmap8 optionsMask = 4; - bitmap8 optionsOverride = 5; + OptionsBitmap optionsMask = 4; + OptionsBitmap optionsOverride = 5; } request struct StepColorTemperatureRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int16u stepSize = 1; int16u transitionTime = 2; int16u colorTemperatureMinimumMireds = 3; int16u colorTemperatureMaximumMireds = 4; - bitmap8 optionsMask = 5; - bitmap8 optionsOverride = 6; + OptionsBitmap optionsMask = 5; + OptionsBitmap optionsOverride = 6; } /** Move to specified hue. */ diff --git a/examples/chef/devices/rootnode_extendedcolorlight_8lcaaYJVAa.matter b/examples/chef/devices/rootnode_extendedcolorlight_8lcaaYJVAa.matter index d9841f769a..0ef1c96972 100644 --- a/examples/chef/devices/rootnode_extendedcolorlight_8lcaaYJVAa.matter +++ b/examples/chef/devices/rootnode_extendedcolorlight_8lcaaYJVAa.matter @@ -1816,65 +1816,62 @@ cluster FixedLabel = 64 { cluster ColorControl = 768 { revision 7; - enum ColorLoopAction : enum8 { + enum ColorLoopActionEnum : enum8 { kDeactivate = 0; kActivateFromColorLoopStartEnhancedHue = 1; kActivateFromEnhancedCurrentHue = 2; } - enum ColorLoopDirection : enum8 { - kDecrementHue = 0; - kIncrementHue = 1; + enum ColorLoopDirectionEnum : enum8 { + kDecrement = 0; + kIncrement = 1; } - enum ColorMode : enum8 { + enum ColorModeEnum : enum8 { kCurrentHueAndCurrentSaturation = 0; kCurrentXAndCurrentY = 1; - kColorTemperature = 2; + kColorTemperatureMireds = 2; } - enum HueDirection : enum8 { - kShortestDistance = 0; - kLongestDistance = 1; + enum DirectionEnum : enum8 { + kShortest = 0; + kLongest = 1; kUp = 2; kDown = 3; } - enum HueMoveMode : enum8 { - kStop = 0; - kUp = 1; - kDown = 3; + enum DriftCompensationEnum : enum8 { + kNone = 0; + kOtherOrUnknown = 1; + kTemperatureMonitoring = 2; + kOpticalLuminanceMonitoringAndFeedback = 3; + kOpticalColorMonitoringAndFeedback = 4; } - enum HueStepMode : enum8 { - kUp = 1; - kDown = 3; + enum EnhancedColorModeEnum : enum8 { + kCurrentHueAndCurrentSaturation = 0; + kCurrentXAndCurrentY = 1; + kColorTemperatureMireds = 2; + kEnhancedCurrentHueAndCurrentSaturation = 3; } - enum SaturationMoveMode : enum8 { + enum MoveModeEnum : enum8 { kStop = 0; kUp = 1; kDown = 3; } - enum SaturationStepMode : enum8 { + enum StepModeEnum : enum8 { kUp = 1; kDown = 3; } - bitmap ColorCapabilities : bitmap16 { - kHueSaturationSupported = 0x1; - kEnhancedHueSupported = 0x2; - kColorLoopSupported = 0x4; - kXYAttributesSupported = 0x8; - kColorTemperatureSupported = 0x10; - } - - bitmap ColorLoopUpdateFlags : bitmap8 { - kUpdateAction = 0x1; - kUpdateDirection = 0x2; - kUpdateTime = 0x4; - kUpdateStartHue = 0x8; + bitmap ColorCapabilitiesBitmap : bitmap16 { + kHueSaturation = 0x1; + kEnhancedHue = 0x2; + kColorLoop = 0x4; + kXY = 0x8; + kColorTemperature = 0x10; } bitmap Feature : bitmap32 { @@ -1885,16 +1882,27 @@ cluster ColorControl = 768 { kColorTemperature = 0x10; } + bitmap OptionsBitmap : bitmap8 { + kExecuteIfOff = 0x1; + } + + bitmap UpdateFlagsBitmap : bitmap8 { + kUpdateAction = 0x1; + kUpdateDirection = 0x2; + kUpdateTime = 0x4; + kUpdateStartHue = 0x8; + } + readonly attribute optional int8u currentHue = 0; readonly attribute optional int8u currentSaturation = 1; readonly attribute optional int16u remainingTime = 2; readonly attribute optional int16u currentX = 3; readonly attribute optional int16u currentY = 4; - readonly attribute optional enum8 driftCompensation = 5; + readonly attribute optional DriftCompensationEnum driftCompensation = 5; readonly attribute optional char_string<254> compensationText = 6; readonly attribute optional int16u colorTemperatureMireds = 7; - readonly attribute enum8 colorMode = 8; - attribute bitmap8 options = 15; + readonly attribute ColorModeEnum colorMode = 8; + attribute OptionsBitmap options = 15; readonly attribute nullable int8u numberOfPrimaries = 16; readonly attribute optional int16u primary1X = 17; readonly attribute optional int16u primary1Y = 18; @@ -1926,13 +1934,13 @@ cluster ColorControl = 768 { attribute access(write: manage) optional int16u colorPointBY = 59; attribute access(write: manage) optional nullable int8u colorPointBIntensity = 60; readonly attribute optional int16u enhancedCurrentHue = 16384; - readonly attribute enum8 enhancedColorMode = 16385; + readonly attribute EnhancedColorModeEnum enhancedColorMode = 16385; readonly attribute optional int8u colorLoopActive = 16386; readonly attribute optional int8u colorLoopDirection = 16387; readonly attribute optional int16u colorLoopTime = 16388; readonly attribute optional int16u colorLoopStartEnhancedHue = 16389; readonly attribute optional int16u colorLoopStoredEnhancedHue = 16390; - readonly attribute bitmap16 colorCapabilities = 16394; + readonly attribute ColorCapabilitiesBitmap colorCapabilities = 16394; readonly attribute optional int16u colorTempPhysicalMinMireds = 16395; readonly attribute optional int16u colorTempPhysicalMaxMireds = 16396; readonly attribute optional int16u coupleColorTempToLevelMinMireds = 16397; @@ -1946,150 +1954,150 @@ cluster ColorControl = 768 { request struct MoveToHueRequest { int8u hue = 0; - HueDirection direction = 1; + DirectionEnum direction = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveHueRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int8u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepHueRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int8u stepSize = 1; int8u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToSaturationRequest { int8u saturation = 0; int16u transitionTime = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct MoveSaturationRequest { - SaturationMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int8u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepSaturationRequest { - SaturationStepMode stepMode = 0; + StepModeEnum stepMode = 0; int8u stepSize = 1; int8u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToHueAndSaturationRequest { int8u hue = 0; int8u saturation = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToColorRequest { int16u colorX = 0; int16u colorY = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveColorRequest { int16s rateX = 0; int16s rateY = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepColorRequest { int16s stepX = 0; int16s stepY = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToColorTemperatureRequest { int16u colorTemperatureMireds = 0; int16u transitionTime = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct EnhancedMoveToHueRequest { int16u enhancedHue = 0; - HueDirection direction = 1; + DirectionEnum direction = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct EnhancedMoveHueRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int16u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct EnhancedStepHueRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int16u stepSize = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct EnhancedMoveToHueAndSaturationRequest { int16u enhancedHue = 0; int8u saturation = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct ColorLoopSetRequest { - ColorLoopUpdateFlags updateFlags = 0; - ColorLoopAction action = 1; - ColorLoopDirection direction = 2; + UpdateFlagsBitmap updateFlags = 0; + ColorLoopActionEnum action = 1; + ColorLoopDirectionEnum direction = 2; int16u time = 3; int16u startHue = 4; - bitmap8 optionsMask = 5; - bitmap8 optionsOverride = 6; + OptionsBitmap optionsMask = 5; + OptionsBitmap optionsOverride = 6; } request struct StopMoveStepRequest { - bitmap8 optionsMask = 0; - bitmap8 optionsOverride = 1; + OptionsBitmap optionsMask = 0; + OptionsBitmap optionsOverride = 1; } request struct MoveColorTemperatureRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int16u rate = 1; int16u colorTemperatureMinimumMireds = 2; int16u colorTemperatureMaximumMireds = 3; - bitmap8 optionsMask = 4; - bitmap8 optionsOverride = 5; + OptionsBitmap optionsMask = 4; + OptionsBitmap optionsOverride = 5; } request struct StepColorTemperatureRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int16u stepSize = 1; int16u transitionTime = 2; int16u colorTemperatureMinimumMireds = 3; int16u colorTemperatureMaximumMireds = 4; - bitmap8 optionsMask = 5; - bitmap8 optionsOverride = 6; + OptionsBitmap optionsMask = 5; + OptionsBitmap optionsOverride = 6; } /** Move to specified hue. */ diff --git a/examples/common/imgui_ui/windows/light.cpp b/examples/common/imgui_ui/windows/light.cpp index 86899e044b..f4950739e6 100644 --- a/examples/common/imgui_ui/windows/light.cpp +++ b/examples/common/imgui_ui/windows/light.cpp @@ -155,14 +155,14 @@ void Light::Render() ImGui::Text("Color Control:"); ImGui::Indent(); const char * mode = // based on ColorMode attribute: spec 3.2.7.9 - (mColorMode == kColorModeCurrentHueAndCurrentSaturation) ? "Hue/Saturation" - : (mColorMode == kColorModeCurrentXAndCurrentY) ? "X/Y" - : (mColorMode == kColorModeColorTemperature) ? "Temperature/Mireds" - : "UNKNOWN"; + (mColorMode == ColorControl::ColorModeEnum::kCurrentHueAndCurrentSaturation) ? "Hue/Saturation" + : (mColorMode == ColorControl::ColorModeEnum::kCurrentXAndCurrentY) ? "X/Y" + : (mColorMode == ColorControl::ColorModeEnum::kColorTemperatureMireds) ? "Temperature/Mireds" + : "UNKNOWN"; ImGui::Text("Mode: %s", mode); - if (mColorMode == kColorModeCurrentHueAndCurrentSaturation) + if (mColorMode == ColorControl::ColorModeEnum::kCurrentHueAndCurrentSaturation) { const float hueDegrees = (mColorHue * 360.0f) / 254.0f; const float saturationPercent = 100.0f * (mColorSaturation / 254.0f); @@ -173,12 +173,12 @@ void Light::Render() ImGui::ColorButton("LightColor", HueSaturationToColor(hueDegrees, saturationPercent), 0 /* ImGuiColorEditFlags_* */, ImVec2(80, 80)); } - else if (mColorMode == kColorModeCurrentXAndCurrentY) + else if (mColorMode == ColorControl::ColorModeEnum::kCurrentXAndCurrentY) { ImGui::Text("Current X: %d", mColorX); ImGui::Text("Current Y: %d", mColorY); } - else if (mColorMode == kColorModeColorTemperature) + else if (mColorMode == ColorControl::ColorModeEnum::kColorTemperatureMireds) { ImGui::Text("Color Temperature Mireds: %d", mColorTemperatureMireds); } diff --git a/examples/common/imgui_ui/windows/light.h b/examples/common/imgui_ui/windows/light.h index 20942373d3..242f6c98b8 100644 --- a/examples/common/imgui_ui/windows/light.h +++ b/examples/common/imgui_ui/windows/light.h @@ -62,7 +62,8 @@ class Light : public Window uint16_t mLevelRemainingTime10sOfSec = 0; // Color control - uint8_t mColorMode = kColorModeCurrentHueAndCurrentSaturation; + chip::app::Clusters::ColorControl::ColorModeEnum mColorMode = + chip::app::Clusters::ColorControl::ColorModeEnum::kCurrentHueAndCurrentSaturation; uint8_t mColorHue = 0; uint8_t mColorSaturation = 0; uint16_t mColorX = 0; diff --git a/examples/light-switch-app/light-switch-common/light-switch-app.matter b/examples/light-switch-app/light-switch-common/light-switch-app.matter index 8cd9c653a7..3909b6073c 100644 --- a/examples/light-switch-app/light-switch-common/light-switch-app.matter +++ b/examples/light-switch-app/light-switch-common/light-switch-app.matter @@ -2502,65 +2502,62 @@ provisional cluster ScenesManagement = 98 { cluster ColorControl = 768 { revision 7; - enum ColorLoopAction : enum8 { + enum ColorLoopActionEnum : enum8 { kDeactivate = 0; kActivateFromColorLoopStartEnhancedHue = 1; kActivateFromEnhancedCurrentHue = 2; } - enum ColorLoopDirection : enum8 { - kDecrementHue = 0; - kIncrementHue = 1; + enum ColorLoopDirectionEnum : enum8 { + kDecrement = 0; + kIncrement = 1; } - enum ColorMode : enum8 { + enum ColorModeEnum : enum8 { kCurrentHueAndCurrentSaturation = 0; kCurrentXAndCurrentY = 1; - kColorTemperature = 2; + kColorTemperatureMireds = 2; } - enum HueDirection : enum8 { - kShortestDistance = 0; - kLongestDistance = 1; + enum DirectionEnum : enum8 { + kShortest = 0; + kLongest = 1; kUp = 2; kDown = 3; } - enum HueMoveMode : enum8 { - kStop = 0; - kUp = 1; - kDown = 3; + enum DriftCompensationEnum : enum8 { + kNone = 0; + kOtherOrUnknown = 1; + kTemperatureMonitoring = 2; + kOpticalLuminanceMonitoringAndFeedback = 3; + kOpticalColorMonitoringAndFeedback = 4; } - enum HueStepMode : enum8 { - kUp = 1; - kDown = 3; + enum EnhancedColorModeEnum : enum8 { + kCurrentHueAndCurrentSaturation = 0; + kCurrentXAndCurrentY = 1; + kColorTemperatureMireds = 2; + kEnhancedCurrentHueAndCurrentSaturation = 3; } - enum SaturationMoveMode : enum8 { + enum MoveModeEnum : enum8 { kStop = 0; kUp = 1; kDown = 3; } - enum SaturationStepMode : enum8 { + enum StepModeEnum : enum8 { kUp = 1; kDown = 3; } - bitmap ColorCapabilities : bitmap16 { - kHueSaturationSupported = 0x1; - kEnhancedHueSupported = 0x2; - kColorLoopSupported = 0x4; - kXYAttributesSupported = 0x8; - kColorTemperatureSupported = 0x10; - } - - bitmap ColorLoopUpdateFlags : bitmap8 { - kUpdateAction = 0x1; - kUpdateDirection = 0x2; - kUpdateTime = 0x4; - kUpdateStartHue = 0x8; + bitmap ColorCapabilitiesBitmap : bitmap16 { + kHueSaturation = 0x1; + kEnhancedHue = 0x2; + kColorLoop = 0x4; + kXY = 0x8; + kColorTemperature = 0x10; } bitmap Feature : bitmap32 { @@ -2571,16 +2568,27 @@ cluster ColorControl = 768 { kColorTemperature = 0x10; } + bitmap OptionsBitmap : bitmap8 { + kExecuteIfOff = 0x1; + } + + bitmap UpdateFlagsBitmap : bitmap8 { + kUpdateAction = 0x1; + kUpdateDirection = 0x2; + kUpdateTime = 0x4; + kUpdateStartHue = 0x8; + } + readonly attribute optional int8u currentHue = 0; readonly attribute optional int8u currentSaturation = 1; readonly attribute optional int16u remainingTime = 2; readonly attribute optional int16u currentX = 3; readonly attribute optional int16u currentY = 4; - readonly attribute optional enum8 driftCompensation = 5; + readonly attribute optional DriftCompensationEnum driftCompensation = 5; readonly attribute optional char_string<254> compensationText = 6; readonly attribute optional int16u colorTemperatureMireds = 7; - readonly attribute enum8 colorMode = 8; - attribute bitmap8 options = 15; + readonly attribute ColorModeEnum colorMode = 8; + attribute OptionsBitmap options = 15; readonly attribute nullable int8u numberOfPrimaries = 16; readonly attribute optional int16u primary1X = 17; readonly attribute optional int16u primary1Y = 18; @@ -2612,13 +2620,13 @@ cluster ColorControl = 768 { attribute access(write: manage) optional int16u colorPointBY = 59; attribute access(write: manage) optional nullable int8u colorPointBIntensity = 60; readonly attribute optional int16u enhancedCurrentHue = 16384; - readonly attribute enum8 enhancedColorMode = 16385; + readonly attribute EnhancedColorModeEnum enhancedColorMode = 16385; readonly attribute optional int8u colorLoopActive = 16386; readonly attribute optional int8u colorLoopDirection = 16387; readonly attribute optional int16u colorLoopTime = 16388; readonly attribute optional int16u colorLoopStartEnhancedHue = 16389; readonly attribute optional int16u colorLoopStoredEnhancedHue = 16390; - readonly attribute bitmap16 colorCapabilities = 16394; + readonly attribute ColorCapabilitiesBitmap colorCapabilities = 16394; readonly attribute optional int16u colorTempPhysicalMinMireds = 16395; readonly attribute optional int16u colorTempPhysicalMaxMireds = 16396; readonly attribute optional int16u coupleColorTempToLevelMinMireds = 16397; @@ -2632,150 +2640,150 @@ cluster ColorControl = 768 { request struct MoveToHueRequest { int8u hue = 0; - HueDirection direction = 1; + DirectionEnum direction = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveHueRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int8u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepHueRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int8u stepSize = 1; int8u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToSaturationRequest { int8u saturation = 0; int16u transitionTime = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct MoveSaturationRequest { - SaturationMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int8u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepSaturationRequest { - SaturationStepMode stepMode = 0; + StepModeEnum stepMode = 0; int8u stepSize = 1; int8u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToHueAndSaturationRequest { int8u hue = 0; int8u saturation = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToColorRequest { int16u colorX = 0; int16u colorY = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveColorRequest { int16s rateX = 0; int16s rateY = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepColorRequest { int16s stepX = 0; int16s stepY = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToColorTemperatureRequest { int16u colorTemperatureMireds = 0; int16u transitionTime = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct EnhancedMoveToHueRequest { int16u enhancedHue = 0; - HueDirection direction = 1; + DirectionEnum direction = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct EnhancedMoveHueRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int16u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct EnhancedStepHueRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int16u stepSize = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct EnhancedMoveToHueAndSaturationRequest { int16u enhancedHue = 0; int8u saturation = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct ColorLoopSetRequest { - ColorLoopUpdateFlags updateFlags = 0; - ColorLoopAction action = 1; - ColorLoopDirection direction = 2; + UpdateFlagsBitmap updateFlags = 0; + ColorLoopActionEnum action = 1; + ColorLoopDirectionEnum direction = 2; int16u time = 3; int16u startHue = 4; - bitmap8 optionsMask = 5; - bitmap8 optionsOverride = 6; + OptionsBitmap optionsMask = 5; + OptionsBitmap optionsOverride = 6; } request struct StopMoveStepRequest { - bitmap8 optionsMask = 0; - bitmap8 optionsOverride = 1; + OptionsBitmap optionsMask = 0; + OptionsBitmap optionsOverride = 1; } request struct MoveColorTemperatureRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int16u rate = 1; int16u colorTemperatureMinimumMireds = 2; int16u colorTemperatureMaximumMireds = 3; - bitmap8 optionsMask = 4; - bitmap8 optionsOverride = 5; + OptionsBitmap optionsMask = 4; + OptionsBitmap optionsOverride = 5; } request struct StepColorTemperatureRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int16u stepSize = 1; int16u transitionTime = 2; int16u colorTemperatureMinimumMireds = 3; int16u colorTemperatureMaximumMireds = 4; - bitmap8 optionsMask = 5; - bitmap8 optionsOverride = 6; + OptionsBitmap optionsMask = 5; + OptionsBitmap optionsOverride = 6; } /** Move to specified hue. */ diff --git a/examples/light-switch-app/qpg/zap/switch.matter b/examples/light-switch-app/qpg/zap/switch.matter index 6924e96503..c93a50bb03 100644 --- a/examples/light-switch-app/qpg/zap/switch.matter +++ b/examples/light-switch-app/qpg/zap/switch.matter @@ -2558,65 +2558,62 @@ provisional cluster ScenesManagement = 98 { cluster ColorControl = 768 { revision 7; - enum ColorLoopAction : enum8 { + enum ColorLoopActionEnum : enum8 { kDeactivate = 0; kActivateFromColorLoopStartEnhancedHue = 1; kActivateFromEnhancedCurrentHue = 2; } - enum ColorLoopDirection : enum8 { - kDecrementHue = 0; - kIncrementHue = 1; + enum ColorLoopDirectionEnum : enum8 { + kDecrement = 0; + kIncrement = 1; } - enum ColorMode : enum8 { + enum ColorModeEnum : enum8 { kCurrentHueAndCurrentSaturation = 0; kCurrentXAndCurrentY = 1; - kColorTemperature = 2; + kColorTemperatureMireds = 2; } - enum HueDirection : enum8 { - kShortestDistance = 0; - kLongestDistance = 1; + enum DirectionEnum : enum8 { + kShortest = 0; + kLongest = 1; kUp = 2; kDown = 3; } - enum HueMoveMode : enum8 { - kStop = 0; - kUp = 1; - kDown = 3; + enum DriftCompensationEnum : enum8 { + kNone = 0; + kOtherOrUnknown = 1; + kTemperatureMonitoring = 2; + kOpticalLuminanceMonitoringAndFeedback = 3; + kOpticalColorMonitoringAndFeedback = 4; } - enum HueStepMode : enum8 { - kUp = 1; - kDown = 3; + enum EnhancedColorModeEnum : enum8 { + kCurrentHueAndCurrentSaturation = 0; + kCurrentXAndCurrentY = 1; + kColorTemperatureMireds = 2; + kEnhancedCurrentHueAndCurrentSaturation = 3; } - enum SaturationMoveMode : enum8 { + enum MoveModeEnum : enum8 { kStop = 0; kUp = 1; kDown = 3; } - enum SaturationStepMode : enum8 { + enum StepModeEnum : enum8 { kUp = 1; kDown = 3; } - bitmap ColorCapabilities : bitmap16 { - kHueSaturationSupported = 0x1; - kEnhancedHueSupported = 0x2; - kColorLoopSupported = 0x4; - kXYAttributesSupported = 0x8; - kColorTemperatureSupported = 0x10; - } - - bitmap ColorLoopUpdateFlags : bitmap8 { - kUpdateAction = 0x1; - kUpdateDirection = 0x2; - kUpdateTime = 0x4; - kUpdateStartHue = 0x8; + bitmap ColorCapabilitiesBitmap : bitmap16 { + kHueSaturation = 0x1; + kEnhancedHue = 0x2; + kColorLoop = 0x4; + kXY = 0x8; + kColorTemperature = 0x10; } bitmap Feature : bitmap32 { @@ -2627,16 +2624,27 @@ cluster ColorControl = 768 { kColorTemperature = 0x10; } + bitmap OptionsBitmap : bitmap8 { + kExecuteIfOff = 0x1; + } + + bitmap UpdateFlagsBitmap : bitmap8 { + kUpdateAction = 0x1; + kUpdateDirection = 0x2; + kUpdateTime = 0x4; + kUpdateStartHue = 0x8; + } + readonly attribute optional int8u currentHue = 0; readonly attribute optional int8u currentSaturation = 1; readonly attribute optional int16u remainingTime = 2; readonly attribute optional int16u currentX = 3; readonly attribute optional int16u currentY = 4; - readonly attribute optional enum8 driftCompensation = 5; + readonly attribute optional DriftCompensationEnum driftCompensation = 5; readonly attribute optional char_string<254> compensationText = 6; readonly attribute optional int16u colorTemperatureMireds = 7; - readonly attribute enum8 colorMode = 8; - attribute bitmap8 options = 15; + readonly attribute ColorModeEnum colorMode = 8; + attribute OptionsBitmap options = 15; readonly attribute nullable int8u numberOfPrimaries = 16; readonly attribute optional int16u primary1X = 17; readonly attribute optional int16u primary1Y = 18; @@ -2668,13 +2676,13 @@ cluster ColorControl = 768 { attribute access(write: manage) optional int16u colorPointBY = 59; attribute access(write: manage) optional nullable int8u colorPointBIntensity = 60; readonly attribute optional int16u enhancedCurrentHue = 16384; - readonly attribute enum8 enhancedColorMode = 16385; + readonly attribute EnhancedColorModeEnum enhancedColorMode = 16385; readonly attribute optional int8u colorLoopActive = 16386; readonly attribute optional int8u colorLoopDirection = 16387; readonly attribute optional int16u colorLoopTime = 16388; readonly attribute optional int16u colorLoopStartEnhancedHue = 16389; readonly attribute optional int16u colorLoopStoredEnhancedHue = 16390; - readonly attribute bitmap16 colorCapabilities = 16394; + readonly attribute ColorCapabilitiesBitmap colorCapabilities = 16394; readonly attribute optional int16u colorTempPhysicalMinMireds = 16395; readonly attribute optional int16u colorTempPhysicalMaxMireds = 16396; readonly attribute optional int16u coupleColorTempToLevelMinMireds = 16397; @@ -2688,150 +2696,150 @@ cluster ColorControl = 768 { request struct MoveToHueRequest { int8u hue = 0; - HueDirection direction = 1; + DirectionEnum direction = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveHueRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int8u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepHueRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int8u stepSize = 1; int8u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToSaturationRequest { int8u saturation = 0; int16u transitionTime = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct MoveSaturationRequest { - SaturationMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int8u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepSaturationRequest { - SaturationStepMode stepMode = 0; + StepModeEnum stepMode = 0; int8u stepSize = 1; int8u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToHueAndSaturationRequest { int8u hue = 0; int8u saturation = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToColorRequest { int16u colorX = 0; int16u colorY = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveColorRequest { int16s rateX = 0; int16s rateY = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepColorRequest { int16s stepX = 0; int16s stepY = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToColorTemperatureRequest { int16u colorTemperatureMireds = 0; int16u transitionTime = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct EnhancedMoveToHueRequest { int16u enhancedHue = 0; - HueDirection direction = 1; + DirectionEnum direction = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct EnhancedMoveHueRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int16u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct EnhancedStepHueRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int16u stepSize = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct EnhancedMoveToHueAndSaturationRequest { int16u enhancedHue = 0; int8u saturation = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct ColorLoopSetRequest { - ColorLoopUpdateFlags updateFlags = 0; - ColorLoopAction action = 1; - ColorLoopDirection direction = 2; + UpdateFlagsBitmap updateFlags = 0; + ColorLoopActionEnum action = 1; + ColorLoopDirectionEnum direction = 2; int16u time = 3; int16u startHue = 4; - bitmap8 optionsMask = 5; - bitmap8 optionsOverride = 6; + OptionsBitmap optionsMask = 5; + OptionsBitmap optionsOverride = 6; } request struct StopMoveStepRequest { - bitmap8 optionsMask = 0; - bitmap8 optionsOverride = 1; + OptionsBitmap optionsMask = 0; + OptionsBitmap optionsOverride = 1; } request struct MoveColorTemperatureRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int16u rate = 1; int16u colorTemperatureMinimumMireds = 2; int16u colorTemperatureMaximumMireds = 3; - bitmap8 optionsMask = 4; - bitmap8 optionsOverride = 5; + OptionsBitmap optionsMask = 4; + OptionsBitmap optionsOverride = 5; } request struct StepColorTemperatureRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int16u stepSize = 1; int16u transitionTime = 2; int16u colorTemperatureMinimumMireds = 3; int16u colorTemperatureMaximumMireds = 4; - bitmap8 optionsMask = 5; - bitmap8 optionsOverride = 6; + OptionsBitmap optionsMask = 5; + OptionsBitmap optionsOverride = 6; } /** Move to specified hue. */ diff --git a/examples/lighting-app/bouffalolab/data_model/lighting-app-ethernet.matter b/examples/lighting-app/bouffalolab/data_model/lighting-app-ethernet.matter index 331f7e79ca..30f4d63c6a 100644 --- a/examples/lighting-app/bouffalolab/data_model/lighting-app-ethernet.matter +++ b/examples/lighting-app/bouffalolab/data_model/lighting-app-ethernet.matter @@ -1855,65 +1855,62 @@ cluster UserLabel = 65 { cluster ColorControl = 768 { revision 7; - enum ColorLoopAction : enum8 { + enum ColorLoopActionEnum : enum8 { kDeactivate = 0; kActivateFromColorLoopStartEnhancedHue = 1; kActivateFromEnhancedCurrentHue = 2; } - enum ColorLoopDirection : enum8 { - kDecrementHue = 0; - kIncrementHue = 1; + enum ColorLoopDirectionEnum : enum8 { + kDecrement = 0; + kIncrement = 1; } - enum ColorMode : enum8 { + enum ColorModeEnum : enum8 { kCurrentHueAndCurrentSaturation = 0; kCurrentXAndCurrentY = 1; - kColorTemperature = 2; + kColorTemperatureMireds = 2; } - enum HueDirection : enum8 { - kShortestDistance = 0; - kLongestDistance = 1; + enum DirectionEnum : enum8 { + kShortest = 0; + kLongest = 1; kUp = 2; kDown = 3; } - enum HueMoveMode : enum8 { - kStop = 0; - kUp = 1; - kDown = 3; + enum DriftCompensationEnum : enum8 { + kNone = 0; + kOtherOrUnknown = 1; + kTemperatureMonitoring = 2; + kOpticalLuminanceMonitoringAndFeedback = 3; + kOpticalColorMonitoringAndFeedback = 4; } - enum HueStepMode : enum8 { - kUp = 1; - kDown = 3; + enum EnhancedColorModeEnum : enum8 { + kCurrentHueAndCurrentSaturation = 0; + kCurrentXAndCurrentY = 1; + kColorTemperatureMireds = 2; + kEnhancedCurrentHueAndCurrentSaturation = 3; } - enum SaturationMoveMode : enum8 { + enum MoveModeEnum : enum8 { kStop = 0; kUp = 1; kDown = 3; } - enum SaturationStepMode : enum8 { + enum StepModeEnum : enum8 { kUp = 1; kDown = 3; } - bitmap ColorCapabilities : bitmap16 { - kHueSaturationSupported = 0x1; - kEnhancedHueSupported = 0x2; - kColorLoopSupported = 0x4; - kXYAttributesSupported = 0x8; - kColorTemperatureSupported = 0x10; - } - - bitmap ColorLoopUpdateFlags : bitmap8 { - kUpdateAction = 0x1; - kUpdateDirection = 0x2; - kUpdateTime = 0x4; - kUpdateStartHue = 0x8; + bitmap ColorCapabilitiesBitmap : bitmap16 { + kHueSaturation = 0x1; + kEnhancedHue = 0x2; + kColorLoop = 0x4; + kXY = 0x8; + kColorTemperature = 0x10; } bitmap Feature : bitmap32 { @@ -1924,16 +1921,27 @@ cluster ColorControl = 768 { kColorTemperature = 0x10; } + bitmap OptionsBitmap : bitmap8 { + kExecuteIfOff = 0x1; + } + + bitmap UpdateFlagsBitmap : bitmap8 { + kUpdateAction = 0x1; + kUpdateDirection = 0x2; + kUpdateTime = 0x4; + kUpdateStartHue = 0x8; + } + readonly attribute optional int8u currentHue = 0; readonly attribute optional int8u currentSaturation = 1; readonly attribute optional int16u remainingTime = 2; readonly attribute optional int16u currentX = 3; readonly attribute optional int16u currentY = 4; - readonly attribute optional enum8 driftCompensation = 5; + readonly attribute optional DriftCompensationEnum driftCompensation = 5; readonly attribute optional char_string<254> compensationText = 6; readonly attribute optional int16u colorTemperatureMireds = 7; - readonly attribute enum8 colorMode = 8; - attribute bitmap8 options = 15; + readonly attribute ColorModeEnum colorMode = 8; + attribute OptionsBitmap options = 15; readonly attribute nullable int8u numberOfPrimaries = 16; readonly attribute optional int16u primary1X = 17; readonly attribute optional int16u primary1Y = 18; @@ -1965,13 +1973,13 @@ cluster ColorControl = 768 { attribute access(write: manage) optional int16u colorPointBY = 59; attribute access(write: manage) optional nullable int8u colorPointBIntensity = 60; readonly attribute optional int16u enhancedCurrentHue = 16384; - readonly attribute enum8 enhancedColorMode = 16385; + readonly attribute EnhancedColorModeEnum enhancedColorMode = 16385; readonly attribute optional int8u colorLoopActive = 16386; readonly attribute optional int8u colorLoopDirection = 16387; readonly attribute optional int16u colorLoopTime = 16388; readonly attribute optional int16u colorLoopStartEnhancedHue = 16389; readonly attribute optional int16u colorLoopStoredEnhancedHue = 16390; - readonly attribute bitmap16 colorCapabilities = 16394; + readonly attribute ColorCapabilitiesBitmap colorCapabilities = 16394; readonly attribute optional int16u colorTempPhysicalMinMireds = 16395; readonly attribute optional int16u colorTempPhysicalMaxMireds = 16396; readonly attribute optional int16u coupleColorTempToLevelMinMireds = 16397; @@ -1985,150 +1993,150 @@ cluster ColorControl = 768 { request struct MoveToHueRequest { int8u hue = 0; - HueDirection direction = 1; + DirectionEnum direction = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveHueRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int8u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepHueRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int8u stepSize = 1; int8u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToSaturationRequest { int8u saturation = 0; int16u transitionTime = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct MoveSaturationRequest { - SaturationMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int8u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepSaturationRequest { - SaturationStepMode stepMode = 0; + StepModeEnum stepMode = 0; int8u stepSize = 1; int8u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToHueAndSaturationRequest { int8u hue = 0; int8u saturation = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToColorRequest { int16u colorX = 0; int16u colorY = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveColorRequest { int16s rateX = 0; int16s rateY = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepColorRequest { int16s stepX = 0; int16s stepY = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToColorTemperatureRequest { int16u colorTemperatureMireds = 0; int16u transitionTime = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct EnhancedMoveToHueRequest { int16u enhancedHue = 0; - HueDirection direction = 1; + DirectionEnum direction = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct EnhancedMoveHueRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int16u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct EnhancedStepHueRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int16u stepSize = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct EnhancedMoveToHueAndSaturationRequest { int16u enhancedHue = 0; int8u saturation = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct ColorLoopSetRequest { - ColorLoopUpdateFlags updateFlags = 0; - ColorLoopAction action = 1; - ColorLoopDirection direction = 2; + UpdateFlagsBitmap updateFlags = 0; + ColorLoopActionEnum action = 1; + ColorLoopDirectionEnum direction = 2; int16u time = 3; int16u startHue = 4; - bitmap8 optionsMask = 5; - bitmap8 optionsOverride = 6; + OptionsBitmap optionsMask = 5; + OptionsBitmap optionsOverride = 6; } request struct StopMoveStepRequest { - bitmap8 optionsMask = 0; - bitmap8 optionsOverride = 1; + OptionsBitmap optionsMask = 0; + OptionsBitmap optionsOverride = 1; } request struct MoveColorTemperatureRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int16u rate = 1; int16u colorTemperatureMinimumMireds = 2; int16u colorTemperatureMaximumMireds = 3; - bitmap8 optionsMask = 4; - bitmap8 optionsOverride = 5; + OptionsBitmap optionsMask = 4; + OptionsBitmap optionsOverride = 5; } request struct StepColorTemperatureRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int16u stepSize = 1; int16u transitionTime = 2; int16u colorTemperatureMinimumMireds = 3; int16u colorTemperatureMaximumMireds = 4; - bitmap8 optionsMask = 5; - bitmap8 optionsOverride = 6; + OptionsBitmap optionsMask = 5; + OptionsBitmap optionsOverride = 6; } /** Move to specified hue. */ diff --git a/examples/lighting-app/bouffalolab/data_model/lighting-app-thread.matter b/examples/lighting-app/bouffalolab/data_model/lighting-app-thread.matter index f6bb26ec68..2abf5c7251 100644 --- a/examples/lighting-app/bouffalolab/data_model/lighting-app-thread.matter +++ b/examples/lighting-app/bouffalolab/data_model/lighting-app-thread.matter @@ -1979,65 +1979,62 @@ cluster UserLabel = 65 { cluster ColorControl = 768 { revision 7; - enum ColorLoopAction : enum8 { + enum ColorLoopActionEnum : enum8 { kDeactivate = 0; kActivateFromColorLoopStartEnhancedHue = 1; kActivateFromEnhancedCurrentHue = 2; } - enum ColorLoopDirection : enum8 { - kDecrementHue = 0; - kIncrementHue = 1; + enum ColorLoopDirectionEnum : enum8 { + kDecrement = 0; + kIncrement = 1; } - enum ColorMode : enum8 { + enum ColorModeEnum : enum8 { kCurrentHueAndCurrentSaturation = 0; kCurrentXAndCurrentY = 1; - kColorTemperature = 2; + kColorTemperatureMireds = 2; } - enum HueDirection : enum8 { - kShortestDistance = 0; - kLongestDistance = 1; + enum DirectionEnum : enum8 { + kShortest = 0; + kLongest = 1; kUp = 2; kDown = 3; } - enum HueMoveMode : enum8 { - kStop = 0; - kUp = 1; - kDown = 3; + enum DriftCompensationEnum : enum8 { + kNone = 0; + kOtherOrUnknown = 1; + kTemperatureMonitoring = 2; + kOpticalLuminanceMonitoringAndFeedback = 3; + kOpticalColorMonitoringAndFeedback = 4; } - enum HueStepMode : enum8 { - kUp = 1; - kDown = 3; + enum EnhancedColorModeEnum : enum8 { + kCurrentHueAndCurrentSaturation = 0; + kCurrentXAndCurrentY = 1; + kColorTemperatureMireds = 2; + kEnhancedCurrentHueAndCurrentSaturation = 3; } - enum SaturationMoveMode : enum8 { + enum MoveModeEnum : enum8 { kStop = 0; kUp = 1; kDown = 3; } - enum SaturationStepMode : enum8 { + enum StepModeEnum : enum8 { kUp = 1; kDown = 3; } - bitmap ColorCapabilities : bitmap16 { - kHueSaturationSupported = 0x1; - kEnhancedHueSupported = 0x2; - kColorLoopSupported = 0x4; - kXYAttributesSupported = 0x8; - kColorTemperatureSupported = 0x10; - } - - bitmap ColorLoopUpdateFlags : bitmap8 { - kUpdateAction = 0x1; - kUpdateDirection = 0x2; - kUpdateTime = 0x4; - kUpdateStartHue = 0x8; + bitmap ColorCapabilitiesBitmap : bitmap16 { + kHueSaturation = 0x1; + kEnhancedHue = 0x2; + kColorLoop = 0x4; + kXY = 0x8; + kColorTemperature = 0x10; } bitmap Feature : bitmap32 { @@ -2048,16 +2045,27 @@ cluster ColorControl = 768 { kColorTemperature = 0x10; } + bitmap OptionsBitmap : bitmap8 { + kExecuteIfOff = 0x1; + } + + bitmap UpdateFlagsBitmap : bitmap8 { + kUpdateAction = 0x1; + kUpdateDirection = 0x2; + kUpdateTime = 0x4; + kUpdateStartHue = 0x8; + } + readonly attribute optional int8u currentHue = 0; readonly attribute optional int8u currentSaturation = 1; readonly attribute optional int16u remainingTime = 2; readonly attribute optional int16u currentX = 3; readonly attribute optional int16u currentY = 4; - readonly attribute optional enum8 driftCompensation = 5; + readonly attribute optional DriftCompensationEnum driftCompensation = 5; readonly attribute optional char_string<254> compensationText = 6; readonly attribute optional int16u colorTemperatureMireds = 7; - readonly attribute enum8 colorMode = 8; - attribute bitmap8 options = 15; + readonly attribute ColorModeEnum colorMode = 8; + attribute OptionsBitmap options = 15; readonly attribute nullable int8u numberOfPrimaries = 16; readonly attribute optional int16u primary1X = 17; readonly attribute optional int16u primary1Y = 18; @@ -2089,13 +2097,13 @@ cluster ColorControl = 768 { attribute access(write: manage) optional int16u colorPointBY = 59; attribute access(write: manage) optional nullable int8u colorPointBIntensity = 60; readonly attribute optional int16u enhancedCurrentHue = 16384; - readonly attribute enum8 enhancedColorMode = 16385; + readonly attribute EnhancedColorModeEnum enhancedColorMode = 16385; readonly attribute optional int8u colorLoopActive = 16386; readonly attribute optional int8u colorLoopDirection = 16387; readonly attribute optional int16u colorLoopTime = 16388; readonly attribute optional int16u colorLoopStartEnhancedHue = 16389; readonly attribute optional int16u colorLoopStoredEnhancedHue = 16390; - readonly attribute bitmap16 colorCapabilities = 16394; + readonly attribute ColorCapabilitiesBitmap colorCapabilities = 16394; readonly attribute optional int16u colorTempPhysicalMinMireds = 16395; readonly attribute optional int16u colorTempPhysicalMaxMireds = 16396; readonly attribute optional int16u coupleColorTempToLevelMinMireds = 16397; @@ -2109,150 +2117,150 @@ cluster ColorControl = 768 { request struct MoveToHueRequest { int8u hue = 0; - HueDirection direction = 1; + DirectionEnum direction = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveHueRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int8u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepHueRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int8u stepSize = 1; int8u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToSaturationRequest { int8u saturation = 0; int16u transitionTime = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct MoveSaturationRequest { - SaturationMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int8u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepSaturationRequest { - SaturationStepMode stepMode = 0; + StepModeEnum stepMode = 0; int8u stepSize = 1; int8u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToHueAndSaturationRequest { int8u hue = 0; int8u saturation = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToColorRequest { int16u colorX = 0; int16u colorY = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveColorRequest { int16s rateX = 0; int16s rateY = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepColorRequest { int16s stepX = 0; int16s stepY = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToColorTemperatureRequest { int16u colorTemperatureMireds = 0; int16u transitionTime = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct EnhancedMoveToHueRequest { int16u enhancedHue = 0; - HueDirection direction = 1; + DirectionEnum direction = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct EnhancedMoveHueRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int16u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct EnhancedStepHueRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int16u stepSize = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct EnhancedMoveToHueAndSaturationRequest { int16u enhancedHue = 0; int8u saturation = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct ColorLoopSetRequest { - ColorLoopUpdateFlags updateFlags = 0; - ColorLoopAction action = 1; - ColorLoopDirection direction = 2; + UpdateFlagsBitmap updateFlags = 0; + ColorLoopActionEnum action = 1; + ColorLoopDirectionEnum direction = 2; int16u time = 3; int16u startHue = 4; - bitmap8 optionsMask = 5; - bitmap8 optionsOverride = 6; + OptionsBitmap optionsMask = 5; + OptionsBitmap optionsOverride = 6; } request struct StopMoveStepRequest { - bitmap8 optionsMask = 0; - bitmap8 optionsOverride = 1; + OptionsBitmap optionsMask = 0; + OptionsBitmap optionsOverride = 1; } request struct MoveColorTemperatureRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int16u rate = 1; int16u colorTemperatureMinimumMireds = 2; int16u colorTemperatureMaximumMireds = 3; - bitmap8 optionsMask = 4; - bitmap8 optionsOverride = 5; + OptionsBitmap optionsMask = 4; + OptionsBitmap optionsOverride = 5; } request struct StepColorTemperatureRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int16u stepSize = 1; int16u transitionTime = 2; int16u colorTemperatureMinimumMireds = 3; int16u colorTemperatureMaximumMireds = 4; - bitmap8 optionsMask = 5; - bitmap8 optionsOverride = 6; + OptionsBitmap optionsMask = 5; + OptionsBitmap optionsOverride = 6; } /** Move to specified hue. */ diff --git a/examples/lighting-app/bouffalolab/data_model/lighting-app-wifi.matter b/examples/lighting-app/bouffalolab/data_model/lighting-app-wifi.matter index 9dee0bdcdb..b9dfeee632 100644 --- a/examples/lighting-app/bouffalolab/data_model/lighting-app-wifi.matter +++ b/examples/lighting-app/bouffalolab/data_model/lighting-app-wifi.matter @@ -1890,65 +1890,62 @@ cluster UserLabel = 65 { cluster ColorControl = 768 { revision 7; - enum ColorLoopAction : enum8 { + enum ColorLoopActionEnum : enum8 { kDeactivate = 0; kActivateFromColorLoopStartEnhancedHue = 1; kActivateFromEnhancedCurrentHue = 2; } - enum ColorLoopDirection : enum8 { - kDecrementHue = 0; - kIncrementHue = 1; + enum ColorLoopDirectionEnum : enum8 { + kDecrement = 0; + kIncrement = 1; } - enum ColorMode : enum8 { + enum ColorModeEnum : enum8 { kCurrentHueAndCurrentSaturation = 0; kCurrentXAndCurrentY = 1; - kColorTemperature = 2; + kColorTemperatureMireds = 2; } - enum HueDirection : enum8 { - kShortestDistance = 0; - kLongestDistance = 1; + enum DirectionEnum : enum8 { + kShortest = 0; + kLongest = 1; kUp = 2; kDown = 3; } - enum HueMoveMode : enum8 { - kStop = 0; - kUp = 1; - kDown = 3; + enum DriftCompensationEnum : enum8 { + kNone = 0; + kOtherOrUnknown = 1; + kTemperatureMonitoring = 2; + kOpticalLuminanceMonitoringAndFeedback = 3; + kOpticalColorMonitoringAndFeedback = 4; } - enum HueStepMode : enum8 { - kUp = 1; - kDown = 3; + enum EnhancedColorModeEnum : enum8 { + kCurrentHueAndCurrentSaturation = 0; + kCurrentXAndCurrentY = 1; + kColorTemperatureMireds = 2; + kEnhancedCurrentHueAndCurrentSaturation = 3; } - enum SaturationMoveMode : enum8 { + enum MoveModeEnum : enum8 { kStop = 0; kUp = 1; kDown = 3; } - enum SaturationStepMode : enum8 { + enum StepModeEnum : enum8 { kUp = 1; kDown = 3; } - bitmap ColorCapabilities : bitmap16 { - kHueSaturationSupported = 0x1; - kEnhancedHueSupported = 0x2; - kColorLoopSupported = 0x4; - kXYAttributesSupported = 0x8; - kColorTemperatureSupported = 0x10; - } - - bitmap ColorLoopUpdateFlags : bitmap8 { - kUpdateAction = 0x1; - kUpdateDirection = 0x2; - kUpdateTime = 0x4; - kUpdateStartHue = 0x8; + bitmap ColorCapabilitiesBitmap : bitmap16 { + kHueSaturation = 0x1; + kEnhancedHue = 0x2; + kColorLoop = 0x4; + kXY = 0x8; + kColorTemperature = 0x10; } bitmap Feature : bitmap32 { @@ -1959,16 +1956,27 @@ cluster ColorControl = 768 { kColorTemperature = 0x10; } + bitmap OptionsBitmap : bitmap8 { + kExecuteIfOff = 0x1; + } + + bitmap UpdateFlagsBitmap : bitmap8 { + kUpdateAction = 0x1; + kUpdateDirection = 0x2; + kUpdateTime = 0x4; + kUpdateStartHue = 0x8; + } + readonly attribute optional int8u currentHue = 0; readonly attribute optional int8u currentSaturation = 1; readonly attribute optional int16u remainingTime = 2; readonly attribute optional int16u currentX = 3; readonly attribute optional int16u currentY = 4; - readonly attribute optional enum8 driftCompensation = 5; + readonly attribute optional DriftCompensationEnum driftCompensation = 5; readonly attribute optional char_string<254> compensationText = 6; readonly attribute optional int16u colorTemperatureMireds = 7; - readonly attribute enum8 colorMode = 8; - attribute bitmap8 options = 15; + readonly attribute ColorModeEnum colorMode = 8; + attribute OptionsBitmap options = 15; readonly attribute nullable int8u numberOfPrimaries = 16; readonly attribute optional int16u primary1X = 17; readonly attribute optional int16u primary1Y = 18; @@ -2000,13 +2008,13 @@ cluster ColorControl = 768 { attribute access(write: manage) optional int16u colorPointBY = 59; attribute access(write: manage) optional nullable int8u colorPointBIntensity = 60; readonly attribute optional int16u enhancedCurrentHue = 16384; - readonly attribute enum8 enhancedColorMode = 16385; + readonly attribute EnhancedColorModeEnum enhancedColorMode = 16385; readonly attribute optional int8u colorLoopActive = 16386; readonly attribute optional int8u colorLoopDirection = 16387; readonly attribute optional int16u colorLoopTime = 16388; readonly attribute optional int16u colorLoopStartEnhancedHue = 16389; readonly attribute optional int16u colorLoopStoredEnhancedHue = 16390; - readonly attribute bitmap16 colorCapabilities = 16394; + readonly attribute ColorCapabilitiesBitmap colorCapabilities = 16394; readonly attribute optional int16u colorTempPhysicalMinMireds = 16395; readonly attribute optional int16u colorTempPhysicalMaxMireds = 16396; readonly attribute optional int16u coupleColorTempToLevelMinMireds = 16397; @@ -2020,150 +2028,150 @@ cluster ColorControl = 768 { request struct MoveToHueRequest { int8u hue = 0; - HueDirection direction = 1; + DirectionEnum direction = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveHueRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int8u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepHueRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int8u stepSize = 1; int8u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToSaturationRequest { int8u saturation = 0; int16u transitionTime = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct MoveSaturationRequest { - SaturationMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int8u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepSaturationRequest { - SaturationStepMode stepMode = 0; + StepModeEnum stepMode = 0; int8u stepSize = 1; int8u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToHueAndSaturationRequest { int8u hue = 0; int8u saturation = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToColorRequest { int16u colorX = 0; int16u colorY = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveColorRequest { int16s rateX = 0; int16s rateY = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepColorRequest { int16s stepX = 0; int16s stepY = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToColorTemperatureRequest { int16u colorTemperatureMireds = 0; int16u transitionTime = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct EnhancedMoveToHueRequest { int16u enhancedHue = 0; - HueDirection direction = 1; + DirectionEnum direction = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct EnhancedMoveHueRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int16u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct EnhancedStepHueRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int16u stepSize = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct EnhancedMoveToHueAndSaturationRequest { int16u enhancedHue = 0; int8u saturation = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct ColorLoopSetRequest { - ColorLoopUpdateFlags updateFlags = 0; - ColorLoopAction action = 1; - ColorLoopDirection direction = 2; + UpdateFlagsBitmap updateFlags = 0; + ColorLoopActionEnum action = 1; + ColorLoopDirectionEnum direction = 2; int16u time = 3; int16u startHue = 4; - bitmap8 optionsMask = 5; - bitmap8 optionsOverride = 6; + OptionsBitmap optionsMask = 5; + OptionsBitmap optionsOverride = 6; } request struct StopMoveStepRequest { - bitmap8 optionsMask = 0; - bitmap8 optionsOverride = 1; + OptionsBitmap optionsMask = 0; + OptionsBitmap optionsOverride = 1; } request struct MoveColorTemperatureRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int16u rate = 1; int16u colorTemperatureMinimumMireds = 2; int16u colorTemperatureMaximumMireds = 3; - bitmap8 optionsMask = 4; - bitmap8 optionsOverride = 5; + OptionsBitmap optionsMask = 4; + OptionsBitmap optionsOverride = 5; } request struct StepColorTemperatureRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int16u stepSize = 1; int16u transitionTime = 2; int16u colorTemperatureMinimumMireds = 3; int16u colorTemperatureMaximumMireds = 4; - bitmap8 optionsMask = 5; - bitmap8 optionsOverride = 6; + OptionsBitmap optionsMask = 5; + OptionsBitmap optionsOverride = 6; } /** Move to specified hue. */ diff --git a/examples/lighting-app/lighting-common/lighting-app.matter b/examples/lighting-app/lighting-common/lighting-app.matter index 5ddd707147..df7f0dfe4d 100644 --- a/examples/lighting-app/lighting-common/lighting-app.matter +++ b/examples/lighting-app/lighting-common/lighting-app.matter @@ -2310,65 +2310,62 @@ provisional cluster ScenesManagement = 98 { cluster ColorControl = 768 { revision 7; - enum ColorLoopAction : enum8 { + enum ColorLoopActionEnum : enum8 { kDeactivate = 0; kActivateFromColorLoopStartEnhancedHue = 1; kActivateFromEnhancedCurrentHue = 2; } - enum ColorLoopDirection : enum8 { - kDecrementHue = 0; - kIncrementHue = 1; + enum ColorLoopDirectionEnum : enum8 { + kDecrement = 0; + kIncrement = 1; } - enum ColorMode : enum8 { + enum ColorModeEnum : enum8 { kCurrentHueAndCurrentSaturation = 0; kCurrentXAndCurrentY = 1; - kColorTemperature = 2; + kColorTemperatureMireds = 2; } - enum HueDirection : enum8 { - kShortestDistance = 0; - kLongestDistance = 1; + enum DirectionEnum : enum8 { + kShortest = 0; + kLongest = 1; kUp = 2; kDown = 3; } - enum HueMoveMode : enum8 { - kStop = 0; - kUp = 1; - kDown = 3; + enum DriftCompensationEnum : enum8 { + kNone = 0; + kOtherOrUnknown = 1; + kTemperatureMonitoring = 2; + kOpticalLuminanceMonitoringAndFeedback = 3; + kOpticalColorMonitoringAndFeedback = 4; } - enum HueStepMode : enum8 { - kUp = 1; - kDown = 3; + enum EnhancedColorModeEnum : enum8 { + kCurrentHueAndCurrentSaturation = 0; + kCurrentXAndCurrentY = 1; + kColorTemperatureMireds = 2; + kEnhancedCurrentHueAndCurrentSaturation = 3; } - enum SaturationMoveMode : enum8 { + enum MoveModeEnum : enum8 { kStop = 0; kUp = 1; kDown = 3; } - enum SaturationStepMode : enum8 { + enum StepModeEnum : enum8 { kUp = 1; kDown = 3; } - bitmap ColorCapabilities : bitmap16 { - kHueSaturationSupported = 0x1; - kEnhancedHueSupported = 0x2; - kColorLoopSupported = 0x4; - kXYAttributesSupported = 0x8; - kColorTemperatureSupported = 0x10; - } - - bitmap ColorLoopUpdateFlags : bitmap8 { - kUpdateAction = 0x1; - kUpdateDirection = 0x2; - kUpdateTime = 0x4; - kUpdateStartHue = 0x8; + bitmap ColorCapabilitiesBitmap : bitmap16 { + kHueSaturation = 0x1; + kEnhancedHue = 0x2; + kColorLoop = 0x4; + kXY = 0x8; + kColorTemperature = 0x10; } bitmap Feature : bitmap32 { @@ -2379,16 +2376,27 @@ cluster ColorControl = 768 { kColorTemperature = 0x10; } + bitmap OptionsBitmap : bitmap8 { + kExecuteIfOff = 0x1; + } + + bitmap UpdateFlagsBitmap : bitmap8 { + kUpdateAction = 0x1; + kUpdateDirection = 0x2; + kUpdateTime = 0x4; + kUpdateStartHue = 0x8; + } + readonly attribute optional int8u currentHue = 0; readonly attribute optional int8u currentSaturation = 1; readonly attribute optional int16u remainingTime = 2; readonly attribute optional int16u currentX = 3; readonly attribute optional int16u currentY = 4; - readonly attribute optional enum8 driftCompensation = 5; + readonly attribute optional DriftCompensationEnum driftCompensation = 5; readonly attribute optional char_string<254> compensationText = 6; readonly attribute optional int16u colorTemperatureMireds = 7; - readonly attribute enum8 colorMode = 8; - attribute bitmap8 options = 15; + readonly attribute ColorModeEnum colorMode = 8; + attribute OptionsBitmap options = 15; readonly attribute nullable int8u numberOfPrimaries = 16; readonly attribute optional int16u primary1X = 17; readonly attribute optional int16u primary1Y = 18; @@ -2420,13 +2428,13 @@ cluster ColorControl = 768 { attribute access(write: manage) optional int16u colorPointBY = 59; attribute access(write: manage) optional nullable int8u colorPointBIntensity = 60; readonly attribute optional int16u enhancedCurrentHue = 16384; - readonly attribute enum8 enhancedColorMode = 16385; + readonly attribute EnhancedColorModeEnum enhancedColorMode = 16385; readonly attribute optional int8u colorLoopActive = 16386; readonly attribute optional int8u colorLoopDirection = 16387; readonly attribute optional int16u colorLoopTime = 16388; readonly attribute optional int16u colorLoopStartEnhancedHue = 16389; readonly attribute optional int16u colorLoopStoredEnhancedHue = 16390; - readonly attribute bitmap16 colorCapabilities = 16394; + readonly attribute ColorCapabilitiesBitmap colorCapabilities = 16394; readonly attribute optional int16u colorTempPhysicalMinMireds = 16395; readonly attribute optional int16u colorTempPhysicalMaxMireds = 16396; readonly attribute optional int16u coupleColorTempToLevelMinMireds = 16397; @@ -2440,150 +2448,150 @@ cluster ColorControl = 768 { request struct MoveToHueRequest { int8u hue = 0; - HueDirection direction = 1; + DirectionEnum direction = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveHueRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int8u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepHueRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int8u stepSize = 1; int8u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToSaturationRequest { int8u saturation = 0; int16u transitionTime = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct MoveSaturationRequest { - SaturationMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int8u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepSaturationRequest { - SaturationStepMode stepMode = 0; + StepModeEnum stepMode = 0; int8u stepSize = 1; int8u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToHueAndSaturationRequest { int8u hue = 0; int8u saturation = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToColorRequest { int16u colorX = 0; int16u colorY = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveColorRequest { int16s rateX = 0; int16s rateY = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepColorRequest { int16s stepX = 0; int16s stepY = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToColorTemperatureRequest { int16u colorTemperatureMireds = 0; int16u transitionTime = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct EnhancedMoveToHueRequest { int16u enhancedHue = 0; - HueDirection direction = 1; + DirectionEnum direction = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct EnhancedMoveHueRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int16u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct EnhancedStepHueRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int16u stepSize = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct EnhancedMoveToHueAndSaturationRequest { int16u enhancedHue = 0; int8u saturation = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct ColorLoopSetRequest { - ColorLoopUpdateFlags updateFlags = 0; - ColorLoopAction action = 1; - ColorLoopDirection direction = 2; + UpdateFlagsBitmap updateFlags = 0; + ColorLoopActionEnum action = 1; + ColorLoopDirectionEnum direction = 2; int16u time = 3; int16u startHue = 4; - bitmap8 optionsMask = 5; - bitmap8 optionsOverride = 6; + OptionsBitmap optionsMask = 5; + OptionsBitmap optionsOverride = 6; } request struct StopMoveStepRequest { - bitmap8 optionsMask = 0; - bitmap8 optionsOverride = 1; + OptionsBitmap optionsMask = 0; + OptionsBitmap optionsOverride = 1; } request struct MoveColorTemperatureRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int16u rate = 1; int16u colorTemperatureMinimumMireds = 2; int16u colorTemperatureMaximumMireds = 3; - bitmap8 optionsMask = 4; - bitmap8 optionsOverride = 5; + OptionsBitmap optionsMask = 4; + OptionsBitmap optionsOverride = 5; } request struct StepColorTemperatureRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int16u stepSize = 1; int16u transitionTime = 2; int16u colorTemperatureMinimumMireds = 3; int16u colorTemperatureMaximumMireds = 4; - bitmap8 optionsMask = 5; - bitmap8 optionsOverride = 6; + OptionsBitmap optionsMask = 5; + OptionsBitmap optionsOverride = 6; } /** Move to specified hue. */ diff --git a/examples/lighting-app/qpg/zap/light.matter b/examples/lighting-app/qpg/zap/light.matter index 6add567a13..35e0005673 100644 --- a/examples/lighting-app/qpg/zap/light.matter +++ b/examples/lighting-app/qpg/zap/light.matter @@ -1918,65 +1918,62 @@ cluster UserLabel = 65 { cluster ColorControl = 768 { revision 7; - enum ColorLoopAction : enum8 { + enum ColorLoopActionEnum : enum8 { kDeactivate = 0; kActivateFromColorLoopStartEnhancedHue = 1; kActivateFromEnhancedCurrentHue = 2; } - enum ColorLoopDirection : enum8 { - kDecrementHue = 0; - kIncrementHue = 1; + enum ColorLoopDirectionEnum : enum8 { + kDecrement = 0; + kIncrement = 1; } - enum ColorMode : enum8 { + enum ColorModeEnum : enum8 { kCurrentHueAndCurrentSaturation = 0; kCurrentXAndCurrentY = 1; - kColorTemperature = 2; + kColorTemperatureMireds = 2; } - enum HueDirection : enum8 { - kShortestDistance = 0; - kLongestDistance = 1; + enum DirectionEnum : enum8 { + kShortest = 0; + kLongest = 1; kUp = 2; kDown = 3; } - enum HueMoveMode : enum8 { - kStop = 0; - kUp = 1; - kDown = 3; + enum DriftCompensationEnum : enum8 { + kNone = 0; + kOtherOrUnknown = 1; + kTemperatureMonitoring = 2; + kOpticalLuminanceMonitoringAndFeedback = 3; + kOpticalColorMonitoringAndFeedback = 4; } - enum HueStepMode : enum8 { - kUp = 1; - kDown = 3; + enum EnhancedColorModeEnum : enum8 { + kCurrentHueAndCurrentSaturation = 0; + kCurrentXAndCurrentY = 1; + kColorTemperatureMireds = 2; + kEnhancedCurrentHueAndCurrentSaturation = 3; } - enum SaturationMoveMode : enum8 { + enum MoveModeEnum : enum8 { kStop = 0; kUp = 1; kDown = 3; } - enum SaturationStepMode : enum8 { + enum StepModeEnum : enum8 { kUp = 1; kDown = 3; } - bitmap ColorCapabilities : bitmap16 { - kHueSaturationSupported = 0x1; - kEnhancedHueSupported = 0x2; - kColorLoopSupported = 0x4; - kXYAttributesSupported = 0x8; - kColorTemperatureSupported = 0x10; - } - - bitmap ColorLoopUpdateFlags : bitmap8 { - kUpdateAction = 0x1; - kUpdateDirection = 0x2; - kUpdateTime = 0x4; - kUpdateStartHue = 0x8; + bitmap ColorCapabilitiesBitmap : bitmap16 { + kHueSaturation = 0x1; + kEnhancedHue = 0x2; + kColorLoop = 0x4; + kXY = 0x8; + kColorTemperature = 0x10; } bitmap Feature : bitmap32 { @@ -1987,16 +1984,27 @@ cluster ColorControl = 768 { kColorTemperature = 0x10; } + bitmap OptionsBitmap : bitmap8 { + kExecuteIfOff = 0x1; + } + + bitmap UpdateFlagsBitmap : bitmap8 { + kUpdateAction = 0x1; + kUpdateDirection = 0x2; + kUpdateTime = 0x4; + kUpdateStartHue = 0x8; + } + readonly attribute optional int8u currentHue = 0; readonly attribute optional int8u currentSaturation = 1; readonly attribute optional int16u remainingTime = 2; readonly attribute optional int16u currentX = 3; readonly attribute optional int16u currentY = 4; - readonly attribute optional enum8 driftCompensation = 5; + readonly attribute optional DriftCompensationEnum driftCompensation = 5; readonly attribute optional char_string<254> compensationText = 6; readonly attribute optional int16u colorTemperatureMireds = 7; - readonly attribute enum8 colorMode = 8; - attribute bitmap8 options = 15; + readonly attribute ColorModeEnum colorMode = 8; + attribute OptionsBitmap options = 15; readonly attribute nullable int8u numberOfPrimaries = 16; readonly attribute optional int16u primary1X = 17; readonly attribute optional int16u primary1Y = 18; @@ -2028,13 +2036,13 @@ cluster ColorControl = 768 { attribute access(write: manage) optional int16u colorPointBY = 59; attribute access(write: manage) optional nullable int8u colorPointBIntensity = 60; readonly attribute optional int16u enhancedCurrentHue = 16384; - readonly attribute enum8 enhancedColorMode = 16385; + readonly attribute EnhancedColorModeEnum enhancedColorMode = 16385; readonly attribute optional int8u colorLoopActive = 16386; readonly attribute optional int8u colorLoopDirection = 16387; readonly attribute optional int16u colorLoopTime = 16388; readonly attribute optional int16u colorLoopStartEnhancedHue = 16389; readonly attribute optional int16u colorLoopStoredEnhancedHue = 16390; - readonly attribute bitmap16 colorCapabilities = 16394; + readonly attribute ColorCapabilitiesBitmap colorCapabilities = 16394; readonly attribute optional int16u colorTempPhysicalMinMireds = 16395; readonly attribute optional int16u colorTempPhysicalMaxMireds = 16396; readonly attribute optional int16u coupleColorTempToLevelMinMireds = 16397; @@ -2048,150 +2056,150 @@ cluster ColorControl = 768 { request struct MoveToHueRequest { int8u hue = 0; - HueDirection direction = 1; + DirectionEnum direction = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveHueRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int8u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepHueRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int8u stepSize = 1; int8u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToSaturationRequest { int8u saturation = 0; int16u transitionTime = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct MoveSaturationRequest { - SaturationMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int8u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepSaturationRequest { - SaturationStepMode stepMode = 0; + StepModeEnum stepMode = 0; int8u stepSize = 1; int8u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToHueAndSaturationRequest { int8u hue = 0; int8u saturation = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToColorRequest { int16u colorX = 0; int16u colorY = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveColorRequest { int16s rateX = 0; int16s rateY = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepColorRequest { int16s stepX = 0; int16s stepY = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToColorTemperatureRequest { int16u colorTemperatureMireds = 0; int16u transitionTime = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct EnhancedMoveToHueRequest { int16u enhancedHue = 0; - HueDirection direction = 1; + DirectionEnum direction = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct EnhancedMoveHueRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int16u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct EnhancedStepHueRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int16u stepSize = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct EnhancedMoveToHueAndSaturationRequest { int16u enhancedHue = 0; int8u saturation = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct ColorLoopSetRequest { - ColorLoopUpdateFlags updateFlags = 0; - ColorLoopAction action = 1; - ColorLoopDirection direction = 2; + UpdateFlagsBitmap updateFlags = 0; + ColorLoopActionEnum action = 1; + ColorLoopDirectionEnum direction = 2; int16u time = 3; int16u startHue = 4; - bitmap8 optionsMask = 5; - bitmap8 optionsOverride = 6; + OptionsBitmap optionsMask = 5; + OptionsBitmap optionsOverride = 6; } request struct StopMoveStepRequest { - bitmap8 optionsMask = 0; - bitmap8 optionsOverride = 1; + OptionsBitmap optionsMask = 0; + OptionsBitmap optionsOverride = 1; } request struct MoveColorTemperatureRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int16u rate = 1; int16u colorTemperatureMinimumMireds = 2; int16u colorTemperatureMaximumMireds = 3; - bitmap8 optionsMask = 4; - bitmap8 optionsOverride = 5; + OptionsBitmap optionsMask = 4; + OptionsBitmap optionsOverride = 5; } request struct StepColorTemperatureRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int16u stepSize = 1; int16u transitionTime = 2; int16u colorTemperatureMinimumMireds = 3; int16u colorTemperatureMaximumMireds = 4; - bitmap8 optionsMask = 5; - bitmap8 optionsOverride = 6; + OptionsBitmap optionsMask = 5; + OptionsBitmap optionsOverride = 6; } /** Move to specified hue. */ 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 d0e06e94f9..f4c2928a35 100644 --- a/examples/lighting-app/silabs/data_model/lighting-thread-app.matter +++ b/examples/lighting-app/silabs/data_model/lighting-thread-app.matter @@ -2014,65 +2014,62 @@ provisional cluster ScenesManagement = 98 { cluster ColorControl = 768 { revision 7; - enum ColorLoopAction : enum8 { + enum ColorLoopActionEnum : enum8 { kDeactivate = 0; kActivateFromColorLoopStartEnhancedHue = 1; kActivateFromEnhancedCurrentHue = 2; } - enum ColorLoopDirection : enum8 { - kDecrementHue = 0; - kIncrementHue = 1; + enum ColorLoopDirectionEnum : enum8 { + kDecrement = 0; + kIncrement = 1; } - enum ColorMode : enum8 { + enum ColorModeEnum : enum8 { kCurrentHueAndCurrentSaturation = 0; kCurrentXAndCurrentY = 1; - kColorTemperature = 2; + kColorTemperatureMireds = 2; } - enum HueDirection : enum8 { - kShortestDistance = 0; - kLongestDistance = 1; + enum DirectionEnum : enum8 { + kShortest = 0; + kLongest = 1; kUp = 2; kDown = 3; } - enum HueMoveMode : enum8 { - kStop = 0; - kUp = 1; - kDown = 3; + enum DriftCompensationEnum : enum8 { + kNone = 0; + kOtherOrUnknown = 1; + kTemperatureMonitoring = 2; + kOpticalLuminanceMonitoringAndFeedback = 3; + kOpticalColorMonitoringAndFeedback = 4; } - enum HueStepMode : enum8 { - kUp = 1; - kDown = 3; + enum EnhancedColorModeEnum : enum8 { + kCurrentHueAndCurrentSaturation = 0; + kCurrentXAndCurrentY = 1; + kColorTemperatureMireds = 2; + kEnhancedCurrentHueAndCurrentSaturation = 3; } - enum SaturationMoveMode : enum8 { + enum MoveModeEnum : enum8 { kStop = 0; kUp = 1; kDown = 3; } - enum SaturationStepMode : enum8 { + enum StepModeEnum : enum8 { kUp = 1; kDown = 3; } - bitmap ColorCapabilities : bitmap16 { - kHueSaturationSupported = 0x1; - kEnhancedHueSupported = 0x2; - kColorLoopSupported = 0x4; - kXYAttributesSupported = 0x8; - kColorTemperatureSupported = 0x10; - } - - bitmap ColorLoopUpdateFlags : bitmap8 { - kUpdateAction = 0x1; - kUpdateDirection = 0x2; - kUpdateTime = 0x4; - kUpdateStartHue = 0x8; + bitmap ColorCapabilitiesBitmap : bitmap16 { + kHueSaturation = 0x1; + kEnhancedHue = 0x2; + kColorLoop = 0x4; + kXY = 0x8; + kColorTemperature = 0x10; } bitmap Feature : bitmap32 { @@ -2083,16 +2080,27 @@ cluster ColorControl = 768 { kColorTemperature = 0x10; } + bitmap OptionsBitmap : bitmap8 { + kExecuteIfOff = 0x1; + } + + bitmap UpdateFlagsBitmap : bitmap8 { + kUpdateAction = 0x1; + kUpdateDirection = 0x2; + kUpdateTime = 0x4; + kUpdateStartHue = 0x8; + } + readonly attribute optional int8u currentHue = 0; readonly attribute optional int8u currentSaturation = 1; readonly attribute optional int16u remainingTime = 2; readonly attribute optional int16u currentX = 3; readonly attribute optional int16u currentY = 4; - readonly attribute optional enum8 driftCompensation = 5; + readonly attribute optional DriftCompensationEnum driftCompensation = 5; readonly attribute optional char_string<254> compensationText = 6; readonly attribute optional int16u colorTemperatureMireds = 7; - readonly attribute enum8 colorMode = 8; - attribute bitmap8 options = 15; + readonly attribute ColorModeEnum colorMode = 8; + attribute OptionsBitmap options = 15; readonly attribute nullable int8u numberOfPrimaries = 16; readonly attribute optional int16u primary1X = 17; readonly attribute optional int16u primary1Y = 18; @@ -2124,13 +2132,13 @@ cluster ColorControl = 768 { attribute access(write: manage) optional int16u colorPointBY = 59; attribute access(write: manage) optional nullable int8u colorPointBIntensity = 60; readonly attribute optional int16u enhancedCurrentHue = 16384; - readonly attribute enum8 enhancedColorMode = 16385; + readonly attribute EnhancedColorModeEnum enhancedColorMode = 16385; readonly attribute optional int8u colorLoopActive = 16386; readonly attribute optional int8u colorLoopDirection = 16387; readonly attribute optional int16u colorLoopTime = 16388; readonly attribute optional int16u colorLoopStartEnhancedHue = 16389; readonly attribute optional int16u colorLoopStoredEnhancedHue = 16390; - readonly attribute bitmap16 colorCapabilities = 16394; + readonly attribute ColorCapabilitiesBitmap colorCapabilities = 16394; readonly attribute optional int16u colorTempPhysicalMinMireds = 16395; readonly attribute optional int16u colorTempPhysicalMaxMireds = 16396; readonly attribute optional int16u coupleColorTempToLevelMinMireds = 16397; @@ -2144,150 +2152,150 @@ cluster ColorControl = 768 { request struct MoveToHueRequest { int8u hue = 0; - HueDirection direction = 1; + DirectionEnum direction = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveHueRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int8u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepHueRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int8u stepSize = 1; int8u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToSaturationRequest { int8u saturation = 0; int16u transitionTime = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct MoveSaturationRequest { - SaturationMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int8u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepSaturationRequest { - SaturationStepMode stepMode = 0; + StepModeEnum stepMode = 0; int8u stepSize = 1; int8u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToHueAndSaturationRequest { int8u hue = 0; int8u saturation = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToColorRequest { int16u colorX = 0; int16u colorY = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveColorRequest { int16s rateX = 0; int16s rateY = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepColorRequest { int16s stepX = 0; int16s stepY = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToColorTemperatureRequest { int16u colorTemperatureMireds = 0; int16u transitionTime = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct EnhancedMoveToHueRequest { int16u enhancedHue = 0; - HueDirection direction = 1; + DirectionEnum direction = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct EnhancedMoveHueRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int16u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct EnhancedStepHueRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int16u stepSize = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct EnhancedMoveToHueAndSaturationRequest { int16u enhancedHue = 0; int8u saturation = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct ColorLoopSetRequest { - ColorLoopUpdateFlags updateFlags = 0; - ColorLoopAction action = 1; - ColorLoopDirection direction = 2; + UpdateFlagsBitmap updateFlags = 0; + ColorLoopActionEnum action = 1; + ColorLoopDirectionEnum direction = 2; int16u time = 3; int16u startHue = 4; - bitmap8 optionsMask = 5; - bitmap8 optionsOverride = 6; + OptionsBitmap optionsMask = 5; + OptionsBitmap optionsOverride = 6; } request struct StopMoveStepRequest { - bitmap8 optionsMask = 0; - bitmap8 optionsOverride = 1; + OptionsBitmap optionsMask = 0; + OptionsBitmap optionsOverride = 1; } request struct MoveColorTemperatureRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int16u rate = 1; int16u colorTemperatureMinimumMireds = 2; int16u colorTemperatureMaximumMireds = 3; - bitmap8 optionsMask = 4; - bitmap8 optionsOverride = 5; + OptionsBitmap optionsMask = 4; + OptionsBitmap optionsOverride = 5; } request struct StepColorTemperatureRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int16u stepSize = 1; int16u transitionTime = 2; int16u colorTemperatureMinimumMireds = 3; int16u colorTemperatureMaximumMireds = 4; - bitmap8 optionsMask = 5; - bitmap8 optionsOverride = 6; + OptionsBitmap optionsMask = 5; + OptionsBitmap optionsOverride = 6; } /** Move to specified hue. */ 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 a9d48f8ae8..59919ee6b4 100644 --- a/examples/lighting-app/silabs/data_model/lighting-wifi-app.matter +++ b/examples/lighting-app/silabs/data_model/lighting-wifi-app.matter @@ -2305,65 +2305,62 @@ provisional cluster ScenesManagement = 98 { cluster ColorControl = 768 { revision 7; - enum ColorLoopAction : enum8 { + enum ColorLoopActionEnum : enum8 { kDeactivate = 0; kActivateFromColorLoopStartEnhancedHue = 1; kActivateFromEnhancedCurrentHue = 2; } - enum ColorLoopDirection : enum8 { - kDecrementHue = 0; - kIncrementHue = 1; + enum ColorLoopDirectionEnum : enum8 { + kDecrement = 0; + kIncrement = 1; } - enum ColorMode : enum8 { + enum ColorModeEnum : enum8 { kCurrentHueAndCurrentSaturation = 0; kCurrentXAndCurrentY = 1; - kColorTemperature = 2; + kColorTemperatureMireds = 2; } - enum HueDirection : enum8 { - kShortestDistance = 0; - kLongestDistance = 1; + enum DirectionEnum : enum8 { + kShortest = 0; + kLongest = 1; kUp = 2; kDown = 3; } - enum HueMoveMode : enum8 { - kStop = 0; - kUp = 1; - kDown = 3; + enum DriftCompensationEnum : enum8 { + kNone = 0; + kOtherOrUnknown = 1; + kTemperatureMonitoring = 2; + kOpticalLuminanceMonitoringAndFeedback = 3; + kOpticalColorMonitoringAndFeedback = 4; } - enum HueStepMode : enum8 { - kUp = 1; - kDown = 3; + enum EnhancedColorModeEnum : enum8 { + kCurrentHueAndCurrentSaturation = 0; + kCurrentXAndCurrentY = 1; + kColorTemperatureMireds = 2; + kEnhancedCurrentHueAndCurrentSaturation = 3; } - enum SaturationMoveMode : enum8 { + enum MoveModeEnum : enum8 { kStop = 0; kUp = 1; kDown = 3; } - enum SaturationStepMode : enum8 { + enum StepModeEnum : enum8 { kUp = 1; kDown = 3; } - bitmap ColorCapabilities : bitmap16 { - kHueSaturationSupported = 0x1; - kEnhancedHueSupported = 0x2; - kColorLoopSupported = 0x4; - kXYAttributesSupported = 0x8; - kColorTemperatureSupported = 0x10; - } - - bitmap ColorLoopUpdateFlags : bitmap8 { - kUpdateAction = 0x1; - kUpdateDirection = 0x2; - kUpdateTime = 0x4; - kUpdateStartHue = 0x8; + bitmap ColorCapabilitiesBitmap : bitmap16 { + kHueSaturation = 0x1; + kEnhancedHue = 0x2; + kColorLoop = 0x4; + kXY = 0x8; + kColorTemperature = 0x10; } bitmap Feature : bitmap32 { @@ -2374,16 +2371,27 @@ cluster ColorControl = 768 { kColorTemperature = 0x10; } + bitmap OptionsBitmap : bitmap8 { + kExecuteIfOff = 0x1; + } + + bitmap UpdateFlagsBitmap : bitmap8 { + kUpdateAction = 0x1; + kUpdateDirection = 0x2; + kUpdateTime = 0x4; + kUpdateStartHue = 0x8; + } + readonly attribute optional int8u currentHue = 0; readonly attribute optional int8u currentSaturation = 1; readonly attribute optional int16u remainingTime = 2; readonly attribute optional int16u currentX = 3; readonly attribute optional int16u currentY = 4; - readonly attribute optional enum8 driftCompensation = 5; + readonly attribute optional DriftCompensationEnum driftCompensation = 5; readonly attribute optional char_string<254> compensationText = 6; readonly attribute optional int16u colorTemperatureMireds = 7; - readonly attribute enum8 colorMode = 8; - attribute bitmap8 options = 15; + readonly attribute ColorModeEnum colorMode = 8; + attribute OptionsBitmap options = 15; readonly attribute nullable int8u numberOfPrimaries = 16; readonly attribute optional int16u primary1X = 17; readonly attribute optional int16u primary1Y = 18; @@ -2415,13 +2423,13 @@ cluster ColorControl = 768 { attribute access(write: manage) optional int16u colorPointBY = 59; attribute access(write: manage) optional nullable int8u colorPointBIntensity = 60; readonly attribute optional int16u enhancedCurrentHue = 16384; - readonly attribute enum8 enhancedColorMode = 16385; + readonly attribute EnhancedColorModeEnum enhancedColorMode = 16385; readonly attribute optional int8u colorLoopActive = 16386; readonly attribute optional int8u colorLoopDirection = 16387; readonly attribute optional int16u colorLoopTime = 16388; readonly attribute optional int16u colorLoopStartEnhancedHue = 16389; readonly attribute optional int16u colorLoopStoredEnhancedHue = 16390; - readonly attribute bitmap16 colorCapabilities = 16394; + readonly attribute ColorCapabilitiesBitmap colorCapabilities = 16394; readonly attribute optional int16u colorTempPhysicalMinMireds = 16395; readonly attribute optional int16u colorTempPhysicalMaxMireds = 16396; readonly attribute optional int16u coupleColorTempToLevelMinMireds = 16397; @@ -2435,150 +2443,150 @@ cluster ColorControl = 768 { request struct MoveToHueRequest { int8u hue = 0; - HueDirection direction = 1; + DirectionEnum direction = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveHueRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int8u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepHueRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int8u stepSize = 1; int8u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToSaturationRequest { int8u saturation = 0; int16u transitionTime = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct MoveSaturationRequest { - SaturationMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int8u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepSaturationRequest { - SaturationStepMode stepMode = 0; + StepModeEnum stepMode = 0; int8u stepSize = 1; int8u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToHueAndSaturationRequest { int8u hue = 0; int8u saturation = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToColorRequest { int16u colorX = 0; int16u colorY = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveColorRequest { int16s rateX = 0; int16s rateY = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepColorRequest { int16s stepX = 0; int16s stepY = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToColorTemperatureRequest { int16u colorTemperatureMireds = 0; int16u transitionTime = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct EnhancedMoveToHueRequest { int16u enhancedHue = 0; - HueDirection direction = 1; + DirectionEnum direction = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct EnhancedMoveHueRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int16u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct EnhancedStepHueRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int16u stepSize = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct EnhancedMoveToHueAndSaturationRequest { int16u enhancedHue = 0; int8u saturation = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct ColorLoopSetRequest { - ColorLoopUpdateFlags updateFlags = 0; - ColorLoopAction action = 1; - ColorLoopDirection direction = 2; + UpdateFlagsBitmap updateFlags = 0; + ColorLoopActionEnum action = 1; + ColorLoopDirectionEnum direction = 2; int16u time = 3; int16u startHue = 4; - bitmap8 optionsMask = 5; - bitmap8 optionsOverride = 6; + OptionsBitmap optionsMask = 5; + OptionsBitmap optionsOverride = 6; } request struct StopMoveStepRequest { - bitmap8 optionsMask = 0; - bitmap8 optionsOverride = 1; + OptionsBitmap optionsMask = 0; + OptionsBitmap optionsOverride = 1; } request struct MoveColorTemperatureRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int16u rate = 1; int16u colorTemperatureMinimumMireds = 2; int16u colorTemperatureMaximumMireds = 3; - bitmap8 optionsMask = 4; - bitmap8 optionsOverride = 5; + OptionsBitmap optionsMask = 4; + OptionsBitmap optionsOverride = 5; } request struct StepColorTemperatureRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int16u stepSize = 1; int16u transitionTime = 2; int16u colorTemperatureMinimumMireds = 3; int16u colorTemperatureMaximumMireds = 4; - bitmap8 optionsMask = 5; - bitmap8 optionsOverride = 6; + OptionsBitmap optionsMask = 5; + OptionsBitmap optionsOverride = 6; } /** Move to specified hue. */ diff --git a/examples/lighting-app/tizen/src/DBusInterface.cpp b/examples/lighting-app/tizen/src/DBusInterface.cpp index 50dbd37930..36c0f19c35 100644 --- a/examples/lighting-app/tizen/src/DBusInterface.cpp +++ b/examples/lighting-app/tizen/src/DBusInterface.cpp @@ -217,11 +217,11 @@ void DBusInterface::InitOnOff() void DBusInterface::InitColor() { { - uint8_t value = 0; - auto status = Clusters::ColorControl::Attributes::ColorMode::Get(mEndpointId, &value); + auto value = Clusters::ColorControl::ColorModeEnum::kCurrentHueAndCurrentSaturation; + auto status = Clusters::ColorControl::Attributes::ColorMode::Get(mEndpointId, &value); VerifyOrReturn(status == Protocols::InteractionModel::Status::Success, ChipLogError(NotSpecified, "Error getting ColorMode: 0x%x", to_underlying(status))); - light_app_color_control_set_color_mode(mIfaceColorControl, value); + light_app_color_control_set_color_mode(mIfaceColorControl, to_underlying(value)); } { uint16_t value = 0; diff --git a/examples/lighting-app/tizen/src/main.cpp b/examples/lighting-app/tizen/src/main.cpp index c1cda62a23..040a8a5fcb 100644 --- a/examples/lighting-app/tizen/src/main.cpp +++ b/examples/lighting-app/tizen/src/main.cpp @@ -123,7 +123,7 @@ void MatterPostAttributeChangeCallback(const chip::app::ConcreteAttributePath & void emberAfColorControlClusterInitCallback(EndpointId endpoint) { // Set the color mode to color temperature. - Clusters::ColorControl::Attributes::ColorMode::Set(endpoint, ColorControlServer::EnhancedColorMode::kColorTemperature); + Clusters::ColorControl::Attributes::ColorMode::Set(endpoint, Clusters::ColorControl::ColorModeEnum::kColorTemperatureMireds); // Preserve the state of the color temperature attribute across reboots. Clusters::ColorControl::Attributes::StartUpColorTemperatureMireds::SetNull(endpoint); } diff --git a/examples/placeholder/linux/apps/app1/config.matter b/examples/placeholder/linux/apps/app1/config.matter index b72a4b2803..8befb87daa 100644 --- a/examples/placeholder/linux/apps/app1/config.matter +++ b/examples/placeholder/linux/apps/app1/config.matter @@ -5872,65 +5872,62 @@ cluster ThermostatUserInterfaceConfiguration = 516 { cluster ColorControl = 768 { revision 7; - enum ColorLoopAction : enum8 { + enum ColorLoopActionEnum : enum8 { kDeactivate = 0; kActivateFromColorLoopStartEnhancedHue = 1; kActivateFromEnhancedCurrentHue = 2; } - enum ColorLoopDirection : enum8 { - kDecrementHue = 0; - kIncrementHue = 1; + enum ColorLoopDirectionEnum : enum8 { + kDecrement = 0; + kIncrement = 1; } - enum ColorMode : enum8 { + enum ColorModeEnum : enum8 { kCurrentHueAndCurrentSaturation = 0; kCurrentXAndCurrentY = 1; - kColorTemperature = 2; + kColorTemperatureMireds = 2; } - enum HueDirection : enum8 { - kShortestDistance = 0; - kLongestDistance = 1; + enum DirectionEnum : enum8 { + kShortest = 0; + kLongest = 1; kUp = 2; kDown = 3; } - enum HueMoveMode : enum8 { - kStop = 0; - kUp = 1; - kDown = 3; + enum DriftCompensationEnum : enum8 { + kNone = 0; + kOtherOrUnknown = 1; + kTemperatureMonitoring = 2; + kOpticalLuminanceMonitoringAndFeedback = 3; + kOpticalColorMonitoringAndFeedback = 4; } - enum HueStepMode : enum8 { - kUp = 1; - kDown = 3; + enum EnhancedColorModeEnum : enum8 { + kCurrentHueAndCurrentSaturation = 0; + kCurrentXAndCurrentY = 1; + kColorTemperatureMireds = 2; + kEnhancedCurrentHueAndCurrentSaturation = 3; } - enum SaturationMoveMode : enum8 { + enum MoveModeEnum : enum8 { kStop = 0; kUp = 1; kDown = 3; } - enum SaturationStepMode : enum8 { + enum StepModeEnum : enum8 { kUp = 1; kDown = 3; } - bitmap ColorCapabilities : bitmap16 { - kHueSaturationSupported = 0x1; - kEnhancedHueSupported = 0x2; - kColorLoopSupported = 0x4; - kXYAttributesSupported = 0x8; - kColorTemperatureSupported = 0x10; - } - - bitmap ColorLoopUpdateFlags : bitmap8 { - kUpdateAction = 0x1; - kUpdateDirection = 0x2; - kUpdateTime = 0x4; - kUpdateStartHue = 0x8; + bitmap ColorCapabilitiesBitmap : bitmap16 { + kHueSaturation = 0x1; + kEnhancedHue = 0x2; + kColorLoop = 0x4; + kXY = 0x8; + kColorTemperature = 0x10; } bitmap Feature : bitmap32 { @@ -5941,16 +5938,27 @@ cluster ColorControl = 768 { kColorTemperature = 0x10; } + bitmap OptionsBitmap : bitmap8 { + kExecuteIfOff = 0x1; + } + + bitmap UpdateFlagsBitmap : bitmap8 { + kUpdateAction = 0x1; + kUpdateDirection = 0x2; + kUpdateTime = 0x4; + kUpdateStartHue = 0x8; + } + readonly attribute optional int8u currentHue = 0; readonly attribute optional int8u currentSaturation = 1; readonly attribute optional int16u remainingTime = 2; readonly attribute optional int16u currentX = 3; readonly attribute optional int16u currentY = 4; - readonly attribute optional enum8 driftCompensation = 5; + readonly attribute optional DriftCompensationEnum driftCompensation = 5; readonly attribute optional char_string<254> compensationText = 6; readonly attribute optional int16u colorTemperatureMireds = 7; - readonly attribute enum8 colorMode = 8; - attribute bitmap8 options = 15; + readonly attribute ColorModeEnum colorMode = 8; + attribute OptionsBitmap options = 15; readonly attribute nullable int8u numberOfPrimaries = 16; readonly attribute optional int16u primary1X = 17; readonly attribute optional int16u primary1Y = 18; @@ -5982,13 +5990,13 @@ cluster ColorControl = 768 { attribute access(write: manage) optional int16u colorPointBY = 59; attribute access(write: manage) optional nullable int8u colorPointBIntensity = 60; readonly attribute optional int16u enhancedCurrentHue = 16384; - readonly attribute enum8 enhancedColorMode = 16385; + readonly attribute EnhancedColorModeEnum enhancedColorMode = 16385; readonly attribute optional int8u colorLoopActive = 16386; readonly attribute optional int8u colorLoopDirection = 16387; readonly attribute optional int16u colorLoopTime = 16388; readonly attribute optional int16u colorLoopStartEnhancedHue = 16389; readonly attribute optional int16u colorLoopStoredEnhancedHue = 16390; - readonly attribute bitmap16 colorCapabilities = 16394; + readonly attribute ColorCapabilitiesBitmap colorCapabilities = 16394; readonly attribute optional int16u colorTempPhysicalMinMireds = 16395; readonly attribute optional int16u colorTempPhysicalMaxMireds = 16396; readonly attribute optional int16u coupleColorTempToLevelMinMireds = 16397; @@ -6002,150 +6010,150 @@ cluster ColorControl = 768 { request struct MoveToHueRequest { int8u hue = 0; - HueDirection direction = 1; + DirectionEnum direction = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveHueRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int8u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepHueRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int8u stepSize = 1; int8u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToSaturationRequest { int8u saturation = 0; int16u transitionTime = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct MoveSaturationRequest { - SaturationMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int8u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepSaturationRequest { - SaturationStepMode stepMode = 0; + StepModeEnum stepMode = 0; int8u stepSize = 1; int8u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToHueAndSaturationRequest { int8u hue = 0; int8u saturation = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToColorRequest { int16u colorX = 0; int16u colorY = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveColorRequest { int16s rateX = 0; int16s rateY = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepColorRequest { int16s stepX = 0; int16s stepY = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToColorTemperatureRequest { int16u colorTemperatureMireds = 0; int16u transitionTime = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct EnhancedMoveToHueRequest { int16u enhancedHue = 0; - HueDirection direction = 1; + DirectionEnum direction = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct EnhancedMoveHueRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int16u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct EnhancedStepHueRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int16u stepSize = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct EnhancedMoveToHueAndSaturationRequest { int16u enhancedHue = 0; int8u saturation = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct ColorLoopSetRequest { - ColorLoopUpdateFlags updateFlags = 0; - ColorLoopAction action = 1; - ColorLoopDirection direction = 2; + UpdateFlagsBitmap updateFlags = 0; + ColorLoopActionEnum action = 1; + ColorLoopDirectionEnum direction = 2; int16u time = 3; int16u startHue = 4; - bitmap8 optionsMask = 5; - bitmap8 optionsOverride = 6; + OptionsBitmap optionsMask = 5; + OptionsBitmap optionsOverride = 6; } request struct StopMoveStepRequest { - bitmap8 optionsMask = 0; - bitmap8 optionsOverride = 1; + OptionsBitmap optionsMask = 0; + OptionsBitmap optionsOverride = 1; } request struct MoveColorTemperatureRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int16u rate = 1; int16u colorTemperatureMinimumMireds = 2; int16u colorTemperatureMaximumMireds = 3; - bitmap8 optionsMask = 4; - bitmap8 optionsOverride = 5; + OptionsBitmap optionsMask = 4; + OptionsBitmap optionsOverride = 5; } request struct StepColorTemperatureRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int16u stepSize = 1; int16u transitionTime = 2; int16u colorTemperatureMinimumMireds = 3; int16u colorTemperatureMaximumMireds = 4; - bitmap8 optionsMask = 5; - bitmap8 optionsOverride = 6; + OptionsBitmap optionsMask = 5; + OptionsBitmap optionsOverride = 6; } /** Move to specified hue. */ @@ -6192,65 +6200,62 @@ cluster ColorControl = 768 { cluster ColorControl = 768 { revision 7; - enum ColorLoopAction : enum8 { + enum ColorLoopActionEnum : enum8 { kDeactivate = 0; kActivateFromColorLoopStartEnhancedHue = 1; kActivateFromEnhancedCurrentHue = 2; } - enum ColorLoopDirection : enum8 { - kDecrementHue = 0; - kIncrementHue = 1; + enum ColorLoopDirectionEnum : enum8 { + kDecrement = 0; + kIncrement = 1; } - enum ColorMode : enum8 { + enum ColorModeEnum : enum8 { kCurrentHueAndCurrentSaturation = 0; kCurrentXAndCurrentY = 1; - kColorTemperature = 2; + kColorTemperatureMireds = 2; } - enum HueDirection : enum8 { - kShortestDistance = 0; - kLongestDistance = 1; + enum DirectionEnum : enum8 { + kShortest = 0; + kLongest = 1; kUp = 2; kDown = 3; } - enum HueMoveMode : enum8 { - kStop = 0; - kUp = 1; - kDown = 3; + enum DriftCompensationEnum : enum8 { + kNone = 0; + kOtherOrUnknown = 1; + kTemperatureMonitoring = 2; + kOpticalLuminanceMonitoringAndFeedback = 3; + kOpticalColorMonitoringAndFeedback = 4; } - enum HueStepMode : enum8 { - kUp = 1; - kDown = 3; + enum EnhancedColorModeEnum : enum8 { + kCurrentHueAndCurrentSaturation = 0; + kCurrentXAndCurrentY = 1; + kColorTemperatureMireds = 2; + kEnhancedCurrentHueAndCurrentSaturation = 3; } - enum SaturationMoveMode : enum8 { + enum MoveModeEnum : enum8 { kStop = 0; kUp = 1; kDown = 3; } - enum SaturationStepMode : enum8 { + enum StepModeEnum : enum8 { kUp = 1; kDown = 3; } - bitmap ColorCapabilities : bitmap16 { - kHueSaturationSupported = 0x1; - kEnhancedHueSupported = 0x2; - kColorLoopSupported = 0x4; - kXYAttributesSupported = 0x8; - kColorTemperatureSupported = 0x10; - } - - bitmap ColorLoopUpdateFlags : bitmap8 { - kUpdateAction = 0x1; - kUpdateDirection = 0x2; - kUpdateTime = 0x4; - kUpdateStartHue = 0x8; + bitmap ColorCapabilitiesBitmap : bitmap16 { + kHueSaturation = 0x1; + kEnhancedHue = 0x2; + kColorLoop = 0x4; + kXY = 0x8; + kColorTemperature = 0x10; } bitmap Feature : bitmap32 { @@ -6261,16 +6266,27 @@ cluster ColorControl = 768 { kColorTemperature = 0x10; } + bitmap OptionsBitmap : bitmap8 { + kExecuteIfOff = 0x1; + } + + bitmap UpdateFlagsBitmap : bitmap8 { + kUpdateAction = 0x1; + kUpdateDirection = 0x2; + kUpdateTime = 0x4; + kUpdateStartHue = 0x8; + } + readonly attribute optional int8u currentHue = 0; readonly attribute optional int8u currentSaturation = 1; readonly attribute optional int16u remainingTime = 2; readonly attribute optional int16u currentX = 3; readonly attribute optional int16u currentY = 4; - readonly attribute optional enum8 driftCompensation = 5; + readonly attribute optional DriftCompensationEnum driftCompensation = 5; readonly attribute optional char_string<254> compensationText = 6; readonly attribute optional int16u colorTemperatureMireds = 7; - readonly attribute enum8 colorMode = 8; - attribute bitmap8 options = 15; + readonly attribute ColorModeEnum colorMode = 8; + attribute OptionsBitmap options = 15; readonly attribute nullable int8u numberOfPrimaries = 16; readonly attribute optional int16u primary1X = 17; readonly attribute optional int16u primary1Y = 18; @@ -6302,13 +6318,13 @@ cluster ColorControl = 768 { attribute access(write: manage) optional int16u colorPointBY = 59; attribute access(write: manage) optional nullable int8u colorPointBIntensity = 60; readonly attribute optional int16u enhancedCurrentHue = 16384; - readonly attribute enum8 enhancedColorMode = 16385; + readonly attribute EnhancedColorModeEnum enhancedColorMode = 16385; readonly attribute optional int8u colorLoopActive = 16386; readonly attribute optional int8u colorLoopDirection = 16387; readonly attribute optional int16u colorLoopTime = 16388; readonly attribute optional int16u colorLoopStartEnhancedHue = 16389; readonly attribute optional int16u colorLoopStoredEnhancedHue = 16390; - readonly attribute bitmap16 colorCapabilities = 16394; + readonly attribute ColorCapabilitiesBitmap colorCapabilities = 16394; readonly attribute optional int16u colorTempPhysicalMinMireds = 16395; readonly attribute optional int16u colorTempPhysicalMaxMireds = 16396; readonly attribute optional int16u coupleColorTempToLevelMinMireds = 16397; @@ -6322,150 +6338,150 @@ cluster ColorControl = 768 { request struct MoveToHueRequest { int8u hue = 0; - HueDirection direction = 1; + DirectionEnum direction = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveHueRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int8u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepHueRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int8u stepSize = 1; int8u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToSaturationRequest { int8u saturation = 0; int16u transitionTime = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct MoveSaturationRequest { - SaturationMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int8u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepSaturationRequest { - SaturationStepMode stepMode = 0; + StepModeEnum stepMode = 0; int8u stepSize = 1; int8u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToHueAndSaturationRequest { int8u hue = 0; int8u saturation = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToColorRequest { int16u colorX = 0; int16u colorY = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveColorRequest { int16s rateX = 0; int16s rateY = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepColorRequest { int16s stepX = 0; int16s stepY = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToColorTemperatureRequest { int16u colorTemperatureMireds = 0; int16u transitionTime = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct EnhancedMoveToHueRequest { int16u enhancedHue = 0; - HueDirection direction = 1; + DirectionEnum direction = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct EnhancedMoveHueRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int16u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct EnhancedStepHueRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int16u stepSize = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct EnhancedMoveToHueAndSaturationRequest { int16u enhancedHue = 0; int8u saturation = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct ColorLoopSetRequest { - ColorLoopUpdateFlags updateFlags = 0; - ColorLoopAction action = 1; - ColorLoopDirection direction = 2; + UpdateFlagsBitmap updateFlags = 0; + ColorLoopActionEnum action = 1; + ColorLoopDirectionEnum direction = 2; int16u time = 3; int16u startHue = 4; - bitmap8 optionsMask = 5; - bitmap8 optionsOverride = 6; + OptionsBitmap optionsMask = 5; + OptionsBitmap optionsOverride = 6; } request struct StopMoveStepRequest { - bitmap8 optionsMask = 0; - bitmap8 optionsOverride = 1; + OptionsBitmap optionsMask = 0; + OptionsBitmap optionsOverride = 1; } request struct MoveColorTemperatureRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int16u rate = 1; int16u colorTemperatureMinimumMireds = 2; int16u colorTemperatureMaximumMireds = 3; - bitmap8 optionsMask = 4; - bitmap8 optionsOverride = 5; + OptionsBitmap optionsMask = 4; + OptionsBitmap optionsOverride = 5; } request struct StepColorTemperatureRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int16u stepSize = 1; int16u transitionTime = 2; int16u colorTemperatureMinimumMireds = 3; int16u colorTemperatureMaximumMireds = 4; - bitmap8 optionsMask = 5; - bitmap8 optionsOverride = 6; + OptionsBitmap optionsMask = 5; + OptionsBitmap optionsOverride = 6; } /** Move to specified hue. */ diff --git a/examples/placeholder/linux/apps/app2/config.matter b/examples/placeholder/linux/apps/app2/config.matter index 41421c7e91..6cfcc1ab7e 100644 --- a/examples/placeholder/linux/apps/app2/config.matter +++ b/examples/placeholder/linux/apps/app2/config.matter @@ -5829,65 +5829,62 @@ cluster ThermostatUserInterfaceConfiguration = 516 { cluster ColorControl = 768 { revision 7; - enum ColorLoopAction : enum8 { + enum ColorLoopActionEnum : enum8 { kDeactivate = 0; kActivateFromColorLoopStartEnhancedHue = 1; kActivateFromEnhancedCurrentHue = 2; } - enum ColorLoopDirection : enum8 { - kDecrementHue = 0; - kIncrementHue = 1; + enum ColorLoopDirectionEnum : enum8 { + kDecrement = 0; + kIncrement = 1; } - enum ColorMode : enum8 { + enum ColorModeEnum : enum8 { kCurrentHueAndCurrentSaturation = 0; kCurrentXAndCurrentY = 1; - kColorTemperature = 2; + kColorTemperatureMireds = 2; } - enum HueDirection : enum8 { - kShortestDistance = 0; - kLongestDistance = 1; + enum DirectionEnum : enum8 { + kShortest = 0; + kLongest = 1; kUp = 2; kDown = 3; } - enum HueMoveMode : enum8 { - kStop = 0; - kUp = 1; - kDown = 3; + enum DriftCompensationEnum : enum8 { + kNone = 0; + kOtherOrUnknown = 1; + kTemperatureMonitoring = 2; + kOpticalLuminanceMonitoringAndFeedback = 3; + kOpticalColorMonitoringAndFeedback = 4; } - enum HueStepMode : enum8 { - kUp = 1; - kDown = 3; + enum EnhancedColorModeEnum : enum8 { + kCurrentHueAndCurrentSaturation = 0; + kCurrentXAndCurrentY = 1; + kColorTemperatureMireds = 2; + kEnhancedCurrentHueAndCurrentSaturation = 3; } - enum SaturationMoveMode : enum8 { + enum MoveModeEnum : enum8 { kStop = 0; kUp = 1; kDown = 3; } - enum SaturationStepMode : enum8 { + enum StepModeEnum : enum8 { kUp = 1; kDown = 3; } - bitmap ColorCapabilities : bitmap16 { - kHueSaturationSupported = 0x1; - kEnhancedHueSupported = 0x2; - kColorLoopSupported = 0x4; - kXYAttributesSupported = 0x8; - kColorTemperatureSupported = 0x10; - } - - bitmap ColorLoopUpdateFlags : bitmap8 { - kUpdateAction = 0x1; - kUpdateDirection = 0x2; - kUpdateTime = 0x4; - kUpdateStartHue = 0x8; + bitmap ColorCapabilitiesBitmap : bitmap16 { + kHueSaturation = 0x1; + kEnhancedHue = 0x2; + kColorLoop = 0x4; + kXY = 0x8; + kColorTemperature = 0x10; } bitmap Feature : bitmap32 { @@ -5898,16 +5895,27 @@ cluster ColorControl = 768 { kColorTemperature = 0x10; } + bitmap OptionsBitmap : bitmap8 { + kExecuteIfOff = 0x1; + } + + bitmap UpdateFlagsBitmap : bitmap8 { + kUpdateAction = 0x1; + kUpdateDirection = 0x2; + kUpdateTime = 0x4; + kUpdateStartHue = 0x8; + } + readonly attribute optional int8u currentHue = 0; readonly attribute optional int8u currentSaturation = 1; readonly attribute optional int16u remainingTime = 2; readonly attribute optional int16u currentX = 3; readonly attribute optional int16u currentY = 4; - readonly attribute optional enum8 driftCompensation = 5; + readonly attribute optional DriftCompensationEnum driftCompensation = 5; readonly attribute optional char_string<254> compensationText = 6; readonly attribute optional int16u colorTemperatureMireds = 7; - readonly attribute enum8 colorMode = 8; - attribute bitmap8 options = 15; + readonly attribute ColorModeEnum colorMode = 8; + attribute OptionsBitmap options = 15; readonly attribute nullable int8u numberOfPrimaries = 16; readonly attribute optional int16u primary1X = 17; readonly attribute optional int16u primary1Y = 18; @@ -5939,13 +5947,13 @@ cluster ColorControl = 768 { attribute access(write: manage) optional int16u colorPointBY = 59; attribute access(write: manage) optional nullable int8u colorPointBIntensity = 60; readonly attribute optional int16u enhancedCurrentHue = 16384; - readonly attribute enum8 enhancedColorMode = 16385; + readonly attribute EnhancedColorModeEnum enhancedColorMode = 16385; readonly attribute optional int8u colorLoopActive = 16386; readonly attribute optional int8u colorLoopDirection = 16387; readonly attribute optional int16u colorLoopTime = 16388; readonly attribute optional int16u colorLoopStartEnhancedHue = 16389; readonly attribute optional int16u colorLoopStoredEnhancedHue = 16390; - readonly attribute bitmap16 colorCapabilities = 16394; + readonly attribute ColorCapabilitiesBitmap colorCapabilities = 16394; readonly attribute optional int16u colorTempPhysicalMinMireds = 16395; readonly attribute optional int16u colorTempPhysicalMaxMireds = 16396; readonly attribute optional int16u coupleColorTempToLevelMinMireds = 16397; @@ -5959,150 +5967,150 @@ cluster ColorControl = 768 { request struct MoveToHueRequest { int8u hue = 0; - HueDirection direction = 1; + DirectionEnum direction = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveHueRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int8u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepHueRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int8u stepSize = 1; int8u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToSaturationRequest { int8u saturation = 0; int16u transitionTime = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct MoveSaturationRequest { - SaturationMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int8u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepSaturationRequest { - SaturationStepMode stepMode = 0; + StepModeEnum stepMode = 0; int8u stepSize = 1; int8u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToHueAndSaturationRequest { int8u hue = 0; int8u saturation = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToColorRequest { int16u colorX = 0; int16u colorY = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveColorRequest { int16s rateX = 0; int16s rateY = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepColorRequest { int16s stepX = 0; int16s stepY = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToColorTemperatureRequest { int16u colorTemperatureMireds = 0; int16u transitionTime = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct EnhancedMoveToHueRequest { int16u enhancedHue = 0; - HueDirection direction = 1; + DirectionEnum direction = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct EnhancedMoveHueRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int16u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct EnhancedStepHueRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int16u stepSize = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct EnhancedMoveToHueAndSaturationRequest { int16u enhancedHue = 0; int8u saturation = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct ColorLoopSetRequest { - ColorLoopUpdateFlags updateFlags = 0; - ColorLoopAction action = 1; - ColorLoopDirection direction = 2; + UpdateFlagsBitmap updateFlags = 0; + ColorLoopActionEnum action = 1; + ColorLoopDirectionEnum direction = 2; int16u time = 3; int16u startHue = 4; - bitmap8 optionsMask = 5; - bitmap8 optionsOverride = 6; + OptionsBitmap optionsMask = 5; + OptionsBitmap optionsOverride = 6; } request struct StopMoveStepRequest { - bitmap8 optionsMask = 0; - bitmap8 optionsOverride = 1; + OptionsBitmap optionsMask = 0; + OptionsBitmap optionsOverride = 1; } request struct MoveColorTemperatureRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int16u rate = 1; int16u colorTemperatureMinimumMireds = 2; int16u colorTemperatureMaximumMireds = 3; - bitmap8 optionsMask = 4; - bitmap8 optionsOverride = 5; + OptionsBitmap optionsMask = 4; + OptionsBitmap optionsOverride = 5; } request struct StepColorTemperatureRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int16u stepSize = 1; int16u transitionTime = 2; int16u colorTemperatureMinimumMireds = 3; int16u colorTemperatureMaximumMireds = 4; - bitmap8 optionsMask = 5; - bitmap8 optionsOverride = 6; + OptionsBitmap optionsMask = 5; + OptionsBitmap optionsOverride = 6; } /** Move to specified hue. */ @@ -6149,65 +6157,62 @@ cluster ColorControl = 768 { cluster ColorControl = 768 { revision 7; - enum ColorLoopAction : enum8 { + enum ColorLoopActionEnum : enum8 { kDeactivate = 0; kActivateFromColorLoopStartEnhancedHue = 1; kActivateFromEnhancedCurrentHue = 2; } - enum ColorLoopDirection : enum8 { - kDecrementHue = 0; - kIncrementHue = 1; + enum ColorLoopDirectionEnum : enum8 { + kDecrement = 0; + kIncrement = 1; } - enum ColorMode : enum8 { + enum ColorModeEnum : enum8 { kCurrentHueAndCurrentSaturation = 0; kCurrentXAndCurrentY = 1; - kColorTemperature = 2; + kColorTemperatureMireds = 2; } - enum HueDirection : enum8 { - kShortestDistance = 0; - kLongestDistance = 1; + enum DirectionEnum : enum8 { + kShortest = 0; + kLongest = 1; kUp = 2; kDown = 3; } - enum HueMoveMode : enum8 { - kStop = 0; - kUp = 1; - kDown = 3; + enum DriftCompensationEnum : enum8 { + kNone = 0; + kOtherOrUnknown = 1; + kTemperatureMonitoring = 2; + kOpticalLuminanceMonitoringAndFeedback = 3; + kOpticalColorMonitoringAndFeedback = 4; } - enum HueStepMode : enum8 { - kUp = 1; - kDown = 3; + enum EnhancedColorModeEnum : enum8 { + kCurrentHueAndCurrentSaturation = 0; + kCurrentXAndCurrentY = 1; + kColorTemperatureMireds = 2; + kEnhancedCurrentHueAndCurrentSaturation = 3; } - enum SaturationMoveMode : enum8 { + enum MoveModeEnum : enum8 { kStop = 0; kUp = 1; kDown = 3; } - enum SaturationStepMode : enum8 { + enum StepModeEnum : enum8 { kUp = 1; kDown = 3; } - bitmap ColorCapabilities : bitmap16 { - kHueSaturationSupported = 0x1; - kEnhancedHueSupported = 0x2; - kColorLoopSupported = 0x4; - kXYAttributesSupported = 0x8; - kColorTemperatureSupported = 0x10; - } - - bitmap ColorLoopUpdateFlags : bitmap8 { - kUpdateAction = 0x1; - kUpdateDirection = 0x2; - kUpdateTime = 0x4; - kUpdateStartHue = 0x8; + bitmap ColorCapabilitiesBitmap : bitmap16 { + kHueSaturation = 0x1; + kEnhancedHue = 0x2; + kColorLoop = 0x4; + kXY = 0x8; + kColorTemperature = 0x10; } bitmap Feature : bitmap32 { @@ -6218,16 +6223,27 @@ cluster ColorControl = 768 { kColorTemperature = 0x10; } + bitmap OptionsBitmap : bitmap8 { + kExecuteIfOff = 0x1; + } + + bitmap UpdateFlagsBitmap : bitmap8 { + kUpdateAction = 0x1; + kUpdateDirection = 0x2; + kUpdateTime = 0x4; + kUpdateStartHue = 0x8; + } + readonly attribute optional int8u currentHue = 0; readonly attribute optional int8u currentSaturation = 1; readonly attribute optional int16u remainingTime = 2; readonly attribute optional int16u currentX = 3; readonly attribute optional int16u currentY = 4; - readonly attribute optional enum8 driftCompensation = 5; + readonly attribute optional DriftCompensationEnum driftCompensation = 5; readonly attribute optional char_string<254> compensationText = 6; readonly attribute optional int16u colorTemperatureMireds = 7; - readonly attribute enum8 colorMode = 8; - attribute bitmap8 options = 15; + readonly attribute ColorModeEnum colorMode = 8; + attribute OptionsBitmap options = 15; readonly attribute nullable int8u numberOfPrimaries = 16; readonly attribute optional int16u primary1X = 17; readonly attribute optional int16u primary1Y = 18; @@ -6259,13 +6275,13 @@ cluster ColorControl = 768 { attribute access(write: manage) optional int16u colorPointBY = 59; attribute access(write: manage) optional nullable int8u colorPointBIntensity = 60; readonly attribute optional int16u enhancedCurrentHue = 16384; - readonly attribute enum8 enhancedColorMode = 16385; + readonly attribute EnhancedColorModeEnum enhancedColorMode = 16385; readonly attribute optional int8u colorLoopActive = 16386; readonly attribute optional int8u colorLoopDirection = 16387; readonly attribute optional int16u colorLoopTime = 16388; readonly attribute optional int16u colorLoopStartEnhancedHue = 16389; readonly attribute optional int16u colorLoopStoredEnhancedHue = 16390; - readonly attribute bitmap16 colorCapabilities = 16394; + readonly attribute ColorCapabilitiesBitmap colorCapabilities = 16394; readonly attribute optional int16u colorTempPhysicalMinMireds = 16395; readonly attribute optional int16u colorTempPhysicalMaxMireds = 16396; readonly attribute optional int16u coupleColorTempToLevelMinMireds = 16397; @@ -6279,150 +6295,150 @@ cluster ColorControl = 768 { request struct MoveToHueRequest { int8u hue = 0; - HueDirection direction = 1; + DirectionEnum direction = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveHueRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int8u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepHueRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int8u stepSize = 1; int8u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToSaturationRequest { int8u saturation = 0; int16u transitionTime = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct MoveSaturationRequest { - SaturationMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int8u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepSaturationRequest { - SaturationStepMode stepMode = 0; + StepModeEnum stepMode = 0; int8u stepSize = 1; int8u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToHueAndSaturationRequest { int8u hue = 0; int8u saturation = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToColorRequest { int16u colorX = 0; int16u colorY = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveColorRequest { int16s rateX = 0; int16s rateY = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepColorRequest { int16s stepX = 0; int16s stepY = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToColorTemperatureRequest { int16u colorTemperatureMireds = 0; int16u transitionTime = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct EnhancedMoveToHueRequest { int16u enhancedHue = 0; - HueDirection direction = 1; + DirectionEnum direction = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct EnhancedMoveHueRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int16u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct EnhancedStepHueRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int16u stepSize = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct EnhancedMoveToHueAndSaturationRequest { int16u enhancedHue = 0; int8u saturation = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct ColorLoopSetRequest { - ColorLoopUpdateFlags updateFlags = 0; - ColorLoopAction action = 1; - ColorLoopDirection direction = 2; + UpdateFlagsBitmap updateFlags = 0; + ColorLoopActionEnum action = 1; + ColorLoopDirectionEnum direction = 2; int16u time = 3; int16u startHue = 4; - bitmap8 optionsMask = 5; - bitmap8 optionsOverride = 6; + OptionsBitmap optionsMask = 5; + OptionsBitmap optionsOverride = 6; } request struct StopMoveStepRequest { - bitmap8 optionsMask = 0; - bitmap8 optionsOverride = 1; + OptionsBitmap optionsMask = 0; + OptionsBitmap optionsOverride = 1; } request struct MoveColorTemperatureRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int16u rate = 1; int16u colorTemperatureMinimumMireds = 2; int16u colorTemperatureMaximumMireds = 3; - bitmap8 optionsMask = 4; - bitmap8 optionsOverride = 5; + OptionsBitmap optionsMask = 4; + OptionsBitmap optionsOverride = 5; } request struct StepColorTemperatureRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int16u stepSize = 1; int16u transitionTime = 2; int16u colorTemperatureMinimumMireds = 3; int16u colorTemperatureMaximumMireds = 4; - bitmap8 optionsMask = 5; - bitmap8 optionsOverride = 6; + OptionsBitmap optionsMask = 5; + OptionsBitmap optionsOverride = 6; } /** Move to specified hue. */ diff --git a/examples/virtual-device-app/virtual-device-common/virtual-device-app.matter b/examples/virtual-device-app/virtual-device-common/virtual-device-app.matter index 135846fd60..3c20256117 100644 --- a/examples/virtual-device-app/virtual-device-common/virtual-device-app.matter +++ b/examples/virtual-device-app/virtual-device-common/virtual-device-app.matter @@ -3161,65 +3161,62 @@ cluster WindowCovering = 258 { cluster ColorControl = 768 { revision 7; - enum ColorLoopAction : enum8 { + enum ColorLoopActionEnum : enum8 { kDeactivate = 0; kActivateFromColorLoopStartEnhancedHue = 1; kActivateFromEnhancedCurrentHue = 2; } - enum ColorLoopDirection : enum8 { - kDecrementHue = 0; - kIncrementHue = 1; + enum ColorLoopDirectionEnum : enum8 { + kDecrement = 0; + kIncrement = 1; } - enum ColorMode : enum8 { + enum ColorModeEnum : enum8 { kCurrentHueAndCurrentSaturation = 0; kCurrentXAndCurrentY = 1; - kColorTemperature = 2; + kColorTemperatureMireds = 2; } - enum HueDirection : enum8 { - kShortestDistance = 0; - kLongestDistance = 1; + enum DirectionEnum : enum8 { + kShortest = 0; + kLongest = 1; kUp = 2; kDown = 3; } - enum HueMoveMode : enum8 { - kStop = 0; - kUp = 1; - kDown = 3; + enum DriftCompensationEnum : enum8 { + kNone = 0; + kOtherOrUnknown = 1; + kTemperatureMonitoring = 2; + kOpticalLuminanceMonitoringAndFeedback = 3; + kOpticalColorMonitoringAndFeedback = 4; } - enum HueStepMode : enum8 { - kUp = 1; - kDown = 3; + enum EnhancedColorModeEnum : enum8 { + kCurrentHueAndCurrentSaturation = 0; + kCurrentXAndCurrentY = 1; + kColorTemperatureMireds = 2; + kEnhancedCurrentHueAndCurrentSaturation = 3; } - enum SaturationMoveMode : enum8 { + enum MoveModeEnum : enum8 { kStop = 0; kUp = 1; kDown = 3; } - enum SaturationStepMode : enum8 { + enum StepModeEnum : enum8 { kUp = 1; kDown = 3; } - bitmap ColorCapabilities : bitmap16 { - kHueSaturationSupported = 0x1; - kEnhancedHueSupported = 0x2; - kColorLoopSupported = 0x4; - kXYAttributesSupported = 0x8; - kColorTemperatureSupported = 0x10; - } - - bitmap ColorLoopUpdateFlags : bitmap8 { - kUpdateAction = 0x1; - kUpdateDirection = 0x2; - kUpdateTime = 0x4; - kUpdateStartHue = 0x8; + bitmap ColorCapabilitiesBitmap : bitmap16 { + kHueSaturation = 0x1; + kEnhancedHue = 0x2; + kColorLoop = 0x4; + kXY = 0x8; + kColorTemperature = 0x10; } bitmap Feature : bitmap32 { @@ -3230,16 +3227,27 @@ cluster ColorControl = 768 { kColorTemperature = 0x10; } + bitmap OptionsBitmap : bitmap8 { + kExecuteIfOff = 0x1; + } + + bitmap UpdateFlagsBitmap : bitmap8 { + kUpdateAction = 0x1; + kUpdateDirection = 0x2; + kUpdateTime = 0x4; + kUpdateStartHue = 0x8; + } + readonly attribute optional int8u currentHue = 0; readonly attribute optional int8u currentSaturation = 1; readonly attribute optional int16u remainingTime = 2; readonly attribute optional int16u currentX = 3; readonly attribute optional int16u currentY = 4; - readonly attribute optional enum8 driftCompensation = 5; + readonly attribute optional DriftCompensationEnum driftCompensation = 5; readonly attribute optional char_string<254> compensationText = 6; readonly attribute optional int16u colorTemperatureMireds = 7; - readonly attribute enum8 colorMode = 8; - attribute bitmap8 options = 15; + readonly attribute ColorModeEnum colorMode = 8; + attribute OptionsBitmap options = 15; readonly attribute nullable int8u numberOfPrimaries = 16; readonly attribute optional int16u primary1X = 17; readonly attribute optional int16u primary1Y = 18; @@ -3271,13 +3279,13 @@ cluster ColorControl = 768 { attribute access(write: manage) optional int16u colorPointBY = 59; attribute access(write: manage) optional nullable int8u colorPointBIntensity = 60; readonly attribute optional int16u enhancedCurrentHue = 16384; - readonly attribute enum8 enhancedColorMode = 16385; + readonly attribute EnhancedColorModeEnum enhancedColorMode = 16385; readonly attribute optional int8u colorLoopActive = 16386; readonly attribute optional int8u colorLoopDirection = 16387; readonly attribute optional int16u colorLoopTime = 16388; readonly attribute optional int16u colorLoopStartEnhancedHue = 16389; readonly attribute optional int16u colorLoopStoredEnhancedHue = 16390; - readonly attribute bitmap16 colorCapabilities = 16394; + readonly attribute ColorCapabilitiesBitmap colorCapabilities = 16394; readonly attribute optional int16u colorTempPhysicalMinMireds = 16395; readonly attribute optional int16u colorTempPhysicalMaxMireds = 16396; readonly attribute optional int16u coupleColorTempToLevelMinMireds = 16397; @@ -3291,150 +3299,150 @@ cluster ColorControl = 768 { request struct MoveToHueRequest { int8u hue = 0; - HueDirection direction = 1; + DirectionEnum direction = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveHueRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int8u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepHueRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int8u stepSize = 1; int8u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToSaturationRequest { int8u saturation = 0; int16u transitionTime = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct MoveSaturationRequest { - SaturationMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int8u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepSaturationRequest { - SaturationStepMode stepMode = 0; + StepModeEnum stepMode = 0; int8u stepSize = 1; int8u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToHueAndSaturationRequest { int8u hue = 0; int8u saturation = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToColorRequest { int16u colorX = 0; int16u colorY = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveColorRequest { int16s rateX = 0; int16s rateY = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepColorRequest { int16s stepX = 0; int16s stepY = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToColorTemperatureRequest { int16u colorTemperatureMireds = 0; int16u transitionTime = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct EnhancedMoveToHueRequest { int16u enhancedHue = 0; - HueDirection direction = 1; + DirectionEnum direction = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct EnhancedMoveHueRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int16u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct EnhancedStepHueRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int16u stepSize = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct EnhancedMoveToHueAndSaturationRequest { int16u enhancedHue = 0; int8u saturation = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct ColorLoopSetRequest { - ColorLoopUpdateFlags updateFlags = 0; - ColorLoopAction action = 1; - ColorLoopDirection direction = 2; + UpdateFlagsBitmap updateFlags = 0; + ColorLoopActionEnum action = 1; + ColorLoopDirectionEnum direction = 2; int16u time = 3; int16u startHue = 4; - bitmap8 optionsMask = 5; - bitmap8 optionsOverride = 6; + OptionsBitmap optionsMask = 5; + OptionsBitmap optionsOverride = 6; } request struct StopMoveStepRequest { - bitmap8 optionsMask = 0; - bitmap8 optionsOverride = 1; + OptionsBitmap optionsMask = 0; + OptionsBitmap optionsOverride = 1; } request struct MoveColorTemperatureRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int16u rate = 1; int16u colorTemperatureMinimumMireds = 2; int16u colorTemperatureMaximumMireds = 3; - bitmap8 optionsMask = 4; - bitmap8 optionsOverride = 5; + OptionsBitmap optionsMask = 4; + OptionsBitmap optionsOverride = 5; } request struct StepColorTemperatureRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int16u stepSize = 1; int16u transitionTime = 2; int16u colorTemperatureMinimumMireds = 3; int16u colorTemperatureMaximumMireds = 4; - bitmap8 optionsMask = 5; - bitmap8 optionsOverride = 6; + OptionsBitmap optionsMask = 5; + OptionsBitmap optionsOverride = 6; } /** Move to specified hue. */ 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 4a4fc69b4e..406d06f4b1 100644 --- a/src/app/clusters/color-control-server/color-control-server.cpp +++ b/src/app/clusters/color-control-server/color-control-server.cpp @@ -21,6 +21,7 @@ #include #include #include +#include #include #include #include @@ -35,31 +36,6 @@ using namespace chip::app::Clusters; using namespace chip::app::Clusters::ColorControl; using chip::Protocols::InteractionModel::Status; -// These constants are NOT currently spec compliant -// These should be changed once we have real specification enumeration -// names. -namespace chip { -namespace app { -namespace Clusters { -namespace ColorControl { - -namespace EnhancedColorMode { -constexpr uint8_t kCurrentHueAndCurrentSaturation = ColorControlServer::EnhancedColorMode::kCurrentHueAndCurrentSaturation; -constexpr uint8_t kCurrentXAndCurrentY = ColorControlServer::EnhancedColorMode::kCurrentXAndCurrentY; -constexpr uint8_t kColorTemperature = ColorControlServer::EnhancedColorMode::kColorTemperature; -constexpr uint8_t kEnhancedCurrentHueAndCurrentSaturation = - ColorControlServer::EnhancedColorMode::kEnhancedCurrentHueAndCurrentSaturation; -} // namespace EnhancedColorMode - -namespace Options { -constexpr uint8_t kExecuteIfOff = 1; -} // namespace Options - -} // namespace ColorControl -} // namespace Clusters -} // namespace app -} // namespace chip - #if defined(MATTER_DM_PLUGIN_SCENES_MANAGEMENT) && CHIP_CONFIG_SCENES_USE_DEFAULT_HANDLERS class DefaultColorControlSceneHandler : public scenes::DefaultSceneHandlerImpl { @@ -174,12 +150,12 @@ class DefaultColorControlSceneHandler : public scenes::DefaultSceneHandlerImpl AddAttributeValuePair(pairs, Attributes::ColorTemperatureMireds::Id, temperatureValue, attributeCount); } - uint8_t modeValue; + EnhancedColorMode modeValue; if (Status::Success != Attributes::EnhancedColorMode::Get(endpoint, &modeValue)) { - modeValue = ColorControl::EnhancedColorMode::kCurrentXAndCurrentY; // Default mode value according to spec + modeValue = EnhancedColorMode::kCurrentXAndCurrentY; // Default mode value according to spec } - AddAttributeValuePair(pairs, Attributes::EnhancedColorMode::Id, modeValue, attributeCount); + AddAttributeValuePair(pairs, Attributes::EnhancedColorMode::Id, to_underlying(modeValue), attributeCount); app::DataModel::List attributeValueList(pairs, attributeCount); @@ -226,7 +202,7 @@ class DefaultColorControlSceneHandler : public scenes::DefaultSceneHandlerImpl #endif // Initialize action attributes to default values in case they are not in the scene - uint8_t targetColorMode = 0x00; + auto targetColorMode = EnhancedColorModeEnum::kCurrentHueAndCurrentSaturation; uint8_t loopActiveValue = 0x00; uint8_t loopDirectionValue = 0x00; uint16_t loopTimeValue = 0x0019; // Default loop time value according to spec @@ -238,7 +214,7 @@ class DefaultColorControlSceneHandler : public scenes::DefaultSceneHandlerImpl switch (decodePair.attributeID) { case Attributes::CurrentX::Id: - if (SupportsColorMode(endpoint, ColorControl::EnhancedColorMode::kCurrentXAndCurrentY)) + if (SupportsColorMode(endpoint, EnhancedColorMode::kCurrentXAndCurrentY)) { VerifyOrReturnError(decodePair.valueUnsigned16.HasValue(), CHIP_ERROR_INVALID_ARGUMENT); colorXTransitionState->finalValue = @@ -246,7 +222,7 @@ class DefaultColorControlSceneHandler : public scenes::DefaultSceneHandlerImpl } break; case Attributes::CurrentY::Id: - if (SupportsColorMode(endpoint, ColorControl::EnhancedColorMode::kCurrentXAndCurrentY)) + if (SupportsColorMode(endpoint, EnhancedColorMode::kCurrentXAndCurrentY)) { VerifyOrReturnError(decodePair.valueUnsigned16.HasValue(), CHIP_ERROR_INVALID_ARGUMENT); colorYTransitionState->finalValue = @@ -254,14 +230,14 @@ class DefaultColorControlSceneHandler : public scenes::DefaultSceneHandlerImpl } break; case Attributes::EnhancedCurrentHue::Id: - if (SupportsColorMode(endpoint, ColorControl::EnhancedColorMode::kEnhancedCurrentHueAndCurrentSaturation)) + if (SupportsColorMode(endpoint, EnhancedColorMode::kEnhancedCurrentHueAndCurrentSaturation)) { VerifyOrReturnError(decodePair.valueUnsigned16.HasValue(), CHIP_ERROR_INVALID_ARGUMENT); colorHueTransitionState->finalEnhancedHue = decodePair.valueUnsigned16.Value(); } break; case Attributes::CurrentSaturation::Id: - if (SupportsColorMode(endpoint, ColorControl::EnhancedColorMode::kCurrentHueAndCurrentSaturation)) + if (SupportsColorMode(endpoint, EnhancedColorMode::kCurrentHueAndCurrentSaturation)) { VerifyOrReturnError(decodePair.valueUnsigned8.HasValue(), CHIP_ERROR_INVALID_ARGUMENT); colorSaturationTransitionState->finalValue = std::min(static_cast(decodePair.valueUnsigned8.Value()), @@ -281,7 +257,7 @@ class DefaultColorControlSceneHandler : public scenes::DefaultSceneHandlerImpl loopTimeValue = decodePair.valueUnsigned16.Value(); break; case Attributes::ColorTemperatureMireds::Id: - if (SupportsColorMode(endpoint, ColorControl::EnhancedColorMode::kColorTemperature)) + if (SupportsColorMode(endpoint, EnhancedColorMode::kColorTemperatureMireds)) { VerifyOrReturnError(decodePair.valueUnsigned16.HasValue(), CHIP_ERROR_INVALID_ARGUMENT); colorTempTransitionState->finalValue = @@ -290,10 +266,9 @@ class DefaultColorControlSceneHandler : public scenes::DefaultSceneHandlerImpl break; case Attributes::EnhancedColorMode::Id: VerifyOrReturnError(decodePair.valueUnsigned8.HasValue(), CHIP_ERROR_INVALID_ARGUMENT); - if (decodePair.valueUnsigned8.Value() <= - static_cast(ColorControl::EnhancedColorMode::kEnhancedCurrentHueAndCurrentSaturation)) + if (decodePair.valueUnsigned8.Value() <= to_underlying(EnhancedColorMode::kEnhancedCurrentHueAndCurrentSaturation)) { - targetColorMode = decodePair.valueUnsigned8.Value(); + targetColorMode = static_cast(decodePair.valueUnsigned8.Value()); } break; default: @@ -328,25 +303,25 @@ class DefaultColorControlSceneHandler : public scenes::DefaultSceneHandlerImpl // Execute movement to value depending on the mode in the saved scene switch (targetColorMode) { - case ColorControl::EnhancedColorMode::kCurrentHueAndCurrentSaturation: + case EnhancedColorMode::kCurrentHueAndCurrentSaturation: #ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_HSV ColorControlServer::Instance().moveToSaturation(static_cast(colorSaturationTransitionState->finalValue), transitionTime10th, endpoint); #endif // MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_HSV break; - case ColorControl::EnhancedColorMode::kCurrentXAndCurrentY: + case EnhancedColorMode::kCurrentXAndCurrentY: #ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_XY ColorControlServer::Instance().moveToColor(colorXTransitionState->finalValue, colorYTransitionState->finalValue, transitionTime10th, endpoint); #endif // MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_XY break; - case ColorControl::EnhancedColorMode::kColorTemperature: + case EnhancedColorMode::kColorTemperatureMireds: #ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_TEMP ColorControlServer::Instance().moveToColorTemp( endpoint, static_cast(colorTempTransitionState->finalValue), transitionTime10th); #endif // MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_TEMP break; - case ColorControl::EnhancedColorMode::kEnhancedCurrentHueAndCurrentSaturation: + case EnhancedColorMode::kEnhancedCurrentHueAndCurrentSaturation: #ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_HSV ColorControlServer::Instance().moveToHueAndSaturation( colorHueTransitionState->finalEnhancedHue, static_cast(colorSaturationTransitionState->finalValue), @@ -361,20 +336,20 @@ class DefaultColorControlSceneHandler : public scenes::DefaultSceneHandlerImpl } private: - bool SupportsColorMode(EndpointId endpoint, uint8_t mode) + bool SupportsColorMode(EndpointId endpoint, EnhancedColorMode mode) { switch (mode) { - case ColorControl::EnhancedColorMode::kCurrentHueAndCurrentSaturation: + case EnhancedColorMode::kCurrentHueAndCurrentSaturation: return ColorControlServer::Instance().HasFeature(endpoint, ColorControlServer::Feature::kHueAndSaturation); break; - case ColorControl::EnhancedColorMode::kCurrentXAndCurrentY: + case EnhancedColorMode::kCurrentXAndCurrentY: return ColorControlServer::Instance().HasFeature(endpoint, ColorControlServer::Feature::kXy); break; - case ColorControl::EnhancedColorMode::kColorTemperature: + case EnhancedColorMode::kColorTemperatureMireds: return ColorControlServer::Instance().HasFeature(endpoint, ColorControlServer::Feature::kColorTemperature); break; - case ColorControl::EnhancedColorMode::kEnhancedCurrentHueAndCurrentSaturation: + case EnhancedColorMode::kEnhancedCurrentHueAndCurrentSaturation: return ColorControlServer::Instance().HasFeature(endpoint, ColorControlServer::Feature::kEnhancedHue); break; default: @@ -494,7 +469,7 @@ Status ColorControlServer::stopAllColorTransitions(EndpointId endpoint) } bool ColorControlServer::stopMoveStepCommand(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, - uint8_t optionsMask, uint8_t optionsOverride) + BitMask optionsMask, BitMask optionsOverride) { EndpointId endpoint = commandPath.mEndpointId; Status status = Status::Success; @@ -534,7 +509,8 @@ bool ColorControlServer::stopMoveStepCommand(app::CommandHandler * commandObj, c return true; } -bool ColorControlServer::shouldExecuteIfOff(EndpointId endpoint, uint8_t optionMask, uint8_t optionOverride) +bool ColorControlServer::shouldExecuteIfOff(EndpointId endpoint, BitMask optionMask, + BitMask optionOverride) { // From 5.2.2.2.1.10 of ZCL7 document 14-0129-15f-zcl-ch-5-lighting.docx: // "Command execution SHALL NOT continue beyond the Options processing if @@ -549,7 +525,7 @@ bool ColorControlServer::shouldExecuteIfOff(EndpointId endpoint, uint8_t optionM return true; } - uint8_t options = 0x00; + BitMask options = 0x00; Attributes::Options::Get(endpoint, &options); bool on = true; @@ -576,23 +552,23 @@ bool ColorControlServer::shouldExecuteIfOff(EndpointId endpoint, uint8_t optionM // ---------- The following order is important in decision making ------- // -----------more readable ---------- // - if (optionMask == 0xFF && optionOverride == 0xFF) + if (optionMask == static_cast(0xFF) && optionOverride == static_cast(0xFF)) { // 0xFF are the default values passed to the command handler when // the payload is not present - in that case there is use of option // attribute to decide execution of the command - return READBITS(options, ColorControl::Options::kExecuteIfOff); + return options.Has(OptionsBitmap::kExecuteIfOff); } // ---------- The above is to distinguish if the payload is present or not - if (READBITS(optionMask, ColorControl::Options::kExecuteIfOff)) + if (optionMask.Has(OptionsBitmap::kExecuteIfOff)) { // Mask is present and set in the command payload, this indicates // use the override as temporary option - return READBITS(optionOverride, ColorControl::Options::kExecuteIfOff); + return optionOverride.Has(OptionsBitmap::kExecuteIfOff); } - // if we are here - use the option attribute bits - return (READBITS(options, ColorControl::Options::kExecuteIfOff)); + // if we are here - use the option bits + return options.Has(OptionsBitmap::kExecuteIfOff); } /** @@ -606,28 +582,28 @@ bool ColorControlServer::shouldExecuteIfOff(EndpointId endpoint, uint8_t optionM * @param endpoint * @param newColorMode */ -void ColorControlServer::handleModeSwitch(EndpointId endpoint, uint8_t newColorMode) +void ColorControlServer::handleModeSwitch(EndpointId endpoint, EnhancedColorModeEnum newColorMode) { - uint8_t oldColorMode = 0; + auto oldColorMode = ColorModeEnum::kCurrentHueAndCurrentSaturation; Attributes::ColorMode::Get(endpoint, &oldColorMode); uint8_t colorModeTransition; - if (oldColorMode == newColorMode) + if (static_cast(oldColorMode) == newColorMode) { return; } Attributes::EnhancedColorMode::Set(endpoint, newColorMode); - if (newColorMode == ColorControl::EnhancedColorMode::kEnhancedCurrentHueAndCurrentSaturation) + if (newColorMode == EnhancedColorMode::kEnhancedCurrentHueAndCurrentSaturation) { - // Transpose COLOR_MODE_EHSV to ColorControl::EnhancedColorMode::kCurrentHueAndCurrentSaturation after setting + // Transpose COLOR_MODE_EHSV to EnhancedColorMode::kCurrentHueAndCurrentSaturation after setting // EnhancedColorMode - newColorMode = ColorControl::EnhancedColorMode::kCurrentHueAndCurrentSaturation; + newColorMode = EnhancedColorMode::kCurrentHueAndCurrentSaturation; } - Attributes::ColorMode::Set(endpoint, newColorMode); + Attributes::ColorMode::Set(endpoint, static_cast(newColorMode)); - colorModeTransition = static_cast((newColorMode << 4) + oldColorMode); + colorModeTransition = static_cast((to_underlying(newColorMode) << 4) + to_underlying(oldColorMode)); // Note: It may be OK to not do anything here. switch (colorModeTransition) @@ -1044,7 +1020,7 @@ void ColorControlServer::startColorLoop(EndpointId endpoint, uint8_t startFromSt colorHueTransitionState->initialEnhancedHue = startHue; - if (direction == to_underlying(ColorLoopDirection::kIncrementHue)) + if (direction == to_underlying(ColorLoopDirectionEnum::kIncrement)) { colorHueTransitionState->finalEnhancedHue = static_cast(startHue - 1); } @@ -1053,7 +1029,7 @@ void ColorControlServer::startColorLoop(EndpointId endpoint, uint8_t startFromSt colorHueTransitionState->finalEnhancedHue = static_cast(startHue + 1); } - colorHueTransitionState->up = (direction == to_underlying(ColorLoopDirection::kIncrementHue)); + colorHueTransitionState->up = (direction == to_underlying(ColorLoopDirectionEnum::kIncrement)); colorHueTransitionState->repeat = true; colorHueTransitionState->stepsRemaining = static_cast(time * TRANSITION_STEPS_PER_1S); @@ -1297,7 +1273,7 @@ Status ColorControlServer::moveToSaturation(uint8_t saturation, uint16_t transit stopAllColorTransitions(endpoint); // Handle color mode transition, if necessary. - handleModeSwitch(endpoint, ColorControl::EnhancedColorMode::kCurrentHueAndCurrentSaturation); + handleModeSwitch(endpoint, EnhancedColorMode::kCurrentHueAndCurrentSaturation); // now, kick off the state machine. initSaturationTransitionState(endpoint, colorSaturationTransitionState); @@ -1421,8 +1397,8 @@ Status ColorControlServer::moveToHueAndSaturation(uint16_t hue, uint8_t saturati * @return false Failed */ bool ColorControlServer::moveHueCommand(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, - HueMoveMode moveMode, uint16_t rate, uint8_t optionsMask, uint8_t optionsOverride, - bool isEnhanced) + HueMoveMode moveMode, uint16_t rate, BitMask optionsMask, + BitMask optionsOverride, bool isEnhanced) { MATTER_TRACE_SCOPE("moveHue", "ColorControl"); EndpointId endpoint = commandPath.mEndpointId; @@ -1464,11 +1440,11 @@ bool ColorControlServer::moveHueCommand(app::CommandHandler * commandObj, const // Handle color mode transition, if necessary. if (isEnhanced) { - handleModeSwitch(endpoint, ColorControl::EnhancedColorMode::kEnhancedCurrentHueAndCurrentSaturation); + handleModeSwitch(endpoint, EnhancedColorMode::kEnhancedCurrentHueAndCurrentSaturation); } else { - handleModeSwitch(endpoint, ColorControl::EnhancedColorMode::kCurrentHueAndCurrentSaturation); + handleModeSwitch(endpoint, EnhancedColorMode::kCurrentHueAndCurrentSaturation); } if (moveMode == HueMoveMode::kUp) @@ -1531,15 +1507,16 @@ bool ColorControlServer::moveHueCommand(app::CommandHandler * commandObj, const * @return false Failed */ bool ColorControlServer::moveToHueCommand(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, - uint16_t hue, HueDirection moveDirection, uint16_t transitionTime, uint8_t optionsMask, - uint8_t optionsOverride, bool isEnhanced) + uint16_t hue, DirectionEnum moveDirection, uint16_t transitionTime, + BitMask optionsMask, BitMask optionsOverride, + bool isEnhanced) { MATTER_TRACE_SCOPE("moveToHue", "ColorControl"); EndpointId endpoint = commandPath.mEndpointId; Status status = Status::Success; uint16_t currentHue = 0; - HueDirection direction; + DirectionEnum direction; ColorHueTransitionState * colorHueTransitionState = getColorHueTransitionState(endpoint); @@ -1568,33 +1545,33 @@ bool ColorControlServer::moveToHueCommand(app::CommandHandler * commandObj, cons // Convert the ShortestDistance/LongestDistance moveDirection values into Up/Down. switch (moveDirection) { - case HueDirection::kShortestDistance: + case DirectionEnum::kShortest: if ((isEnhanced && (static_cast(currentHue - hue) > HALF_MAX_UINT16T)) || (!isEnhanced && (static_cast(currentHue - hue) > HALF_MAX_UINT8T))) { - direction = HueDirection::kUp; + direction = DirectionEnum::kUp; } else { - direction = HueDirection::kDown; + direction = DirectionEnum::kDown; } break; - case HueDirection::kLongestDistance: + case DirectionEnum::kLongest: if ((isEnhanced && (static_cast(currentHue - hue) > HALF_MAX_UINT16T)) || (!isEnhanced && (static_cast(currentHue - hue) > HALF_MAX_UINT8T))) { - direction = HueDirection::kDown; + direction = DirectionEnum::kDown; } else { - direction = HueDirection::kUp; + direction = DirectionEnum::kUp; } break; - case HueDirection::kUp: - case HueDirection::kDown: + case DirectionEnum::kUp: + case DirectionEnum::kDown: direction = moveDirection; break; - case HueDirection::kUnknownEnumValue: + case DirectionEnum::kUnknownEnumValue: commandObj->AddStatus(commandPath, Status::InvalidCommand); return true; /* No default case, so if a new direction value gets added we will just fail @@ -1613,11 +1590,11 @@ bool ColorControlServer::moveToHueCommand(app::CommandHandler * commandObj, cons // Handle color mode transition, if necessary. if (isEnhanced) { - handleModeSwitch(endpoint, ColorControl::EnhancedColorMode::kEnhancedCurrentHueAndCurrentSaturation); + handleModeSwitch(endpoint, EnhancedColorMode::kEnhancedCurrentHueAndCurrentSaturation); } else { - handleModeSwitch(endpoint, ColorControl::EnhancedColorMode::kCurrentHueAndCurrentSaturation); + handleModeSwitch(endpoint, EnhancedColorMode::kCurrentHueAndCurrentSaturation); } // now, kick off the state machine. @@ -1637,7 +1614,7 @@ bool ColorControlServer::moveToHueCommand(app::CommandHandler * commandObj, cons colorHueTransitionState->timeRemaining = transitionTime; colorHueTransitionState->transitionTime = transitionTime; colorHueTransitionState->endpoint = endpoint; - colorHueTransitionState->up = (direction == HueDirection::kUp); + colorHueTransitionState->up = (direction == DirectionEnum::kUp); colorHueTransitionState->repeat = false; SetHSVRemainingTime(endpoint); @@ -1667,8 +1644,9 @@ bool ColorControlServer::moveToHueCommand(app::CommandHandler * commandObj, cons */ bool ColorControlServer::moveToHueAndSaturationCommand(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, uint16_t hue, - uint8_t saturation, uint16_t transitionTime, uint8_t optionsMask, - uint8_t optionsOverride, bool isEnhanced) + 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 @@ -1707,8 +1685,8 @@ bool ColorControlServer::moveToHueAndSaturationCommand(app::CommandHandler * com * @return false Failed */ bool ColorControlServer::stepHueCommand(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, - HueStepMode stepMode, uint16_t stepSize, uint16_t transitionTime, uint8_t optionsMask, - uint8_t optionsOverride, bool isEnhanced) + HueStepMode stepMode, uint16_t stepSize, uint16_t transitionTime, + BitMask optionsMask, BitMask optionsOverride, bool isEnhanced) { MATTER_TRACE_SCOPE("stepHue", "ColorControl"); EndpointId endpoint = commandPath.mEndpointId; @@ -1737,11 +1715,11 @@ bool ColorControlServer::stepHueCommand(app::CommandHandler * commandObj, const // Handle color mode transition, if necessary. if (isEnhanced) { - handleModeSwitch(endpoint, ColorControl::EnhancedColorMode::kEnhancedCurrentHueAndCurrentSaturation); + handleModeSwitch(endpoint, EnhancedColorMode::kEnhancedCurrentHueAndCurrentSaturation); } else { - handleModeSwitch(endpoint, ColorControl::EnhancedColorMode::kCurrentHueAndCurrentSaturation); + handleModeSwitch(endpoint, EnhancedColorMode::kCurrentHueAndCurrentSaturation); } // now, kick off the state machine. @@ -1839,7 +1817,7 @@ bool ColorControlServer::moveSaturationCommand(app::CommandHandler * commandObj, } // Handle color mode transition, if necessary. - handleModeSwitch(endpoint, ColorControl::EnhancedColorMode::kCurrentHueAndCurrentSaturation); + handleModeSwitch(endpoint, EnhancedColorMode::kCurrentHueAndCurrentSaturation); if (moveMode == SaturationMoveMode::kUp) { @@ -1908,14 +1886,14 @@ bool ColorControlServer::stepSaturationCommand(app::CommandHandler * commandObj, const Commands::StepSaturation::DecodableType & commandData) { MATTER_TRACE_SCOPE("stepSaturation", "ColorControl"); - auto stepMode = commandData.stepMode; - uint8_t stepSize = commandData.stepSize; - uint8_t transitionTime = commandData.transitionTime; - uint8_t optionsMask = commandData.optionsMask; - uint8_t optionsOverride = commandData.optionsOverride; - EndpointId endpoint = commandPath.mEndpointId; - Status status = Status::Success; - uint8_t currentSaturation = 0; + 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; Color16uTransitionState * colorSaturationTransitionState = getSaturationTransitionState(endpoint); VerifyOrExit(colorSaturationTransitionState != nullptr, status = Status::UnsupportedEndpoint); @@ -1937,7 +1915,7 @@ bool ColorControlServer::stepSaturationCommand(app::CommandHandler * commandObj, stopAllColorTransitions(endpoint); // Handle color mode transition, if necessary. - handleModeSwitch(endpoint, ColorControl::EnhancedColorMode::kCurrentHueAndCurrentSaturation); + handleModeSwitch(endpoint, EnhancedColorMode::kCurrentHueAndCurrentSaturation); // now, kick off the state machine. initSaturationTransitionState(endpoint, colorSaturationTransitionState); @@ -1973,24 +1951,24 @@ bool ColorControlServer::colorLoopCommand(app::CommandHandler * commandObj, cons 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; - uint8_t optionsMask = commandData.optionsMask; - uint8_t optionsOverride = commandData.optionsOverride; - EndpointId endpoint = commandPath.mEndpointId; - Status status = Status::Success; - uint8_t isColorLoopActive = 0; - uint8_t deactiveColorLoop = 0; + 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; uint16_t epIndex = getEndpointIndex(endpoint); ColorHueTransitionState * colorHueTransitionState = getColorHueTransitionStateByIndex(epIndex); VerifyOrExit(colorHueTransitionState != nullptr, status = Status::UnsupportedEndpoint); // Validate the action and direction parameters of the command - if (action == ColorLoopAction::kUnknownEnumValue || direction == ColorLoopDirection::kUnknownEnumValue) + if (action == ColorLoopActionEnum::kUnknownEnumValue || direction == ColorLoopDirectionEnum::kUnknownEnumValue) { commandObj->AddStatus(commandPath, Status::InvalidCommand); return true; @@ -2017,10 +1995,10 @@ bool ColorControlServer::colorLoopCommand(app::CommandHandler * commandObj, cons // Checks if color loop is active and stays active if (isColorLoopActive && !deactiveColorLoop) { - colorHueTransitionState->up = (direction == ColorLoopDirection::kIncrementHue); + colorHueTransitionState->up = (direction == ColorLoopDirectionEnum::kIncrement); colorHueTransitionState->initialEnhancedHue = colorHueTransitionState->currentEnhancedHue; - if (direction == ColorLoopDirection::kIncrementHue) + if (direction == ColorLoopDirectionEnum::kIncrement) { colorHueTransitionState->finalEnhancedHue = static_cast(colorHueTransitionState->initialEnhancedHue - 1); } @@ -2346,12 +2324,12 @@ bool ColorControlServer::moveToColorCommand(app::CommandHandler * commandObj, co bool ColorControlServer::moveColorCommand(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, const Commands::MoveColor::DecodableType & commandData) { - int16_t rateX = commandData.rateX; - int16_t rateY = commandData.rateY; - uint8_t optionsMask = commandData.optionsMask; - uint8_t optionsOverride = commandData.optionsOverride; - EndpointId endpoint = commandPath.mEndpointId; - Status status = Status::Success; + 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); @@ -2380,7 +2358,7 @@ bool ColorControlServer::moveColorCommand(app::CommandHandler * commandObj, cons } // Handle color mode transition, if necessary. - handleModeSwitch(endpoint, ColorControl::EnhancedColorMode::kCurrentXAndCurrentY); + handleModeSwitch(endpoint, EnhancedColorMode::kCurrentXAndCurrentY); // now, kick off the state machine. Attributes::CurrentX::Get(endpoint, &(colorXTransitionState->initialValue)); @@ -2438,16 +2416,16 @@ bool ColorControlServer::moveColorCommand(app::CommandHandler * commandObj, cons bool ColorControlServer::stepColorCommand(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, const Commands::StepColor::DecodableType & commandData) { - int16_t stepX = commandData.stepX; - int16_t stepY = commandData.stepY; - uint16_t transitionTime = commandData.transitionTime; - uint8_t optionsMask = commandData.optionsMask; - uint8_t optionsOverride = commandData.optionsOverride; - EndpointId endpoint = commandPath.mEndpointId; - uint16_t currentColorX = 0; - uint16_t currentColorY = 0; - uint16_t colorX = 0; - uint16_t colorY = 0; + 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; @@ -2480,7 +2458,7 @@ bool ColorControlServer::stepColorCommand(app::CommandHandler * commandObj, cons stopAllColorTransitions(endpoint); // Handle color mode transition, if necessary. - handleModeSwitch(endpoint, ColorControl::EnhancedColorMode::kCurrentXAndCurrentY); + handleModeSwitch(endpoint, EnhancedColorMode::kCurrentXAndCurrentY); // now, kick off the state machine. colorXTransitionState->initialValue = currentColorX; @@ -2615,7 +2593,7 @@ Status ColorControlServer::moveToColorTemp(EndpointId aEndpoint, uint16_t colorT stopAllColorTransitions(endpoint); // Handle color mode transition, if necessary. - handleModeSwitch(endpoint, ColorControl::EnhancedColorMode::kColorTemperature); + handleModeSwitch(endpoint, EnhancedColorMode::kColorTemperatureMireds); if (colorTemperature < temperatureMin) { @@ -2724,11 +2702,10 @@ void ColorControlServer::startUpColorTempCommand(EndpointId endpoint) if (status == Status::Success) { // Set ColorMode attributes to reflect ColorTemperature. - uint8_t updateColorMode = ColorControl::EnhancedColorMode::kColorTemperature; + auto updateColorMode = ColorModeEnum::kColorTemperatureMireds; Attributes::ColorMode::Set(endpoint, updateColorMode); - updateColorMode = ColorControl::EnhancedColorMode::kColorTemperature; - Attributes::EnhancedColorMode::Set(endpoint, updateColorMode); + Attributes::EnhancedColorMode::Set(endpoint, static_cast(updateColorMode)); } } } @@ -2798,16 +2775,16 @@ void ColorControlServer::updateTempCommand(EndpointId endpoint) 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; - uint8_t optionsMask = commandData.optionsMask; - uint8_t optionsOverride = commandData.optionsOverride; - EndpointId endpoint = commandPath.mEndpointId; - Status status = Status::Success; - uint16_t tempPhysicalMin = MIN_TEMPERATURE_VALUE; - uint16_t tempPhysicalMax = MAX_TEMPERATURE_VALUE; + 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); @@ -2854,7 +2831,7 @@ bool ColorControlServer::moveColorTempCommand(app::CommandHandler * commandObj, } // Handle color mode transition, if necessary. - handleModeSwitch(endpoint, ColorControl::EnhancedColorMode::kColorTemperature); + handleModeSwitch(endpoint, EnhancedColorMode::kColorTemperatureMireds); // now, kick off the state machine. colorTempTransitionState->initialValue = 0; @@ -2922,17 +2899,17 @@ bool ColorControlServer::moveToColorTempCommand(app::CommandHandler * commandObj bool ColorControlServer::stepColorTempCommand(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, 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; - uint8_t optionsMask = commandData.optionsMask; - uint8_t optionsOverride = commandData.optionsOverride; - EndpointId endpoint = commandPath.mEndpointId; - Status status = Status::Success; - uint16_t tempPhysicalMin = MIN_TEMPERATURE_VALUE; - uint16_t tempPhysicalMax = MAX_TEMPERATURE_VALUE; + 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; Color16uTransitionState * colorTempTransitionState = getTempTransitionState(endpoint); VerifyOrExit(colorTempTransitionState != nullptr, status = Status::UnsupportedEndpoint); @@ -2971,7 +2948,7 @@ bool ColorControlServer::stepColorTempCommand(app::CommandHandler * commandObj, } // Handle color mode transition, if necessary. - handleModeSwitch(endpoint, ColorControl::EnhancedColorMode::kColorTemperature); + handleModeSwitch(endpoint, EnhancedColorMode::kColorTemperatureMireds); // now, kick off the state machine. colorTempTransitionState->initialValue = 0; @@ -3058,10 +3035,10 @@ void ColorControlServer::levelControlColorTempChangeCommand(EndpointId endpoint) return; } - uint8_t colorMode = 0; + auto colorMode = ColorModeEnum::kCurrentHueAndCurrentSaturation; Attributes::ColorMode::Get(endpoint, &colorMode); - if (colorMode == ColorControl::EnhancedColorMode::kColorTemperature) + if (static_cast(colorMode) == EnhancedColorMode::kColorTemperatureMireds) { app::DataModel::Nullable currentLevel; Status status = LevelControl::Attributes::CurrentLevel::Get(endpoint, currentLevel); 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 4238fed1dd..1ed9e33c40 100644 --- a/src/app/clusters/color-control-server/color-control-server.h +++ b/src/app/clusters/color-control-server/color-control-server.h @@ -71,18 +71,10 @@ class ColorControlServer /********************************************************** * Enums *********************************************************/ - using HueStepMode = chip::app::Clusters::ColorControl::HueStepMode; - using HueMoveMode = chip::app::Clusters::ColorControl::HueMoveMode; - using HueDirection = chip::app::Clusters::ColorControl::HueDirection; - using Feature = chip::app::Clusters::ColorControl::Feature; - - enum EnhancedColorMode : uint8_t - { - kCurrentHueAndCurrentSaturation = 0, - kCurrentXAndCurrentY = 1, - kColorTemperature = 2, - kEnhancedCurrentHueAndCurrentSaturation = 3, - }; + using StepModeEnum = chip::app::Clusters::ColorControl::StepModeEnum; + using MoveModeEnum = chip::app::Clusters::ColorControl::MoveModeEnum; + using DirectionEnum = chip::app::Clusters::ColorControl::DirectionEnum; + using Feature = chip::app::Clusters::ColorControl::Feature; enum Conversion { @@ -150,20 +142,27 @@ 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, - uint8_t optionsMask, uint8_t optionsOverride); + chip::BitMask optionsMask, + chip::BitMask optionsOverride); #ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_HSV bool moveHueCommand(chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, - HueMoveMode moveMode, uint16_t rate, uint8_t optionsMask, uint8_t optionsOverride, bool isEnhanced); + 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, - HueDirection moveDirection, uint16_t transitionTime, uint8_t optionsMask, uint8_t optionsOverride, - bool isEnhanced); + 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, uint8_t optionsMask, - uint8_t optionsOverride, bool isEnhanced); + 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, - HueStepMode stepMode, uint16_t stepSize, uint16_t transitionTime, uint8_t optionsMask, - uint8_t optionsOverride, bool isEnhanced); + 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, @@ -224,8 +223,9 @@ class ColorControlServer } } - bool shouldExecuteIfOff(chip::EndpointId endpoint, uint8_t optionMask, uint8_t optionOverride); - void handleModeSwitch(chip::EndpointId endpoint, uint8_t newColorMode); + bool shouldExecuteIfOff(chip::EndpointId endpoint, chip::BitMask optionMask, + chip::BitMask optionOverride); + void handleModeSwitch(chip::EndpointId endpoint, chip::app::Clusters::ColorControl::EnhancedColorModeEnum newColorMode); uint16_t computeTransitionTimeFromStateAndRate(Color16uTransitionState * p, uint16_t rate); EmberEventControl * getEventControl(chip::EndpointId endpoint); void computePwmFromHsv(chip::EndpointId endpoint); diff --git a/src/app/common/CompatEnumNames.h b/src/app/common/CompatEnumNames.h index ceb91c1981..a3154cbb68 100644 --- a/src/app/common/CompatEnumNames.h +++ b/src/app/common/CompatEnumNames.h @@ -21,6 +21,8 @@ */ #pragma once +#include + namespace chip { namespace app { namespace Clusters { @@ -80,6 +82,50 @@ using StepMode = StepModeEnum; using LevelControlOptions = OptionsBitmap; } // namespace LevelControl +namespace ColorControl { +// https://github.com/project-chip/connectedhomeip/pull/33612 renamed this +enum class ColorMode : uint8_t +{ + kCurrentHueAndCurrentSaturation = to_underlying(ColorModeEnum::kCurrentHueAndCurrentSaturation), + kCurrentXAndCurrentY = to_underlying(ColorModeEnum::kCurrentXAndCurrentY), + kColorTemperature = to_underlying(ColorModeEnum::kColorTemperatureMireds), + kUnknownEnumValue = to_underlying(ColorModeEnum::kUnknownEnumValue) +}; + +enum class HueDirection : uint8_t +{ + ShortestDistance = to_underlying(DirectionEnum::kShortest), + LongestDistance = to_underlying(DirectionEnum::kLongest), + Up = to_underlying(DirectionEnum::kUp), + Down = to_underlying(DirectionEnum::kDown), + kUnknownEnumValue = to_underlying(DirectionEnum::kUnknownEnumValue) +}; + +enum class ColorCapabilities : uint16_t +{ + ColorLoopSupported = to_underlying(ColorCapabilitiesBitmap::kColorLoop), + ColorTemperatureSupported = to_underlying(ColorCapabilitiesBitmap::kColorTemperature), + EnhancedHueSupported = to_underlying(ColorCapabilitiesBitmap::kEnhancedHue), + HueSaturationSupported = to_underlying(ColorCapabilitiesBitmap::kHueSaturation), + XYAttributesSupported = to_underlying(ColorCapabilitiesBitmap::kXy) +}; + +enum class ColorLoopDirection : uint8_t +{ + DecrementHue = to_underlying(ColorLoopDirectionEnum::kDecrement), + IncrementHue = to_underlying(ColorLoopDirectionEnum::kIncrement), + kUnknownEnumValue = to_underlying(ColorLoopDirectionEnum::kUnknownEnumValue) +}; + +using EnhancedColorMode = EnhancedColorModeEnum; +using ColorLoopUpdateFlags = UpdateFlagsBitmap; +using ColorLoopAction = ColorLoopActionEnum; +using HueMoveMode = MoveModeEnum; +using HueStepMode = StepModeEnum; +using SaturationMoveMode = MoveModeEnum; +using SaturationStepMode = StepModeEnum; +} // namespace ColorControl + namespace RefrigeratorAlarm { // https://github.com/project-chip/connectedhomeip/pull/31517 renamed this using AlarmMap = AlarmBitmap; 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 c97d4a59ba..f72140e712 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 @@ -17,57 +17,44 @@ limitations under the License. - + - - + + - + - + - - - - - - - - - - - - - - + - + - + - - - - - + + + + + - + @@ -75,17 +62,39 @@ limitations under the License. - + - + + + + + + + + + + + + + + + + + + + + + + + - - + + @@ -128,15 +137,15 @@ limitations under the License. CurrentY - DriftCompensation + DriftCompensation CompensationText ColorTemperatureMireds - ColorMode + ColorMode - Options + Options NumberOfPrimaries @@ -254,31 +263,31 @@ limitations under the License. Move to specified hue. - + - - + + Move hue up or down at specified rate. - + - - + + Step hue up or down by specified size at specified rate. - + - - + + @@ -287,29 +296,29 @@ limitations under the License. - - + + Move saturation up or down at specified rate. - + - - + + Step saturation up or down by specified size at specified rate. - + - - + + @@ -319,8 +328,8 @@ limitations under the License. - - + + @@ -330,8 +339,8 @@ limitations under the License. - - + + @@ -340,8 +349,8 @@ limitations under the License. - - + + @@ -351,8 +360,8 @@ limitations under the License. - - + + @@ -361,20 +370,20 @@ limitations under the License. - - + + EnhancedCurrentHue - EnhancedColorMode - ColorLoopActive - ColorLoopDirection + EnhancedColorMode + ColorLoopActive + ColorLoopDirection ColorLoopTime ColorLoopStartEnhancedHue ColorLoopStoredEnhancedHue - ColorCapabilities + ColorCapabilities ColorTempPhysicalMinMireds ColorTempPhysicalMaxMireds @@ -383,31 +392,31 @@ limitations under the License. Command description for EnhancedMoveToHue - + - - + + Command description for EnhancedMoveHue - + - - + + Command description for EnhancedStepHue - + - - + + @@ -417,54 +426,54 @@ limitations under the License. - - + + Command description for ColorLoopSet - - - + + + - - + + Command description for StopMoveStep - - + + Command description for MoveColorTemperature - + - - + + Command description for StepColorTemperature - + - - + + diff --git a/src/controller/data_model/controller-clusters.matter b/src/controller/data_model/controller-clusters.matter index 02408e1ecf..bfb1354849 100644 --- a/src/controller/data_model/controller-clusters.matter +++ b/src/controller/data_model/controller-clusters.matter @@ -7145,65 +7145,62 @@ cluster ThermostatUserInterfaceConfiguration = 516 { cluster ColorControl = 768 { revision 7; - enum ColorLoopAction : enum8 { + enum ColorLoopActionEnum : enum8 { kDeactivate = 0; kActivateFromColorLoopStartEnhancedHue = 1; kActivateFromEnhancedCurrentHue = 2; } - enum ColorLoopDirection : enum8 { - kDecrementHue = 0; - kIncrementHue = 1; + enum ColorLoopDirectionEnum : enum8 { + kDecrement = 0; + kIncrement = 1; } - enum ColorMode : enum8 { + enum ColorModeEnum : enum8 { kCurrentHueAndCurrentSaturation = 0; kCurrentXAndCurrentY = 1; - kColorTemperature = 2; + kColorTemperatureMireds = 2; } - enum HueDirection : enum8 { - kShortestDistance = 0; - kLongestDistance = 1; + enum DirectionEnum : enum8 { + kShortest = 0; + kLongest = 1; kUp = 2; kDown = 3; } - enum HueMoveMode : enum8 { - kStop = 0; - kUp = 1; - kDown = 3; + enum DriftCompensationEnum : enum8 { + kNone = 0; + kOtherOrUnknown = 1; + kTemperatureMonitoring = 2; + kOpticalLuminanceMonitoringAndFeedback = 3; + kOpticalColorMonitoringAndFeedback = 4; } - enum HueStepMode : enum8 { - kUp = 1; - kDown = 3; + enum EnhancedColorModeEnum : enum8 { + kCurrentHueAndCurrentSaturation = 0; + kCurrentXAndCurrentY = 1; + kColorTemperatureMireds = 2; + kEnhancedCurrentHueAndCurrentSaturation = 3; } - enum SaturationMoveMode : enum8 { + enum MoveModeEnum : enum8 { kStop = 0; kUp = 1; kDown = 3; } - enum SaturationStepMode : enum8 { + enum StepModeEnum : enum8 { kUp = 1; kDown = 3; } - bitmap ColorCapabilities : bitmap16 { - kHueSaturationSupported = 0x1; - kEnhancedHueSupported = 0x2; - kColorLoopSupported = 0x4; - kXYAttributesSupported = 0x8; - kColorTemperatureSupported = 0x10; - } - - bitmap ColorLoopUpdateFlags : bitmap8 { - kUpdateAction = 0x1; - kUpdateDirection = 0x2; - kUpdateTime = 0x4; - kUpdateStartHue = 0x8; + bitmap ColorCapabilitiesBitmap : bitmap16 { + kHueSaturation = 0x1; + kEnhancedHue = 0x2; + kColorLoop = 0x4; + kXY = 0x8; + kColorTemperature = 0x10; } bitmap Feature : bitmap32 { @@ -7214,16 +7211,27 @@ cluster ColorControl = 768 { kColorTemperature = 0x10; } + bitmap OptionsBitmap : bitmap8 { + kExecuteIfOff = 0x1; + } + + bitmap UpdateFlagsBitmap : bitmap8 { + kUpdateAction = 0x1; + kUpdateDirection = 0x2; + kUpdateTime = 0x4; + kUpdateStartHue = 0x8; + } + readonly attribute optional int8u currentHue = 0; readonly attribute optional int8u currentSaturation = 1; readonly attribute optional int16u remainingTime = 2; readonly attribute optional int16u currentX = 3; readonly attribute optional int16u currentY = 4; - readonly attribute optional enum8 driftCompensation = 5; + readonly attribute optional DriftCompensationEnum driftCompensation = 5; readonly attribute optional char_string<254> compensationText = 6; readonly attribute optional int16u colorTemperatureMireds = 7; - readonly attribute enum8 colorMode = 8; - attribute bitmap8 options = 15; + readonly attribute ColorModeEnum colorMode = 8; + attribute OptionsBitmap options = 15; readonly attribute nullable int8u numberOfPrimaries = 16; readonly attribute optional int16u primary1X = 17; readonly attribute optional int16u primary1Y = 18; @@ -7255,13 +7263,13 @@ cluster ColorControl = 768 { attribute access(write: manage) optional int16u colorPointBY = 59; attribute access(write: manage) optional nullable int8u colorPointBIntensity = 60; readonly attribute optional int16u enhancedCurrentHue = 16384; - readonly attribute enum8 enhancedColorMode = 16385; + readonly attribute EnhancedColorModeEnum enhancedColorMode = 16385; readonly attribute optional int8u colorLoopActive = 16386; readonly attribute optional int8u colorLoopDirection = 16387; readonly attribute optional int16u colorLoopTime = 16388; readonly attribute optional int16u colorLoopStartEnhancedHue = 16389; readonly attribute optional int16u colorLoopStoredEnhancedHue = 16390; - readonly attribute bitmap16 colorCapabilities = 16394; + readonly attribute ColorCapabilitiesBitmap colorCapabilities = 16394; readonly attribute optional int16u colorTempPhysicalMinMireds = 16395; readonly attribute optional int16u colorTempPhysicalMaxMireds = 16396; readonly attribute optional int16u coupleColorTempToLevelMinMireds = 16397; @@ -7275,150 +7283,150 @@ cluster ColorControl = 768 { request struct MoveToHueRequest { int8u hue = 0; - HueDirection direction = 1; + DirectionEnum direction = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveHueRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int8u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepHueRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int8u stepSize = 1; int8u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToSaturationRequest { int8u saturation = 0; int16u transitionTime = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct MoveSaturationRequest { - SaturationMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int8u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepSaturationRequest { - SaturationStepMode stepMode = 0; + StepModeEnum stepMode = 0; int8u stepSize = 1; int8u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToHueAndSaturationRequest { int8u hue = 0; int8u saturation = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToColorRequest { int16u colorX = 0; int16u colorY = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveColorRequest { int16s rateX = 0; int16s rateY = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct StepColorRequest { int16s stepX = 0; int16s stepY = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct MoveToColorTemperatureRequest { int16u colorTemperatureMireds = 0; int16u transitionTime = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct EnhancedMoveToHueRequest { int16u enhancedHue = 0; - HueDirection direction = 1; + DirectionEnum direction = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct EnhancedMoveHueRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int16u rate = 1; - bitmap8 optionsMask = 2; - bitmap8 optionsOverride = 3; + OptionsBitmap optionsMask = 2; + OptionsBitmap optionsOverride = 3; } request struct EnhancedStepHueRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int16u stepSize = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct EnhancedMoveToHueAndSaturationRequest { int16u enhancedHue = 0; int8u saturation = 1; int16u transitionTime = 2; - bitmap8 optionsMask = 3; - bitmap8 optionsOverride = 4; + OptionsBitmap optionsMask = 3; + OptionsBitmap optionsOverride = 4; } request struct ColorLoopSetRequest { - ColorLoopUpdateFlags updateFlags = 0; - ColorLoopAction action = 1; - ColorLoopDirection direction = 2; + UpdateFlagsBitmap updateFlags = 0; + ColorLoopActionEnum action = 1; + ColorLoopDirectionEnum direction = 2; int16u time = 3; int16u startHue = 4; - bitmap8 optionsMask = 5; - bitmap8 optionsOverride = 6; + OptionsBitmap optionsMask = 5; + OptionsBitmap optionsOverride = 6; } request struct StopMoveStepRequest { - bitmap8 optionsMask = 0; - bitmap8 optionsOverride = 1; + OptionsBitmap optionsMask = 0; + OptionsBitmap optionsOverride = 1; } request struct MoveColorTemperatureRequest { - HueMoveMode moveMode = 0; + MoveModeEnum moveMode = 0; int16u rate = 1; int16u colorTemperatureMinimumMireds = 2; int16u colorTemperatureMaximumMireds = 3; - bitmap8 optionsMask = 4; - bitmap8 optionsOverride = 5; + OptionsBitmap optionsMask = 4; + OptionsBitmap optionsOverride = 5; } request struct StepColorTemperatureRequest { - HueStepMode stepMode = 0; + StepModeEnum stepMode = 0; int16u stepSize = 1; int16u transitionTime = 2; int16u colorTemperatureMinimumMireds = 3; int16u colorTemperatureMaximumMireds = 4; - bitmap8 optionsMask = 5; - bitmap8 optionsOverride = 6; + OptionsBitmap optionsMask = 5; + OptionsBitmap optionsOverride = 6; } /** Move to specified hue. */ diff --git a/src/controller/java/zap-generated/CHIPAttributeTLVValueDecoder.cpp b/src/controller/java/zap-generated/CHIPAttributeTLVValueDecoder.cpp index 82a4a6fe42..db775e5d52 100644 --- a/src/controller/java/zap-generated/CHIPAttributeTLVValueDecoder.cpp +++ b/src/controller/java/zap-generated/CHIPAttributeTLVValueDecoder.cpp @@ -32152,7 +32152,7 @@ jobject DecodeAttributeValue(const app::ConcreteAttributePath & aPath, TLV::TLVR jobject value; std::string valueClassName = "java/lang/Integer"; std::string valueCtorSignature = "(I)V"; - jint jnivalue = static_cast(cppValue); + jint jnivalue = static_cast(cppValue.Raw()); chip::JniReferences::GetInstance().CreateBoxedObject(valueClassName.c_str(), valueCtorSignature.c_str(), jnivalue, value); return value; @@ -32830,7 +32830,7 @@ jobject DecodeAttributeValue(const app::ConcreteAttributePath & aPath, TLV::TLVR jobject value; std::string valueClassName = "java/lang/Integer"; std::string valueCtorSignature = "(I)V"; - jint jnivalue = static_cast(cppValue); + jint jnivalue = static_cast(cppValue.Raw()); chip::JniReferences::GetInstance().CreateBoxedObject(valueClassName.c_str(), valueCtorSignature.c_str(), jnivalue, value); return value; diff --git a/src/controller/python/chip/clusters/Objects.py b/src/controller/python/chip/clusters/Objects.py index ed3c9154cc..6b8ecd1c82 100644 --- a/src/controller/python/chip/clusters/Objects.py +++ b/src/controller/python/chip/clusters/Objects.py @@ -34913,10 +34913,10 @@ def descriptor(cls) -> ClusterObjectDescriptor: ClusterObjectFieldDescriptor(Label="remainingTime", Tag=0x00000002, Type=typing.Optional[uint]), ClusterObjectFieldDescriptor(Label="currentX", Tag=0x00000003, Type=typing.Optional[uint]), ClusterObjectFieldDescriptor(Label="currentY", Tag=0x00000004, Type=typing.Optional[uint]), - ClusterObjectFieldDescriptor(Label="driftCompensation", Tag=0x00000005, Type=typing.Optional[uint]), + ClusterObjectFieldDescriptor(Label="driftCompensation", Tag=0x00000005, Type=typing.Optional[ColorControl.Enums.DriftCompensationEnum]), ClusterObjectFieldDescriptor(Label="compensationText", Tag=0x00000006, Type=typing.Optional[str]), ClusterObjectFieldDescriptor(Label="colorTemperatureMireds", Tag=0x00000007, Type=typing.Optional[uint]), - ClusterObjectFieldDescriptor(Label="colorMode", Tag=0x00000008, Type=uint), + ClusterObjectFieldDescriptor(Label="colorMode", Tag=0x00000008, Type=ColorControl.Enums.ColorModeEnum), ClusterObjectFieldDescriptor(Label="options", Tag=0x0000000F, Type=uint), ClusterObjectFieldDescriptor(Label="numberOfPrimaries", Tag=0x00000010, Type=typing.Union[Nullable, uint]), ClusterObjectFieldDescriptor(Label="primary1X", Tag=0x00000011, Type=typing.Optional[uint]), @@ -34949,7 +34949,7 @@ def descriptor(cls) -> ClusterObjectDescriptor: ClusterObjectFieldDescriptor(Label="colorPointBY", Tag=0x0000003B, Type=typing.Optional[uint]), ClusterObjectFieldDescriptor(Label="colorPointBIntensity", Tag=0x0000003C, Type=typing.Union[None, Nullable, uint]), ClusterObjectFieldDescriptor(Label="enhancedCurrentHue", Tag=0x00004000, Type=typing.Optional[uint]), - ClusterObjectFieldDescriptor(Label="enhancedColorMode", Tag=0x00004001, Type=uint), + ClusterObjectFieldDescriptor(Label="enhancedColorMode", Tag=0x00004001, Type=ColorControl.Enums.EnhancedColorModeEnum), ClusterObjectFieldDescriptor(Label="colorLoopActive", Tag=0x00004002, Type=typing.Optional[uint]), ClusterObjectFieldDescriptor(Label="colorLoopDirection", Tag=0x00004003, Type=typing.Optional[uint]), ClusterObjectFieldDescriptor(Label="colorLoopTime", Tag=0x00004004, Type=typing.Optional[uint]), @@ -34973,10 +34973,10 @@ def descriptor(cls) -> ClusterObjectDescriptor: remainingTime: 'typing.Optional[uint]' = None currentX: 'typing.Optional[uint]' = None currentY: 'typing.Optional[uint]' = None - driftCompensation: 'typing.Optional[uint]' = None + driftCompensation: 'typing.Optional[ColorControl.Enums.DriftCompensationEnum]' = None compensationText: 'typing.Optional[str]' = None colorTemperatureMireds: 'typing.Optional[uint]' = None - colorMode: 'uint' = None + colorMode: 'ColorControl.Enums.ColorModeEnum' = None options: 'uint' = None numberOfPrimaries: 'typing.Union[Nullable, uint]' = None primary1X: 'typing.Optional[uint]' = None @@ -35009,7 +35009,7 @@ def descriptor(cls) -> ClusterObjectDescriptor: colorPointBY: 'typing.Optional[uint]' = None colorPointBIntensity: 'typing.Union[None, Nullable, uint]' = None enhancedCurrentHue: 'typing.Optional[uint]' = None - enhancedColorMode: 'uint' = None + enhancedColorMode: 'ColorControl.Enums.EnhancedColorModeEnum' = None colorLoopActive: 'typing.Optional[uint]' = None colorLoopDirection: 'typing.Optional[uint]' = None colorLoopTime: 'typing.Optional[uint]' = None @@ -35028,7 +35028,7 @@ def descriptor(cls) -> ClusterObjectDescriptor: clusterRevision: 'uint' = None class Enums: - class ColorLoopAction(MatterIntEnum): + class ColorLoopActionEnum(MatterIntEnum): kDeactivate = 0x00 kActivateFromColorLoopStartEnhancedHue = 0x01 kActivateFromEnhancedCurrentHue = 0x02 @@ -35038,28 +35038,28 @@ class ColorLoopAction(MatterIntEnum): # enum value. This specific value should never be transmitted. kUnknownEnumValue = 3, - class ColorLoopDirection(MatterIntEnum): - kDecrementHue = 0x00 - kIncrementHue = 0x01 + class ColorLoopDirectionEnum(MatterIntEnum): + kDecrement = 0x00 + kIncrement = 0x01 # All received enum values that are not listed above will be mapped # to kUnknownEnumValue. This is a helper enum value that should only # be used by code to process how it handles receiving an unknown # enum value. This specific value should never be transmitted. kUnknownEnumValue = 2, - class ColorMode(MatterIntEnum): + class ColorModeEnum(MatterIntEnum): kCurrentHueAndCurrentSaturation = 0x00 kCurrentXAndCurrentY = 0x01 - kColorTemperature = 0x02 + kColorTemperatureMireds = 0x02 # All received enum values that are not listed above will be mapped # to kUnknownEnumValue. This is a helper enum value that should only # be used by code to process how it handles receiving an unknown # enum value. This specific value should never be transmitted. kUnknownEnumValue = 3, - class HueDirection(MatterIntEnum): - kShortestDistance = 0x00 - kLongestDistance = 0x01 + class DirectionEnum(MatterIntEnum): + kShortest = 0x00 + kLongest = 0x01 kUp = 0x02 kDown = 0x03 # All received enum values that are not listed above will be mapped @@ -35068,26 +35068,30 @@ class HueDirection(MatterIntEnum): # enum value. This specific value should never be transmitted. kUnknownEnumValue = 4, - class HueMoveMode(MatterIntEnum): - kStop = 0x00 - kUp = 0x01 - kDown = 0x03 + class DriftCompensationEnum(MatterIntEnum): + kNone = 0x00 + kOtherOrUnknown = 0x01 + kTemperatureMonitoring = 0x02 + kOpticalLuminanceMonitoringAndFeedback = 0x03 + kOpticalColorMonitoringAndFeedback = 0x04 # All received enum values that are not listed above will be mapped # to kUnknownEnumValue. This is a helper enum value that should only # be used by code to process how it handles receiving an unknown # enum value. This specific value should never be transmitted. - kUnknownEnumValue = 2, + kUnknownEnumValue = 5, - class HueStepMode(MatterIntEnum): - kUp = 0x01 - kDown = 0x03 + class EnhancedColorModeEnum(MatterIntEnum): + kCurrentHueAndCurrentSaturation = 0x00 + kCurrentXAndCurrentY = 0x01 + kColorTemperatureMireds = 0x02 + kEnhancedCurrentHueAndCurrentSaturation = 0x03 # All received enum values that are not listed above will be mapped # to kUnknownEnumValue. This is a helper enum value that should only # be used by code to process how it handles receiving an unknown # enum value. This specific value should never be transmitted. - kUnknownEnumValue = 0, + kUnknownEnumValue = 4, - class SaturationMoveMode(MatterIntEnum): + class MoveModeEnum(MatterIntEnum): kStop = 0x00 kUp = 0x01 kDown = 0x03 @@ -35097,7 +35101,7 @@ class SaturationMoveMode(MatterIntEnum): # enum value. This specific value should never be transmitted. kUnknownEnumValue = 2, - class SaturationStepMode(MatterIntEnum): + class StepModeEnum(MatterIntEnum): kUp = 0x01 kDown = 0x03 # All received enum values that are not listed above will be mapped @@ -35107,18 +35111,12 @@ class SaturationStepMode(MatterIntEnum): kUnknownEnumValue = 0, class Bitmaps: - class ColorCapabilities(IntFlag): - kHueSaturationSupported = 0x1 - kEnhancedHueSupported = 0x2 - kColorLoopSupported = 0x4 - kXYAttributesSupported = 0x8 - kColorTemperatureSupported = 0x10 - - class ColorLoopUpdateFlags(IntFlag): - kUpdateAction = 0x1 - kUpdateDirection = 0x2 - kUpdateTime = 0x4 - kUpdateStartHue = 0x8 + class ColorCapabilitiesBitmap(IntFlag): + kHueSaturation = 0x1 + kEnhancedHue = 0x2 + kColorLoop = 0x4 + kXy = 0x8 + kColorTemperature = 0x10 class Feature(IntFlag): kHueAndSaturation = 0x1 @@ -35127,6 +35125,15 @@ class Feature(IntFlag): kXy = 0x8 kColorTemperature = 0x10 + class OptionsBitmap(IntFlag): + kExecuteIfOff = 0x1 + + class UpdateFlagsBitmap(IntFlag): + kUpdateAction = 0x1 + kUpdateDirection = 0x2 + kUpdateTime = 0x4 + kUpdateStartHue = 0x8 + class Commands: @dataclass class MoveToHue(ClusterCommand): @@ -35140,14 +35147,14 @@ def descriptor(cls) -> ClusterObjectDescriptor: return ClusterObjectDescriptor( Fields=[ ClusterObjectFieldDescriptor(Label="hue", Tag=0, Type=uint), - ClusterObjectFieldDescriptor(Label="direction", Tag=1, Type=ColorControl.Enums.HueDirection), + ClusterObjectFieldDescriptor(Label="direction", Tag=1, Type=ColorControl.Enums.DirectionEnum), ClusterObjectFieldDescriptor(Label="transitionTime", Tag=2, Type=uint), ClusterObjectFieldDescriptor(Label="optionsMask", Tag=3, Type=uint), ClusterObjectFieldDescriptor(Label="optionsOverride", Tag=4, Type=uint), ]) hue: 'uint' = 0 - direction: 'ColorControl.Enums.HueDirection' = 0 + direction: 'ColorControl.Enums.DirectionEnum' = 0 transitionTime: 'uint' = 0 optionsMask: 'uint' = 0 optionsOverride: 'uint' = 0 @@ -35163,13 +35170,13 @@ class MoveHue(ClusterCommand): def descriptor(cls) -> ClusterObjectDescriptor: return ClusterObjectDescriptor( Fields=[ - ClusterObjectFieldDescriptor(Label="moveMode", Tag=0, Type=ColorControl.Enums.HueMoveMode), + ClusterObjectFieldDescriptor(Label="moveMode", Tag=0, Type=ColorControl.Enums.MoveModeEnum), ClusterObjectFieldDescriptor(Label="rate", Tag=1, Type=uint), ClusterObjectFieldDescriptor(Label="optionsMask", Tag=2, Type=uint), ClusterObjectFieldDescriptor(Label="optionsOverride", Tag=3, Type=uint), ]) - moveMode: 'ColorControl.Enums.HueMoveMode' = 0 + moveMode: 'ColorControl.Enums.MoveModeEnum' = 0 rate: 'uint' = 0 optionsMask: 'uint' = 0 optionsOverride: 'uint' = 0 @@ -35185,14 +35192,14 @@ class StepHue(ClusterCommand): def descriptor(cls) -> ClusterObjectDescriptor: return ClusterObjectDescriptor( Fields=[ - ClusterObjectFieldDescriptor(Label="stepMode", Tag=0, Type=ColorControl.Enums.HueStepMode), + ClusterObjectFieldDescriptor(Label="stepMode", Tag=0, Type=ColorControl.Enums.StepModeEnum), ClusterObjectFieldDescriptor(Label="stepSize", Tag=1, Type=uint), ClusterObjectFieldDescriptor(Label="transitionTime", Tag=2, Type=uint), ClusterObjectFieldDescriptor(Label="optionsMask", Tag=3, Type=uint), ClusterObjectFieldDescriptor(Label="optionsOverride", Tag=4, Type=uint), ]) - stepMode: 'ColorControl.Enums.HueStepMode' = 0 + stepMode: 'ColorControl.Enums.StepModeEnum' = 0 stepSize: 'uint' = 0 transitionTime: 'uint' = 0 optionsMask: 'uint' = 0 @@ -35231,13 +35238,13 @@ class MoveSaturation(ClusterCommand): def descriptor(cls) -> ClusterObjectDescriptor: return ClusterObjectDescriptor( Fields=[ - ClusterObjectFieldDescriptor(Label="moveMode", Tag=0, Type=ColorControl.Enums.SaturationMoveMode), + ClusterObjectFieldDescriptor(Label="moveMode", Tag=0, Type=ColorControl.Enums.MoveModeEnum), ClusterObjectFieldDescriptor(Label="rate", Tag=1, Type=uint), ClusterObjectFieldDescriptor(Label="optionsMask", Tag=2, Type=uint), ClusterObjectFieldDescriptor(Label="optionsOverride", Tag=3, Type=uint), ]) - moveMode: 'ColorControl.Enums.SaturationMoveMode' = 0 + moveMode: 'ColorControl.Enums.MoveModeEnum' = 0 rate: 'uint' = 0 optionsMask: 'uint' = 0 optionsOverride: 'uint' = 0 @@ -35253,14 +35260,14 @@ class StepSaturation(ClusterCommand): def descriptor(cls) -> ClusterObjectDescriptor: return ClusterObjectDescriptor( Fields=[ - ClusterObjectFieldDescriptor(Label="stepMode", Tag=0, Type=ColorControl.Enums.SaturationStepMode), + ClusterObjectFieldDescriptor(Label="stepMode", Tag=0, Type=ColorControl.Enums.StepModeEnum), ClusterObjectFieldDescriptor(Label="stepSize", Tag=1, Type=uint), ClusterObjectFieldDescriptor(Label="transitionTime", Tag=2, Type=uint), ClusterObjectFieldDescriptor(Label="optionsMask", Tag=3, Type=uint), ClusterObjectFieldDescriptor(Label="optionsOverride", Tag=4, Type=uint), ]) - stepMode: 'ColorControl.Enums.SaturationStepMode' = 0 + stepMode: 'ColorControl.Enums.StepModeEnum' = 0 stepSize: 'uint' = 0 transitionTime: 'uint' = 0 optionsMask: 'uint' = 0 @@ -35394,14 +35401,14 @@ def descriptor(cls) -> ClusterObjectDescriptor: return ClusterObjectDescriptor( Fields=[ ClusterObjectFieldDescriptor(Label="enhancedHue", Tag=0, Type=uint), - ClusterObjectFieldDescriptor(Label="direction", Tag=1, Type=ColorControl.Enums.HueDirection), + ClusterObjectFieldDescriptor(Label="direction", Tag=1, Type=ColorControl.Enums.DirectionEnum), ClusterObjectFieldDescriptor(Label="transitionTime", Tag=2, Type=uint), ClusterObjectFieldDescriptor(Label="optionsMask", Tag=3, Type=uint), ClusterObjectFieldDescriptor(Label="optionsOverride", Tag=4, Type=uint), ]) enhancedHue: 'uint' = 0 - direction: 'ColorControl.Enums.HueDirection' = 0 + direction: 'ColorControl.Enums.DirectionEnum' = 0 transitionTime: 'uint' = 0 optionsMask: 'uint' = 0 optionsOverride: 'uint' = 0 @@ -35417,13 +35424,13 @@ class EnhancedMoveHue(ClusterCommand): def descriptor(cls) -> ClusterObjectDescriptor: return ClusterObjectDescriptor( Fields=[ - ClusterObjectFieldDescriptor(Label="moveMode", Tag=0, Type=ColorControl.Enums.HueMoveMode), + ClusterObjectFieldDescriptor(Label="moveMode", Tag=0, Type=ColorControl.Enums.MoveModeEnum), ClusterObjectFieldDescriptor(Label="rate", Tag=1, Type=uint), ClusterObjectFieldDescriptor(Label="optionsMask", Tag=2, Type=uint), ClusterObjectFieldDescriptor(Label="optionsOverride", Tag=3, Type=uint), ]) - moveMode: 'ColorControl.Enums.HueMoveMode' = 0 + moveMode: 'ColorControl.Enums.MoveModeEnum' = 0 rate: 'uint' = 0 optionsMask: 'uint' = 0 optionsOverride: 'uint' = 0 @@ -35439,14 +35446,14 @@ class EnhancedStepHue(ClusterCommand): def descriptor(cls) -> ClusterObjectDescriptor: return ClusterObjectDescriptor( Fields=[ - ClusterObjectFieldDescriptor(Label="stepMode", Tag=0, Type=ColorControl.Enums.HueStepMode), + ClusterObjectFieldDescriptor(Label="stepMode", Tag=0, Type=ColorControl.Enums.StepModeEnum), ClusterObjectFieldDescriptor(Label="stepSize", Tag=1, Type=uint), ClusterObjectFieldDescriptor(Label="transitionTime", Tag=2, Type=uint), ClusterObjectFieldDescriptor(Label="optionsMask", Tag=3, Type=uint), ClusterObjectFieldDescriptor(Label="optionsOverride", Tag=4, Type=uint), ]) - stepMode: 'ColorControl.Enums.HueStepMode' = 0 + stepMode: 'ColorControl.Enums.StepModeEnum' = 0 stepSize: 'uint' = 0 transitionTime: 'uint' = 0 optionsMask: 'uint' = 0 @@ -35488,8 +35495,8 @@ def descriptor(cls) -> ClusterObjectDescriptor: return ClusterObjectDescriptor( Fields=[ ClusterObjectFieldDescriptor(Label="updateFlags", Tag=0, Type=uint), - ClusterObjectFieldDescriptor(Label="action", Tag=1, Type=ColorControl.Enums.ColorLoopAction), - ClusterObjectFieldDescriptor(Label="direction", Tag=2, Type=ColorControl.Enums.ColorLoopDirection), + ClusterObjectFieldDescriptor(Label="action", Tag=1, Type=ColorControl.Enums.ColorLoopActionEnum), + ClusterObjectFieldDescriptor(Label="direction", Tag=2, Type=ColorControl.Enums.ColorLoopDirectionEnum), ClusterObjectFieldDescriptor(Label="time", Tag=3, Type=uint), ClusterObjectFieldDescriptor(Label="startHue", Tag=4, Type=uint), ClusterObjectFieldDescriptor(Label="optionsMask", Tag=5, Type=uint), @@ -35497,8 +35504,8 @@ def descriptor(cls) -> ClusterObjectDescriptor: ]) updateFlags: 'uint' = 0 - action: 'ColorControl.Enums.ColorLoopAction' = 0 - direction: 'ColorControl.Enums.ColorLoopDirection' = 0 + action: 'ColorControl.Enums.ColorLoopActionEnum' = 0 + direction: 'ColorControl.Enums.ColorLoopDirectionEnum' = 0 time: 'uint' = 0 startHue: 'uint' = 0 optionsMask: 'uint' = 0 @@ -35533,7 +35540,7 @@ class MoveColorTemperature(ClusterCommand): def descriptor(cls) -> ClusterObjectDescriptor: return ClusterObjectDescriptor( Fields=[ - ClusterObjectFieldDescriptor(Label="moveMode", Tag=0, Type=ColorControl.Enums.HueMoveMode), + ClusterObjectFieldDescriptor(Label="moveMode", Tag=0, Type=ColorControl.Enums.MoveModeEnum), ClusterObjectFieldDescriptor(Label="rate", Tag=1, Type=uint), ClusterObjectFieldDescriptor(Label="colorTemperatureMinimumMireds", Tag=2, Type=uint), ClusterObjectFieldDescriptor(Label="colorTemperatureMaximumMireds", Tag=3, Type=uint), @@ -35541,7 +35548,7 @@ def descriptor(cls) -> ClusterObjectDescriptor: ClusterObjectFieldDescriptor(Label="optionsOverride", Tag=5, Type=uint), ]) - moveMode: 'ColorControl.Enums.HueMoveMode' = 0 + moveMode: 'ColorControl.Enums.MoveModeEnum' = 0 rate: 'uint' = 0 colorTemperatureMinimumMireds: 'uint' = 0 colorTemperatureMaximumMireds: 'uint' = 0 @@ -35559,7 +35566,7 @@ class StepColorTemperature(ClusterCommand): def descriptor(cls) -> ClusterObjectDescriptor: return ClusterObjectDescriptor( Fields=[ - ClusterObjectFieldDescriptor(Label="stepMode", Tag=0, Type=ColorControl.Enums.HueStepMode), + ClusterObjectFieldDescriptor(Label="stepMode", Tag=0, Type=ColorControl.Enums.StepModeEnum), ClusterObjectFieldDescriptor(Label="stepSize", Tag=1, Type=uint), ClusterObjectFieldDescriptor(Label="transitionTime", Tag=2, Type=uint), ClusterObjectFieldDescriptor(Label="colorTemperatureMinimumMireds", Tag=3, Type=uint), @@ -35568,7 +35575,7 @@ def descriptor(cls) -> ClusterObjectDescriptor: ClusterObjectFieldDescriptor(Label="optionsOverride", Tag=6, Type=uint), ]) - stepMode: 'ColorControl.Enums.HueStepMode' = 0 + stepMode: 'ColorControl.Enums.StepModeEnum' = 0 stepSize: 'uint' = 0 transitionTime: 'uint' = 0 colorTemperatureMinimumMireds: 'uint' = 0 @@ -35669,9 +35676,9 @@ def attribute_id(cls) -> int: @ChipUtility.classproperty def attribute_type(cls) -> ClusterObjectFieldDescriptor: - return ClusterObjectFieldDescriptor(Type=typing.Optional[uint]) + return ClusterObjectFieldDescriptor(Type=typing.Optional[ColorControl.Enums.DriftCompensationEnum]) - value: 'typing.Optional[uint]' = None + value: 'typing.Optional[ColorControl.Enums.DriftCompensationEnum]' = None @dataclass class CompensationText(ClusterAttributeDescriptor): @@ -35717,9 +35724,9 @@ def attribute_id(cls) -> int: @ChipUtility.classproperty def attribute_type(cls) -> ClusterObjectFieldDescriptor: - return ClusterObjectFieldDescriptor(Type=uint) + return ClusterObjectFieldDescriptor(Type=ColorControl.Enums.ColorModeEnum) - value: 'uint' = 0 + value: 'ColorControl.Enums.ColorModeEnum' = 0 @dataclass class Options(ClusterAttributeDescriptor): @@ -36245,9 +36252,9 @@ def attribute_id(cls) -> int: @ChipUtility.classproperty def attribute_type(cls) -> ClusterObjectFieldDescriptor: - return ClusterObjectFieldDescriptor(Type=uint) + return ClusterObjectFieldDescriptor(Type=ColorControl.Enums.EnhancedColorModeEnum) - value: 'uint' = 0 + value: 'ColorControl.Enums.EnhancedColorModeEnum' = 0 @dataclass class ColorLoopActive(ClusterAttributeDescriptor): diff --git a/src/darwin/Framework/CHIP/zap-generated/MTRAttributeTLVValueDecoder.mm b/src/darwin/Framework/CHIP/zap-generated/MTRAttributeTLVValueDecoder.mm index f899dba1fa..472a630d93 100644 --- a/src/darwin/Framework/CHIP/zap-generated/MTRAttributeTLVValueDecoder.mm +++ b/src/darwin/Framework/CHIP/zap-generated/MTRAttributeTLVValueDecoder.mm @@ -12882,7 +12882,7 @@ static id _Nullable DecodeAttributeValueForColorControlCluster(AttributeId aAttr return nil; } NSNumber * _Nonnull value; - value = [NSNumber numberWithUnsignedChar:cppValue]; + value = [NSNumber numberWithUnsignedChar:chip::to_underlying(cppValue)]; return value; } case Attributes::CompensationText::Id: { @@ -12920,7 +12920,7 @@ static id _Nullable DecodeAttributeValueForColorControlCluster(AttributeId aAttr return nil; } NSNumber * _Nonnull value; - value = [NSNumber numberWithUnsignedChar:cppValue]; + value = [NSNumber numberWithUnsignedChar:chip::to_underlying(cppValue)]; return value; } case Attributes::Options::Id: { @@ -12931,7 +12931,7 @@ static id _Nullable DecodeAttributeValueForColorControlCluster(AttributeId aAttr return nil; } NSNumber * _Nonnull value; - value = [NSNumber numberWithUnsignedChar:cppValue]; + value = [NSNumber numberWithUnsignedChar:cppValue.Raw()]; return value; } case Attributes::NumberOfPrimaries::Id: { @@ -13323,7 +13323,7 @@ static id _Nullable DecodeAttributeValueForColorControlCluster(AttributeId aAttr return nil; } NSNumber * _Nonnull value; - value = [NSNumber numberWithUnsignedChar:cppValue]; + value = [NSNumber numberWithUnsignedChar:chip::to_underlying(cppValue)]; return value; } case Attributes::ColorLoopActive::Id: { @@ -13389,7 +13389,7 @@ static id _Nullable DecodeAttributeValueForColorControlCluster(AttributeId aAttr return nil; } NSNumber * _Nonnull value; - value = [NSNumber numberWithUnsignedShort:cppValue]; + value = [NSNumber numberWithUnsignedShort:cppValue.Raw()]; return value; } case Attributes::ColorTempPhysicalMinMireds::Id: { diff --git a/src/darwin/Framework/CHIP/zap-generated/MTRBaseClusters.h b/src/darwin/Framework/CHIP/zap-generated/MTRBaseClusters.h index fab6862dd9..efb5fca954 100644 --- a/src/darwin/Framework/CHIP/zap-generated/MTRBaseClusters.h +++ b/src/darwin/Framework/CHIP/zap-generated/MTRBaseClusters.h @@ -20203,65 +20203,62 @@ typedef NS_ENUM(uint8_t, MTRThermostatUserInterfaceConfigurationTemperatureDispl } MTR_AVAILABLE(ios(17.4), macos(14.4), watchos(10.4), tvos(17.4)); typedef NS_ENUM(uint8_t, MTRColorControlColorLoopAction) { - MTRColorControlColorLoopActionDeactivate MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) = 0x00, - MTRColorControlColorLoopActionActivateFromColorLoopStartEnhancedHue MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) = 0x01, - MTRColorControlColorLoopActionActivateFromEnhancedCurrentHue MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) = 0x02, -} MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)); + MTRColorControlColorLoopActionDeactivate MTR_PROVISIONALLY_AVAILABLE = 0x00, + MTRColorControlColorLoopActionActivateFromColorLoopStartEnhancedHue MTR_PROVISIONALLY_AVAILABLE = 0x01, + MTRColorControlColorLoopActionActivateFromEnhancedCurrentHue MTR_PROVISIONALLY_AVAILABLE = 0x02, +} MTR_PROVISIONALLY_AVAILABLE; typedef NS_ENUM(uint8_t, MTRColorControlColorLoopDirection) { - MTRColorControlColorLoopDirectionDecrementHue MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) = 0x00, - MTRColorControlColorLoopDirectionIncrementHue MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) = 0x01, -} MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)); + MTRColorControlColorLoopDirectionDecrement MTR_PROVISIONALLY_AVAILABLE = 0x00, + MTRColorControlColorLoopDirectionIncrement MTR_PROVISIONALLY_AVAILABLE = 0x01, +} MTR_PROVISIONALLY_AVAILABLE; 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, - MTRColorControlColorModeColorTemperature MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) = 0x02, -} MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)); - -typedef NS_ENUM(uint8_t, MTRColorControlHueDirection) { - MTRColorControlHueDirectionShortestDistance MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) = 0x00, - MTRColorControlHueDirectionLongestDistance MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) = 0x01, - MTRColorControlHueDirectionUp MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) = 0x02, - MTRColorControlHueDirectionDown MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) = 0x03, -} MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)); + MTRColorControlColorModeCurrentHueAndCurrentSaturation MTR_PROVISIONALLY_AVAILABLE = 0x00, + MTRColorControlColorModeCurrentXAndCurrentY MTR_PROVISIONALLY_AVAILABLE = 0x01, + MTRColorControlColorModeColorTemperatureMireds MTR_PROVISIONALLY_AVAILABLE = 0x02, +} MTR_PROVISIONALLY_AVAILABLE; -typedef NS_ENUM(uint8_t, MTRColorControlHueMoveMode) { - MTRColorControlHueMoveModeStop MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) = 0x00, - MTRColorControlHueMoveModeUp MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) = 0x01, - MTRColorControlHueMoveModeDown MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) = 0x03, -} MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)); +typedef NS_ENUM(uint8_t, MTRColorControlDirection) { + MTRColorControlDirectionShortest MTR_PROVISIONALLY_AVAILABLE = 0x00, + MTRColorControlDirectionLongest MTR_PROVISIONALLY_AVAILABLE = 0x01, + MTRColorControlDirectionUp MTR_PROVISIONALLY_AVAILABLE = 0x02, + MTRColorControlDirectionDown MTR_PROVISIONALLY_AVAILABLE = 0x03, +} MTR_PROVISIONALLY_AVAILABLE; -typedef NS_ENUM(uint8_t, MTRColorControlHueStepMode) { - MTRColorControlHueStepModeUp MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) = 0x01, - MTRColorControlHueStepModeDown MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) = 0x03, -} MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)); +typedef NS_ENUM(uint8_t, MTRColorControlDriftCompensation) { + MTRColorControlDriftCompensationNone MTR_PROVISIONALLY_AVAILABLE = 0x00, + MTRColorControlDriftCompensationOtherOrUnknown MTR_PROVISIONALLY_AVAILABLE = 0x01, + MTRColorControlDriftCompensationTemperatureMonitoring MTR_PROVISIONALLY_AVAILABLE = 0x02, + MTRColorControlDriftCompensationOpticalLuminanceMonitoringAndFeedback MTR_PROVISIONALLY_AVAILABLE = 0x03, + MTRColorControlDriftCompensationOpticalColorMonitoringAndFeedback MTR_PROVISIONALLY_AVAILABLE = 0x04, +} MTR_PROVISIONALLY_AVAILABLE; -typedef NS_ENUM(uint8_t, MTRColorControlSaturationMoveMode) { - MTRColorControlSaturationMoveModeStop MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) = 0x00, - MTRColorControlSaturationMoveModeUp MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) = 0x01, - MTRColorControlSaturationMoveModeDown MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) = 0x03, -} MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)); +typedef NS_ENUM(uint8_t, MTRColorControlEnhancedColorMode) { + MTRColorControlEnhancedColorModeCurrentHueAndCurrentSaturation MTR_PROVISIONALLY_AVAILABLE = 0x00, + MTRColorControlEnhancedColorModeCurrentXAndCurrentY MTR_PROVISIONALLY_AVAILABLE = 0x01, + MTRColorControlEnhancedColorModeColorTemperatureMireds MTR_PROVISIONALLY_AVAILABLE = 0x02, + MTRColorControlEnhancedColorModeEnhancedCurrentHueAndCurrentSaturation MTR_PROVISIONALLY_AVAILABLE = 0x03, +} MTR_PROVISIONALLY_AVAILABLE; -typedef NS_ENUM(uint8_t, MTRColorControlSaturationStepMode) { - MTRColorControlSaturationStepModeUp MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) = 0x01, - MTRColorControlSaturationStepModeDown MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) = 0x03, -} MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)); +typedef NS_ENUM(uint8_t, MTRColorControlMoveMode) { + MTRColorControlMoveModeStop MTR_PROVISIONALLY_AVAILABLE = 0x00, + MTRColorControlMoveModeUp MTR_PROVISIONALLY_AVAILABLE = 0x01, + MTRColorControlMoveModeDown MTR_PROVISIONALLY_AVAILABLE = 0x03, +} MTR_PROVISIONALLY_AVAILABLE; -typedef NS_OPTIONS(uint16_t, MTRColorControlColorCapabilities) { - MTRColorControlColorCapabilitiesHueSaturationSupported MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) = 0x1, - MTRColorControlColorCapabilitiesEnhancedHueSupported MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) = 0x2, - MTRColorControlColorCapabilitiesColorLoopSupported MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) = 0x4, - MTRColorControlColorCapabilitiesXYAttributesSupported MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) = 0x8, - MTRColorControlColorCapabilitiesColorTemperatureSupported MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) = 0x10, -} MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)); +typedef NS_ENUM(uint8_t, MTRColorControlStepMode) { + MTRColorControlStepModeUp MTR_PROVISIONALLY_AVAILABLE = 0x01, + MTRColorControlStepModeDown MTR_PROVISIONALLY_AVAILABLE = 0x03, +} MTR_PROVISIONALLY_AVAILABLE; -typedef NS_OPTIONS(uint8_t, MTRColorControlColorLoopUpdateFlags) { - MTRColorControlColorLoopUpdateFlagsUpdateAction MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) = 0x1, - MTRColorControlColorLoopUpdateFlagsUpdateDirection MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) = 0x2, - MTRColorControlColorLoopUpdateFlagsUpdateTime MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) = 0x4, - MTRColorControlColorLoopUpdateFlagsUpdateStartHue MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) = 0x8, -} MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)); +typedef NS_OPTIONS(uint16_t, MTRColorControlColorCapabilitiesBitmap) { + MTRColorControlColorCapabilitiesBitmapHueSaturation MTR_PROVISIONALLY_AVAILABLE = 0x1, + MTRColorControlColorCapabilitiesBitmapEnhancedHue MTR_PROVISIONALLY_AVAILABLE = 0x2, + MTRColorControlColorCapabilitiesBitmapColorLoop MTR_PROVISIONALLY_AVAILABLE = 0x4, + MTRColorControlColorCapabilitiesBitmapXY MTR_PROVISIONALLY_AVAILABLE = 0x8, + MTRColorControlColorCapabilitiesBitmapColorTemperature MTR_PROVISIONALLY_AVAILABLE = 0x10, +} MTR_PROVISIONALLY_AVAILABLE; typedef NS_OPTIONS(uint32_t, MTRColorControlFeature) { MTRColorControlFeatureHueAndSaturation MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) = 0x1, @@ -20271,6 +20268,17 @@ typedef NS_OPTIONS(uint32_t, MTRColorControlFeature) { MTRColorControlFeatureColorTemperature MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) = 0x10, } MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)); +typedef NS_OPTIONS(uint8_t, MTRColorControlOptionsBitmap) { + MTRColorControlOptionsBitmapExecuteIfOff MTR_PROVISIONALLY_AVAILABLE = 0x1, +} MTR_PROVISIONALLY_AVAILABLE; + +typedef NS_OPTIONS(uint8_t, MTRColorControlUpdateFlagsBitmap) { + MTRColorControlUpdateFlagsBitmapUpdateAction MTR_PROVISIONALLY_AVAILABLE = 0x1, + MTRColorControlUpdateFlagsBitmapUpdateDirection MTR_PROVISIONALLY_AVAILABLE = 0x2, + MTRColorControlUpdateFlagsBitmapUpdateTime MTR_PROVISIONALLY_AVAILABLE = 0x4, + MTRColorControlUpdateFlagsBitmapUpdateStartHue MTR_PROVISIONALLY_AVAILABLE = 0x8, +} MTR_PROVISIONALLY_AVAILABLE; + typedef NS_OPTIONS(uint8_t, MTRBallastConfigurationBallastStatusBitmap) { MTRBallastConfigurationBallastStatusBitmapBallastNonOperational MTR_PROVISIONALLY_AVAILABLE = 0x1, MTRBallastConfigurationBallastStatusBitmapLampFailure MTR_PROVISIONALLY_AVAILABLE = 0x2, diff --git a/src/darwin/Framework/CHIP/zap-generated/MTRBaseClusters.mm b/src/darwin/Framework/CHIP/zap-generated/MTRBaseClusters.mm index 756425bba1..2c81423cfb 100644 --- a/src/darwin/Framework/CHIP/zap-generated/MTRBaseClusters.mm +++ b/src/darwin/Framework/CHIP/zap-generated/MTRBaseClusters.mm @@ -76739,7 +76739,7 @@ - (void)writeAttributeOptionsWithValue:(NSNumber * _Nonnull)value params:(MTRWri ListFreer listFreer; using TypeInfo = ColorControl::Attributes::Options::TypeInfo; TypeInfo::Type cppValue; - cppValue = value.unsignedCharValue; + cppValue = static_cast>(value.unsignedCharValue); chip::Controller::ClusterBase cppCluster(exchangeManager, session, self.endpointID.unsignedShortValue); return cppCluster.WriteAttribute(cppValue, bridge, successCb, failureCb, timedWriteTimeout); }); diff --git a/src/darwin/Framework/CHIP/zap-generated/MTRCommandPayloadsObjc.mm b/src/darwin/Framework/CHIP/zap-generated/MTRCommandPayloadsObjc.mm index 976d5a0ef2..1334d8beba 100644 --- a/src/darwin/Framework/CHIP/zap-generated/MTRCommandPayloadsObjc.mm +++ b/src/darwin/Framework/CHIP/zap-generated/MTRCommandPayloadsObjc.mm @@ -23153,10 +23153,10 @@ - (CHIP_ERROR)_encodeToTLVReader:(chip::System::PacketBufferTLVReader &)reader encodableStruct.transitionTime = self.transitionTime.unsignedShortValue; } { - encodableStruct.optionsMask = self.optionsMask.unsignedCharValue; + encodableStruct.optionsMask = static_cast>(self.optionsMask.unsignedCharValue); } { - encodableStruct.optionsOverride = self.optionsOverride.unsignedCharValue; + encodableStruct.optionsOverride = static_cast>(self.optionsOverride.unsignedCharValue); } auto buffer = chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSizeWithoutReserve, 0); @@ -23250,10 +23250,10 @@ - (CHIP_ERROR)_encodeToTLVReader:(chip::System::PacketBufferTLVReader &)reader encodableStruct.rate = self.rate.unsignedCharValue; } { - encodableStruct.optionsMask = self.optionsMask.unsignedCharValue; + encodableStruct.optionsMask = static_cast>(self.optionsMask.unsignedCharValue); } { - encodableStruct.optionsOverride = self.optionsOverride.unsignedCharValue; + encodableStruct.optionsOverride = static_cast>(self.optionsOverride.unsignedCharValue); } auto buffer = chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSizeWithoutReserve, 0); @@ -23353,10 +23353,10 @@ - (CHIP_ERROR)_encodeToTLVReader:(chip::System::PacketBufferTLVReader &)reader encodableStruct.transitionTime = self.transitionTime.unsignedCharValue; } { - encodableStruct.optionsMask = self.optionsMask.unsignedCharValue; + encodableStruct.optionsMask = static_cast>(self.optionsMask.unsignedCharValue); } { - encodableStruct.optionsOverride = self.optionsOverride.unsignedCharValue; + encodableStruct.optionsOverride = static_cast>(self.optionsOverride.unsignedCharValue); } auto buffer = chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSizeWithoutReserve, 0); @@ -23450,10 +23450,10 @@ - (CHIP_ERROR)_encodeToTLVReader:(chip::System::PacketBufferTLVReader &)reader encodableStruct.transitionTime = self.transitionTime.unsignedShortValue; } { - encodableStruct.optionsMask = self.optionsMask.unsignedCharValue; + encodableStruct.optionsMask = static_cast>(self.optionsMask.unsignedCharValue); } { - encodableStruct.optionsOverride = self.optionsOverride.unsignedCharValue; + encodableStruct.optionsOverride = static_cast>(self.optionsOverride.unsignedCharValue); } auto buffer = chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSizeWithoutReserve, 0); @@ -23547,10 +23547,10 @@ - (CHIP_ERROR)_encodeToTLVReader:(chip::System::PacketBufferTLVReader &)reader encodableStruct.rate = self.rate.unsignedCharValue; } { - encodableStruct.optionsMask = self.optionsMask.unsignedCharValue; + encodableStruct.optionsMask = static_cast>(self.optionsMask.unsignedCharValue); } { - encodableStruct.optionsOverride = self.optionsOverride.unsignedCharValue; + encodableStruct.optionsOverride = static_cast>(self.optionsOverride.unsignedCharValue); } auto buffer = chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSizeWithoutReserve, 0); @@ -23650,10 +23650,10 @@ - (CHIP_ERROR)_encodeToTLVReader:(chip::System::PacketBufferTLVReader &)reader encodableStruct.transitionTime = self.transitionTime.unsignedCharValue; } { - encodableStruct.optionsMask = self.optionsMask.unsignedCharValue; + encodableStruct.optionsMask = static_cast>(self.optionsMask.unsignedCharValue); } { - encodableStruct.optionsOverride = self.optionsOverride.unsignedCharValue; + encodableStruct.optionsOverride = static_cast>(self.optionsOverride.unsignedCharValue); } auto buffer = chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSizeWithoutReserve, 0); @@ -23753,10 +23753,10 @@ - (CHIP_ERROR)_encodeToTLVReader:(chip::System::PacketBufferTLVReader &)reader encodableStruct.transitionTime = self.transitionTime.unsignedShortValue; } { - encodableStruct.optionsMask = self.optionsMask.unsignedCharValue; + encodableStruct.optionsMask = static_cast>(self.optionsMask.unsignedCharValue); } { - encodableStruct.optionsOverride = self.optionsOverride.unsignedCharValue; + encodableStruct.optionsOverride = static_cast>(self.optionsOverride.unsignedCharValue); } auto buffer = chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSizeWithoutReserve, 0); @@ -23856,10 +23856,10 @@ - (CHIP_ERROR)_encodeToTLVReader:(chip::System::PacketBufferTLVReader &)reader encodableStruct.transitionTime = self.transitionTime.unsignedShortValue; } { - encodableStruct.optionsMask = self.optionsMask.unsignedCharValue; + encodableStruct.optionsMask = static_cast>(self.optionsMask.unsignedCharValue); } { - encodableStruct.optionsOverride = self.optionsOverride.unsignedCharValue; + encodableStruct.optionsOverride = static_cast>(self.optionsOverride.unsignedCharValue); } auto buffer = chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSizeWithoutReserve, 0); @@ -23953,10 +23953,10 @@ - (CHIP_ERROR)_encodeToTLVReader:(chip::System::PacketBufferTLVReader &)reader encodableStruct.rateY = self.rateY.shortValue; } { - encodableStruct.optionsMask = self.optionsMask.unsignedCharValue; + encodableStruct.optionsMask = static_cast>(self.optionsMask.unsignedCharValue); } { - encodableStruct.optionsOverride = self.optionsOverride.unsignedCharValue; + encodableStruct.optionsOverride = static_cast>(self.optionsOverride.unsignedCharValue); } auto buffer = chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSizeWithoutReserve, 0); @@ -24056,10 +24056,10 @@ - (CHIP_ERROR)_encodeToTLVReader:(chip::System::PacketBufferTLVReader &)reader encodableStruct.transitionTime = self.transitionTime.unsignedShortValue; } { - encodableStruct.optionsMask = self.optionsMask.unsignedCharValue; + encodableStruct.optionsMask = static_cast>(self.optionsMask.unsignedCharValue); } { - encodableStruct.optionsOverride = self.optionsOverride.unsignedCharValue; + encodableStruct.optionsOverride = static_cast>(self.optionsOverride.unsignedCharValue); } auto buffer = chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSizeWithoutReserve, 0); @@ -24153,10 +24153,10 @@ - (CHIP_ERROR)_encodeToTLVReader:(chip::System::PacketBufferTLVReader &)reader encodableStruct.transitionTime = self.transitionTime.unsignedShortValue; } { - encodableStruct.optionsMask = self.optionsMask.unsignedCharValue; + encodableStruct.optionsMask = static_cast>(self.optionsMask.unsignedCharValue); } { - encodableStruct.optionsOverride = self.optionsOverride.unsignedCharValue; + encodableStruct.optionsOverride = static_cast>(self.optionsOverride.unsignedCharValue); } auto buffer = chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSizeWithoutReserve, 0); @@ -24268,10 +24268,10 @@ - (CHIP_ERROR)_encodeToTLVReader:(chip::System::PacketBufferTLVReader &)reader encodableStruct.transitionTime = self.transitionTime.unsignedShortValue; } { - encodableStruct.optionsMask = self.optionsMask.unsignedCharValue; + encodableStruct.optionsMask = static_cast>(self.optionsMask.unsignedCharValue); } { - encodableStruct.optionsOverride = self.optionsOverride.unsignedCharValue; + encodableStruct.optionsOverride = static_cast>(self.optionsOverride.unsignedCharValue); } auto buffer = chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSizeWithoutReserve, 0); @@ -24365,10 +24365,10 @@ - (CHIP_ERROR)_encodeToTLVReader:(chip::System::PacketBufferTLVReader &)reader encodableStruct.rate = self.rate.unsignedShortValue; } { - encodableStruct.optionsMask = self.optionsMask.unsignedCharValue; + encodableStruct.optionsMask = static_cast>(self.optionsMask.unsignedCharValue); } { - encodableStruct.optionsOverride = self.optionsOverride.unsignedCharValue; + encodableStruct.optionsOverride = static_cast>(self.optionsOverride.unsignedCharValue); } auto buffer = chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSizeWithoutReserve, 0); @@ -24468,10 +24468,10 @@ - (CHIP_ERROR)_encodeToTLVReader:(chip::System::PacketBufferTLVReader &)reader encodableStruct.transitionTime = self.transitionTime.unsignedShortValue; } { - encodableStruct.optionsMask = self.optionsMask.unsignedCharValue; + encodableStruct.optionsMask = static_cast>(self.optionsMask.unsignedCharValue); } { - encodableStruct.optionsOverride = self.optionsOverride.unsignedCharValue; + encodableStruct.optionsOverride = static_cast>(self.optionsOverride.unsignedCharValue); } auto buffer = chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSizeWithoutReserve, 0); @@ -24571,10 +24571,10 @@ - (CHIP_ERROR)_encodeToTLVReader:(chip::System::PacketBufferTLVReader &)reader encodableStruct.transitionTime = self.transitionTime.unsignedShortValue; } { - encodableStruct.optionsMask = self.optionsMask.unsignedCharValue; + encodableStruct.optionsMask = static_cast>(self.optionsMask.unsignedCharValue); } { - encodableStruct.optionsOverride = self.optionsOverride.unsignedCharValue; + encodableStruct.optionsOverride = static_cast>(self.optionsOverride.unsignedCharValue); } auto buffer = chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSizeWithoutReserve, 0); @@ -24686,10 +24686,10 @@ - (CHIP_ERROR)_encodeToTLVReader:(chip::System::PacketBufferTLVReader &)reader encodableStruct.startHue = self.startHue.unsignedShortValue; } { - encodableStruct.optionsMask = self.optionsMask.unsignedCharValue; + encodableStruct.optionsMask = static_cast>(self.optionsMask.unsignedCharValue); } { - encodableStruct.optionsOverride = self.optionsOverride.unsignedCharValue; + encodableStruct.optionsOverride = static_cast>(self.optionsOverride.unsignedCharValue); } auto buffer = chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSizeWithoutReserve, 0); @@ -24771,10 +24771,10 @@ - (CHIP_ERROR)_encodeToTLVReader:(chip::System::PacketBufferTLVReader &)reader chip::app::Clusters::ColorControl::Commands::StopMoveStep::Type encodableStruct; ListFreer listFreer; { - encodableStruct.optionsMask = self.optionsMask.unsignedCharValue; + encodableStruct.optionsMask = static_cast>(self.optionsMask.unsignedCharValue); } { - encodableStruct.optionsOverride = self.optionsOverride.unsignedCharValue; + encodableStruct.optionsOverride = static_cast>(self.optionsOverride.unsignedCharValue); } auto buffer = chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSizeWithoutReserve, 0); @@ -24880,10 +24880,10 @@ - (CHIP_ERROR)_encodeToTLVReader:(chip::System::PacketBufferTLVReader &)reader encodableStruct.colorTemperatureMaximumMireds = self.colorTemperatureMaximumMireds.unsignedShortValue; } { - encodableStruct.optionsMask = self.optionsMask.unsignedCharValue; + encodableStruct.optionsMask = static_cast>(self.optionsMask.unsignedCharValue); } { - encodableStruct.optionsOverride = self.optionsOverride.unsignedCharValue; + encodableStruct.optionsOverride = static_cast>(self.optionsOverride.unsignedCharValue); } auto buffer = chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSizeWithoutReserve, 0); @@ -24995,10 +24995,10 @@ - (CHIP_ERROR)_encodeToTLVReader:(chip::System::PacketBufferTLVReader &)reader encodableStruct.colorTemperatureMaximumMireds = self.colorTemperatureMaximumMireds.unsignedShortValue; } { - encodableStruct.optionsMask = self.optionsMask.unsignedCharValue; + encodableStruct.optionsMask = static_cast>(self.optionsMask.unsignedCharValue); } { - encodableStruct.optionsOverride = self.optionsOverride.unsignedCharValue; + encodableStruct.optionsOverride = static_cast>(self.optionsOverride.unsignedCharValue); } auto buffer = chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSizeWithoutReserve, 0); diff --git a/src/python_testing/TC_CC_2_2.py b/src/python_testing/TC_CC_2_2.py index 4f6a21b1ba..86080efd35 100644 --- a/src/python_testing/TC_CC_2_2.py +++ b/src/python_testing/TC_CC_2_2.py @@ -137,14 +137,14 @@ async def test_TC_CC_2_2(self): self.step(6) if supports_hs: - cmd = cc.Commands.MoveHue(moveMode=cc.Enums.HueMoveMode.kDown, rate=225) + cmd = cc.Commands.MoveHue(moveMode=cc.Enums.MoveModeEnum.kDown, rate=225) await self.send_single_cmd(cmd) else: self.mark_current_step_skipped() self.step(7) if supports_hs: - cmd = cc.Commands.MoveSaturation(moveMode=cc.Enums.SaturationMoveMode.kDown, rate=225) + cmd = cc.Commands.MoveSaturation(moveMode=cc.Enums.MoveModeEnum.kDown, rate=225) await self.send_single_cmd(cmd) else: self.mark_current_step_skipped() @@ -173,7 +173,7 @@ def check_report_counts(attr: ClusterObjects.ClusterAttributeDescriptor): self.skip_step(15) else: self.step(10) - cmd = cc.Commands.MoveToHue(hue=254, transitionTime=100, direction=cc.Enums.HueDirection.kShortestDistance) + cmd = cc.Commands.MoveToHue(hue=254, transitionTime=100, direction=cc.Enums.DirectionEnum.kShortest) await self.send_single_cmd(cmd) self.step(11) @@ -228,7 +228,7 @@ def check_report_counts(attr: ClusterObjects.ClusterAttributeDescriptor): else: self.step(23) cmd = cc.Commands.EnhancedMoveToHue(enhancedHue=0, transitionTime=100, - direction=cc.Enums.HueDirection.kShortestDistance) + direction=cc.Enums.DirectionEnum.kShortest) await self.send_single_cmd(cmd) self.step(24) 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 c5768be8b7..a8fc013fa0 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 @@ -27161,9 +27161,9 @@ Protocols::InteractionModel::Status Set(chip::EndpointId endpoint, uint16_t valu namespace DriftCompensation { -Protocols::InteractionModel::Status Get(chip::EndpointId endpoint, uint8_t * value) +Protocols::InteractionModel::Status Get(chip::EndpointId endpoint, chip::app::Clusters::ColorControl::DriftCompensationEnum * value) { - using Traits = NumericAttributeTraits; + using Traits = NumericAttributeTraits; Traits::StorageType temp; uint8_t * readable = Traits::ToAttributeStoreRepresentation(temp); Protocols::InteractionModel::Status status = @@ -27177,9 +27177,10 @@ Protocols::InteractionModel::Status Get(chip::EndpointId endpoint, uint8_t * val return status; } -Protocols::InteractionModel::Status Set(chip::EndpointId endpoint, uint8_t value, MarkAttributeDirty markDirty) +Protocols::InteractionModel::Status Set(chip::EndpointId endpoint, chip::app::Clusters::ColorControl::DriftCompensationEnum value, + MarkAttributeDirty markDirty) { - using Traits = NumericAttributeTraits; + using Traits = NumericAttributeTraits; if (!Traits::CanRepresentValue(/* isNullable = */ false, value)) { return Protocols::InteractionModel::Status::ConstraintError; @@ -27190,9 +27191,9 @@ Protocols::InteractionModel::Status Set(chip::EndpointId endpoint, uint8_t value return emberAfWriteAttribute(endpoint, Clusters::ColorControl::Id, Id, writable, ZCL_ENUM8_ATTRIBUTE_TYPE, markDirty); } -Protocols::InteractionModel::Status Set(chip::EndpointId endpoint, uint8_t value) +Protocols::InteractionModel::Status Set(chip::EndpointId endpoint, chip::app::Clusters::ColorControl::DriftCompensationEnum value) { - using Traits = NumericAttributeTraits; + using Traits = NumericAttributeTraits; if (!Traits::CanRepresentValue(/* isNullable = */ false, value)) { return Protocols::InteractionModel::Status::ConstraintError; @@ -27299,9 +27300,9 @@ Protocols::InteractionModel::Status Set(chip::EndpointId endpoint, uint16_t valu namespace ColorMode { -Protocols::InteractionModel::Status Get(chip::EndpointId endpoint, uint8_t * value) +Protocols::InteractionModel::Status Get(chip::EndpointId endpoint, chip::app::Clusters::ColorControl::ColorModeEnum * value) { - using Traits = NumericAttributeTraits; + using Traits = NumericAttributeTraits; Traits::StorageType temp; uint8_t * readable = Traits::ToAttributeStoreRepresentation(temp); Protocols::InteractionModel::Status status = @@ -27315,9 +27316,10 @@ Protocols::InteractionModel::Status Get(chip::EndpointId endpoint, uint8_t * val return status; } -Protocols::InteractionModel::Status Set(chip::EndpointId endpoint, uint8_t value, MarkAttributeDirty markDirty) +Protocols::InteractionModel::Status Set(chip::EndpointId endpoint, chip::app::Clusters::ColorControl::ColorModeEnum value, + MarkAttributeDirty markDirty) { - using Traits = NumericAttributeTraits; + using Traits = NumericAttributeTraits; if (!Traits::CanRepresentValue(/* isNullable = */ false, value)) { return Protocols::InteractionModel::Status::ConstraintError; @@ -27328,9 +27330,9 @@ Protocols::InteractionModel::Status Set(chip::EndpointId endpoint, uint8_t value return emberAfWriteAttribute(endpoint, Clusters::ColorControl::Id, Id, writable, ZCL_ENUM8_ATTRIBUTE_TYPE, markDirty); } -Protocols::InteractionModel::Status Set(chip::EndpointId endpoint, uint8_t value) +Protocols::InteractionModel::Status Set(chip::EndpointId endpoint, chip::app::Clusters::ColorControl::ColorModeEnum value) { - using Traits = NumericAttributeTraits; + using Traits = NumericAttributeTraits; if (!Traits::CanRepresentValue(/* isNullable = */ false, value)) { return Protocols::InteractionModel::Status::ConstraintError; @@ -27345,9 +27347,10 @@ Protocols::InteractionModel::Status Set(chip::EndpointId endpoint, uint8_t value namespace Options { -Protocols::InteractionModel::Status Get(chip::EndpointId endpoint, uint8_t * value) +Protocols::InteractionModel::Status Get(chip::EndpointId endpoint, + chip::BitMask * value) { - using Traits = NumericAttributeTraits; + using Traits = NumericAttributeTraits>; Traits::StorageType temp; uint8_t * readable = Traits::ToAttributeStoreRepresentation(temp); Protocols::InteractionModel::Status status = @@ -27361,9 +27364,10 @@ Protocols::InteractionModel::Status Get(chip::EndpointId endpoint, uint8_t * val return status; } -Protocols::InteractionModel::Status Set(chip::EndpointId endpoint, uint8_t value, MarkAttributeDirty markDirty) +Protocols::InteractionModel::Status +Set(chip::EndpointId endpoint, chip::BitMask value, MarkAttributeDirty markDirty) { - using Traits = NumericAttributeTraits; + using Traits = NumericAttributeTraits>; if (!Traits::CanRepresentValue(/* isNullable = */ false, value)) { return Protocols::InteractionModel::Status::ConstraintError; @@ -27374,9 +27378,10 @@ Protocols::InteractionModel::Status Set(chip::EndpointId endpoint, uint8_t value return emberAfWriteAttribute(endpoint, Clusters::ColorControl::Id, Id, writable, ZCL_BITMAP8_ATTRIBUTE_TYPE, markDirty); } -Protocols::InteractionModel::Status Set(chip::EndpointId endpoint, uint8_t value) +Protocols::InteractionModel::Status Set(chip::EndpointId endpoint, + chip::BitMask value) { - using Traits = NumericAttributeTraits; + using Traits = NumericAttributeTraits>; if (!Traits::CanRepresentValue(/* isNullable = */ false, value)) { return Protocols::InteractionModel::Status::ConstraintError; @@ -29237,9 +29242,9 @@ Protocols::InteractionModel::Status Set(chip::EndpointId endpoint, uint16_t valu namespace EnhancedColorMode { -Protocols::InteractionModel::Status Get(chip::EndpointId endpoint, uint8_t * value) +Protocols::InteractionModel::Status Get(chip::EndpointId endpoint, chip::app::Clusters::ColorControl::EnhancedColorModeEnum * value) { - using Traits = NumericAttributeTraits; + using Traits = NumericAttributeTraits; Traits::StorageType temp; uint8_t * readable = Traits::ToAttributeStoreRepresentation(temp); Protocols::InteractionModel::Status status = @@ -29253,9 +29258,10 @@ Protocols::InteractionModel::Status Get(chip::EndpointId endpoint, uint8_t * val return status; } -Protocols::InteractionModel::Status Set(chip::EndpointId endpoint, uint8_t value, MarkAttributeDirty markDirty) +Protocols::InteractionModel::Status Set(chip::EndpointId endpoint, chip::app::Clusters::ColorControl::EnhancedColorModeEnum value, + MarkAttributeDirty markDirty) { - using Traits = NumericAttributeTraits; + using Traits = NumericAttributeTraits; if (!Traits::CanRepresentValue(/* isNullable = */ false, value)) { return Protocols::InteractionModel::Status::ConstraintError; @@ -29266,9 +29272,9 @@ Protocols::InteractionModel::Status Set(chip::EndpointId endpoint, uint8_t value return emberAfWriteAttribute(endpoint, Clusters::ColorControl::Id, Id, writable, ZCL_ENUM8_ATTRIBUTE_TYPE, markDirty); } -Protocols::InteractionModel::Status Set(chip::EndpointId endpoint, uint8_t value) +Protocols::InteractionModel::Status Set(chip::EndpointId endpoint, chip::app::Clusters::ColorControl::EnhancedColorModeEnum value) { - using Traits = NumericAttributeTraits; + using Traits = NumericAttributeTraits; if (!Traits::CanRepresentValue(/* isNullable = */ false, value)) { return Protocols::InteractionModel::Status::ConstraintError; @@ -29513,9 +29519,10 @@ Protocols::InteractionModel::Status Set(chip::EndpointId endpoint, uint16_t valu namespace ColorCapabilities { -Protocols::InteractionModel::Status Get(chip::EndpointId endpoint, uint16_t * value) +Protocols::InteractionModel::Status Get(chip::EndpointId endpoint, + chip::BitMask * value) { - using Traits = NumericAttributeTraits; + using Traits = NumericAttributeTraits>; Traits::StorageType temp; uint8_t * readable = Traits::ToAttributeStoreRepresentation(temp); Protocols::InteractionModel::Status status = @@ -29529,9 +29536,11 @@ Protocols::InteractionModel::Status Get(chip::EndpointId endpoint, uint16_t * va return status; } -Protocols::InteractionModel::Status Set(chip::EndpointId endpoint, uint16_t value, MarkAttributeDirty markDirty) +Protocols::InteractionModel::Status Set(chip::EndpointId endpoint, + chip::BitMask value, + MarkAttributeDirty markDirty) { - using Traits = NumericAttributeTraits; + using Traits = NumericAttributeTraits>; if (!Traits::CanRepresentValue(/* isNullable = */ false, value)) { return Protocols::InteractionModel::Status::ConstraintError; @@ -29542,9 +29551,10 @@ Protocols::InteractionModel::Status Set(chip::EndpointId endpoint, uint16_t valu return emberAfWriteAttribute(endpoint, Clusters::ColorControl::Id, Id, writable, ZCL_BITMAP16_ATTRIBUTE_TYPE, markDirty); } -Protocols::InteractionModel::Status Set(chip::EndpointId endpoint, uint16_t value) +Protocols::InteractionModel::Status Set(chip::EndpointId endpoint, + chip::BitMask value) { - using Traits = NumericAttributeTraits; + using Traits = NumericAttributeTraits>; if (!Traits::CanRepresentValue(/* isNullable = */ false, value)) { return Protocols::InteractionModel::Status::ConstraintError; 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 41422b72ca..cab9691ebb 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 @@ -4267,9 +4267,11 @@ Protocols::InteractionModel::Status Set(chip::EndpointId endpoint, uint16_t valu } // namespace CurrentY namespace DriftCompensation { -Protocols::InteractionModel::Status Get(chip::EndpointId endpoint, uint8_t * value); // enum8 -Protocols::InteractionModel::Status Set(chip::EndpointId endpoint, uint8_t value); -Protocols::InteractionModel::Status Set(chip::EndpointId endpoint, uint8_t value, MarkAttributeDirty markDirty); +Protocols::InteractionModel::Status Get(chip::EndpointId endpoint, + chip::app::Clusters::ColorControl::DriftCompensationEnum * value); // DriftCompensationEnum +Protocols::InteractionModel::Status Set(chip::EndpointId endpoint, chip::app::Clusters::ColorControl::DriftCompensationEnum value); +Protocols::InteractionModel::Status Set(chip::EndpointId endpoint, chip::app::Clusters::ColorControl::DriftCompensationEnum value, + MarkAttributeDirty markDirty); } // namespace DriftCompensation namespace CompensationText { @@ -4285,15 +4287,20 @@ Protocols::InteractionModel::Status Set(chip::EndpointId endpoint, uint16_t valu } // namespace ColorTemperatureMireds namespace ColorMode { -Protocols::InteractionModel::Status Get(chip::EndpointId endpoint, uint8_t * value); // enum8 -Protocols::InteractionModel::Status Set(chip::EndpointId endpoint, uint8_t value); -Protocols::InteractionModel::Status Set(chip::EndpointId endpoint, uint8_t value, MarkAttributeDirty markDirty); +Protocols::InteractionModel::Status Get(chip::EndpointId endpoint, + chip::app::Clusters::ColorControl::ColorModeEnum * value); // ColorModeEnum +Protocols::InteractionModel::Status Set(chip::EndpointId endpoint, chip::app::Clusters::ColorControl::ColorModeEnum value); +Protocols::InteractionModel::Status Set(chip::EndpointId endpoint, chip::app::Clusters::ColorControl::ColorModeEnum value, + MarkAttributeDirty markDirty); } // namespace ColorMode namespace Options { -Protocols::InteractionModel::Status Get(chip::EndpointId endpoint, uint8_t * value); // bitmap8 -Protocols::InteractionModel::Status Set(chip::EndpointId endpoint, uint8_t value); -Protocols::InteractionModel::Status Set(chip::EndpointId endpoint, uint8_t value, MarkAttributeDirty markDirty); +Protocols::InteractionModel::Status Get(chip::EndpointId endpoint, + chip::BitMask * value); // OptionsBitmap +Protocols::InteractionModel::Status Set(chip::EndpointId endpoint, + chip::BitMask value); +Protocols::InteractionModel::Status +Set(chip::EndpointId endpoint, chip::BitMask value, MarkAttributeDirty markDirty); } // namespace Options namespace NumberOfPrimaries { @@ -4533,9 +4540,11 @@ Protocols::InteractionModel::Status Set(chip::EndpointId endpoint, uint16_t valu } // namespace EnhancedCurrentHue namespace EnhancedColorMode { -Protocols::InteractionModel::Status Get(chip::EndpointId endpoint, uint8_t * value); // enum8 -Protocols::InteractionModel::Status Set(chip::EndpointId endpoint, uint8_t value); -Protocols::InteractionModel::Status Set(chip::EndpointId endpoint, uint8_t value, MarkAttributeDirty markDirty); +Protocols::InteractionModel::Status Get(chip::EndpointId endpoint, + chip::app::Clusters::ColorControl::EnhancedColorModeEnum * value); // EnhancedColorModeEnum +Protocols::InteractionModel::Status Set(chip::EndpointId endpoint, chip::app::Clusters::ColorControl::EnhancedColorModeEnum value); +Protocols::InteractionModel::Status Set(chip::EndpointId endpoint, chip::app::Clusters::ColorControl::EnhancedColorModeEnum value, + MarkAttributeDirty markDirty); } // namespace EnhancedColorMode namespace ColorLoopActive { @@ -4569,9 +4578,14 @@ Protocols::InteractionModel::Status Set(chip::EndpointId endpoint, uint16_t valu } // namespace ColorLoopStoredEnhancedHue namespace ColorCapabilities { -Protocols::InteractionModel::Status Get(chip::EndpointId endpoint, uint16_t * value); // bitmap16 -Protocols::InteractionModel::Status Set(chip::EndpointId endpoint, uint16_t value); -Protocols::InteractionModel::Status Set(chip::EndpointId endpoint, uint16_t value, MarkAttributeDirty markDirty); +Protocols::InteractionModel::Status +Get(chip::EndpointId endpoint, + chip::BitMask * value); // ColorCapabilitiesBitmap +Protocols::InteractionModel::Status Set(chip::EndpointId endpoint, + chip::BitMask value); +Protocols::InteractionModel::Status Set(chip::EndpointId endpoint, + chip::BitMask value, + MarkAttributeDirty markDirty); } // namespace ColorCapabilities namespace ColorTempPhysicalMinMireds { diff --git a/zzz_generated/app-common/app-common/zap-generated/cluster-enums-check.h b/zzz_generated/app-common/app-common/zap-generated/cluster-enums-check.h index da2047e745..f63782c221 100644 --- a/zzz_generated/app-common/app-common/zap-generated/cluster-enums-check.h +++ b/zzz_generated/app-common/app-common/zap-generated/cluster-enums-check.h @@ -2942,9 +2942,9 @@ static auto __attribute__((unused)) EnsureKnownEnumValue(ThermostatUserInterface } } -static auto __attribute__((unused)) EnsureKnownEnumValue(ColorControl::ColorLoopAction val) +static auto __attribute__((unused)) EnsureKnownEnumValue(ColorControl::ColorLoopActionEnum val) { - using EnumType = ColorControl::ColorLoopAction; + using EnumType = ColorControl::ColorLoopActionEnum; switch (val) { case EnumType::kDeactivate: @@ -2955,38 +2955,38 @@ static auto __attribute__((unused)) EnsureKnownEnumValue(ColorControl::ColorLoop return EnumType::kUnknownEnumValue; } } -static auto __attribute__((unused)) EnsureKnownEnumValue(ColorControl::ColorLoopDirection val) +static auto __attribute__((unused)) EnsureKnownEnumValue(ColorControl::ColorLoopDirectionEnum val) { - using EnumType = ColorControl::ColorLoopDirection; + using EnumType = ColorControl::ColorLoopDirectionEnum; switch (val) { - case EnumType::kDecrementHue: - case EnumType::kIncrementHue: + case EnumType::kDecrement: + case EnumType::kIncrement: return val; default: return EnumType::kUnknownEnumValue; } } -static auto __attribute__((unused)) EnsureKnownEnumValue(ColorControl::ColorMode val) +static auto __attribute__((unused)) EnsureKnownEnumValue(ColorControl::ColorModeEnum val) { - using EnumType = ColorControl::ColorMode; + using EnumType = ColorControl::ColorModeEnum; switch (val) { case EnumType::kCurrentHueAndCurrentSaturation: case EnumType::kCurrentXAndCurrentY: - case EnumType::kColorTemperature: + case EnumType::kColorTemperatureMireds: return val; default: return EnumType::kUnknownEnumValue; } } -static auto __attribute__((unused)) EnsureKnownEnumValue(ColorControl::HueDirection val) +static auto __attribute__((unused)) EnsureKnownEnumValue(ColorControl::DirectionEnum val) { - using EnumType = ColorControl::HueDirection; + using EnumType = ColorControl::DirectionEnum; switch (val) { - case EnumType::kShortestDistance: - case EnumType::kLongestDistance: + case EnumType::kShortest: + case EnumType::kLongest: case EnumType::kUp: case EnumType::kDown: return val; @@ -2994,34 +2994,38 @@ static auto __attribute__((unused)) EnsureKnownEnumValue(ColorControl::HueDirect return EnumType::kUnknownEnumValue; } } -static auto __attribute__((unused)) EnsureKnownEnumValue(ColorControl::HueMoveMode val) +static auto __attribute__((unused)) EnsureKnownEnumValue(ColorControl::DriftCompensationEnum val) { - using EnumType = ColorControl::HueMoveMode; + using EnumType = ColorControl::DriftCompensationEnum; switch (val) { - case EnumType::kStop: - case EnumType::kUp: - case EnumType::kDown: + case EnumType::kNone: + case EnumType::kOtherOrUnknown: + case EnumType::kTemperatureMonitoring: + case EnumType::kOpticalLuminanceMonitoringAndFeedback: + case EnumType::kOpticalColorMonitoringAndFeedback: return val; default: return EnumType::kUnknownEnumValue; } } -static auto __attribute__((unused)) EnsureKnownEnumValue(ColorControl::HueStepMode val) +static auto __attribute__((unused)) EnsureKnownEnumValue(ColorControl::EnhancedColorModeEnum val) { - using EnumType = ColorControl::HueStepMode; + using EnumType = ColorControl::EnhancedColorModeEnum; switch (val) { - case EnumType::kUp: - case EnumType::kDown: + case EnumType::kCurrentHueAndCurrentSaturation: + case EnumType::kCurrentXAndCurrentY: + case EnumType::kColorTemperatureMireds: + case EnumType::kEnhancedCurrentHueAndCurrentSaturation: return val; default: return EnumType::kUnknownEnumValue; } } -static auto __attribute__((unused)) EnsureKnownEnumValue(ColorControl::SaturationMoveMode val) +static auto __attribute__((unused)) EnsureKnownEnumValue(ColorControl::MoveModeEnum val) { - using EnumType = ColorControl::SaturationMoveMode; + using EnumType = ColorControl::MoveModeEnum; switch (val) { case EnumType::kStop: @@ -3032,9 +3036,9 @@ static auto __attribute__((unused)) EnsureKnownEnumValue(ColorControl::Saturatio return EnumType::kUnknownEnumValue; } } -static auto __attribute__((unused)) EnsureKnownEnumValue(ColorControl::SaturationStepMode val) +static auto __attribute__((unused)) EnsureKnownEnumValue(ColorControl::StepModeEnum val) { - using EnumType = ColorControl::SaturationStepMode; + using EnumType = ColorControl::StepModeEnum; switch (val) { case EnumType::kUp: 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 571439625e..e78f8f4d06 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 @@ -4343,8 +4343,8 @@ enum class TemperatureDisplayModeEnum : uint8_t namespace ColorControl { -// Enum for ColorLoopAction -enum class ColorLoopAction : uint8_t +// Enum for ColorLoopActionEnum +enum class ColorLoopActionEnum : uint8_t { kDeactivate = 0x00, kActivateFromColorLoopStartEnhancedHue = 0x01, @@ -4356,11 +4356,11 @@ enum class ColorLoopAction : uint8_t kUnknownEnumValue = 3, }; -// Enum for ColorLoopDirection -enum class ColorLoopDirection : uint8_t +// Enum for ColorLoopDirectionEnum +enum class ColorLoopDirectionEnum : uint8_t { - kDecrementHue = 0x00, - kIncrementHue = 0x01, + kDecrement = 0x00, + kIncrement = 0x01, // All received enum values that are not listed above will be mapped // to kUnknownEnumValue. This is a helper enum value that should only // be used by code to process how it handles receiving and unknown @@ -4368,12 +4368,12 @@ enum class ColorLoopDirection : uint8_t kUnknownEnumValue = 2, }; -// Enum for ColorMode -enum class ColorMode : uint8_t +// Enum for ColorModeEnum +enum class ColorModeEnum : uint8_t { kCurrentHueAndCurrentSaturation = 0x00, kCurrentXAndCurrentY = 0x01, - kColorTemperature = 0x02, + kColorTemperatureMireds = 0x02, // All received enum values that are not listed above will be mapped // to kUnknownEnumValue. This is a helper enum value that should only // be used by code to process how it handles receiving and unknown @@ -4381,13 +4381,13 @@ enum class ColorMode : uint8_t kUnknownEnumValue = 3, }; -// Enum for HueDirection -enum class HueDirection : uint8_t +// Enum for DirectionEnum +enum class DirectionEnum : uint8_t { - kShortestDistance = 0x00, - kLongestDistance = 0x01, - kUp = 0x02, - kDown = 0x03, + kShortest = 0x00, + kLongest = 0x01, + kUp = 0x02, + kDown = 0x03, // All received enum values that are not listed above will be mapped // to kUnknownEnumValue. This is a helper enum value that should only // be used by code to process how it handles receiving and unknown @@ -4395,33 +4395,37 @@ enum class HueDirection : uint8_t kUnknownEnumValue = 4, }; -// Enum for HueMoveMode -enum class HueMoveMode : uint8_t +// Enum for DriftCompensationEnum +enum class DriftCompensationEnum : uint8_t { - kStop = 0x00, - kUp = 0x01, - kDown = 0x03, + kNone = 0x00, + kOtherOrUnknown = 0x01, + kTemperatureMonitoring = 0x02, + kOpticalLuminanceMonitoringAndFeedback = 0x03, + kOpticalColorMonitoringAndFeedback = 0x04, // All received enum values that are not listed above will be mapped // to kUnknownEnumValue. This is a helper enum value that should only // be used by code to process how it handles receiving and unknown // enum value. This specific should never be transmitted. - kUnknownEnumValue = 2, + kUnknownEnumValue = 5, }; -// Enum for HueStepMode -enum class HueStepMode : uint8_t +// Enum for EnhancedColorModeEnum +enum class EnhancedColorModeEnum : uint8_t { - kUp = 0x01, - kDown = 0x03, + kCurrentHueAndCurrentSaturation = 0x00, + kCurrentXAndCurrentY = 0x01, + kColorTemperatureMireds = 0x02, + kEnhancedCurrentHueAndCurrentSaturation = 0x03, // All received enum values that are not listed above will be mapped // to kUnknownEnumValue. This is a helper enum value that should only // be used by code to process how it handles receiving and unknown // enum value. This specific should never be transmitted. - kUnknownEnumValue = 0, + kUnknownEnumValue = 4, }; -// Enum for SaturationMoveMode -enum class SaturationMoveMode : uint8_t +// Enum for MoveModeEnum +enum class MoveModeEnum : uint8_t { kStop = 0x00, kUp = 0x01, @@ -4433,8 +4437,8 @@ enum class SaturationMoveMode : uint8_t kUnknownEnumValue = 2, }; -// Enum for SaturationStepMode -enum class SaturationStepMode : uint8_t +// Enum for StepModeEnum +enum class StepModeEnum : uint8_t { kUp = 0x01, kDown = 0x03, @@ -4445,23 +4449,14 @@ enum class SaturationStepMode : uint8_t kUnknownEnumValue = 0, }; -// Bitmap for ColorCapabilities -enum class ColorCapabilities : uint16_t +// Bitmap for ColorCapabilitiesBitmap +enum class ColorCapabilitiesBitmap : uint16_t { - kHueSaturationSupported = 0x1, - kEnhancedHueSupported = 0x2, - kColorLoopSupported = 0x4, - kXYAttributesSupported = 0x8, - kColorTemperatureSupported = 0x10, -}; - -// Bitmap for ColorLoopUpdateFlags -enum class ColorLoopUpdateFlags : uint8_t -{ - kUpdateAction = 0x1, - kUpdateDirection = 0x2, - kUpdateTime = 0x4, - kUpdateStartHue = 0x8, + kHueSaturation = 0x1, + kEnhancedHue = 0x2, + kColorLoop = 0x4, + kXy = 0x8, + kColorTemperature = 0x10, }; // Bitmap for Feature @@ -4473,6 +4468,21 @@ enum class Feature : uint32_t kXy = 0x8, kColorTemperature = 0x10, }; + +// Bitmap for OptionsBitmap +enum class OptionsBitmap : uint8_t +{ + kExecuteIfOff = 0x1, +}; + +// Bitmap for UpdateFlagsBitmap +enum class UpdateFlagsBitmap : uint8_t +{ + kUpdateAction = 0x1, + kUpdateDirection = 0x2, + kUpdateTime = 0x4, + kUpdateStartHue = 0x8, +}; } // namespace ColorControl namespace BallastConfiguration { 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 f0f1dea1de..e18b64797b 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 @@ -31602,11 +31602,11 @@ struct Type static constexpr CommandId GetCommandId() { return Commands::MoveToHue::Id; } static constexpr ClusterId GetClusterId() { return Clusters::ColorControl::Id; } - uint8_t hue = static_cast(0); - HueDirection direction = static_cast(0); - uint16_t transitionTime = static_cast(0); - uint8_t optionsMask = static_cast(0); - uint8_t optionsOverride = static_cast(0); + uint8_t hue = static_cast(0); + DirectionEnum direction = static_cast(0); + uint16_t transitionTime = static_cast(0); + chip::BitMask optionsMask = static_cast>(0); + chip::BitMask optionsOverride = static_cast>(0); CHIP_ERROR Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const; @@ -31621,11 +31621,11 @@ struct DecodableType static constexpr CommandId GetCommandId() { return Commands::MoveToHue::Id; } static constexpr ClusterId GetClusterId() { return Clusters::ColorControl::Id; } - uint8_t hue = static_cast(0); - HueDirection direction = static_cast(0); - uint16_t transitionTime = static_cast(0); - uint8_t optionsMask = static_cast(0); - uint8_t optionsOverride = static_cast(0); + uint8_t hue = static_cast(0); + DirectionEnum direction = static_cast(0); + uint16_t transitionTime = static_cast(0); + chip::BitMask optionsMask = static_cast>(0); + chip::BitMask optionsOverride = static_cast>(0); CHIP_ERROR Decode(TLV::TLVReader & reader); }; }; // namespace MoveToHue @@ -31645,10 +31645,10 @@ struct Type static constexpr CommandId GetCommandId() { return Commands::MoveHue::Id; } static constexpr ClusterId GetClusterId() { return Clusters::ColorControl::Id; } - HueMoveMode moveMode = static_cast(0); - uint8_t rate = static_cast(0); - uint8_t optionsMask = static_cast(0); - uint8_t optionsOverride = static_cast(0); + MoveModeEnum moveMode = static_cast(0); + uint8_t rate = static_cast(0); + chip::BitMask optionsMask = static_cast>(0); + chip::BitMask optionsOverride = static_cast>(0); CHIP_ERROR Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const; @@ -31663,10 +31663,10 @@ struct DecodableType static constexpr CommandId GetCommandId() { return Commands::MoveHue::Id; } static constexpr ClusterId GetClusterId() { return Clusters::ColorControl::Id; } - HueMoveMode moveMode = static_cast(0); - uint8_t rate = static_cast(0); - uint8_t optionsMask = static_cast(0); - uint8_t optionsOverride = static_cast(0); + MoveModeEnum moveMode = static_cast(0); + uint8_t rate = static_cast(0); + chip::BitMask optionsMask = static_cast>(0); + chip::BitMask optionsOverride = static_cast>(0); CHIP_ERROR Decode(TLV::TLVReader & reader); }; }; // namespace MoveHue @@ -31687,11 +31687,11 @@ struct Type static constexpr CommandId GetCommandId() { return Commands::StepHue::Id; } static constexpr ClusterId GetClusterId() { return Clusters::ColorControl::Id; } - HueStepMode stepMode = static_cast(0); - uint8_t stepSize = static_cast(0); - uint8_t transitionTime = static_cast(0); - uint8_t optionsMask = static_cast(0); - uint8_t optionsOverride = static_cast(0); + StepModeEnum stepMode = static_cast(0); + uint8_t stepSize = static_cast(0); + uint8_t transitionTime = static_cast(0); + chip::BitMask optionsMask = static_cast>(0); + chip::BitMask optionsOverride = static_cast>(0); CHIP_ERROR Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const; @@ -31706,11 +31706,11 @@ struct DecodableType static constexpr CommandId GetCommandId() { return Commands::StepHue::Id; } static constexpr ClusterId GetClusterId() { return Clusters::ColorControl::Id; } - HueStepMode stepMode = static_cast(0); - uint8_t stepSize = static_cast(0); - uint8_t transitionTime = static_cast(0); - uint8_t optionsMask = static_cast(0); - uint8_t optionsOverride = static_cast(0); + StepModeEnum stepMode = static_cast(0); + uint8_t stepSize = static_cast(0); + uint8_t transitionTime = static_cast(0); + chip::BitMask optionsMask = static_cast>(0); + chip::BitMask optionsOverride = static_cast>(0); CHIP_ERROR Decode(TLV::TLVReader & reader); }; }; // namespace StepHue @@ -31730,10 +31730,10 @@ struct Type static constexpr CommandId GetCommandId() { return Commands::MoveToSaturation::Id; } static constexpr ClusterId GetClusterId() { return Clusters::ColorControl::Id; } - uint8_t saturation = static_cast(0); - uint16_t transitionTime = static_cast(0); - uint8_t optionsMask = static_cast(0); - uint8_t optionsOverride = static_cast(0); + uint8_t saturation = static_cast(0); + uint16_t transitionTime = static_cast(0); + chip::BitMask optionsMask = static_cast>(0); + chip::BitMask optionsOverride = static_cast>(0); CHIP_ERROR Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const; @@ -31748,10 +31748,10 @@ struct DecodableType static constexpr CommandId GetCommandId() { return Commands::MoveToSaturation::Id; } static constexpr ClusterId GetClusterId() { return Clusters::ColorControl::Id; } - uint8_t saturation = static_cast(0); - uint16_t transitionTime = static_cast(0); - uint8_t optionsMask = static_cast(0); - uint8_t optionsOverride = static_cast(0); + uint8_t saturation = static_cast(0); + uint16_t transitionTime = static_cast(0); + chip::BitMask optionsMask = static_cast>(0); + chip::BitMask optionsOverride = static_cast>(0); CHIP_ERROR Decode(TLV::TLVReader & reader); }; }; // namespace MoveToSaturation @@ -31771,10 +31771,10 @@ struct Type static constexpr CommandId GetCommandId() { return Commands::MoveSaturation::Id; } static constexpr ClusterId GetClusterId() { return Clusters::ColorControl::Id; } - SaturationMoveMode moveMode = static_cast(0); - uint8_t rate = static_cast(0); - uint8_t optionsMask = static_cast(0); - uint8_t optionsOverride = static_cast(0); + MoveModeEnum moveMode = static_cast(0); + uint8_t rate = static_cast(0); + chip::BitMask optionsMask = static_cast>(0); + chip::BitMask optionsOverride = static_cast>(0); CHIP_ERROR Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const; @@ -31789,10 +31789,10 @@ struct DecodableType static constexpr CommandId GetCommandId() { return Commands::MoveSaturation::Id; } static constexpr ClusterId GetClusterId() { return Clusters::ColorControl::Id; } - SaturationMoveMode moveMode = static_cast(0); - uint8_t rate = static_cast(0); - uint8_t optionsMask = static_cast(0); - uint8_t optionsOverride = static_cast(0); + MoveModeEnum moveMode = static_cast(0); + uint8_t rate = static_cast(0); + chip::BitMask optionsMask = static_cast>(0); + chip::BitMask optionsOverride = static_cast>(0); CHIP_ERROR Decode(TLV::TLVReader & reader); }; }; // namespace MoveSaturation @@ -31813,11 +31813,11 @@ struct Type static constexpr CommandId GetCommandId() { return Commands::StepSaturation::Id; } static constexpr ClusterId GetClusterId() { return Clusters::ColorControl::Id; } - SaturationStepMode stepMode = static_cast(0); - uint8_t stepSize = static_cast(0); - uint8_t transitionTime = static_cast(0); - uint8_t optionsMask = static_cast(0); - uint8_t optionsOverride = static_cast(0); + StepModeEnum stepMode = static_cast(0); + uint8_t stepSize = static_cast(0); + uint8_t transitionTime = static_cast(0); + chip::BitMask optionsMask = static_cast>(0); + chip::BitMask optionsOverride = static_cast>(0); CHIP_ERROR Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const; @@ -31832,11 +31832,11 @@ struct DecodableType static constexpr CommandId GetCommandId() { return Commands::StepSaturation::Id; } static constexpr ClusterId GetClusterId() { return Clusters::ColorControl::Id; } - SaturationStepMode stepMode = static_cast(0); - uint8_t stepSize = static_cast(0); - uint8_t transitionTime = static_cast(0); - uint8_t optionsMask = static_cast(0); - uint8_t optionsOverride = static_cast(0); + StepModeEnum stepMode = static_cast(0); + uint8_t stepSize = static_cast(0); + uint8_t transitionTime = static_cast(0); + chip::BitMask optionsMask = static_cast>(0); + chip::BitMask optionsOverride = static_cast>(0); CHIP_ERROR Decode(TLV::TLVReader & reader); }; }; // namespace StepSaturation @@ -31857,11 +31857,11 @@ struct Type static constexpr CommandId GetCommandId() { return Commands::MoveToHueAndSaturation::Id; } static constexpr ClusterId GetClusterId() { return Clusters::ColorControl::Id; } - uint8_t hue = static_cast(0); - uint8_t saturation = static_cast(0); - uint16_t transitionTime = static_cast(0); - uint8_t optionsMask = static_cast(0); - uint8_t optionsOverride = static_cast(0); + uint8_t hue = static_cast(0); + uint8_t saturation = static_cast(0); + uint16_t transitionTime = static_cast(0); + chip::BitMask optionsMask = static_cast>(0); + chip::BitMask optionsOverride = static_cast>(0); CHIP_ERROR Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const; @@ -31876,11 +31876,11 @@ struct DecodableType static constexpr CommandId GetCommandId() { return Commands::MoveToHueAndSaturation::Id; } static constexpr ClusterId GetClusterId() { return Clusters::ColorControl::Id; } - uint8_t hue = static_cast(0); - uint8_t saturation = static_cast(0); - uint16_t transitionTime = static_cast(0); - uint8_t optionsMask = static_cast(0); - uint8_t optionsOverride = static_cast(0); + uint8_t hue = static_cast(0); + uint8_t saturation = static_cast(0); + uint16_t transitionTime = static_cast(0); + chip::BitMask optionsMask = static_cast>(0); + chip::BitMask optionsOverride = static_cast>(0); CHIP_ERROR Decode(TLV::TLVReader & reader); }; }; // namespace MoveToHueAndSaturation @@ -31901,11 +31901,11 @@ struct Type static constexpr CommandId GetCommandId() { return Commands::MoveToColor::Id; } static constexpr ClusterId GetClusterId() { return Clusters::ColorControl::Id; } - uint16_t colorX = static_cast(0); - uint16_t colorY = static_cast(0); - uint16_t transitionTime = static_cast(0); - uint8_t optionsMask = static_cast(0); - uint8_t optionsOverride = static_cast(0); + uint16_t colorX = static_cast(0); + uint16_t colorY = static_cast(0); + uint16_t transitionTime = static_cast(0); + chip::BitMask optionsMask = static_cast>(0); + chip::BitMask optionsOverride = static_cast>(0); CHIP_ERROR Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const; @@ -31920,11 +31920,11 @@ struct DecodableType static constexpr CommandId GetCommandId() { return Commands::MoveToColor::Id; } static constexpr ClusterId GetClusterId() { return Clusters::ColorControl::Id; } - uint16_t colorX = static_cast(0); - uint16_t colorY = static_cast(0); - uint16_t transitionTime = static_cast(0); - uint8_t optionsMask = static_cast(0); - uint8_t optionsOverride = static_cast(0); + uint16_t colorX = static_cast(0); + uint16_t colorY = static_cast(0); + uint16_t transitionTime = static_cast(0); + chip::BitMask optionsMask = static_cast>(0); + chip::BitMask optionsOverride = static_cast>(0); CHIP_ERROR Decode(TLV::TLVReader & reader); }; }; // namespace MoveToColor @@ -31944,10 +31944,10 @@ struct Type static constexpr CommandId GetCommandId() { return Commands::MoveColor::Id; } static constexpr ClusterId GetClusterId() { return Clusters::ColorControl::Id; } - int16_t rateX = static_cast(0); - int16_t rateY = static_cast(0); - uint8_t optionsMask = static_cast(0); - uint8_t optionsOverride = static_cast(0); + int16_t rateX = static_cast(0); + int16_t rateY = static_cast(0); + chip::BitMask optionsMask = static_cast>(0); + chip::BitMask optionsOverride = static_cast>(0); CHIP_ERROR Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const; @@ -31962,10 +31962,10 @@ struct DecodableType static constexpr CommandId GetCommandId() { return Commands::MoveColor::Id; } static constexpr ClusterId GetClusterId() { return Clusters::ColorControl::Id; } - int16_t rateX = static_cast(0); - int16_t rateY = static_cast(0); - uint8_t optionsMask = static_cast(0); - uint8_t optionsOverride = static_cast(0); + int16_t rateX = static_cast(0); + int16_t rateY = static_cast(0); + chip::BitMask optionsMask = static_cast>(0); + chip::BitMask optionsOverride = static_cast>(0); CHIP_ERROR Decode(TLV::TLVReader & reader); }; }; // namespace MoveColor @@ -31986,11 +31986,11 @@ struct Type static constexpr CommandId GetCommandId() { return Commands::StepColor::Id; } static constexpr ClusterId GetClusterId() { return Clusters::ColorControl::Id; } - int16_t stepX = static_cast(0); - int16_t stepY = static_cast(0); - uint16_t transitionTime = static_cast(0); - uint8_t optionsMask = static_cast(0); - uint8_t optionsOverride = static_cast(0); + int16_t stepX = static_cast(0); + int16_t stepY = static_cast(0); + uint16_t transitionTime = static_cast(0); + chip::BitMask optionsMask = static_cast>(0); + chip::BitMask optionsOverride = static_cast>(0); CHIP_ERROR Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const; @@ -32005,11 +32005,11 @@ struct DecodableType static constexpr CommandId GetCommandId() { return Commands::StepColor::Id; } static constexpr ClusterId GetClusterId() { return Clusters::ColorControl::Id; } - int16_t stepX = static_cast(0); - int16_t stepY = static_cast(0); - uint16_t transitionTime = static_cast(0); - uint8_t optionsMask = static_cast(0); - uint8_t optionsOverride = static_cast(0); + int16_t stepX = static_cast(0); + int16_t stepY = static_cast(0); + uint16_t transitionTime = static_cast(0); + chip::BitMask optionsMask = static_cast>(0); + chip::BitMask optionsOverride = static_cast>(0); CHIP_ERROR Decode(TLV::TLVReader & reader); }; }; // namespace StepColor @@ -32029,10 +32029,10 @@ struct Type static constexpr CommandId GetCommandId() { return Commands::MoveToColorTemperature::Id; } static constexpr ClusterId GetClusterId() { return Clusters::ColorControl::Id; } - uint16_t colorTemperatureMireds = static_cast(0); - uint16_t transitionTime = static_cast(0); - uint8_t optionsMask = static_cast(0); - uint8_t optionsOverride = static_cast(0); + uint16_t colorTemperatureMireds = static_cast(0); + uint16_t transitionTime = static_cast(0); + chip::BitMask optionsMask = static_cast>(0); + chip::BitMask optionsOverride = static_cast>(0); CHIP_ERROR Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const; @@ -32047,10 +32047,10 @@ struct DecodableType static constexpr CommandId GetCommandId() { return Commands::MoveToColorTemperature::Id; } static constexpr ClusterId GetClusterId() { return Clusters::ColorControl::Id; } - uint16_t colorTemperatureMireds = static_cast(0); - uint16_t transitionTime = static_cast(0); - uint8_t optionsMask = static_cast(0); - uint8_t optionsOverride = static_cast(0); + uint16_t colorTemperatureMireds = static_cast(0); + uint16_t transitionTime = static_cast(0); + chip::BitMask optionsMask = static_cast>(0); + chip::BitMask optionsOverride = static_cast>(0); CHIP_ERROR Decode(TLV::TLVReader & reader); }; }; // namespace MoveToColorTemperature @@ -32071,11 +32071,11 @@ struct Type static constexpr CommandId GetCommandId() { return Commands::EnhancedMoveToHue::Id; } static constexpr ClusterId GetClusterId() { return Clusters::ColorControl::Id; } - uint16_t enhancedHue = static_cast(0); - HueDirection direction = static_cast(0); - uint16_t transitionTime = static_cast(0); - uint8_t optionsMask = static_cast(0); - uint8_t optionsOverride = static_cast(0); + uint16_t enhancedHue = static_cast(0); + DirectionEnum direction = static_cast(0); + uint16_t transitionTime = static_cast(0); + chip::BitMask optionsMask = static_cast>(0); + chip::BitMask optionsOverride = static_cast>(0); CHIP_ERROR Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const; @@ -32090,11 +32090,11 @@ struct DecodableType static constexpr CommandId GetCommandId() { return Commands::EnhancedMoveToHue::Id; } static constexpr ClusterId GetClusterId() { return Clusters::ColorControl::Id; } - uint16_t enhancedHue = static_cast(0); - HueDirection direction = static_cast(0); - uint16_t transitionTime = static_cast(0); - uint8_t optionsMask = static_cast(0); - uint8_t optionsOverride = static_cast(0); + uint16_t enhancedHue = static_cast(0); + DirectionEnum direction = static_cast(0); + uint16_t transitionTime = static_cast(0); + chip::BitMask optionsMask = static_cast>(0); + chip::BitMask optionsOverride = static_cast>(0); CHIP_ERROR Decode(TLV::TLVReader & reader); }; }; // namespace EnhancedMoveToHue @@ -32114,10 +32114,10 @@ struct Type static constexpr CommandId GetCommandId() { return Commands::EnhancedMoveHue::Id; } static constexpr ClusterId GetClusterId() { return Clusters::ColorControl::Id; } - HueMoveMode moveMode = static_cast(0); - uint16_t rate = static_cast(0); - uint8_t optionsMask = static_cast(0); - uint8_t optionsOverride = static_cast(0); + MoveModeEnum moveMode = static_cast(0); + uint16_t rate = static_cast(0); + chip::BitMask optionsMask = static_cast>(0); + chip::BitMask optionsOverride = static_cast>(0); CHIP_ERROR Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const; @@ -32132,10 +32132,10 @@ struct DecodableType static constexpr CommandId GetCommandId() { return Commands::EnhancedMoveHue::Id; } static constexpr ClusterId GetClusterId() { return Clusters::ColorControl::Id; } - HueMoveMode moveMode = static_cast(0); - uint16_t rate = static_cast(0); - uint8_t optionsMask = static_cast(0); - uint8_t optionsOverride = static_cast(0); + MoveModeEnum moveMode = static_cast(0); + uint16_t rate = static_cast(0); + chip::BitMask optionsMask = static_cast>(0); + chip::BitMask optionsOverride = static_cast>(0); CHIP_ERROR Decode(TLV::TLVReader & reader); }; }; // namespace EnhancedMoveHue @@ -32156,11 +32156,11 @@ struct Type static constexpr CommandId GetCommandId() { return Commands::EnhancedStepHue::Id; } static constexpr ClusterId GetClusterId() { return Clusters::ColorControl::Id; } - HueStepMode stepMode = static_cast(0); - uint16_t stepSize = static_cast(0); - uint16_t transitionTime = static_cast(0); - uint8_t optionsMask = static_cast(0); - uint8_t optionsOverride = static_cast(0); + StepModeEnum stepMode = static_cast(0); + uint16_t stepSize = static_cast(0); + uint16_t transitionTime = static_cast(0); + chip::BitMask optionsMask = static_cast>(0); + chip::BitMask optionsOverride = static_cast>(0); CHIP_ERROR Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const; @@ -32175,11 +32175,11 @@ struct DecodableType static constexpr CommandId GetCommandId() { return Commands::EnhancedStepHue::Id; } static constexpr ClusterId GetClusterId() { return Clusters::ColorControl::Id; } - HueStepMode stepMode = static_cast(0); - uint16_t stepSize = static_cast(0); - uint16_t transitionTime = static_cast(0); - uint8_t optionsMask = static_cast(0); - uint8_t optionsOverride = static_cast(0); + StepModeEnum stepMode = static_cast(0); + uint16_t stepSize = static_cast(0); + uint16_t transitionTime = static_cast(0); + chip::BitMask optionsMask = static_cast>(0); + chip::BitMask optionsOverride = static_cast>(0); CHIP_ERROR Decode(TLV::TLVReader & reader); }; }; // namespace EnhancedStepHue @@ -32200,11 +32200,11 @@ struct Type static constexpr CommandId GetCommandId() { return Commands::EnhancedMoveToHueAndSaturation::Id; } static constexpr ClusterId GetClusterId() { return Clusters::ColorControl::Id; } - uint16_t enhancedHue = static_cast(0); - uint8_t saturation = static_cast(0); - uint16_t transitionTime = static_cast(0); - uint8_t optionsMask = static_cast(0); - uint8_t optionsOverride = static_cast(0); + uint16_t enhancedHue = static_cast(0); + uint8_t saturation = static_cast(0); + uint16_t transitionTime = static_cast(0); + chip::BitMask optionsMask = static_cast>(0); + chip::BitMask optionsOverride = static_cast>(0); CHIP_ERROR Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const; @@ -32219,11 +32219,11 @@ struct DecodableType static constexpr CommandId GetCommandId() { return Commands::EnhancedMoveToHueAndSaturation::Id; } static constexpr ClusterId GetClusterId() { return Clusters::ColorControl::Id; } - uint16_t enhancedHue = static_cast(0); - uint8_t saturation = static_cast(0); - uint16_t transitionTime = static_cast(0); - uint8_t optionsMask = static_cast(0); - uint8_t optionsOverride = static_cast(0); + uint16_t enhancedHue = static_cast(0); + uint8_t saturation = static_cast(0); + uint16_t transitionTime = static_cast(0); + chip::BitMask optionsMask = static_cast>(0); + chip::BitMask optionsOverride = static_cast>(0); CHIP_ERROR Decode(TLV::TLVReader & reader); }; }; // namespace EnhancedMoveToHueAndSaturation @@ -32246,13 +32246,13 @@ struct Type static constexpr CommandId GetCommandId() { return Commands::ColorLoopSet::Id; } static constexpr ClusterId GetClusterId() { return Clusters::ColorControl::Id; } - chip::BitMask updateFlags = static_cast>(0); - ColorLoopAction action = static_cast(0); - ColorLoopDirection direction = static_cast(0); - uint16_t time = static_cast(0); - uint16_t startHue = static_cast(0); - uint8_t optionsMask = static_cast(0); - uint8_t optionsOverride = static_cast(0); + chip::BitMask updateFlags = static_cast>(0); + ColorLoopActionEnum action = static_cast(0); + ColorLoopDirectionEnum direction = static_cast(0); + uint16_t time = static_cast(0); + uint16_t startHue = static_cast(0); + chip::BitMask optionsMask = static_cast>(0); + chip::BitMask optionsOverride = static_cast>(0); CHIP_ERROR Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const; @@ -32267,13 +32267,13 @@ struct DecodableType static constexpr CommandId GetCommandId() { return Commands::ColorLoopSet::Id; } static constexpr ClusterId GetClusterId() { return Clusters::ColorControl::Id; } - chip::BitMask updateFlags = static_cast>(0); - ColorLoopAction action = static_cast(0); - ColorLoopDirection direction = static_cast(0); - uint16_t time = static_cast(0); - uint16_t startHue = static_cast(0); - uint8_t optionsMask = static_cast(0); - uint8_t optionsOverride = static_cast(0); + chip::BitMask updateFlags = static_cast>(0); + ColorLoopActionEnum action = static_cast(0); + ColorLoopDirectionEnum direction = static_cast(0); + uint16_t time = static_cast(0); + uint16_t startHue = static_cast(0); + chip::BitMask optionsMask = static_cast>(0); + chip::BitMask optionsOverride = static_cast>(0); CHIP_ERROR Decode(TLV::TLVReader & reader); }; }; // namespace ColorLoopSet @@ -32291,8 +32291,8 @@ struct Type static constexpr CommandId GetCommandId() { return Commands::StopMoveStep::Id; } static constexpr ClusterId GetClusterId() { return Clusters::ColorControl::Id; } - uint8_t optionsMask = static_cast(0); - uint8_t optionsOverride = static_cast(0); + chip::BitMask optionsMask = static_cast>(0); + chip::BitMask optionsOverride = static_cast>(0); CHIP_ERROR Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const; @@ -32307,8 +32307,8 @@ struct DecodableType static constexpr CommandId GetCommandId() { return Commands::StopMoveStep::Id; } static constexpr ClusterId GetClusterId() { return Clusters::ColorControl::Id; } - uint8_t optionsMask = static_cast(0); - uint8_t optionsOverride = static_cast(0); + chip::BitMask optionsMask = static_cast>(0); + chip::BitMask optionsOverride = static_cast>(0); CHIP_ERROR Decode(TLV::TLVReader & reader); }; }; // namespace StopMoveStep @@ -32330,12 +32330,12 @@ struct Type static constexpr CommandId GetCommandId() { return Commands::MoveColorTemperature::Id; } static constexpr ClusterId GetClusterId() { return Clusters::ColorControl::Id; } - HueMoveMode moveMode = static_cast(0); - uint16_t rate = static_cast(0); - uint16_t colorTemperatureMinimumMireds = static_cast(0); - uint16_t colorTemperatureMaximumMireds = static_cast(0); - uint8_t optionsMask = static_cast(0); - uint8_t optionsOverride = static_cast(0); + MoveModeEnum moveMode = static_cast(0); + uint16_t rate = static_cast(0); + uint16_t colorTemperatureMinimumMireds = static_cast(0); + uint16_t colorTemperatureMaximumMireds = static_cast(0); + chip::BitMask optionsMask = static_cast>(0); + chip::BitMask optionsOverride = static_cast>(0); CHIP_ERROR Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const; @@ -32350,12 +32350,12 @@ struct DecodableType static constexpr CommandId GetCommandId() { return Commands::MoveColorTemperature::Id; } static constexpr ClusterId GetClusterId() { return Clusters::ColorControl::Id; } - HueMoveMode moveMode = static_cast(0); - uint16_t rate = static_cast(0); - uint16_t colorTemperatureMinimumMireds = static_cast(0); - uint16_t colorTemperatureMaximumMireds = static_cast(0); - uint8_t optionsMask = static_cast(0); - uint8_t optionsOverride = static_cast(0); + MoveModeEnum moveMode = static_cast(0); + uint16_t rate = static_cast(0); + uint16_t colorTemperatureMinimumMireds = static_cast(0); + uint16_t colorTemperatureMaximumMireds = static_cast(0); + chip::BitMask optionsMask = static_cast>(0); + chip::BitMask optionsOverride = static_cast>(0); CHIP_ERROR Decode(TLV::TLVReader & reader); }; }; // namespace MoveColorTemperature @@ -32378,13 +32378,13 @@ struct Type static constexpr CommandId GetCommandId() { return Commands::StepColorTemperature::Id; } static constexpr ClusterId GetClusterId() { return Clusters::ColorControl::Id; } - HueStepMode stepMode = static_cast(0); - uint16_t stepSize = static_cast(0); - uint16_t transitionTime = static_cast(0); - uint16_t colorTemperatureMinimumMireds = static_cast(0); - uint16_t colorTemperatureMaximumMireds = static_cast(0); - uint8_t optionsMask = static_cast(0); - uint8_t optionsOverride = static_cast(0); + StepModeEnum stepMode = static_cast(0); + uint16_t stepSize = static_cast(0); + uint16_t transitionTime = static_cast(0); + uint16_t colorTemperatureMinimumMireds = static_cast(0); + uint16_t colorTemperatureMaximumMireds = static_cast(0); + chip::BitMask optionsMask = static_cast>(0); + chip::BitMask optionsOverride = static_cast>(0); CHIP_ERROR Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const; @@ -32399,13 +32399,13 @@ struct DecodableType static constexpr CommandId GetCommandId() { return Commands::StepColorTemperature::Id; } static constexpr ClusterId GetClusterId() { return Clusters::ColorControl::Id; } - HueStepMode stepMode = static_cast(0); - uint16_t stepSize = static_cast(0); - uint16_t transitionTime = static_cast(0); - uint16_t colorTemperatureMinimumMireds = static_cast(0); - uint16_t colorTemperatureMaximumMireds = static_cast(0); - uint8_t optionsMask = static_cast(0); - uint8_t optionsOverride = static_cast(0); + StepModeEnum stepMode = static_cast(0); + uint16_t stepSize = static_cast(0); + uint16_t transitionTime = static_cast(0); + uint16_t colorTemperatureMinimumMireds = static_cast(0); + uint16_t colorTemperatureMaximumMireds = static_cast(0); + chip::BitMask optionsMask = static_cast>(0); + chip::BitMask optionsOverride = static_cast>(0); CHIP_ERROR Decode(TLV::TLVReader & reader); }; }; // namespace StepColorTemperature @@ -32476,9 +32476,9 @@ struct TypeInfo namespace DriftCompensation { struct TypeInfo { - using Type = uint8_t; - using DecodableType = uint8_t; - using DecodableArgType = uint8_t; + using Type = chip::app::Clusters::ColorControl::DriftCompensationEnum; + using DecodableType = chip::app::Clusters::ColorControl::DriftCompensationEnum; + using DecodableArgType = chip::app::Clusters::ColorControl::DriftCompensationEnum; static constexpr ClusterId GetClusterId() { return Clusters::ColorControl::Id; } static constexpr AttributeId GetAttributeId() { return Attributes::DriftCompensation::Id; } @@ -32513,9 +32513,9 @@ struct TypeInfo namespace ColorMode { struct TypeInfo { - using Type = uint8_t; - using DecodableType = uint8_t; - using DecodableArgType = uint8_t; + using Type = chip::app::Clusters::ColorControl::ColorModeEnum; + using DecodableType = chip::app::Clusters::ColorControl::ColorModeEnum; + using DecodableArgType = chip::app::Clusters::ColorControl::ColorModeEnum; static constexpr ClusterId GetClusterId() { return Clusters::ColorControl::Id; } static constexpr AttributeId GetAttributeId() { return Attributes::ColorMode::Id; } @@ -32525,9 +32525,9 @@ struct TypeInfo namespace Options { struct TypeInfo { - using Type = uint8_t; - using DecodableType = uint8_t; - using DecodableArgType = uint8_t; + using Type = chip::BitMask; + using DecodableType = chip::BitMask; + using DecodableArgType = chip::BitMask; static constexpr ClusterId GetClusterId() { return Clusters::ColorControl::Id; } static constexpr AttributeId GetAttributeId() { return Attributes::Options::Id; } @@ -32909,9 +32909,9 @@ struct TypeInfo namespace EnhancedColorMode { struct TypeInfo { - using Type = uint8_t; - using DecodableType = uint8_t; - using DecodableArgType = uint8_t; + using Type = chip::app::Clusters::ColorControl::EnhancedColorModeEnum; + using DecodableType = chip::app::Clusters::ColorControl::EnhancedColorModeEnum; + using DecodableArgType = chip::app::Clusters::ColorControl::EnhancedColorModeEnum; static constexpr ClusterId GetClusterId() { return Clusters::ColorControl::Id; } static constexpr AttributeId GetAttributeId() { return Attributes::EnhancedColorMode::Id; } @@ -32981,9 +32981,9 @@ struct TypeInfo namespace ColorCapabilities { struct TypeInfo { - using Type = uint16_t; - using DecodableType = uint16_t; - using DecodableArgType = uint16_t; + using Type = chip::BitMask; + using DecodableType = chip::BitMask; + using DecodableArgType = chip::BitMask; static constexpr ClusterId GetClusterId() { return Clusters::ColorControl::Id; } static constexpr AttributeId GetAttributeId() { return Attributes::ColorCapabilities::Id; } @@ -33088,11 +33088,13 @@ struct TypeInfo Attributes::RemainingTime::TypeInfo::DecodableType remainingTime = static_cast(0); Attributes::CurrentX::TypeInfo::DecodableType currentX = static_cast(0); Attributes::CurrentY::TypeInfo::DecodableType currentY = static_cast(0); - Attributes::DriftCompensation::TypeInfo::DecodableType driftCompensation = static_cast(0); + Attributes::DriftCompensation::TypeInfo::DecodableType driftCompensation = + static_cast(0); Attributes::CompensationText::TypeInfo::DecodableType compensationText; Attributes::ColorTemperatureMireds::TypeInfo::DecodableType colorTemperatureMireds = static_cast(0); - Attributes::ColorMode::TypeInfo::DecodableType colorMode = static_cast(0); - Attributes::Options::TypeInfo::DecodableType options = static_cast(0); + Attributes::ColorMode::TypeInfo::DecodableType colorMode = static_cast(0); + Attributes::Options::TypeInfo::DecodableType options = + static_cast>(0); Attributes::NumberOfPrimaries::TypeInfo::DecodableType numberOfPrimaries; Attributes::Primary1X::TypeInfo::DecodableType primary1X = static_cast(0); Attributes::Primary1Y::TypeInfo::DecodableType primary1Y = static_cast(0); @@ -33123,14 +33125,16 @@ struct TypeInfo Attributes::ColorPointBX::TypeInfo::DecodableType colorPointBX = static_cast(0); Attributes::ColorPointBY::TypeInfo::DecodableType colorPointBY = static_cast(0); Attributes::ColorPointBIntensity::TypeInfo::DecodableType colorPointBIntensity; - Attributes::EnhancedCurrentHue::TypeInfo::DecodableType enhancedCurrentHue = static_cast(0); - Attributes::EnhancedColorMode::TypeInfo::DecodableType enhancedColorMode = static_cast(0); + Attributes::EnhancedCurrentHue::TypeInfo::DecodableType enhancedCurrentHue = static_cast(0); + Attributes::EnhancedColorMode::TypeInfo::DecodableType enhancedColorMode = + static_cast(0); Attributes::ColorLoopActive::TypeInfo::DecodableType colorLoopActive = static_cast(0); Attributes::ColorLoopDirection::TypeInfo::DecodableType colorLoopDirection = static_cast(0); Attributes::ColorLoopTime::TypeInfo::DecodableType colorLoopTime = static_cast(0); Attributes::ColorLoopStartEnhancedHue::TypeInfo::DecodableType colorLoopStartEnhancedHue = static_cast(0); Attributes::ColorLoopStoredEnhancedHue::TypeInfo::DecodableType colorLoopStoredEnhancedHue = static_cast(0); - Attributes::ColorCapabilities::TypeInfo::DecodableType colorCapabilities = static_cast(0); + Attributes::ColorCapabilities::TypeInfo::DecodableType colorCapabilities = + static_cast>(0); Attributes::ColorTempPhysicalMinMireds::TypeInfo::DecodableType colorTempPhysicalMinMireds = static_cast(0); Attributes::ColorTempPhysicalMaxMireds::TypeInfo::DecodableType colorTempPhysicalMaxMireds = static_cast(0); Attributes::CoupleColorTempToLevelMinMireds::TypeInfo::DecodableType coupleColorTempToLevelMinMireds = diff --git a/zzz_generated/chip-tool/zap-generated/cluster/Commands.h b/zzz_generated/chip-tool/zap-generated/cluster/Commands.h index 57259e33d6..add8258f1e 100644 --- a/zzz_generated/chip-tool/zap-generated/cluster/Commands.h +++ b/zzz_generated/chip-tool/zap-generated/cluster/Commands.h @@ -23695,16 +23695,17 @@ void registerClusterColorControl(Commands & commands, CredentialIssuerCommands * WriteCommandType::kForceWrite, credsIssuerConfig), // make_unique>(Id, "current-y", 0, UINT16_MAX, Attributes::CurrentY::Id, WriteCommandType::kForceWrite, credsIssuerConfig), // - make_unique>(Id, "drift-compensation", 0, UINT8_MAX, Attributes::DriftCompensation::Id, - WriteCommandType::kForceWrite, credsIssuerConfig), // + make_unique>( + Id, "drift-compensation", 0, UINT8_MAX, Attributes::DriftCompensation::Id, WriteCommandType::kForceWrite, + credsIssuerConfig), // make_unique>(Id, "compensation-text", Attributes::CompensationText::Id, WriteCommandType::kForceWrite, credsIssuerConfig), // make_unique>(Id, "color-temperature-mireds", 0, UINT16_MAX, Attributes::ColorTemperatureMireds::Id, WriteCommandType::kForceWrite, credsIssuerConfig), // - make_unique>(Id, "color-mode", 0, UINT8_MAX, Attributes::ColorMode::Id, - WriteCommandType::kForceWrite, credsIssuerConfig), // - make_unique>(Id, "options", 0, UINT8_MAX, Attributes::Options::Id, WriteCommandType::kWrite, - credsIssuerConfig), // + make_unique>( + Id, "color-mode", 0, UINT8_MAX, Attributes::ColorMode::Id, WriteCommandType::kForceWrite, credsIssuerConfig), // + make_unique>>( + Id, "options", 0, UINT8_MAX, Attributes::Options::Id, WriteCommandType::kWrite, credsIssuerConfig), // make_unique>>(Id, "number-of-primaries", 0, UINT8_MAX, Attributes::NumberOfPrimaries::Id, WriteCommandType::kForceWrite, credsIssuerConfig), // @@ -23777,8 +23778,9 @@ void registerClusterColorControl(Commands & commands, CredentialIssuerCommands * WriteCommandType::kWrite, credsIssuerConfig), // make_unique>(Id, "enhanced-current-hue", 0, UINT16_MAX, Attributes::EnhancedCurrentHue::Id, WriteCommandType::kForceWrite, credsIssuerConfig), // - make_unique>(Id, "enhanced-color-mode", 0, UINT8_MAX, Attributes::EnhancedColorMode::Id, - WriteCommandType::kForceWrite, credsIssuerConfig), // + make_unique>( + Id, "enhanced-color-mode", 0, UINT8_MAX, Attributes::EnhancedColorMode::Id, WriteCommandType::kForceWrite, + credsIssuerConfig), // make_unique>(Id, "color-loop-active", 0, UINT8_MAX, Attributes::ColorLoopActive::Id, WriteCommandType::kForceWrite, credsIssuerConfig), // make_unique>(Id, "color-loop-direction", 0, UINT8_MAX, Attributes::ColorLoopDirection::Id, @@ -23791,8 +23793,9 @@ void registerClusterColorControl(Commands & commands, CredentialIssuerCommands * make_unique>(Id, "color-loop-stored-enhanced-hue", 0, UINT16_MAX, Attributes::ColorLoopStoredEnhancedHue::Id, WriteCommandType::kForceWrite, credsIssuerConfig), // - make_unique>(Id, "color-capabilities", 0, UINT16_MAX, Attributes::ColorCapabilities::Id, - WriteCommandType::kForceWrite, credsIssuerConfig), // + make_unique>>( + Id, "color-capabilities", 0, UINT16_MAX, Attributes::ColorCapabilities::Id, WriteCommandType::kForceWrite, + credsIssuerConfig), // make_unique>(Id, "color-temp-physical-min-mireds", 0, UINT16_MAX, Attributes::ColorTempPhysicalMinMireds::Id, WriteCommandType::kForceWrite, 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 aa122cb62d..12382e3cb4 100644 --- a/zzz_generated/chip-tool/zap-generated/cluster/logging/DataModelLogger.cpp +++ b/zzz_generated/chip-tool/zap-generated/cluster/logging/DataModelLogger.cpp @@ -15550,7 +15550,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP return DataModelLogger::LogValue("CurrentY", 1, value); } case ColorControl::Attributes::DriftCompensation::Id: { - uint8_t value; + chip::app::Clusters::ColorControl::DriftCompensationEnum value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); return DataModelLogger::LogValue("DriftCompensation", 1, value); } @@ -15565,12 +15565,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP return DataModelLogger::LogValue("ColorTemperatureMireds", 1, value); } case ColorControl::Attributes::ColorMode::Id: { - uint8_t value; + chip::app::Clusters::ColorControl::ColorModeEnum value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); return DataModelLogger::LogValue("ColorMode", 1, value); } case ColorControl::Attributes::Options::Id: { - uint8_t value; + chip::BitMask value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); return DataModelLogger::LogValue("Options", 1, value); } @@ -15730,7 +15730,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP return DataModelLogger::LogValue("EnhancedCurrentHue", 1, value); } case ColorControl::Attributes::EnhancedColorMode::Id: { - uint8_t value; + chip::app::Clusters::ColorControl::EnhancedColorModeEnum value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); return DataModelLogger::LogValue("EnhancedColorMode", 1, value); } @@ -15760,7 +15760,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP return DataModelLogger::LogValue("ColorLoopStoredEnhancedHue", 1, value); } case ColorControl::Attributes::ColorCapabilities::Id: { - uint16_t value; + chip::BitMask value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); return DataModelLogger::LogValue("ColorCapabilities", 1, value); } 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 a61f2a6fa6..004bb29c54 100644 --- a/zzz_generated/darwin-framework-tool/zap-generated/cluster/Commands.h +++ b/zzz_generated/darwin-framework-tool/zap-generated/cluster/Commands.h @@ -117680,8 +117680,8 @@ class ColorControlMoveToHue : public ClusterCommand { params.hue = [NSNumber numberWithUnsignedChar:mRequest.hue]; params.direction = [NSNumber numberWithUnsignedChar:chip::to_underlying(mRequest.direction)]; params.transitionTime = [NSNumber numberWithUnsignedShort:mRequest.transitionTime]; - params.optionsMask = [NSNumber numberWithUnsignedChar:mRequest.optionsMask]; - params.optionsOverride = [NSNumber numberWithUnsignedChar:mRequest.optionsOverride]; + params.optionsMask = [NSNumber numberWithUnsignedChar:mRequest.optionsMask.Raw()]; + params.optionsOverride = [NSNumber numberWithUnsignedChar:mRequest.optionsOverride.Raw()]; uint16_t repeatCount = mRepeatCount.ValueOr(1); uint16_t __block responsesNeeded = repeatCount; while (repeatCount--) { @@ -117733,8 +117733,8 @@ class ColorControlMoveHue : public ClusterCommand { params.timedInvokeTimeoutMs = mTimedInteractionTimeoutMs.HasValue() ? [NSNumber numberWithUnsignedShort:mTimedInteractionTimeoutMs.Value()] : nil; params.moveMode = [NSNumber numberWithUnsignedChar:chip::to_underlying(mRequest.moveMode)]; params.rate = [NSNumber numberWithUnsignedChar:mRequest.rate]; - params.optionsMask = [NSNumber numberWithUnsignedChar:mRequest.optionsMask]; - params.optionsOverride = [NSNumber numberWithUnsignedChar:mRequest.optionsOverride]; + params.optionsMask = [NSNumber numberWithUnsignedChar:mRequest.optionsMask.Raw()]; + params.optionsOverride = [NSNumber numberWithUnsignedChar:mRequest.optionsOverride.Raw()]; uint16_t repeatCount = mRepeatCount.ValueOr(1); uint16_t __block responsesNeeded = repeatCount; while (repeatCount--) { @@ -117788,8 +117788,8 @@ class ColorControlStepHue : public ClusterCommand { params.stepMode = [NSNumber numberWithUnsignedChar:chip::to_underlying(mRequest.stepMode)]; params.stepSize = [NSNumber numberWithUnsignedChar:mRequest.stepSize]; params.transitionTime = [NSNumber numberWithUnsignedChar:mRequest.transitionTime]; - params.optionsMask = [NSNumber numberWithUnsignedChar:mRequest.optionsMask]; - params.optionsOverride = [NSNumber numberWithUnsignedChar:mRequest.optionsOverride]; + params.optionsMask = [NSNumber numberWithUnsignedChar:mRequest.optionsMask.Raw()]; + params.optionsOverride = [NSNumber numberWithUnsignedChar:mRequest.optionsOverride.Raw()]; uint16_t repeatCount = mRepeatCount.ValueOr(1); uint16_t __block responsesNeeded = repeatCount; while (repeatCount--) { @@ -117841,8 +117841,8 @@ class ColorControlMoveToSaturation : public ClusterCommand { params.timedInvokeTimeoutMs = mTimedInteractionTimeoutMs.HasValue() ? [NSNumber numberWithUnsignedShort:mTimedInteractionTimeoutMs.Value()] : nil; params.saturation = [NSNumber numberWithUnsignedChar:mRequest.saturation]; params.transitionTime = [NSNumber numberWithUnsignedShort:mRequest.transitionTime]; - params.optionsMask = [NSNumber numberWithUnsignedChar:mRequest.optionsMask]; - params.optionsOverride = [NSNumber numberWithUnsignedChar:mRequest.optionsOverride]; + params.optionsMask = [NSNumber numberWithUnsignedChar:mRequest.optionsMask.Raw()]; + params.optionsOverride = [NSNumber numberWithUnsignedChar:mRequest.optionsOverride.Raw()]; uint16_t repeatCount = mRepeatCount.ValueOr(1); uint16_t __block responsesNeeded = repeatCount; while (repeatCount--) { @@ -117894,8 +117894,8 @@ class ColorControlMoveSaturation : public ClusterCommand { params.timedInvokeTimeoutMs = mTimedInteractionTimeoutMs.HasValue() ? [NSNumber numberWithUnsignedShort:mTimedInteractionTimeoutMs.Value()] : nil; params.moveMode = [NSNumber numberWithUnsignedChar:chip::to_underlying(mRequest.moveMode)]; params.rate = [NSNumber numberWithUnsignedChar:mRequest.rate]; - params.optionsMask = [NSNumber numberWithUnsignedChar:mRequest.optionsMask]; - params.optionsOverride = [NSNumber numberWithUnsignedChar:mRequest.optionsOverride]; + params.optionsMask = [NSNumber numberWithUnsignedChar:mRequest.optionsMask.Raw()]; + params.optionsOverride = [NSNumber numberWithUnsignedChar:mRequest.optionsOverride.Raw()]; uint16_t repeatCount = mRepeatCount.ValueOr(1); uint16_t __block responsesNeeded = repeatCount; while (repeatCount--) { @@ -117949,8 +117949,8 @@ class ColorControlStepSaturation : public ClusterCommand { params.stepMode = [NSNumber numberWithUnsignedChar:chip::to_underlying(mRequest.stepMode)]; params.stepSize = [NSNumber numberWithUnsignedChar:mRequest.stepSize]; params.transitionTime = [NSNumber numberWithUnsignedChar:mRequest.transitionTime]; - params.optionsMask = [NSNumber numberWithUnsignedChar:mRequest.optionsMask]; - params.optionsOverride = [NSNumber numberWithUnsignedChar:mRequest.optionsOverride]; + params.optionsMask = [NSNumber numberWithUnsignedChar:mRequest.optionsMask.Raw()]; + params.optionsOverride = [NSNumber numberWithUnsignedChar:mRequest.optionsOverride.Raw()]; uint16_t repeatCount = mRepeatCount.ValueOr(1); uint16_t __block responsesNeeded = repeatCount; while (repeatCount--) { @@ -118004,8 +118004,8 @@ class ColorControlMoveToHueAndSaturation : public ClusterCommand { params.hue = [NSNumber numberWithUnsignedChar:mRequest.hue]; params.saturation = [NSNumber numberWithUnsignedChar:mRequest.saturation]; params.transitionTime = [NSNumber numberWithUnsignedShort:mRequest.transitionTime]; - params.optionsMask = [NSNumber numberWithUnsignedChar:mRequest.optionsMask]; - params.optionsOverride = [NSNumber numberWithUnsignedChar:mRequest.optionsOverride]; + params.optionsMask = [NSNumber numberWithUnsignedChar:mRequest.optionsMask.Raw()]; + params.optionsOverride = [NSNumber numberWithUnsignedChar:mRequest.optionsOverride.Raw()]; uint16_t repeatCount = mRepeatCount.ValueOr(1); uint16_t __block responsesNeeded = repeatCount; while (repeatCount--) { @@ -118059,8 +118059,8 @@ class ColorControlMoveToColor : public ClusterCommand { params.colorX = [NSNumber numberWithUnsignedShort:mRequest.colorX]; params.colorY = [NSNumber numberWithUnsignedShort:mRequest.colorY]; params.transitionTime = [NSNumber numberWithUnsignedShort:mRequest.transitionTime]; - params.optionsMask = [NSNumber numberWithUnsignedChar:mRequest.optionsMask]; - params.optionsOverride = [NSNumber numberWithUnsignedChar:mRequest.optionsOverride]; + params.optionsMask = [NSNumber numberWithUnsignedChar:mRequest.optionsMask.Raw()]; + params.optionsOverride = [NSNumber numberWithUnsignedChar:mRequest.optionsOverride.Raw()]; uint16_t repeatCount = mRepeatCount.ValueOr(1); uint16_t __block responsesNeeded = repeatCount; while (repeatCount--) { @@ -118112,8 +118112,8 @@ class ColorControlMoveColor : public ClusterCommand { params.timedInvokeTimeoutMs = mTimedInteractionTimeoutMs.HasValue() ? [NSNumber numberWithUnsignedShort:mTimedInteractionTimeoutMs.Value()] : nil; params.rateX = [NSNumber numberWithShort:mRequest.rateX]; params.rateY = [NSNumber numberWithShort:mRequest.rateY]; - params.optionsMask = [NSNumber numberWithUnsignedChar:mRequest.optionsMask]; - params.optionsOverride = [NSNumber numberWithUnsignedChar:mRequest.optionsOverride]; + params.optionsMask = [NSNumber numberWithUnsignedChar:mRequest.optionsMask.Raw()]; + params.optionsOverride = [NSNumber numberWithUnsignedChar:mRequest.optionsOverride.Raw()]; uint16_t repeatCount = mRepeatCount.ValueOr(1); uint16_t __block responsesNeeded = repeatCount; while (repeatCount--) { @@ -118167,8 +118167,8 @@ class ColorControlStepColor : public ClusterCommand { params.stepX = [NSNumber numberWithShort:mRequest.stepX]; params.stepY = [NSNumber numberWithShort:mRequest.stepY]; params.transitionTime = [NSNumber numberWithUnsignedShort:mRequest.transitionTime]; - params.optionsMask = [NSNumber numberWithUnsignedChar:mRequest.optionsMask]; - params.optionsOverride = [NSNumber numberWithUnsignedChar:mRequest.optionsOverride]; + params.optionsMask = [NSNumber numberWithUnsignedChar:mRequest.optionsMask.Raw()]; + params.optionsOverride = [NSNumber numberWithUnsignedChar:mRequest.optionsOverride.Raw()]; uint16_t repeatCount = mRepeatCount.ValueOr(1); uint16_t __block responsesNeeded = repeatCount; while (repeatCount--) { @@ -118220,8 +118220,8 @@ class ColorControlMoveToColorTemperature : public ClusterCommand { params.timedInvokeTimeoutMs = mTimedInteractionTimeoutMs.HasValue() ? [NSNumber numberWithUnsignedShort:mTimedInteractionTimeoutMs.Value()] : nil; params.colorTemperatureMireds = [NSNumber numberWithUnsignedShort:mRequest.colorTemperatureMireds]; params.transitionTime = [NSNumber numberWithUnsignedShort:mRequest.transitionTime]; - params.optionsMask = [NSNumber numberWithUnsignedChar:mRequest.optionsMask]; - params.optionsOverride = [NSNumber numberWithUnsignedChar:mRequest.optionsOverride]; + params.optionsMask = [NSNumber numberWithUnsignedChar:mRequest.optionsMask.Raw()]; + params.optionsOverride = [NSNumber numberWithUnsignedChar:mRequest.optionsOverride.Raw()]; uint16_t repeatCount = mRepeatCount.ValueOr(1); uint16_t __block responsesNeeded = repeatCount; while (repeatCount--) { @@ -118275,8 +118275,8 @@ class ColorControlEnhancedMoveToHue : public ClusterCommand { params.enhancedHue = [NSNumber numberWithUnsignedShort:mRequest.enhancedHue]; params.direction = [NSNumber numberWithUnsignedChar:chip::to_underlying(mRequest.direction)]; params.transitionTime = [NSNumber numberWithUnsignedShort:mRequest.transitionTime]; - params.optionsMask = [NSNumber numberWithUnsignedChar:mRequest.optionsMask]; - params.optionsOverride = [NSNumber numberWithUnsignedChar:mRequest.optionsOverride]; + params.optionsMask = [NSNumber numberWithUnsignedChar:mRequest.optionsMask.Raw()]; + params.optionsOverride = [NSNumber numberWithUnsignedChar:mRequest.optionsOverride.Raw()]; uint16_t repeatCount = mRepeatCount.ValueOr(1); uint16_t __block responsesNeeded = repeatCount; while (repeatCount--) { @@ -118328,8 +118328,8 @@ class ColorControlEnhancedMoveHue : public ClusterCommand { params.timedInvokeTimeoutMs = mTimedInteractionTimeoutMs.HasValue() ? [NSNumber numberWithUnsignedShort:mTimedInteractionTimeoutMs.Value()] : nil; params.moveMode = [NSNumber numberWithUnsignedChar:chip::to_underlying(mRequest.moveMode)]; params.rate = [NSNumber numberWithUnsignedShort:mRequest.rate]; - params.optionsMask = [NSNumber numberWithUnsignedChar:mRequest.optionsMask]; - params.optionsOverride = [NSNumber numberWithUnsignedChar:mRequest.optionsOverride]; + params.optionsMask = [NSNumber numberWithUnsignedChar:mRequest.optionsMask.Raw()]; + params.optionsOverride = [NSNumber numberWithUnsignedChar:mRequest.optionsOverride.Raw()]; uint16_t repeatCount = mRepeatCount.ValueOr(1); uint16_t __block responsesNeeded = repeatCount; while (repeatCount--) { @@ -118383,8 +118383,8 @@ class ColorControlEnhancedStepHue : public ClusterCommand { params.stepMode = [NSNumber numberWithUnsignedChar:chip::to_underlying(mRequest.stepMode)]; params.stepSize = [NSNumber numberWithUnsignedShort:mRequest.stepSize]; params.transitionTime = [NSNumber numberWithUnsignedShort:mRequest.transitionTime]; - params.optionsMask = [NSNumber numberWithUnsignedChar:mRequest.optionsMask]; - params.optionsOverride = [NSNumber numberWithUnsignedChar:mRequest.optionsOverride]; + params.optionsMask = [NSNumber numberWithUnsignedChar:mRequest.optionsMask.Raw()]; + params.optionsOverride = [NSNumber numberWithUnsignedChar:mRequest.optionsOverride.Raw()]; uint16_t repeatCount = mRepeatCount.ValueOr(1); uint16_t __block responsesNeeded = repeatCount; while (repeatCount--) { @@ -118438,8 +118438,8 @@ class ColorControlEnhancedMoveToHueAndSaturation : public ClusterCommand { params.enhancedHue = [NSNumber numberWithUnsignedShort:mRequest.enhancedHue]; params.saturation = [NSNumber numberWithUnsignedChar:mRequest.saturation]; params.transitionTime = [NSNumber numberWithUnsignedShort:mRequest.transitionTime]; - params.optionsMask = [NSNumber numberWithUnsignedChar:mRequest.optionsMask]; - params.optionsOverride = [NSNumber numberWithUnsignedChar:mRequest.optionsOverride]; + params.optionsMask = [NSNumber numberWithUnsignedChar:mRequest.optionsMask.Raw()]; + params.optionsOverride = [NSNumber numberWithUnsignedChar:mRequest.optionsOverride.Raw()]; uint16_t repeatCount = mRepeatCount.ValueOr(1); uint16_t __block responsesNeeded = repeatCount; while (repeatCount--) { @@ -118497,8 +118497,8 @@ class ColorControlColorLoopSet : public ClusterCommand { params.direction = [NSNumber numberWithUnsignedChar:chip::to_underlying(mRequest.direction)]; params.time = [NSNumber numberWithUnsignedShort:mRequest.time]; params.startHue = [NSNumber numberWithUnsignedShort:mRequest.startHue]; - params.optionsMask = [NSNumber numberWithUnsignedChar:mRequest.optionsMask]; - params.optionsOverride = [NSNumber numberWithUnsignedChar:mRequest.optionsOverride]; + params.optionsMask = [NSNumber numberWithUnsignedChar:mRequest.optionsMask.Raw()]; + params.optionsOverride = [NSNumber numberWithUnsignedChar:mRequest.optionsOverride.Raw()]; uint16_t repeatCount = mRepeatCount.ValueOr(1); uint16_t __block responsesNeeded = repeatCount; while (repeatCount--) { @@ -118546,8 +118546,8 @@ class ColorControlStopMoveStep : public ClusterCommand { __auto_type * cluster = [[MTRBaseClusterColorControl alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; __auto_type * params = [[MTRColorControlClusterStopMoveStepParams alloc] init]; params.timedInvokeTimeoutMs = mTimedInteractionTimeoutMs.HasValue() ? [NSNumber numberWithUnsignedShort:mTimedInteractionTimeoutMs.Value()] : nil; - params.optionsMask = [NSNumber numberWithUnsignedChar:mRequest.optionsMask]; - params.optionsOverride = [NSNumber numberWithUnsignedChar:mRequest.optionsOverride]; + params.optionsMask = [NSNumber numberWithUnsignedChar:mRequest.optionsMask.Raw()]; + params.optionsOverride = [NSNumber numberWithUnsignedChar:mRequest.optionsOverride.Raw()]; uint16_t repeatCount = mRepeatCount.ValueOr(1); uint16_t __block responsesNeeded = repeatCount; while (repeatCount--) { @@ -118603,8 +118603,8 @@ class ColorControlMoveColorTemperature : public ClusterCommand { params.rate = [NSNumber numberWithUnsignedShort:mRequest.rate]; params.colorTemperatureMinimumMireds = [NSNumber numberWithUnsignedShort:mRequest.colorTemperatureMinimumMireds]; params.colorTemperatureMaximumMireds = [NSNumber numberWithUnsignedShort:mRequest.colorTemperatureMaximumMireds]; - params.optionsMask = [NSNumber numberWithUnsignedChar:mRequest.optionsMask]; - params.optionsOverride = [NSNumber numberWithUnsignedChar:mRequest.optionsOverride]; + params.optionsMask = [NSNumber numberWithUnsignedChar:mRequest.optionsMask.Raw()]; + params.optionsOverride = [NSNumber numberWithUnsignedChar:mRequest.optionsOverride.Raw()]; uint16_t repeatCount = mRepeatCount.ValueOr(1); uint16_t __block responsesNeeded = repeatCount; while (repeatCount--) { @@ -118662,8 +118662,8 @@ class ColorControlStepColorTemperature : public ClusterCommand { params.transitionTime = [NSNumber numberWithUnsignedShort:mRequest.transitionTime]; params.colorTemperatureMinimumMireds = [NSNumber numberWithUnsignedShort:mRequest.colorTemperatureMinimumMireds]; params.colorTemperatureMaximumMireds = [NSNumber numberWithUnsignedShort:mRequest.colorTemperatureMaximumMireds]; - params.optionsMask = [NSNumber numberWithUnsignedChar:mRequest.optionsMask]; - params.optionsOverride = [NSNumber numberWithUnsignedChar:mRequest.optionsOverride]; + params.optionsMask = [NSNumber numberWithUnsignedChar:mRequest.optionsMask.Raw()]; + params.optionsOverride = [NSNumber numberWithUnsignedChar:mRequest.optionsOverride.Raw()]; uint16_t repeatCount = mRepeatCount.ValueOr(1); uint16_t __block responsesNeeded = repeatCount; while (repeatCount--) { From 0c4dde5230d5b0e3eb349b5411ceb356ddf2622e Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Wed, 21 Aug 2024 14:03:08 -0400 Subject: [PATCH 123/165] Update Darwin availability annotations. (#35108) --- .../CHIP/templates/availability.yaml | 51 ++++++++++++++++++- 1 file changed, 50 insertions(+), 1 deletion(-) diff --git a/src/darwin/Framework/CHIP/templates/availability.yaml b/src/darwin/Framework/CHIP/templates/availability.yaml index 507e19eae0..c1f1e1bd6f 100644 --- a/src/darwin/Framework/CHIP/templates/availability.yaml +++ b/src/darwin/Framework/CHIP/templates/availability.yaml @@ -9694,6 +9694,13 @@ - WaterHeaterMode - WiFiNetworkManagement attributes: + AccessControl: + # Targeting 1.4 + - CommissioningARL + - ARL + BridgedDeviceBasicInformation: + # Targeting 1.4 + - ProductID GeneralCommissioning: # Targeting 1.4 - TCAcceptedVersion @@ -9712,6 +9719,10 @@ - NullableGlobalEnum - NullableGlobalStruct commands: + AccessControl: + # Targeting 1.4 + - ReviewFabricRestrictions + - ReviewFabricRestrictionsResponse BridgedDeviceBasicInformation: # Targeting 1.4 - KeepActive @@ -9719,6 +9730,10 @@ # Targeting 1.4 - SetTCAcknowledgements - SetTCAcknowledgementsResponse + Thermostat: + # Targeting 1.4 + - AtomicRequest + - AtomicResponse UnitTesting: # Ideally none of UnitTesting would be exposed as public API, but # for now just start doing that for new additions to it. @@ -9727,9 +9742,17 @@ - StringEchoRequest - StringEchoResponse structs: + AccessControl: + # Targeting 1.4 + - AccessRestrictionEntryStruct + - AccessRestrictionStruct + - CommissioningAccessRestrictionEntryStruct Globals: # Test-only value - TestGlobalStruct + # Targeting 1.4 + - AtomicAttributeStatusStruct + - LocationDescriptorStruct OccupancySensing: # Targeting 1.4 - HoldTimeLimitsStruct @@ -9742,21 +9765,44 @@ NestedStruct: - d events: + AccessControl: + # Targeting 1.4 + - AccessRestrictionEntryChanged + - FabricRestrictionReviewUpdate BridgedDeviceBasicInformation: # Targeting 1.4 - ActiveChanged enums: + AccessControl: + # Targeting 1.4 + - AccessRestrictionTypeEnum Globals: # Test-only value - TestGlobalEnum + # Targeting 1.4 + - AreaTypeTag + - AtomicRequestTypeEnum + - FloorSurfaceTag + - LandmarkTag + - PositionTag + - RelativePositionTag enum values: + ApplicationLauncher: + StatusEnum: + # Targeting 1.4 + - Downloading + - Installing + - PendingUserApproval GeneralCommissioning: - # Targeting 1.4 CommissioningErrorEnum: + # Targeting 1.4 - RequiredTCNotAccepted - TCAcknowledgementsNotReceived - TCMinVersionNotMet bitmaps: + AccessControl: + # Targeting 1.4 + - Feature BridgedDeviceBasicInformation: # Targeting 1.4 - Feature @@ -9766,6 +9812,9 @@ OccupancySensing: # Targeting 1.4 - Feature + Thermostat: + # Targeting 1.4 + - OccupancyBitmap bitmap values: Switch: Feature: From 229df0c9d8cf5d58ce20ba7411de6b4de68891af Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Wed, 21 Aug 2024 14:04:16 -0400 Subject: [PATCH 124/165] Make descriptions for MTRDevice clearly say whether it's the XPC version. (#35112) This requires hoisting _nodeID and _deviceController ivars clearly into the MTRDevice superclass, so they can be accessed from subclasses. The XPC version does not have a bunch of the state the non-XPC one does, so for now it does not try to log that --- src/darwin/Framework/CHIP/MTRDevice.mm | 73 ------------------- .../Framework/CHIP/MTRDevice_Concrete.mm | 8 +- .../Framework/CHIP/MTRDevice_Internal.h | 8 ++ src/darwin/Framework/CHIP/MTRDevice_XPC.mm | 10 +++ 4 files changed, 19 insertions(+), 80 deletions(-) diff --git a/src/darwin/Framework/CHIP/MTRDevice.mm b/src/darwin/Framework/CHIP/MTRDevice.mm index 4fc30b90b3..f17e6d5c90 100644 --- a/src/darwin/Framework/CHIP/MTRDevice.mm +++ b/src/darwin/Framework/CHIP/MTRDevice.mm @@ -173,23 +173,6 @@ bool HaveSubscriptionEstablishedRightNow(MTRInternalDeviceState state) return state == MTRInternalDeviceStateInitialSubscriptionEstablished || state == MTRInternalDeviceStateLaterSubscriptionEstablished; } -NSString * InternalDeviceStateString(MTRInternalDeviceState state) -{ - switch (state) { - case MTRInternalDeviceStateUnsubscribed: - return @"Unsubscribed"; - case MTRInternalDeviceStateSubscribing: - return @"Subscribing"; - case MTRInternalDeviceStateInitialSubscriptionEstablished: - return @"InitialSubscriptionEstablished"; - case MTRInternalDeviceStateResubscribing: - return @"Resubscribing"; - case MTRInternalDeviceStateLaterSubscriptionEstablished: - return @"LaterSubscriptionEstablished"; - default: - return @"Unknown"; - } -} } // anonymous namespace typedef NS_ENUM(NSUInteger, MTRDeviceExpectedValueFieldIndex) { @@ -548,62 +531,6 @@ - (void)dealloc MTR_LOG("MTRDevice dealloc: %p", self); } -- (NSString *)description -{ - id _Nullable vid; - id _Nullable pid; - NSNumber * _Nullable networkFeatures; - MTRInternalDeviceState internalDeviceState; - uint32_t lastSubscriptionAttemptWait; - NSDate * _Nullable mostRecentReportTime; - NSDate * _Nullable lastSubscriptionFailureTime; - { - std::lock_guard lock(_descriptionLock); - vid = _vid; - pid = _pid; - networkFeatures = _allNetworkFeatures; - internalDeviceState = _internalDeviceStateForDescription; - lastSubscriptionAttemptWait = _lastSubscriptionAttemptWaitForDescription; - mostRecentReportTime = _mostRecentReportTimeForDescription; - lastSubscriptionFailureTime = _lastSubscriptionFailureTimeForDescription; - } - - if (vid == nil) { - vid = @"Unknown"; - } - - if (pid == nil) { - pid = @"Unknown"; - } - - NSString * wifi; - NSString * thread; - if (networkFeatures == nil) { - wifi = @"NO"; - thread = @"NO"; - } else { - wifi = YES_NO(networkFeatures.unsignedLongLongValue & MTRNetworkCommissioningFeatureWiFiNetworkInterface); - thread = YES_NO(networkFeatures.unsignedLongLongValue & MTRNetworkCommissioningFeatureThreadNetworkInterface); - } - - NSString * reportAge; - if (mostRecentReportTime) { - reportAge = [NSString stringWithFormat:@" (%.0lfs ago)", -[mostRecentReportTime timeIntervalSinceNow]]; - } else { - reportAge = @""; - } - - NSString * subscriptionFailureAge; - if (lastSubscriptionFailureTime) { - subscriptionFailureAge = [NSString stringWithFormat:@" (%.0lfs ago)", -[lastSubscriptionFailureTime timeIntervalSinceNow]]; - } else { - subscriptionFailureAge = @""; - } - - return [NSString - stringWithFormat:@"", self, _deviceController.compressedFabricID.unsignedLongLongValue, _nodeID.unsignedLongLongValue, _nodeID.unsignedLongLongValue, vid, pid, wifi, thread, InternalDeviceStateString(internalDeviceState), static_cast(lastSubscriptionAttemptWait), static_cast(_asyncWorkQueue.itemCount), mostRecentReportTime, reportAge, lastSubscriptionFailureTime, subscriptionFailureAge, _deviceController.uniqueIdentifier]; -} - + (MTRDevice *)deviceWithNodeID:(NSNumber *)nodeID controller:(MTRDeviceController *)controller { return [controller deviceForNodeID:nodeID]; diff --git a/src/darwin/Framework/CHIP/MTRDevice_Concrete.mm b/src/darwin/Framework/CHIP/MTRDevice_Concrete.mm index c9f4b7f07d..120d29aff1 100644 --- a/src/darwin/Framework/CHIP/MTRDevice_Concrete.mm +++ b/src/darwin/Framework/CHIP/MTRDevice_Concrete.mm @@ -58,8 +58,6 @@ // allow readwrite access to superclass properties @interface MTRDevice_Concrete () -@property (nonatomic, readwrite, copy) NSNumber * nodeID; -@property (nonatomic, readwrite, nullable) MTRDeviceController * deviceController; @property (nonatomic, readwrite) MTRAsyncWorkQueue * asyncWorkQueue; @property (nonatomic, readwrite) MTRDeviceState state; @property (nonatomic, readwrite, nullable) NSDate * estimatedStartTime; @@ -356,8 +354,6 @@ @implementation MTRDevice_Concrete { } // synthesize superclass property readwrite accessors -@synthesize nodeID = _nodeID; -@synthesize deviceController = _deviceController; @synthesize queue = _queue; @synthesize asyncWorkQueue = _asyncWorkQueue; @synthesize state = _state; @@ -372,9 +368,7 @@ - (instancetype)initWithNodeID:(NSNumber *)nodeID controller:(MTRDeviceControlle if (self = [super initForSubclassesWithNodeID:nodeID controller:controller]) { _timeSyncLock = OS_UNFAIR_LOCK_INIT; _descriptionLock = OS_UNFAIR_LOCK_INIT; - _nodeID = [nodeID copy]; _fabricIndex = controller.fabricIndex; - _deviceController = controller; _queue = dispatch_queue_create("org.csa-iot.matter.framework.device.workqueue", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); _expectedValueCache = [NSMutableDictionary dictionary]; @@ -467,7 +461,7 @@ - (NSString *)description } return [NSString - stringWithFormat:@"", self, _deviceController.compressedFabricID.unsignedLongLongValue, _nodeID.unsignedLongLongValue, _nodeID.unsignedLongLongValue, vid, pid, wifi, thread, InternalDeviceStateString(internalDeviceState), static_cast(lastSubscriptionAttemptWait), static_cast(_asyncWorkQueue.itemCount), mostRecentReportTime, reportAge, lastSubscriptionFailureTime, subscriptionFailureAge, _deviceController.uniqueIdentifier]; + stringWithFormat:@"", self, _deviceController.compressedFabricID.unsignedLongLongValue, _nodeID.unsignedLongLongValue, _nodeID.unsignedLongLongValue, vid, pid, wifi, thread, InternalDeviceStateString(internalDeviceState), static_cast(lastSubscriptionAttemptWait), static_cast(_asyncWorkQueue.itemCount), mostRecentReportTime, reportAge, lastSubscriptionFailureTime, subscriptionFailureAge, _deviceController.uniqueIdentifier]; } + (MTRDevice *)deviceWithNodeID:(NSNumber *)nodeID controller:(MTRDeviceController *)controller diff --git a/src/darwin/Framework/CHIP/MTRDevice_Internal.h b/src/darwin/Framework/CHIP/MTRDevice_Internal.h index bce5abfdfe..b6a59ac932 100644 --- a/src/darwin/Framework/CHIP/MTRDevice_Internal.h +++ b/src/darwin/Framework/CHIP/MTRDevice_Internal.h @@ -112,6 +112,14 @@ MTR_DIRECT_MEMBERS // Lock that protects overall device state, including delegate storage. os_unfair_lock _lock; NSMutableSet * _delegates; + + // Our node ID, with the ivar declared explicitly so it's accessible to + // subclasses. + NSNumber * _nodeID; + + // Our controller. Declared nullable because our property is, though in + // practice it does not look like we ever set it to nil. + MTRDeviceController * _Nullable _deviceController; } - (instancetype)initForSubclassesWithNodeID:(NSNumber *)nodeID controller:(MTRDeviceController *)controller; diff --git a/src/darwin/Framework/CHIP/MTRDevice_XPC.mm b/src/darwin/Framework/CHIP/MTRDevice_XPC.mm index 7dfb8da370..03f318d835 100644 --- a/src/darwin/Framework/CHIP/MTRDevice_XPC.mm +++ b/src/darwin/Framework/CHIP/MTRDevice_XPC.mm @@ -93,6 +93,16 @@ - (instancetype)initWithNodeID:(NSNumber *)nodeID controller:(MTRDeviceControlle return self; } +- (NSString *)description +{ + // TODO: Figure out whether, and if so how, to log: VID, PID, WiFi, Thread, + // internalDeviceState (do we even have such a thing here?), last + // subscription attempt wait (does that apply to us?) queued work (do we + // have any?), last report, last subscription failure (does that apply to us?). + return [NSString + stringWithFormat:@"", self, _deviceController.compressedFabricID.unsignedLongLongValue, _nodeID.unsignedLongLongValue, _nodeID.unsignedLongLongValue, _deviceController.uniqueIdentifier]; +} + #pragma mark - Client Callbacks (MTRDeviceDelegate) // required methods for MTRDeviceDelegates From 329c965cc41ed39399a123587efb72639174571a Mon Sep 17 00:00:00 2001 From: sarthak shaha <130495524+Sarthak-Shaha@users.noreply.github.com> Date: Wed, 21 Aug 2024 14:15:25 -0400 Subject: [PATCH 125/165] removed invalid symlinks (#35129) --- .../esp32/external_platform/ESP32_custom/WiFiDnssdImpl.cpp | 1 - .../esp32/external_platform/ESP32_custom/WiFiDnssdImpl.h | 1 - 2 files changed, 2 deletions(-) delete mode 120000 examples/platform/esp32/external_platform/ESP32_custom/WiFiDnssdImpl.cpp delete mode 120000 examples/platform/esp32/external_platform/ESP32_custom/WiFiDnssdImpl.h diff --git a/examples/platform/esp32/external_platform/ESP32_custom/WiFiDnssdImpl.cpp b/examples/platform/esp32/external_platform/ESP32_custom/WiFiDnssdImpl.cpp deleted file mode 120000 index 6ca9fce6a3..0000000000 --- a/examples/platform/esp32/external_platform/ESP32_custom/WiFiDnssdImpl.cpp +++ /dev/null @@ -1 +0,0 @@ -../../../../../src/platform/ESP32/WiFiDnssdImpl.cpp \ No newline at end of file diff --git a/examples/platform/esp32/external_platform/ESP32_custom/WiFiDnssdImpl.h b/examples/platform/esp32/external_platform/ESP32_custom/WiFiDnssdImpl.h deleted file mode 120000 index 213e499587..0000000000 --- a/examples/platform/esp32/external_platform/ESP32_custom/WiFiDnssdImpl.h +++ /dev/null @@ -1 +0,0 @@ -../../../../../src/platform/ESP32/WiFiDnssdImpl.h \ No newline at end of file From 68f0407592806c00b84ac3045c591e7287f3173e Mon Sep 17 00:00:00 2001 From: Terence Hampson Date: Wed, 21 Aug 2024 14:18:43 -0400 Subject: [PATCH 126/165] Update MCORE_FS_1_2 to latest testplan (#35097) --- src/python_testing/TC_MCORE_FS_1_2.py | 253 +++++++++++++++++--------- 1 file changed, 163 insertions(+), 90 deletions(-) diff --git a/src/python_testing/TC_MCORE_FS_1_2.py b/src/python_testing/TC_MCORE_FS_1_2.py index 1085b0fac0..c199225b33 100644 --- a/src/python_testing/TC_MCORE_FS_1_2.py +++ b/src/python_testing/TC_MCORE_FS_1_2.py @@ -19,27 +19,102 @@ # for details about the block below. # -import base64 +import hashlib import logging +import os import queue +import secrets +import signal +import struct +import subprocess import time +import uuid +from dataclasses import dataclass import chip.clusters as Clusters from chip import ChipDeviceCtrl -from matter_testing_support import MatterBaseTest, TestStep, async_test_body, default_matter_test_main +from ecdsa.curves import NIST256p +from matter_testing_support import MatterBaseTest, TestStep, async_test_body, default_matter_test_main, type_matches from mobly import asserts from TC_SC_3_6 import AttributeChangeAccumulator +# Length of `w0s` and `w1s` elements +WS_LENGTH = NIST256p.baselen + 8 + + +def _generate_verifier(passcode: int, salt: bytes, iterations: int) -> bytes: + ws = hashlib.pbkdf2_hmac('sha256', struct.pack('>> pairing onnetwork 111 {setup_params.passcode}") + def steps_TC_MCORE_FS_1_2(self) -> list[TestStep]: - steps = [TestStep(1, "TH_FSA subscribes to all the Bridged Device Basic Information clusters provided by DUT_FSA to identify the presence of a Bridged Node endpoint with a UniqueID matching the UniqueID provided by the BasicInformationCluster of the TH_SED_DUT."), - TestStep(2, "TH_FSA initiates commissioning of TH_SED_DUT by sending the OpenCommissioningWindow command to the Administrator Commissioning Cluster on the endpoint with the uniqueID matching that of TH_SED_DUT."), - TestStep(3, "TH_FSA completes commissioning of TH_SED_DUT using the Enhanced Commissioning Method."), - TestStep(4, "Commission TH_SED_L onto DUT_FSA’s fabric using the manufacturer specified mechanism."), - TestStep(5, "TH_FSA waits for subscription report from a the Bridged Device Basic Information clusters provided by DUT_FSA to identify the presence of a Bridged Node endpoint with a UniqueID matching the UniqueID provided by the BasicInformationCluster of the TH_SED_L."), - TestStep(6, "TH_FSA initiates commissions of TH_SED_L by sending the OpenCommissioningWindow command to the Administrator Commissioning Cluster on the endpoint with the uniqueID matching that of TH_SED_L."), - TestStep(7, "TH_FSA completes commissioning of TH_SED_L using the Enhanced Commissioning Method.")] + steps = [TestStep(1, "TH subscribes to PartsList attribute of the Descriptor cluster of DUT_FSA endpoint 0."), + TestStep(2, "Follow manufacturer provided instructions to have DUT_FSA commission TH_SERVER"), + TestStep(3, "TH waits up to 30 seconds for subscription report from the PartsList attribute of the Descriptor to contain new endpoint"), + + TestStep(4, "TH uses DUT to open commissioning window to TH_SERVER"), + TestStep(5, "TH commissions TH_SERVER"), + TestStep(6, "TH reads all attributes in Basic Information cluster from TH_SERVER directly"), + TestStep(7, "TH reads all attributes in the Bridged Device Basic Information cluster on new endpoint identified in step 3 from the DUT_FSA")] return steps @property @@ -49,16 +124,21 @@ def default_timeout(self) -> int: @async_test_body async def test_TC_MCORE_FS_1_2(self): self.is_ci = self.check_pics('PICS_SDK_CI_ONLY') + min_report_interval_sec = self.user_params.get("min_report_interval_sec", 0) - max_report_interval_sec = self.user_params.get("max_report_interval_sec", 2) - report_waiting_timeout_delay_sec = self.user_params.get("report_waiting_timeout_delay_sec", 10) + max_report_interval_sec = self.user_params.get("max_report_interval_sec", 30) + th_server_port = self.user_params.get("th_server_port", 5543) + self._th_server_app_path = self.user_params.get("th_server_app_path", None) + if not self._th_server_app_path: + asserts.fail('This test requires a TH_SERVER app. Specify app path with --string-arg th_server_app_path:') + if not os.path.exists(self._th_server_app_path): + asserts.fail(f'The path {self._th_server_app_path} does not exist') self.step(1) - - # Subscribe to the UniqueIDs - unique_id_queue = queue.Queue() + # Subscribe to the PartsList + root_endpoint = 0 subscription_contents = [ - (Clusters.BridgedDeviceBasicInformation.Attributes.UniqueID) # On all endpoints + (root_endpoint, Clusters.Descriptor.Attributes.PartsList) ] sub = await self.default_controller.ReadAttribute( nodeid=self.dut_node_id, @@ -66,82 +146,38 @@ async def test_TC_MCORE_FS_1_2(self): reportInterval=(min_report_interval_sec, max_report_interval_sec), keepSubscriptions=False ) + + parts_list_queue = queue.Queue() attribute_handler = AttributeChangeAccumulator( - name=self.default_controller.name, expected_attribute=Clusters.BridgedDeviceBasicInformation.Attributes.UniqueID, output=unique_id_queue) + name=self.default_controller.name, expected_attribute=Clusters.Descriptor.Attributes.PartsList, output=parts_list_queue) sub.SetAttributeUpdateCallback(attribute_handler) + cached_attributes = sub.GetAttributes() + step_1_dut_parts_list = cached_attributes[root_endpoint][Clusters.Descriptor][Clusters.Descriptor.Attributes.PartsList] - logging.info("Waiting for First BridgedDeviceBasicInformation.") - start_time = time.time() - elapsed = 0 - time_remaining = report_waiting_timeout_delay_sec - - th_sed_dut_bdbi_endpoint = -1 - th_sed_dut_unique_id = -1 - - while time_remaining > 0 and th_sed_dut_bdbi_endpoint < 0: - try: - item = unique_id_queue.get(block=True, timeout=time_remaining) - endpoint, attribute, value = item['endpoint'], item['attribute'], item['value'] - - # Record arrival of an expected subscription change when seen - if attribute == Clusters.BridgedDeviceBasicInformation.Attributes.UniqueID: - th_sed_dut_bdbi_endpoint = endpoint - th_sed_dut_unique_id = value - - 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 - - asserts.assert_greater(th_sed_dut_bdbi_endpoint, 0, "Failed to find any BDBI instances with UniqueID present.") - logging.info("Found BDBI with UniqueID (%d) on endpoint %d." % th_sed_dut_unique_id, th_sed_dut_bdbi_endpoint) + asserts.assert_true(type_matches(step_1_dut_parts_list, list), "PartsList is expected to be a list") self.step(2) - - self.sync_passcode = 20202024 - self.th_sed_dut_discriminator = 2222 - cmd = Clusters.AdministratorCommissioning.Commands.OpenCommissioningWindow(commissioningTimeout=3*60, - PAKEPasscodeVerifier=b"+w1qZQR05Zn0bc2LDyNaDAhsrhDS5iRHPTN10+EmNx8E2OpIPC4SjWRDQVOgqcbnXdYMlpiZ168xLBqn1fx9659gGK/7f9Yc6GxpoJH8kwAUYAYyLGsYeEBt1kL6kpXjgA==", - discriminator=self.th_sed_dut_discriminator, - iterations=10000, salt=base64.b64encode(bytes('SaltyMcSalterson', 'utf-8'))) - await self.send_single_cmd(cmd, endpoint=th_sed_dut_bdbi_endpoint, timedRequestTimeoutMs=5000) - - logging.info("Commissioning Window open for TH_SED_DUT.") + setup_params = await self._create_th_server(th_server_port) + self._ask_for_vendor_commissioning_ux_operation(setup_params) self.step(3) - - self.th_sed_dut_nodeid = 1111 - await self.TH_server_controller.CommissionOnNetwork(nodeId=self.th_sed_dut_nodeid, setupPinCode=self.sync_passcode, filterType=ChipDeviceCtrl.DiscoveryFilterType.LONG_DISCRIMINATOR, filter=self.th_sed_dut_discriminator) - logging.info("Commissioning TH_SED_DUT complete") - - self.step(4) - if not self.is_ci: - self.wait_for_user_input( - "Commission TH_SED_DUT onto DUT_FSA’s fabric using the manufacturer specified mechanism. (ensure Synchronization is enabled.)") - else: - logging.info("Stopping after step 3 while running in CI to avoid manual steps.") - return - - self.step(5) - - th_sed_later_bdbi_endpoint = -1 - th_sed_later_unique_id = -1 - logging.info("Waiting for Second BridgedDeviceBasicInformation.") + report_waiting_timeout_delay_sec = 30 + logging.info("Waiting for update to PartsList.") start_time = time.time() elapsed = 0 time_remaining = report_waiting_timeout_delay_sec - while time_remaining > 0 and th_sed_later_bdbi_endpoint < 0: + parts_list_endpoint_count_from_step_1 = len(step_1_dut_parts_list) + step_3_dut_parts_list = None + while time_remaining > 0: try: - item = unique_id_queue.get(block=True, timeout=time_remaining) + item = parts_list_queue.get(block=True, timeout=time_remaining) endpoint, attribute, value = item['endpoint'], item['attribute'], item['value'] # Record arrival of an expected subscription change when seen - if attribute == Clusters.BridgedDeviceBasicInformation.Attributes.UniqueID and endpoint != th_sed_dut_bdbi_endpoint and th_sed_later_unique_id != th_sed_dut_unique_id: - th_sed_later_bdbi_endpoint = endpoint - th_sed_later_unique_id = value + if endpoint == root_endpoint and attribute == Clusters.Descriptor.Attributes.PartsList and len(value) > parts_list_endpoint_count_from_step_1: + step_3_dut_parts_list = value + break except queue.Empty: # No error, we update timeouts and keep going @@ -150,26 +186,63 @@ async def test_TC_MCORE_FS_1_2(self): elapsed = time.time() - start_time time_remaining = report_waiting_timeout_delay_sec - elapsed - asserts.assert_greater(th_sed_later_bdbi_endpoint, 0, "Failed to find any BDBI instances with UniqueID present.") - logging.info("Found another BDBI with UniqueID (%d) on endpoint %d." % th_sed_later_unique_id, th_sed_later_bdbi_endpoint) + asserts.assert_not_equal(step_3_dut_parts_list, None, "Timed out getting updated PartsList with new endpoint") + set_of_step_1_parts_list_endpoint = set(step_1_dut_parts_list) + set_of_step_3_parts_list_endpoint = set(step_3_dut_parts_list) + unique_endpoints_set = set_of_step_3_parts_list_endpoint - set_of_step_1_parts_list_endpoint + asserts.assert_equal(len(unique_endpoints_set), 1, "Expected only one new endpoint") + newly_added_endpoint = list(unique_endpoints_set)[0] - self.step(6) + self.step(4) - self.th_sed_later_discriminator = 3333 - # min commissioning timeout is 3*60 seconds, so use that even though the command said 30. + discriminator = 3840 + passcode = 20202021 + salt = secrets.token_bytes(16) + iterations = 2000 + verifier = _generate_verifier(passcode, salt, iterations) + + # min commissioning timeout is 3*60 seconds cmd = Clusters.AdministratorCommissioning.Commands.OpenCommissioningWindow(commissioningTimeout=3*60, - PAKEPasscodeVerifier=b"+w1qZQR05Zn0bc2LDyNaDAhsrhDS5iRHPTN10+EmNx8E2OpIPC4SjWRDQVOgqcbnXdYMlpiZ168xLBqn1fx9659gGK/7f9Yc6GxpoJH8kwAUYAYyLGsYeEBt1kL6kpXjgA==", - discriminator=self.th_sed_later_discriminator, - iterations=10000, salt=base64.b64encode(bytes('SaltyMcSalterson', 'utf-8'))) - await self.send_single_cmd(cmd, endpoint=th_sed_later_bdbi_endpoint, timedRequestTimeoutMs=5000) + PAKEPasscodeVerifier=verifier, + discriminator=discriminator, + iterations=iterations, + salt=salt) + await self.send_single_cmd(cmd, dev_ctrl=self.default_controller, node_id=self.dut_node_id, endpoint=newly_added_endpoint, timedRequestTimeoutMs=5000) - logging.info("Commissioning Window open for TH_SED_L.") + self.step(5) + self.th_server_local_nodeid = 1111 + await self.default_controller.CommissionOnNetwork(nodeId=self.th_server_local_nodeid, setupPinCode=passcode, filterType=ChipDeviceCtrl.DiscoveryFilterType.LONG_DISCRIMINATOR, filter=discriminator) - self.step(7) + self.step(6) + th_server_directly_read_result = await self.default_controller.ReadAttribute(self.th_server_local_nodeid, [(root_endpoint, Clusters.BasicInformation)]) + th_server_basic_info = th_server_directly_read_result[root_endpoint][Clusters.BasicInformation] - self.th_sed_later_nodeid = 2222 - await self.TH_server_controller.CommissionOnNetwork(nodeId=self.th_sed_later_nodeid, setupPinCode=self.sync_passcode, filterType=ChipDeviceCtrl.DiscoveryFilterType.LONG_DISCRIMINATOR, filter=self.th_sed_later_discriminator) - logging.info("Commissioning TH_SED_L complete") + self.step(7) + dut_read = await self.default_controller.ReadAttribute(self.dut_node_id, [(newly_added_endpoint, Clusters.BridgedDeviceBasicInformation)]) + bridged_info_for_th_server = dut_read[newly_added_endpoint][Clusters.BridgedDeviceBasicInformation] + basic_info_attr = Clusters.BasicInformation.Attributes + bridged_device_info_attr = Clusters.BridgedDeviceBasicInformation.Attributes + Clusters.BasicInformation.Attributes + asserts.assert_equal(th_server_basic_info[basic_info_attr.VendorName], + bridged_info_for_th_server[bridged_device_info_attr.VendorName], "VendorName incorrectly reported by DUT") + asserts.assert_equal(th_server_basic_info[basic_info_attr.VendorID], + bridged_info_for_th_server[bridged_device_info_attr.VendorID], "VendorID incorrectly reported by DUT") + asserts.assert_equal(th_server_basic_info[basic_info_attr.ProductName], + bridged_info_for_th_server[bridged_device_info_attr.ProductName], "ProductName incorrectly reported by DUT") + asserts.assert_equal(th_server_basic_info[basic_info_attr.ProductID], + bridged_info_for_th_server[bridged_device_info_attr.ProductID], "ProductID incorrectly reported by DUT") + asserts.assert_equal(th_server_basic_info[basic_info_attr.NodeLabel], + bridged_info_for_th_server[bridged_device_info_attr.NodeLabel], "NodeLabel incorrectly reported by DUT") + asserts.assert_equal(th_server_basic_info[basic_info_attr.HardwareVersion], + bridged_info_for_th_server[bridged_device_info_attr.HardwareVersion], "HardwareVersion incorrectly reported by DUT") + asserts.assert_equal(th_server_basic_info[basic_info_attr.HardwareVersionString], + bridged_info_for_th_server[bridged_device_info_attr.HardwareVersionString], "HardwareVersionString incorrectly reported by DUT") + asserts.assert_equal(th_server_basic_info[basic_info_attr.SoftwareVersion], + bridged_info_for_th_server[bridged_device_info_attr.SoftwareVersion], "SoftwareVersion incorrectly reported by DUT") + asserts.assert_equal(th_server_basic_info[basic_info_attr.SoftwareVersionString], + bridged_info_for_th_server[bridged_device_info_attr.SoftwareVersionString], "SoftwareVersionString incorrectly reported by DUT") + asserts.assert_equal(th_server_basic_info[basic_info_attr.UniqueID], + bridged_info_for_th_server[bridged_device_info_attr.UniqueID], "UniqueID incorrectly reported by DUT") if __name__ == "__main__": From fe20d1901a4991627ead3df3868ae5cce53358f8 Mon Sep 17 00:00:00 2001 From: lpbeliveau-silabs <112982107+lpbeliveau-silabs@users.noreply.github.com> Date: Wed, 21 Aug 2024 14:32:51 -0400 Subject: [PATCH 127/165] Removed Arithmetics operations relying on Unit test cluster from TC_S_2_2 and TC_S_2_3 (#35130) --- .../suites/certification/Test_TC_S_2_2.yaml | 33 ++----------------- .../suites/certification/Test_TC_S_2_3.yaml | 33 ++----------------- 2 files changed, 4 insertions(+), 62 deletions(-) diff --git a/src/app/tests/suites/certification/Test_TC_S_2_2.yaml b/src/app/tests/suites/certification/Test_TC_S_2_2.yaml index bdb3d2b8ad..7e5121680c 100644 --- a/src/app/tests/suites/certification/Test_TC_S_2_2.yaml +++ b/src/app/tests/suites/certification/Test_TC_S_2_2.yaml @@ -50,36 +50,6 @@ tests: - name: "SceneTableSize" saveAs: maxScenes - - label: "Arithmetic operation to get the maxScenes - 1" - cluster: "Unit Testing" - command: "TestAddArguments" - arguments: - values: - - name: "arg1" - value: maxScenes - 1 - - name: "arg2" - value: 0 - response: - values: - - name: "returnValue" - saveAs: maxScenesMinusOne - value: maxScenes - 1 - - - label: "Arithmetic operation to get the fabric Capacity" - cluster: "Unit Testing" - command: "TestAddArguments" - arguments: - values: - - name: "arg1" - value: maxScenesMinusOne / 2 - - name: "arg2" - value: 0 - response: - values: - - name: "returnValue" - saveAs: fabricCapacity - value: maxScenesMinusOne / 2 - - label: "Step 0a :TH reads attribute {ServerList} from the Descriptor cluster of the endpoint that implements the Scenes Management server on the @@ -202,7 +172,8 @@ tests: - name: "Status" value: 0x00 - name: "Capacity" - value: fabricCapacity + value: (maxScenes - 1) / 2 + saveAs: fabricCapacity - name: "GroupID" value: G1 diff --git a/src/app/tests/suites/certification/Test_TC_S_2_3.yaml b/src/app/tests/suites/certification/Test_TC_S_2_3.yaml index 5a76916edb..817ab532ba 100644 --- a/src/app/tests/suites/certification/Test_TC_S_2_3.yaml +++ b/src/app/tests/suites/certification/Test_TC_S_2_3.yaml @@ -50,36 +50,6 @@ tests: - name: "SceneTableSize" saveAs: maxScenes - - label: "Arithmetic operation to get the maxScenes - 1" - cluster: "Unit Testing" - command: "TestAddArguments" - arguments: - values: - - name: "arg1" - value: maxScenes - 1 - - name: "arg2" - value: 0 - response: - values: - - name: "returnValue" - saveAs: maxScenesMinusOne - value: maxScenes - 1 - - - label: "Arithmetic operation to get the fabric Capacity" - cluster: "Unit Testing" - command: "TestAddArguments" - arguments: - values: - - name: "arg1" - value: maxScenesMinusOne / 2 - - name: "arg2" - value: 0 - response: - values: - - name: "returnValue" - saveAs: fabricCapacity - value: maxScenesMinusOne / 2 - - label: "Step 0a: TH sends KeySetWrite command in the GroupKeyManagement cluster to DUT using a key that is pre-installed on the TH. @@ -259,7 +229,8 @@ tests: - name: "Status" value: 0x00 - name: "Capacity" - value: fabricCapacity + value: (maxScenes - 1) / 2 + saveAs: fabricCapacity - name: "GroupID" value: G1 - name: "SceneList" From 85bdb2e05f3d9e48070710b064525b002f874725 Mon Sep 17 00:00:00 2001 From: Terence Hampson Date: Wed, 21 Aug 2024 14:37:32 -0400 Subject: [PATCH 128/165] Add expiry to KeepActive as per spec into fabric-admin example (#35099) * Add expiry to KeepActive as per spec into fabric-admin example * Restyled by clang-format * Self Review fix * Restyled by clang-format * Name fix * Address PR comments * Address PR comments * Restyled by clang-format * Address PR comments --------- Co-authored-by: Restyled.io --- examples/fabric-admin/rpc/RpcServer.cpp | 52 +++++++++++++++++++------ 1 file changed, 40 insertions(+), 12 deletions(-) diff --git a/examples/fabric-admin/rpc/RpcServer.cpp b/examples/fabric-admin/rpc/RpcServer.cpp index d56399514a..fca25c25a1 100644 --- a/examples/fabric-admin/rpc/RpcServer.cpp +++ b/examples/fabric-admin/rpc/RpcServer.cpp @@ -47,20 +47,32 @@ class FabricAdmin final : public rpc::FabricAdmin, public IcdManager::Delegate public: void OnCheckInCompleted(const chip::app::ICDClientInfo & clientInfo) override { - chip::NodeId nodeId = clientInfo.peer_node.GetNodeId(); - auto it = mPendingKeepActiveTimesMs.find(nodeId); - VerifyOrReturn(it != mPendingKeepActiveTimesMs.end()); - // TODO(#33221): We also need a mechanism here to drop KeepActive - // request if they were recieved over 60 mins ago. - uint32_t stayActiveDurationMs = it->second; + // Needs for accessing mPendingCheckIn + assertChipStackLockedByCurrentThread(); + NodeId nodeId = clientInfo.peer_node.GetNodeId(); + auto it = mPendingCheckIn.find(nodeId); + VerifyOrReturn(it != mPendingCheckIn.end()); + + KeepActiveDataForCheckIn checkInData = it->second; + // Removed from pending map as check-in from this node has occured and we will handle the pending KeepActive + // request. + mPendingCheckIn.erase(nodeId); + + auto timeNow = System::SystemClock().GetMonotonicTimestamp(); + if (timeNow > checkInData.mRequestExpiryTimestamp) + { + ChipLogError( + NotSpecified, + "ICD check-in for device we have been waiting, came after KeepActive expiry. Reqeust dropped for Node ID: 0x%lx", + nodeId); + return; + } // TODO(#33221): If there is a failure in sending the message this request just gets dropped. // Work to see if there should be update to spec on whether some sort of failure later on // Should be indicated in some manner, or identify a better recovery mechanism here. - mPendingKeepActiveTimesMs.erase(nodeId); - auto onDone = [=](uint32_t promisedActiveDuration) { ActiveChanged(nodeId, promisedActiveDuration); }; - CHIP_ERROR err = StayActiveSender::SendStayActiveCommand(stayActiveDurationMs, clientInfo.peer_node, + CHIP_ERROR err = StayActiveSender::SendStayActiveCommand(checkInData.mStayActiveDurationMs, clientInfo.peer_node, chip::app::InteractionModelEngine::GetInstance(), onDone); if (err != CHIP_NO_ERROR) { @@ -147,10 +159,24 @@ class FabricAdmin final : public rpc::FabricAdmin, public IcdManager::Delegate void ScheduleSendingKeepActiveOnCheckIn(chip::NodeId nodeId, uint32_t stayActiveDurationMs) { - mPendingKeepActiveTimesMs[nodeId] = stayActiveDurationMs; + // Needs for accessing mPendingCheckIn + assertChipStackLockedByCurrentThread(); + + auto timeNow = System::SystemClock().GetMonotonicTimestamp(); + // Spec says we should expire the request 60 mins after we get it + System::Clock::Timestamp expiryTimestamp = timeNow + System::Clock::Seconds64(60 * 60); + KeepActiveDataForCheckIn checkInData = { .mStayActiveDurationMs = stayActiveDurationMs, + .mRequestExpiryTimestamp = expiryTimestamp }; + mPendingCheckIn[nodeId] = checkInData; } private: + struct KeepActiveDataForCheckIn + { + uint32_t mStayActiveDurationMs = 0; + System::Clock::Timestamp mRequestExpiryTimestamp; + }; + struct KeepActiveWorkData { KeepActiveWorkData(FabricAdmin * fabricAdmin, chip::NodeId nodeId, uint32_t stayActiveDurationMs) : @@ -169,8 +195,10 @@ class FabricAdmin final : public rpc::FabricAdmin, public IcdManager::Delegate chip::Platform::Delete(data); } - // Modifications to mPendingKeepActiveTimesMs should be done on the MatterEventLoop thread - std::map mPendingKeepActiveTimesMs; + // Modifications to mPendingCheckIn should be done on the MatterEventLoop thread + // otherwise we would need a mutex protecting this data to prevent race as this + // data is accessible by both RPC thread and Matter eventloop. + std::unordered_map mPendingCheckIn; }; FabricAdmin fabric_admin_service; From 6f22db05ca340fb001cc9a9ee58bf5fd37a5e5a1 Mon Sep 17 00:00:00 2001 From: Terence Hampson Date: Wed, 21 Aug 2024 15:15:25 -0400 Subject: [PATCH 129/165] Move TC_BR_5 to the right directory (#35128) --- scripts/tests/chiptest/__init__.py | 2 +- .../Test_TC_BR_5.yaml} | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) rename src/app/tests/suites/{TestFabricSyncBridgedNode.yaml => certification/Test_TC_BR_5.yaml} (96%) diff --git a/scripts/tests/chiptest/__init__.py b/scripts/tests/chiptest/__init__.py index d85e82fec6..aef22e030e 100644 --- a/scripts/tests/chiptest/__init__.py +++ b/scripts/tests/chiptest/__init__.py @@ -157,7 +157,7 @@ def _GetInDevelopmentTests() -> Set[str]: # TestEventTriggersEnabled is true, which it's not in CI. "Test_TC_SMOKECO_2_6.yaml", # chip-repl does not support local timeout (07/20/2023) and test assumes # TestEventTriggersEnabled is true, which it's not in CI. - "TestFabricSyncBridgedNode.yaml", # [TODO] fabric-bridge-app lacks some feature so this test currently fails + "Test_TC_BR_5.yaml", # [TODO] Fabric Sync example app has not been integrated into CI yet. } diff --git a/src/app/tests/suites/TestFabricSyncBridgedNode.yaml b/src/app/tests/suites/certification/Test_TC_BR_5.yaml similarity index 96% rename from src/app/tests/suites/TestFabricSyncBridgedNode.yaml rename to src/app/tests/suites/certification/Test_TC_BR_5.yaml index 6624e71012..958f98d076 100644 --- a/src/app/tests/suites/TestFabricSyncBridgedNode.yaml +++ b/src/app/tests/suites/certification/Test_TC_BR_5.yaml @@ -12,7 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -name: Test Fabric Synchronization condition on Bridged Node Device Type +name: 3.1.5. [TC-BR-5] Conditions for Fabric Synchronization (DUT server) PICS: - MCORE.FS From 4d5beae7ecf5e4e1aa5423139e632e43228e91d5 Mon Sep 17 00:00:00 2001 From: Nivi Sarkar <55898241+nivi-apple@users.noreply.github.com> Date: Wed, 21 Aug 2024 13:03:36 -0700 Subject: [PATCH 130/165] =?UTF-8?q?Update=20the=20preset=20handle=20field?= =?UTF-8?q?=20in=20the=20SetActivePresetRequest=20c=E2=80=A6=20(#35105)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Update the preset handle field in the SetActivePresetRequestRequest command to be nullable - Update the deleagte API for getting the active preset handle to return a nullable handle * Return error if CopySpanToMutableSpan fails * Restyled by clang-format * Apply suggestions from code review Co-authored-by: Boris Zbarsky --------- Co-authored-by: Restyled.io Co-authored-by: Boris Zbarsky --- .../air-purifier-app.matter | 2 +- .../all-clusters-app.matter | 2 +- .../all-clusters-minimal-app.matter | 2 +- ...umiditysensor_thermostat_56de3d5f45.matter | 2 +- ...tnode_heatingcoolingunit_ncdGai1E5a.matter | 2 +- ...tnode_roomairconditioner_9cf3607804.matter | 2 +- .../rootnode_thermostat_bm3fb8dhYi.matter | 2 +- .../placeholder/linux/apps/app1/config.matter | 4 +-- .../placeholder/linux/apps/app2/config.matter | 4 +-- .../linux/include/thermostat-delegate-impl.h | 2 +- .../linux/thermostat-delegate-impl.cpp | 14 +++++++++-- .../nxp/zap/thermostat_matter_thread.matter | 2 +- .../nxp/zap/thermostat_matter_wifi.matter | 2 +- .../qpg/zap/thermostaticRadiatorValve.matter | 2 +- .../thermostat-common/thermostat.matter | 2 +- .../thermostat-server/thermostat-delegate.h | 7 +++--- .../thermostat-server/thermostat-server.cpp | 25 ++++++++----------- .../data-model/chip/thermostat-cluster.xml | 2 +- .../data_model/controller-clusters.matter | 2 +- .../chip/devicecontroller/ChipClusters.java | 6 ++--- .../cluster/clusters/ThermostatCluster.kt | 4 +-- .../python/chip/clusters/Objects.py | 4 +-- .../zap-generated/MTRCommandPayloadsObjc.h | 2 +- .../zap-generated/MTRCommandPayloadsObjc.mm | 9 +++++-- .../zap-generated/cluster-objects.h | 4 +-- .../zap-generated/cluster/Commands.h | 6 ++++- 26 files changed, 65 insertions(+), 52 deletions(-) diff --git a/examples/air-purifier-app/air-purifier-common/air-purifier-app.matter b/examples/air-purifier-app/air-purifier-common/air-purifier-app.matter index cb1c102b23..c35b8b62e2 100644 --- a/examples/air-purifier-app/air-purifier-common/air-purifier-app.matter +++ b/examples/air-purifier-app/air-purifier-common/air-purifier-app.matter @@ -1856,7 +1856,7 @@ cluster Thermostat = 513 { } request struct SetActivePresetRequestRequest { - octet_string<16> presetHandle = 0; + nullable octet_string<16> presetHandle = 0; } response struct AtomicResponse = 253 { diff --git a/examples/all-clusters-app/all-clusters-common/all-clusters-app.matter b/examples/all-clusters-app/all-clusters-common/all-clusters-app.matter index c18c6164c5..4180b1eef7 100644 --- a/examples/all-clusters-app/all-clusters-common/all-clusters-app.matter +++ b/examples/all-clusters-app/all-clusters-common/all-clusters-app.matter @@ -5696,7 +5696,7 @@ cluster Thermostat = 513 { } request struct SetActivePresetRequestRequest { - octet_string<16> presetHandle = 0; + nullable octet_string<16> presetHandle = 0; } response struct AtomicResponse = 253 { diff --git a/examples/all-clusters-minimal-app/all-clusters-common/all-clusters-minimal-app.matter b/examples/all-clusters-minimal-app/all-clusters-common/all-clusters-minimal-app.matter index 16f170c137..363da41015 100644 --- a/examples/all-clusters-minimal-app/all-clusters-common/all-clusters-minimal-app.matter +++ b/examples/all-clusters-minimal-app/all-clusters-common/all-clusters-minimal-app.matter @@ -4130,7 +4130,7 @@ cluster Thermostat = 513 { } request struct SetActivePresetRequestRequest { - octet_string<16> presetHandle = 0; + nullable octet_string<16> presetHandle = 0; } response struct AtomicResponse = 253 { diff --git a/examples/chef/devices/rootnode_airpurifier_airqualitysensor_temperaturesensor_humiditysensor_thermostat_56de3d5f45.matter b/examples/chef/devices/rootnode_airpurifier_airqualitysensor_temperaturesensor_humiditysensor_thermostat_56de3d5f45.matter index ed130f2931..d47b3a9092 100644 --- a/examples/chef/devices/rootnode_airpurifier_airqualitysensor_temperaturesensor_humiditysensor_thermostat_56de3d5f45.matter +++ b/examples/chef/devices/rootnode_airpurifier_airqualitysensor_temperaturesensor_humiditysensor_thermostat_56de3d5f45.matter @@ -1779,7 +1779,7 @@ cluster Thermostat = 513 { } request struct SetActivePresetRequestRequest { - octet_string<16> presetHandle = 0; + nullable octet_string<16> presetHandle = 0; } response struct AtomicResponse = 253 { diff --git a/examples/chef/devices/rootnode_heatingcoolingunit_ncdGai1E5a.matter b/examples/chef/devices/rootnode_heatingcoolingunit_ncdGai1E5a.matter index ec62d4504f..84b5d949b6 100644 --- a/examples/chef/devices/rootnode_heatingcoolingunit_ncdGai1E5a.matter +++ b/examples/chef/devices/rootnode_heatingcoolingunit_ncdGai1E5a.matter @@ -2136,7 +2136,7 @@ cluster Thermostat = 513 { } request struct SetActivePresetRequestRequest { - octet_string<16> presetHandle = 0; + nullable octet_string<16> presetHandle = 0; } response struct AtomicResponse = 253 { diff --git a/examples/chef/devices/rootnode_roomairconditioner_9cf3607804.matter b/examples/chef/devices/rootnode_roomairconditioner_9cf3607804.matter index 95e0ba20d4..20b7d6b80d 100644 --- a/examples/chef/devices/rootnode_roomairconditioner_9cf3607804.matter +++ b/examples/chef/devices/rootnode_roomairconditioner_9cf3607804.matter @@ -1719,7 +1719,7 @@ cluster Thermostat = 513 { } request struct SetActivePresetRequestRequest { - octet_string<16> presetHandle = 0; + nullable octet_string<16> presetHandle = 0; } response struct AtomicResponse = 253 { diff --git a/examples/chef/devices/rootnode_thermostat_bm3fb8dhYi.matter b/examples/chef/devices/rootnode_thermostat_bm3fb8dhYi.matter index 6c27235c7d..ae6441c2ea 100644 --- a/examples/chef/devices/rootnode_thermostat_bm3fb8dhYi.matter +++ b/examples/chef/devices/rootnode_thermostat_bm3fb8dhYi.matter @@ -1939,7 +1939,7 @@ cluster Thermostat = 513 { } request struct SetActivePresetRequestRequest { - octet_string<16> presetHandle = 0; + nullable octet_string<16> presetHandle = 0; } response struct AtomicResponse = 253 { diff --git a/examples/placeholder/linux/apps/app1/config.matter b/examples/placeholder/linux/apps/app1/config.matter index 8befb87daa..33521a7a93 100644 --- a/examples/placeholder/linux/apps/app1/config.matter +++ b/examples/placeholder/linux/apps/app1/config.matter @@ -5414,7 +5414,7 @@ cluster Thermostat = 513 { } request struct SetActivePresetRequestRequest { - octet_string<16> presetHandle = 0; + nullable octet_string<16> presetHandle = 0; } response struct AtomicResponse = 253 { @@ -5769,7 +5769,7 @@ cluster Thermostat = 513 { } request struct SetActivePresetRequestRequest { - octet_string<16> presetHandle = 0; + nullable octet_string<16> presetHandle = 0; } response struct AtomicResponse = 253 { diff --git a/examples/placeholder/linux/apps/app2/config.matter b/examples/placeholder/linux/apps/app2/config.matter index 6cfcc1ab7e..86d20b24a4 100644 --- a/examples/placeholder/linux/apps/app2/config.matter +++ b/examples/placeholder/linux/apps/app2/config.matter @@ -5371,7 +5371,7 @@ cluster Thermostat = 513 { } request struct SetActivePresetRequestRequest { - octet_string<16> presetHandle = 0; + nullable octet_string<16> presetHandle = 0; } response struct AtomicResponse = 253 { @@ -5726,7 +5726,7 @@ cluster Thermostat = 513 { } request struct SetActivePresetRequestRequest { - octet_string<16> presetHandle = 0; + nullable octet_string<16> presetHandle = 0; } response struct AtomicResponse = 253 { diff --git a/examples/thermostat/linux/include/thermostat-delegate-impl.h b/examples/thermostat/linux/include/thermostat-delegate-impl.h index 8252f2274f..6bf9d02cea 100644 --- a/examples/thermostat/linux/include/thermostat-delegate-impl.h +++ b/examples/thermostat/linux/include/thermostat-delegate-impl.h @@ -54,7 +54,7 @@ class ThermostatDelegate : public Delegate CHIP_ERROR GetPresetAtIndex(size_t index, PresetStructWithOwnedMembers & preset) override; - CHIP_ERROR GetActivePresetHandle(MutableByteSpan & activePresetHandle) override; + CHIP_ERROR GetActivePresetHandle(DataModel::Nullable & activePresetHandle) override; CHIP_ERROR SetActivePresetHandle(const DataModel::Nullable & newActivePresetHandle) override; diff --git a/examples/thermostat/linux/thermostat-delegate-impl.cpp b/examples/thermostat/linux/thermostat-delegate-impl.cpp index c39a757a8b..b931db20b7 100644 --- a/examples/thermostat/linux/thermostat-delegate-impl.cpp +++ b/examples/thermostat/linux/thermostat-delegate-impl.cpp @@ -117,9 +117,19 @@ CHIP_ERROR ThermostatDelegate::GetPresetAtIndex(size_t index, PresetStructWithOw return CHIP_ERROR_PROVIDER_LIST_EXHAUSTED; } -CHIP_ERROR ThermostatDelegate::GetActivePresetHandle(MutableByteSpan & activePresetHandle) +CHIP_ERROR ThermostatDelegate::GetActivePresetHandle(DataModel::Nullable & activePresetHandle) { - return CopySpanToMutableSpan(ByteSpan(mActivePresetHandleData, mActivePresetHandleDataSize), activePresetHandle); + if (mActivePresetHandleDataSize != 0) + { + ReturnErrorOnFailure( + CopySpanToMutableSpan(ByteSpan(mActivePresetHandleData, mActivePresetHandleDataSize), activePresetHandle.Value())); + activePresetHandle.Value().reduce_size(mActivePresetHandleDataSize); + } + else + { + activePresetHandle.SetNull(); + } + return CHIP_NO_ERROR; } CHIP_ERROR ThermostatDelegate::SetActivePresetHandle(const DataModel::Nullable & newActivePresetHandle) diff --git a/examples/thermostat/nxp/zap/thermostat_matter_thread.matter b/examples/thermostat/nxp/zap/thermostat_matter_thread.matter index 001e1b43ac..cbe6a6280d 100644 --- a/examples/thermostat/nxp/zap/thermostat_matter_thread.matter +++ b/examples/thermostat/nxp/zap/thermostat_matter_thread.matter @@ -2530,7 +2530,7 @@ cluster Thermostat = 513 { } request struct SetActivePresetRequestRequest { - octet_string<16> presetHandle = 0; + nullable octet_string<16> presetHandle = 0; } response struct AtomicResponse = 253 { diff --git a/examples/thermostat/nxp/zap/thermostat_matter_wifi.matter b/examples/thermostat/nxp/zap/thermostat_matter_wifi.matter index 066afc8550..cd9ddc362e 100644 --- a/examples/thermostat/nxp/zap/thermostat_matter_wifi.matter +++ b/examples/thermostat/nxp/zap/thermostat_matter_wifi.matter @@ -2441,7 +2441,7 @@ cluster Thermostat = 513 { } request struct SetActivePresetRequestRequest { - octet_string<16> presetHandle = 0; + nullable octet_string<16> presetHandle = 0; } response struct AtomicResponse = 253 { diff --git a/examples/thermostat/qpg/zap/thermostaticRadiatorValve.matter b/examples/thermostat/qpg/zap/thermostaticRadiatorValve.matter index 31e5775d88..548db02c52 100644 --- a/examples/thermostat/qpg/zap/thermostaticRadiatorValve.matter +++ b/examples/thermostat/qpg/zap/thermostaticRadiatorValve.matter @@ -2138,7 +2138,7 @@ cluster Thermostat = 513 { } request struct SetActivePresetRequestRequest { - octet_string<16> presetHandle = 0; + nullable octet_string<16> presetHandle = 0; } response struct AtomicResponse = 253 { diff --git a/examples/thermostat/thermostat-common/thermostat.matter b/examples/thermostat/thermostat-common/thermostat.matter index c53651c537..a66c2dfdad 100644 --- a/examples/thermostat/thermostat-common/thermostat.matter +++ b/examples/thermostat/thermostat-common/thermostat.matter @@ -2318,7 +2318,7 @@ cluster Thermostat = 513 { } request struct SetActivePresetRequestRequest { - octet_string<16> presetHandle = 0; + nullable octet_string<16> presetHandle = 0; } response struct AtomicResponse = 253 { diff --git a/src/app/clusters/thermostat-server/thermostat-delegate.h b/src/app/clusters/thermostat-server/thermostat-delegate.h index c8c21d898a..0f89f69468 100644 --- a/src/app/clusters/thermostat-server/thermostat-delegate.h +++ b/src/app/clusters/thermostat-server/thermostat-delegate.h @@ -78,11 +78,10 @@ class Delegate /** * @brief Get the ActivePresetHandle attribute value. * - * @param[out] activePresetHandle The MutableByteSpan to copy the active preset handle into. On success, - * the callee must update the length to the length of the copied data. If the value of - * the attribute is null, the callee must set the MutableByteSpan to empty. + * @param[out] activePresetHandle The nullable MutableByteSpan to copy the active preset handle into. On success, + * the size of the activePresetHandle is updated to the length of the copied data. */ - virtual CHIP_ERROR GetActivePresetHandle(MutableByteSpan & activePresetHandle) = 0; + virtual CHIP_ERROR GetActivePresetHandle(DataModel::Nullable & activePresetHandle) = 0; /** * @brief Set the ActivePresetHandle attribute value. diff --git a/src/app/clusters/thermostat-server/thermostat-server.cpp b/src/app/clusters/thermostat-server/thermostat-server.cpp index 91c045c5ff..8fe70211ee 100644 --- a/src/app/clusters/thermostat-server/thermostat-server.cpp +++ b/src/app/clusters/thermostat-server/thermostat-server.cpp @@ -761,19 +761,13 @@ CHIP_ERROR ThermostatAttrAccess::Read(const ConcreteReadAttributePath & aPath, A VerifyOrReturnError(delegate != nullptr, CHIP_ERROR_INCORRECT_STATE, ChipLogError(Zcl, "Delegate is null")); uint8_t buffer[kPresetHandleSize]; - MutableByteSpan activePresetHandle(buffer); + MutableByteSpan activePresetHandleSpan(buffer); + auto activePresetHandle = DataModel::MakeNullable(activePresetHandleSpan); CHIP_ERROR err = delegate->GetActivePresetHandle(activePresetHandle); ReturnErrorOnFailure(err); - if (activePresetHandle.empty()) - { - ReturnErrorOnFailure(aEncoder.EncodeNull()); - } - else - { - ReturnErrorOnFailure(aEncoder.Encode(activePresetHandle)); - } + ReturnErrorOnFailure(aEncoder.Encode(activePresetHandle)); } break; case ScheduleTypes::Id: { @@ -1299,16 +1293,16 @@ bool emberAfThermostatClusterSetActivePresetRequestCallback( return true; } - ByteSpan newPresetHandle = commandData.presetHandle; + DataModel::Nullable newPresetHandle = commandData.presetHandle; // If the preset handle passed in the command is not present in the Presets attribute, return INVALID_COMMAND. - if (!IsPresetHandlePresentInPresets(delegate, newPresetHandle)) + if (!newPresetHandle.IsNull() && !IsPresetHandlePresentInPresets(delegate, newPresetHandle.Value())) { commandObj->AddStatus(commandPath, imcode::InvalidCommand); return true; } - CHIP_ERROR err = delegate->SetActivePresetHandle(DataModel::MakeNullable(newPresetHandle)); + CHIP_ERROR err = delegate->SetActivePresetHandle(newPresetHandle); if (err != CHIP_NO_ERROR) { @@ -1470,7 +1464,8 @@ imcode commitPresets(Delegate * delegate, EndpointId endpoint) // attribute. If a preset is not found with the same presetHandle, return INVALID_IN_STATE. If there is no ActivePresetHandle // attribute set, continue with other checks. uint8_t buffer[kPresetHandleSize]; - MutableByteSpan activePresetHandle(buffer); + MutableByteSpan activePresetHandleSpan(buffer); + auto activePresetHandle = DataModel::MakeNullable(activePresetHandleSpan); err = delegate->GetActivePresetHandle(activePresetHandle); @@ -1479,9 +1474,9 @@ imcode commitPresets(Delegate * delegate, EndpointId endpoint) return imcode::InvalidInState; } - if (!activePresetHandle.empty()) + if (!activePresetHandle.IsNull()) { - uint8_t count = CountPresetsInPendingListWithPresetHandle(delegate, activePresetHandle); + uint8_t count = CountPresetsInPendingListWithPresetHandle(delegate, activePresetHandle.Value()); if (count == 0) { return imcode::InvalidInState; 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 546692b1a4..6f75aa45e9 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 @@ -481,7 +481,7 @@ limitations under the License. ID - + diff --git a/src/controller/data_model/controller-clusters.matter b/src/controller/data_model/controller-clusters.matter index bfb1354849..52f43c048a 100644 --- a/src/controller/data_model/controller-clusters.matter +++ b/src/controller/data_model/controller-clusters.matter @@ -6994,7 +6994,7 @@ cluster Thermostat = 513 { } request struct SetActivePresetRequestRequest { - octet_string<16> presetHandle = 0; + nullable octet_string<16> presetHandle = 0; } response struct AtomicResponse = 253 { diff --git a/src/controller/java/generated/java/chip/devicecontroller/ChipClusters.java b/src/controller/java/generated/java/chip/devicecontroller/ChipClusters.java index 6f3e6f62d3..cf344db593 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/ChipClusters.java +++ b/src/controller/java/generated/java/chip/devicecontroller/ChipClusters.java @@ -40637,16 +40637,16 @@ public void onResponse(StructType invokeStructValue) { }}, commandId, commandArgs, timedInvokeTimeoutMs); } - public void setActivePresetRequest(DefaultClusterCallback callback, byte[] presetHandle) { + public void setActivePresetRequest(DefaultClusterCallback callback, @Nullable byte[] presetHandle) { setActivePresetRequest(callback, presetHandle, 0); } - public void setActivePresetRequest(DefaultClusterCallback callback, byte[] presetHandle, int timedInvokeTimeoutMs) { + public void setActivePresetRequest(DefaultClusterCallback callback, @Nullable byte[] presetHandle, int timedInvokeTimeoutMs) { final long commandId = 6L; ArrayList elements = new ArrayList<>(); final long presetHandleFieldID = 0L; - BaseTLVType presetHandletlvValue = new ByteArrayType(presetHandle); + BaseTLVType presetHandletlvValue = presetHandle != null ? new ByteArrayType(presetHandle) : new NullType(); elements.add(new StructElement(presetHandleFieldID, presetHandletlvValue)); StructType commandArgs = new StructType(elements); diff --git a/src/controller/java/generated/java/matter/controller/cluster/clusters/ThermostatCluster.kt b/src/controller/java/generated/java/matter/controller/cluster/clusters/ThermostatCluster.kt index b9166c12e9..6f193e694e 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/clusters/ThermostatCluster.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/clusters/ThermostatCluster.kt @@ -504,7 +504,7 @@ class ThermostatCluster(private val controller: MatterController, private val en } suspend fun setActivePresetRequest( - presetHandle: ByteArray, + presetHandle: ByteArray?, timedInvokeTimeout: Duration? = null, ) { val commandId: UInt = 6u @@ -513,7 +513,7 @@ class ThermostatCluster(private val controller: MatterController, private val en tlvWriter.startStructure(AnonymousTag) val TAG_PRESET_HANDLE_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_PRESET_HANDLE_REQ), presetHandle) + presetHandle?.let { tlvWriter.put(ContextSpecificTag(TAG_PRESET_HANDLE_REQ), presetHandle) } tlvWriter.endStructure() val request: InvokeRequest = diff --git a/src/controller/python/chip/clusters/Objects.py b/src/controller/python/chip/clusters/Objects.py index 6b8ecd1c82..624f42c8e8 100644 --- a/src/controller/python/chip/clusters/Objects.py +++ b/src/controller/python/chip/clusters/Objects.py @@ -33168,10 +33168,10 @@ class SetActivePresetRequest(ClusterCommand): def descriptor(cls) -> ClusterObjectDescriptor: return ClusterObjectDescriptor( Fields=[ - ClusterObjectFieldDescriptor(Label="presetHandle", Tag=0, Type=bytes), + ClusterObjectFieldDescriptor(Label="presetHandle", Tag=0, Type=typing.Union[Nullable, bytes]), ]) - presetHandle: 'bytes' = b"" + presetHandle: 'typing.Union[Nullable, bytes]' = NullValue @dataclass class AtomicResponse(ClusterCommand): diff --git a/src/darwin/Framework/CHIP/zap-generated/MTRCommandPayloadsObjc.h b/src/darwin/Framework/CHIP/zap-generated/MTRCommandPayloadsObjc.h index 5c86961626..a5934b1697 100644 --- a/src/darwin/Framework/CHIP/zap-generated/MTRCommandPayloadsObjc.h +++ b/src/darwin/Framework/CHIP/zap-generated/MTRCommandPayloadsObjc.h @@ -7929,7 +7929,7 @@ MTR_PROVISIONALLY_AVAILABLE MTR_PROVISIONALLY_AVAILABLE @interface MTRThermostatClusterSetActivePresetRequestParams : NSObject -@property (nonatomic, copy) NSData * _Nonnull presetHandle MTR_PROVISIONALLY_AVAILABLE; +@property (nonatomic, copy) NSData * _Nullable presetHandle MTR_PROVISIONALLY_AVAILABLE; /** * Controls whether the command is a timed command (using Timed Invoke). * diff --git a/src/darwin/Framework/CHIP/zap-generated/MTRCommandPayloadsObjc.mm b/src/darwin/Framework/CHIP/zap-generated/MTRCommandPayloadsObjc.mm index 1334d8beba..5ae975508e 100644 --- a/src/darwin/Framework/CHIP/zap-generated/MTRCommandPayloadsObjc.mm +++ b/src/darwin/Framework/CHIP/zap-generated/MTRCommandPayloadsObjc.mm @@ -22697,7 +22697,7 @@ - (instancetype)init { if (self = [super init]) { - _presetHandle = [NSData data]; + _presetHandle = nil; _timedInvokeTimeoutMs = nil; _serverSideProcessingTimeout = nil; } @@ -22730,7 +22730,12 @@ - (CHIP_ERROR)_encodeToTLVReader:(chip::System::PacketBufferTLVReader &)reader chip::app::Clusters::Thermostat::Commands::SetActivePresetRequest::Type encodableStruct; ListFreer listFreer; { - encodableStruct.presetHandle = AsByteSpan(self.presetHandle); + if (self.presetHandle == nil) { + encodableStruct.presetHandle.SetNull(); + } else { + auto & nonNullValue_0 = encodableStruct.presetHandle.SetNonNull(); + nonNullValue_0 = AsByteSpan(self.presetHandle); + } } auto buffer = chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSizeWithoutReserve, 0); 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 e18b64797b..c2c1697ce2 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 @@ -30149,7 +30149,7 @@ struct Type static constexpr CommandId GetCommandId() { return Commands::SetActivePresetRequest::Id; } static constexpr ClusterId GetClusterId() { return Clusters::Thermostat::Id; } - chip::ByteSpan presetHandle; + DataModel::Nullable presetHandle; CHIP_ERROR Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const; @@ -30164,7 +30164,7 @@ struct DecodableType static constexpr CommandId GetCommandId() { return Commands::SetActivePresetRequest::Id; } static constexpr ClusterId GetClusterId() { return Clusters::Thermostat::Id; } - chip::ByteSpan presetHandle; + DataModel::Nullable presetHandle; CHIP_ERROR Decode(TLV::TLVReader & reader); }; }; // namespace SetActivePresetRequest 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 004bb29c54..dc438df840 100644 --- a/zzz_generated/darwin-framework-tool/zap-generated/cluster/Commands.h +++ b/zzz_generated/darwin-framework-tool/zap-generated/cluster/Commands.h @@ -107995,7 +107995,11 @@ class ThermostatSetActivePresetRequest : public ClusterCommand { __auto_type * params = [[MTRThermostatClusterSetActivePresetRequestParams alloc] init]; params.timedInvokeTimeoutMs = mTimedInteractionTimeoutMs.HasValue() ? [NSNumber numberWithUnsignedShort:mTimedInteractionTimeoutMs.Value()] : nil; #if MTR_ENABLE_PROVISIONAL - params.presetHandle = [NSData dataWithBytes:mRequest.presetHandle.data() length:mRequest.presetHandle.size()]; + if (mRequest.presetHandle.IsNull()) { + params.presetHandle = nil; + } else { + params.presetHandle = [NSData dataWithBytes:mRequest.presetHandle.Value().data() length:mRequest.presetHandle.Value().size()]; + } #endif // MTR_ENABLE_PROVISIONAL uint16_t repeatCount = mRepeatCount.ValueOr(1); uint16_t __block responsesNeeded = repeatCount; From 2302c57932101f880df969cd7907d905ef33f467 Mon Sep 17 00:00:00 2001 From: Yufeng Wang Date: Wed, 21 Aug 2024 13:05:25 -0700 Subject: [PATCH 131/165] Fix fabric-bridge is accidentally added into sync list (#35132) --- .../commands/pairing/DeviceSynchronization.cpp | 6 +++++- examples/fabric-admin/device_manager/DeviceManager.h | 9 +++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/examples/fabric-admin/commands/pairing/DeviceSynchronization.cpp b/examples/fabric-admin/commands/pairing/DeviceSynchronization.cpp index 3974761fdc..69ca9cdb72 100644 --- a/examples/fabric-admin/commands/pairing/DeviceSynchronization.cpp +++ b/examples/fabric-admin/commands/pairing/DeviceSynchronization.cpp @@ -24,6 +24,7 @@ #include #include +#include using namespace ::chip; using namespace ::chip::app; @@ -120,7 +121,10 @@ void DeviceSynchronizer::OnReportEnd() { // Report end is at the end of all attributes (success) #if defined(PW_RPC_ENABLED) - AddSynchronizedDevice(mCurrentDeviceData); + if (!DeviceMgr().IsCurrentBridgeDevice(mCurrentDeviceData.node_id)) + { + AddSynchronizedDevice(mCurrentDeviceData); + } #else ChipLogError(NotSpecified, "Cannot synchronize device with fabric bridge: RPC not enabled"); #endif diff --git a/examples/fabric-admin/device_manager/DeviceManager.h b/examples/fabric-admin/device_manager/DeviceManager.h index 1fb2ad5224..fa94f3d09d 100644 --- a/examples/fabric-admin/device_manager/DeviceManager.h +++ b/examples/fabric-admin/device_manager/DeviceManager.h @@ -75,6 +75,15 @@ class DeviceManager : public PairingDelegate void RemoveSyncedDevice(chip::NodeId nodeId); + /** + * @brief Determines whether a given nodeId corresponds to the "current bridge device," either local or remote. + * + * @param nodeId The ID of the node being checked. + * + * @return true if the nodeId matches either the local or remote bridge device; otherwise, false. + */ + bool IsCurrentBridgeDevice(chip::NodeId nodeId) const { return nodeId == mLocalBridgeNodeId || nodeId == mRemoteBridgeNodeId; } + /** * @brief Open the commissioning window for a specific device within its own fabric. * From 3cdef41e1d548bb0eeccc647a5c4ff64874936cd Mon Sep 17 00:00:00 2001 From: Harshith-GRL <145322529+Harshith-GRL@users.noreply.github.com> Date: Thu, 22 Aug 2024 02:21:57 +0530 Subject: [PATCH 132/165] Yaml scripts update (#35093) * Removed scripts Test_TC_SC_4_10.yaml and Test_TC_SC_4_5.yaml as Test plan have removed them * step numbers corrected in Test_TC_CC_7_3.yaml and action id is updated in Test_TC_ACT_3_2.yaml * Removed scripts Test_TC_SC_4_10.yaml and Test_TC_SC_4_5.yaml as Test plan have removed them * step numbers corrected in Test_TC_CC_7_3.yaml and action id is updated in Test_TC_ACT_3_2.yaml * Reverted Action of Test_TC_ACT_3_2.yaml --- .../suites/certification/Test_TC_ACT_3_2.yaml | 6 +- .../suites/certification/Test_TC_CC_7_3.yaml | 20 ++-- .../suites/certification/Test_TC_SC_4_10.yaml | 60 ------------ .../suites/certification/Test_TC_SC_4_5.yaml | 92 ------------------- 4 files changed, 13 insertions(+), 165 deletions(-) delete mode 100644 src/app/tests/suites/certification/Test_TC_SC_4_10.yaml delete mode 100644 src/app/tests/suites/certification/Test_TC_SC_4_5.yaml diff --git a/src/app/tests/suites/certification/Test_TC_ACT_3_2.yaml b/src/app/tests/suites/certification/Test_TC_ACT_3_2.yaml index 914718896d..cc409a67c6 100644 --- a/src/app/tests/suites/certification/Test_TC_ACT_3_2.yaml +++ b/src/app/tests/suites/certification/Test_TC_ACT_3_2.yaml @@ -33,7 +33,7 @@ tests: "Step 0: Preparation: TH as server exposes an Actions server cluster on EP 1, with one action (supporting all possible commands) and corresponding ActionLists and EndpointLists attributes: ActionList: - contains one list element (ActionListStruct): ActionIO = 0x1001 Name + contains one list element (ActionListStruct): ActionIO = 0xA001 Name = 'some test' Type = other EndpointListID = 0xE001 SupportedCommands = 0x0fff // suppports all commands State = Inactive EndpointLists: contains one list element @@ -92,13 +92,13 @@ tests: 2. Use the above obtained ActionID to verify the following commands - ./chip-tool actions instant-action 4097 1 1 + ./chip-tool actions instant-action 40961 1 1 disabled: true - label: "Step 1: DUT issues an InstantAction command to TH" PICS: ACT.C.C00.Tx verification: | - ./chip-tool actions instant-action 4097 1 1 + ./chip-tool actions instant-action 40961 1 1 Via the TH (bridge-app), verify the InstantAction response that contains ActionID . diff --git a/src/app/tests/suites/certification/Test_TC_CC_7_3.yaml b/src/app/tests/suites/certification/Test_TC_CC_7_3.yaml index bfdfd26ed3..4aae05d10f 100644 --- a/src/app/tests/suites/certification/Test_TC_CC_7_3.yaml +++ b/src/app/tests/suites/certification/Test_TC_CC_7_3.yaml @@ -162,7 +162,7 @@ tests: maxValue: 13800 - label: - "Step 5a: TH sends EnhancedMoveToHue command to DUT with + "Step 3a: TH sends EnhancedMoveToHue command to DUT with EnhancedHue=12000, Direction=0x00 (shortest distance) and TransitionTime=0 (immediately)." PICS: CC.S.F01 && CC.S.C40.Rsp @@ -190,7 +190,7 @@ tests: value: 100 - label: - "Step 5b: TH sends EnhancedStepHue command to DUT with StepMode=0x03 + "Step 3b: TH sends EnhancedStepHue command to DUT with StepMode=0x03 (down), StepSize=6000 and TransitionTime=300 (30s)" PICS: CC.S.F01 && CC.S.C42.Rsp command: "EnhancedStepHue" @@ -216,7 +216,7 @@ tests: - name: "ms" value: 10000 - - label: "Step 5c: TH reads EnhancedCurrentHue attribute from DUT" + - label: "Step 3c: TH reads EnhancedCurrentHue attribute from DUT" command: "readAttribute" PICS: CC.S.F01 && CC.S.A4000 && CC.S.C41.Rsp attribute: "EnhancedCurrentHue" @@ -234,7 +234,7 @@ tests: - name: "ms" value: 10000 - - label: "Step 2d: TH reads EnhancedCurrentHue attribute from DUT" + - label: "Step 3d: TH reads EnhancedCurrentHue attribute from DUT" command: "readAttribute" PICS: CC.S.F01 && CC.S.A4000 && CC.S.C41.Rsp attribute: "EnhancedCurrentHue" @@ -252,7 +252,7 @@ tests: - name: "ms" value: 10000 - - label: "Step 2e: TH reads EnhancedCurrentHue attribute from DUT" + - label: "Step 3e: TH reads EnhancedCurrentHue attribute from DUT" command: "readAttribute" PICS: CC.S.F01 && CC.S.A4000 && CC.S.C41.Rsp attribute: "EnhancedCurrentHue" @@ -270,7 +270,7 @@ tests: - name: "ms" value: 5000 - - label: "Step 2f: TH reads EnhancedCurrentHue attribute from DUT" + - label: "Step 3f: TH reads EnhancedCurrentHue attribute from DUT" command: "readAttribute" PICS: CC.S.F01 && CC.S.A4000 && CC.S.C41.Rsp attribute: "EnhancedCurrentHue" @@ -279,7 +279,7 @@ tests: minValue: 5100 maxValue: 6900 - - label: "Step 6a: TH reads ColorMode attribute from DUT" + - label: "Step 4a: TH reads ColorMode attribute from DUT" PICS: CC.S.F01 && CC.S.A0008 command: "readAttribute" attribute: "ColorMode" @@ -289,7 +289,7 @@ tests: minValue: 0 maxValue: 2 - - label: "Step 6b: TH reads EnhancedColorMode attribute from DUT" + - label: "Step 4b: TH reads EnhancedColorMode attribute from DUT" PICS: CC.S.F01 && CC.S.A4001 command: "readAttribute" attribute: "EnhancedColorMode" @@ -300,7 +300,7 @@ tests: maxValue: 3 - label: - "Step 7a: TH sends EnhancedStepHue command to DUT with StepMode=0x01 + "Step 5a: TH sends EnhancedStepHue command to DUT with StepMode=0x01 (up), StepSize=0" PICS: CC.S.F01 && CC.S.C42.Rsp command: "EnhancedStepHue" @@ -320,7 +320,7 @@ tests: error: INVALID_COMMAND - label: - "Step 7b: TH sends EnhancedStepHue command to DUT with StepMode=0x03 + "Step 5b: TH sends EnhancedStepHue command to DUT with StepMode=0x03 (down), StepSize=0" PICS: CC.S.F01 && CC.S.C42.Rsp command: "EnhancedStepHue" diff --git a/src/app/tests/suites/certification/Test_TC_SC_4_10.yaml b/src/app/tests/suites/certification/Test_TC_SC_4_10.yaml deleted file mode 100644 index 987bc62790..0000000000 --- a/src/app/tests/suites/certification/Test_TC_SC_4_10.yaml +++ /dev/null @@ -1,60 +0,0 @@ -# Copyright (c) 2021 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. -# Auto-generated scripts for harness use only, please review before automation. The endpoints and cluster names are currently set to default - -name: - 15.4.10. [TC-SC-4.10] Operational Discovery - SIT ICD Node - [{DUT_Commissionee}] - -PICS: - - MCORE.ROLE.COMMISSIONEE - - MCORE.SC.SED - -config: - nodeId: 0x12344321 - cluster: "Basic Information" - endpoint: 0 - -tests: - - label: "Precondition" - verification: | - 1. Nodes are joined in the same Fabric - 2. DUT is a sleepy device (MCORE.SC.SED) - disabled: true - - - label: "Step 1: DUT is instructed to advertise its service" - verification: | - 1. Provision the DUT by TH (Chip-tool) - disabled: true - - - label: "Step 2: TH scans for DNS-SD advertising" - verification: | - avahi-browse -rt _matter._tcp - On the TH(Chip-tool) Log: Verify the DUT is advertising for: - - SII key is higher than the SESSION_IDLE_INTERVAL default value (> 500 milliseconds) - - SII key and SAI key is less than 3600000 (1hour in milliseconds) - - + eth0 IPv6 3A235FF3FA2DAC10-0000000000000055 _matter._tcp local - + eth0 IPv4 3A235FF3FA2DAC10-0000000000000055 _matter._tcp local - = eth0 IPv4 3A235FF3FA2DAC10-0000000000000055 _matter._tcp local - hostname = [D21165B5F440B033.local] - address = [fd11:22::4b31:9932:cffe:b41a] - port = [5540] - txt = ["T=0" "SAI=300" "SII=5000" "SAT=4000"] - = eth0 IPv6 3A235FF3FA2DAC10-0000000000000055 _matter._tcp local - hostname = [D21165B5F440B033.local] - address = [fd11:22::4b31:9932:cffe:b41a] - port = [5540] - txt = ["T=0" "SAI=300" "SII=5000"] - disabled: true diff --git a/src/app/tests/suites/certification/Test_TC_SC_4_5.yaml b/src/app/tests/suites/certification/Test_TC_SC_4_5.yaml deleted file mode 100644 index a3ba4b4f41..0000000000 --- a/src/app/tests/suites/certification/Test_TC_SC_4_5.yaml +++ /dev/null @@ -1,92 +0,0 @@ -# Copyright (c) 2021 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. -# Auto-generated scripts for harness use only, please review before automation. The endpoints and cluster names are currently set to default - -name: 15.4.5. [TC-SC-4.5] Discovery [DUT as Commissionee][Thread] - -PICS: - - MCORE.ROLE.COMMISSIONEE - -config: - nodeId: 0x12344321 - cluster: "Basic Information" - endpoint: 0 - -tests: - - label: - "Step 1: TH is instructed to start advertising two or more services - using DNS-SD" - verification: | - 1. On the raspi controller, publish matter service, using below command - - $avahi-publish-service 87E1B004E235A130-8FC7772401CD0696 _matter._tcp 22222 SII=3000 SAI=4000 T=0 - disabled: true - - - label: - "Step 2: By any means, DUT is instructed to perform an unicast UDP - query to the DNS-SD Discovery Proxy on TH for services" - PICS: - MCORE.SC.SII_OP_DISCOVERY_KEY && MCORE.SC.SAI_OP_DISCOVERY_KEY && - MCORE.SC.T_KEY - verification: | - avahi-browse -rt _matter._tcp - - Verify advertisement on the TH Log: - - + eth0 IPv6 3A235FF3FA2DAC10-0000000000000055 _matter._tcp local - + eth0 IPv4 3A235FF3FA2DAC10-0000000000000055 _matter._tcp local - = eth0 IPv4 3A235FF3FA2DAC10-0000000000000055 _matter._tcp local - hostname = [D21165B5F440B033.local] - address = [fd11:22::4b31:9932:cffe:b41a] - port = [5540] - txt = ["T=0" "SAI=300" "SII=5000"] - = eth0 IPv6 3A235FF3FA2DAC10-0000000000000055 _matter._tcp local - hostname = [D21165B5F440B033.local] - address = [fd11:22::4b31:9932:cffe:b41a] - port = [5540] - txt = ["T=0" "SAI=300" "SII=5000"] - disabled: true - - - label: - "Step 3: TH performs a change in one of the services configured at - step 1" - verification: | - 1. On the raspi controller, publish matter service chanding the T value 1, using below command - - $avahi-publish-service 87E1B004E235A130-8FC7772401CD0696 _matter._tcp 22222 SII=3000 SAI=4000 T=1 - disabled: true - - - label: "Step 4: DUT must receive a notification with new data" - PICS: - MCORE.SC.SII_OP_DISCOVERY_KEY && MCORE.SC.SAI_OP_DISCOVERY_KEY && - MCORE.SC.T_KEY - verification: | - avahi-browse -rt _matter._tcp - - - Verify advertisement on the TH Log: - - + eth0 IPv6 3A235FF3FA2DAC10-0000000000000055 _matter._tcp local - + eth0 IPv4 3A235FF3FA2DAC10-0000000000000055 _matter._tcp local - = eth0 IPv4 3A235FF3FA2DAC10-0000000000000055 _matter._tcp local - hostname = [D21165B5F440B033.local] - address = [fd11:22::4b31:9932:cffe:b41a] - port = [5540] - txt = ["T=1" "SAI=300" "SII=5000"] - = eth0 IPv6 3A235FF3FA2DAC10-0000000000000055 _matter._tcp local - hostname = [D21165B5F440B033.local] - address = [fd11:22::4b31:9932:cffe:b41a] - port = [5540] - txt = ["T=1" "SAI=300" "SII=5000"] - disabled: true From 03a14efa717c6ce729245ed227daf88de7d97e2a Mon Sep 17 00:00:00 2001 From: Jeff Tung <100387939+jtung-apple@users.noreply.github.com> Date: Wed, 21 Aug 2024 14:24:06 -0700 Subject: [PATCH 133/165] [Darwin] XPC interface for invoke needs to take into account the reply may contain non-property-list objects (#35131) --- .../Framework/CHIP/MTRDeviceController_XPC.mm | 21 ++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm b/src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm index 31acadcce5..7111aa4eb7 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm +++ b/src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm @@ -43,6 +43,21 @@ @implementation MTRDeviceController_XPC @synthesize uniqueIdentifier = _uniqueIdentifier; +- (NSXPCInterface *)_interfaceForServerProtocol +{ + NSXPCInterface * interface = [NSXPCInterface interfaceWithProtocol:@protocol(MTRXPCServerProtocol)]; + + NSSet * allowedClasses = [NSSet setWithArray:@[ + [NSString class], [NSNumber class], [NSData class], [NSArray class], [NSDictionary class], [NSError class], [MTRCommandPath class], [MTRAttributePath class] + ]]; + + [interface setClasses:allowedClasses + forSelector:@selector(deviceController:nodeID:invokeCommandWithEndpointID:clusterID:commandID:commandFields:expectedValues:expectedValueInterval:timedInvokeTimeout:completion:) + argumentIndex:0 + ofReply:YES]; + return interface; +} + - (NSXPCInterface *)_interfaceForClientProtocol { NSXPCInterface * interface = [NSXPCInterface interfaceWithProtocol:@protocol(MTRXPCClientProtocol)]; @@ -84,7 +99,7 @@ - (id)initWithUniqueIdentifier:(NSUUID *)UUID xpConnectionBlock:(NSXPCConnection MTR_LOG("Set up XPC Connection: %@", self.xpcConnection); if (self.xpcConnection) { - self.xpcConnection.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(MTRXPCServerProtocol)]; + self.xpcConnection.remoteObjectInterface = [self _interfaceForServerProtocol]; self.xpcConnection.exportedInterface = [self _interfaceForClientProtocol]; self.xpcConnection.exportedObject = self; @@ -118,9 +133,9 @@ - (id)initWithUniqueIdentifier:(NSUUID *)UUID machServiceName:(NSString *)machSe MTR_LOG("Set up XPC Connection: %@", self.xpcConnection); if (self.xpcConnection) { - self.xpcConnection.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(MTRXPCServerProtocol)]; + self.xpcConnection.remoteObjectInterface = [self _interfaceForServerProtocol]; - self.xpcConnection.exportedInterface = [NSXPCInterface interfaceWithProtocol:@protocol(MTRXPCClientProtocol)]; + self.xpcConnection.exportedInterface = [self _interfaceForClientProtocol]; self.xpcConnection.exportedObject = self; MTR_LOG("%s: resuming new XPC connection"); From 62bf76b142208dd8b8b5bfb15a6daacd930415b1 Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Wed, 21 Aug 2024 19:41:16 -0400 Subject: [PATCH 134/165] Fix Darwin to handle renames of Color Control data types. (#35135) https://github.com/project-chip/connectedhomeip/pull/33612 made the following changes to the Color Control cluster: 1) Renamed HueDirection to DirectionEnum 2) Renamed the ShortestDistance and LongestDistance values of DirectionEnum to Shortest and Longest, respectively. 3) Renamed HueMoveMode to MoveModeEnum. 4) Renamed HueStepMode to StepModeEnum. 5) Removed SaturationMoveMode in favor of MoveModeEnum. 6) Removed SaturationStepMode in favor of StepModeEnum. 7) Renamed ColorMode to ColorModeEnum. 8) Renamed the ColorTemperature value to ColorTemperatureMireds 8) Renamed ColorCapabilities to ColorCapabilitiesBitmap. 9) Renamed various fields of ColorCapabilitiesBitmap. 10) Renamed ColorLoopUpdateFlags to UpdateFlagsBitmap. 11) Renamed ColorLoopAction to ColorLoopActionEnum. 12) Added OptionsBitmap, EnhancedColorModeEnum, DriftCompensationEnum. 13) Renamed ColorLoopDirection to ColorLoopDirectionEnum. 14) Renamed the DecrementHue and IncrementHue values of ColorLoopDirectionEnum to Decrement and Increment, respectively. This change adds the right renamed/introduced/deprecated annotations for the above changes, and adds manual shims for the enums that got removed. --- .../Framework/CHIP/MTRBackwardsCompatShims.h | 29 +++ .../CHIP/templates/availability.yaml | 143 +++++++++++++- .../CHIP/zap-generated/MTRBaseClusters.h | 177 +++++++++++++----- 3 files changed, 296 insertions(+), 53 deletions(-) diff --git a/src/darwin/Framework/CHIP/MTRBackwardsCompatShims.h b/src/darwin/Framework/CHIP/MTRBackwardsCompatShims.h index 8903957414..1a183c83de 100644 --- a/src/darwin/Framework/CHIP/MTRBackwardsCompatShims.h +++ b/src/darwin/Framework/CHIP/MTRBackwardsCompatShims.h @@ -159,4 +159,33 @@ typedef NS_ENUM(uint8_t, MTROTASoftwareUpdateRequestorOTAUpdateState) { = 0x08, } MTR_DEPRECATED("Please use MTROTASoftwareUpdateRequestorUpdateState", ios(16.4, 17.2), macos(13.3, 14.2), watchos(9.4, 10.2), tvos(16.4, 17.2)); +/** + * ColorControl used to have HueMoveMode/SaturationMoveMode and HueStepMode/SaturationStepMode that had + * identical values. Those got replaced with MoveModeEnum and StepModeEnum respectively. We codegen + * HueMoveMode and HueStepMode as aliases of MoveModeEnum and StepModeEnum, but we need manual shims for + * 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") + = 0x00, + MTRColorControlSaturationMoveModeUp MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) + MTR_NEWLY_DEPRECATED("Please use MTRColorControlMoveModeUp") + = 0x01, + MTRColorControlSaturationMoveModeDown 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"); + +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") + = 0x01, + MTRColorControlSaturationStepModeDown 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"); + NS_ASSUME_NONNULL_END diff --git a/src/darwin/Framework/CHIP/templates/availability.yaml b/src/darwin/Framework/CHIP/templates/availability.yaml index c1f1e1bd6f..2272d5256d 100644 --- a/src/darwin/Framework/CHIP/templates/availability.yaml +++ b/src/darwin/Framework/CHIP/templates/availability.yaml @@ -3237,9 +3237,15 @@ - FanModeSequenceType - FanModeType ColorControl: - - ColorLoopAction - - ColorLoopDirection - - ColorMode + # ColorLoopActionEnum, ColorLoopDirectionEnum and ColorModeEnum + # were originally named ColorLoopAction, ColorLoopDirection, and + # ColorMode, but we generate the same API for the names + # with/without "Enum" at the end and the cluster name + # present/absent at the beginning, so the names can just change + # here. + - ColorLoopActionEnum + - ColorLoopDirectionEnum + - ColorModeEnum - HueDirection - HueMoveMode - HueStepMode @@ -3980,14 +3986,20 @@ - Auto - Smart ColorControl: - ColorLoopAction: + # ColorLoopActionEnum, ColorLoopDirectionEnum and ColorModeEnum + # were originally named ColorLoopAction, ColorLoopDirection, and + # ColorMode, but we generate the same API for the names + # with/without "Enum" at the end and the cluster name + # present/absent at the beginning, so the names can just change + # here. + ColorLoopActionEnum: - Deactivate - ActivateFromColorLoopStartEnhancedHue - ActivateFromEnhancedCurrentHue - ColorLoopDirection: + ColorLoopDirectionEnum: - DecrementHue - IncrementHue - ColorMode: + ColorModeEnum: - CurrentHueAndCurrentSaturation - CurrentXAndCurrentY - ColorTemperature @@ -9682,6 +9694,64 @@ - release: "Future" versions: "future" + introduced: + enums: + ColorControl: + - DirectionEnum + - DriftCompensationEnum + - EnhancedColorModeEnum + - MoveModeEnum + - StepModeEnum + enum values: + ColorControl: + ColorLoopDirectionEnum: + - Decrement + - Increment + ColorModeEnum: + - ColorTemperatureMireds + DirectionEnum: + - Shortest + - Longest + - Up + - Down + DriftCompensationEnum: + - None + - OtherOrUnknown + - TemperatureMonitoring + - OpticalLuminanceMonitoringAndFeedback + - OpticalColorMonitoringAndFeedback + EnhancedColorModeEnum: + - CurrentHueAndCurrentSaturation + - CurrentXAndCurrentY + - ColorTemperatureMireds + - EnhancedCurrentHueAndCurrentSaturation + MoveModeEnum: + - Stop + - Up + - Down + StepModeEnum: + - Up + - Down + bitmaps: + ColorControl: + - ColorCapabilitiesBitmap + - OptionsBitmap + - UpdateFlagsBitmap + bitmap values: + ColorControl: + ColorCapabilitiesBitmap: + - HueSaturation + - EnhancedHue + - ColorLoop + - XY + - ColorTemperature + OptionsBitmap: + - ExecuteIfOff + UpdateFlagsBitmap: + - UpdateAction + - UpdateDirection + - UpdateTime + - UpdateStartHue provisional: clusters: # Targeting 1.4 @@ -9820,3 +9890,64 @@ Feature: # Targeting 1.4 - ActionSwitch + renames: + enums: + ColorControl: + DirectionEnum: HueDirection + MoveModeEnum: HueMoveMode + StepModeEnum: HueStepMode + enum values: + ColorControl: + ColorLoopDirectionEnum: + Decrement: DecrementHue + Increment: IncrementHue + ColorModeEnum: + ColorTemperatureMireds: ColorTemperature + HueDirection: + Shortest: ShortestDistance + Longest: LongestDistance + bitmaps: + ColorControl: + ColorCapabilitiesBitmap: ColorCapabilities + UpdateFlagsBitmap: ColorLoopUpdateFlags + bitmap values: + ColorControl: + ColorCapabilities: + HueSaturation: HueSaturationSupported + EnhancedHue: EnhancedHueSupported + ColorLoop: ColorLoopSupported + XY: XYAttributesSupported + ColorTemperature: ColorTemperatureSupported + deprecated: + enums: + ColorControl: + - HueDirection + - HueMoveMode + - HueStepMode + enum values: + ColorControl: + ColorLoopDirectionEnum: + - DecrementHue + - IncrementHue + ColorModeEnum: + - ColorTemperature + bitmaps: + ColorControl: + - ColorCapabilities + - ColorLoopUpdateFlags + removed: + enum values: + ColorControl: + # Don't expose the new value names on the old enum names + HueDirection: + - Shortest + - Longest + bitmap values: + ColorControl: + # Don't expose the new field names on the old bitmap names + ColorCapabilities: + - HueSaturation + - EnhancedHue + - ColorLoop + - XY + - ColorTemperature diff --git a/src/darwin/Framework/CHIP/zap-generated/MTRBaseClusters.h b/src/darwin/Framework/CHIP/zap-generated/MTRBaseClusters.h index efb5fca954..c00233470f 100644 --- a/src/darwin/Framework/CHIP/zap-generated/MTRBaseClusters.h +++ b/src/darwin/Framework/CHIP/zap-generated/MTRBaseClusters.h @@ -20203,62 +20203,129 @@ typedef NS_ENUM(uint8_t, MTRThermostatUserInterfaceConfigurationTemperatureDispl } MTR_AVAILABLE(ios(17.4), macos(14.4), watchos(10.4), tvos(17.4)); typedef NS_ENUM(uint8_t, MTRColorControlColorLoopAction) { - MTRColorControlColorLoopActionDeactivate MTR_PROVISIONALLY_AVAILABLE = 0x00, - MTRColorControlColorLoopActionActivateFromColorLoopStartEnhancedHue MTR_PROVISIONALLY_AVAILABLE = 0x01, - MTRColorControlColorLoopActionActivateFromEnhancedCurrentHue MTR_PROVISIONALLY_AVAILABLE = 0x02, -} MTR_PROVISIONALLY_AVAILABLE; + MTRColorControlColorLoopActionDeactivate MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) = 0x00, + MTRColorControlColorLoopActionActivateFromColorLoopStartEnhancedHue MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) = 0x01, + MTRColorControlColorLoopActionActivateFromEnhancedCurrentHue MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) = 0x02, +} MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)); typedef NS_ENUM(uint8_t, MTRColorControlColorLoopDirection) { - MTRColorControlColorLoopDirectionDecrement MTR_PROVISIONALLY_AVAILABLE = 0x00, - MTRColorControlColorLoopDirectionIncrement MTR_PROVISIONALLY_AVAILABLE = 0x01, -} MTR_PROVISIONALLY_AVAILABLE; + 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, +} MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)); typedef NS_ENUM(uint8_t, MTRColorControlColorMode) { - MTRColorControlColorModeCurrentHueAndCurrentSaturation MTR_PROVISIONALLY_AVAILABLE = 0x00, - MTRColorControlColorModeCurrentXAndCurrentY MTR_PROVISIONALLY_AVAILABLE = 0x01, - MTRColorControlColorModeColorTemperatureMireds MTR_PROVISIONALLY_AVAILABLE = 0x02, -} MTR_PROVISIONALLY_AVAILABLE; + 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, +} MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)); typedef NS_ENUM(uint8_t, MTRColorControlDirection) { - MTRColorControlDirectionShortest MTR_PROVISIONALLY_AVAILABLE = 0x00, - MTRColorControlDirectionLongest MTR_PROVISIONALLY_AVAILABLE = 0x01, - MTRColorControlDirectionUp MTR_PROVISIONALLY_AVAILABLE = 0x02, - MTRColorControlDirectionDown MTR_PROVISIONALLY_AVAILABLE = 0x03, -} MTR_PROVISIONALLY_AVAILABLE; + MTRColorControlDirectionShortest MTR_NEWLY_AVAILABLE = 0x00, + MTRColorControlDirectionLongest MTR_NEWLY_AVAILABLE = 0x01, + MTRColorControlDirectionUp MTR_NEWLY_AVAILABLE = 0x02, + MTRColorControlDirectionDown MTR_NEWLY_AVAILABLE = 0x03, +} MTR_NEWLY_AVAILABLE; + +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"); typedef NS_ENUM(uint8_t, MTRColorControlDriftCompensation) { - MTRColorControlDriftCompensationNone MTR_PROVISIONALLY_AVAILABLE = 0x00, - MTRColorControlDriftCompensationOtherOrUnknown MTR_PROVISIONALLY_AVAILABLE = 0x01, - MTRColorControlDriftCompensationTemperatureMonitoring MTR_PROVISIONALLY_AVAILABLE = 0x02, - MTRColorControlDriftCompensationOpticalLuminanceMonitoringAndFeedback MTR_PROVISIONALLY_AVAILABLE = 0x03, - MTRColorControlDriftCompensationOpticalColorMonitoringAndFeedback MTR_PROVISIONALLY_AVAILABLE = 0x04, -} MTR_PROVISIONALLY_AVAILABLE; + 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; typedef NS_ENUM(uint8_t, MTRColorControlEnhancedColorMode) { - MTRColorControlEnhancedColorModeCurrentHueAndCurrentSaturation MTR_PROVISIONALLY_AVAILABLE = 0x00, - MTRColorControlEnhancedColorModeCurrentXAndCurrentY MTR_PROVISIONALLY_AVAILABLE = 0x01, - MTRColorControlEnhancedColorModeColorTemperatureMireds MTR_PROVISIONALLY_AVAILABLE = 0x02, - MTRColorControlEnhancedColorModeEnhancedCurrentHueAndCurrentSaturation MTR_PROVISIONALLY_AVAILABLE = 0x03, -} MTR_PROVISIONALLY_AVAILABLE; + MTRColorControlEnhancedColorModeCurrentHueAndCurrentSaturation MTR_NEWLY_AVAILABLE = 0x00, + MTRColorControlEnhancedColorModeCurrentXAndCurrentY MTR_NEWLY_AVAILABLE = 0x01, + MTRColorControlEnhancedColorModeColorTemperatureMireds MTR_NEWLY_AVAILABLE = 0x02, + MTRColorControlEnhancedColorModeEnhancedCurrentHueAndCurrentSaturation MTR_NEWLY_AVAILABLE = 0x03, +} MTR_NEWLY_AVAILABLE; typedef NS_ENUM(uint8_t, MTRColorControlMoveMode) { - MTRColorControlMoveModeStop MTR_PROVISIONALLY_AVAILABLE = 0x00, - MTRColorControlMoveModeUp MTR_PROVISIONALLY_AVAILABLE = 0x01, - MTRColorControlMoveModeDown MTR_PROVISIONALLY_AVAILABLE = 0x03, -} MTR_PROVISIONALLY_AVAILABLE; + MTRColorControlMoveModeStop MTR_NEWLY_AVAILABLE = 0x00, + MTRColorControlMoveModeUp MTR_NEWLY_AVAILABLE = 0x01, + MTRColorControlMoveModeDown MTR_NEWLY_AVAILABLE = 0x03, +} MTR_NEWLY_AVAILABLE; + +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"); typedef NS_ENUM(uint8_t, MTRColorControlStepMode) { - MTRColorControlStepModeUp MTR_PROVISIONALLY_AVAILABLE = 0x01, - MTRColorControlStepModeDown MTR_PROVISIONALLY_AVAILABLE = 0x03, -} MTR_PROVISIONALLY_AVAILABLE; + MTRColorControlStepModeUp MTR_NEWLY_AVAILABLE = 0x01, + MTRColorControlStepModeDown MTR_NEWLY_AVAILABLE = 0x03, +} MTR_NEWLY_AVAILABLE; + +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"); typedef NS_OPTIONS(uint16_t, MTRColorControlColorCapabilitiesBitmap) { - MTRColorControlColorCapabilitiesBitmapHueSaturation MTR_PROVISIONALLY_AVAILABLE = 0x1, - MTRColorControlColorCapabilitiesBitmapEnhancedHue MTR_PROVISIONALLY_AVAILABLE = 0x2, - MTRColorControlColorCapabilitiesBitmapColorLoop MTR_PROVISIONALLY_AVAILABLE = 0x4, - MTRColorControlColorCapabilitiesBitmapXY MTR_PROVISIONALLY_AVAILABLE = 0x8, - MTRColorControlColorCapabilitiesBitmapColorTemperature MTR_PROVISIONALLY_AVAILABLE = 0x10, -} MTR_PROVISIONALLY_AVAILABLE; + 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; + +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"); typedef NS_OPTIONS(uint32_t, MTRColorControlFeature) { MTRColorControlFeatureHueAndSaturation MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) = 0x1, @@ -20269,15 +20336,31 @@ 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_PROVISIONALLY_AVAILABLE = 0x1, -} MTR_PROVISIONALLY_AVAILABLE; + MTRColorControlOptionsBitmapExecuteIfOff MTR_NEWLY_AVAILABLE = 0x1, +} MTR_NEWLY_AVAILABLE; typedef NS_OPTIONS(uint8_t, MTRColorControlUpdateFlagsBitmap) { - MTRColorControlUpdateFlagsBitmapUpdateAction MTR_PROVISIONALLY_AVAILABLE = 0x1, - MTRColorControlUpdateFlagsBitmapUpdateDirection MTR_PROVISIONALLY_AVAILABLE = 0x2, - MTRColorControlUpdateFlagsBitmapUpdateTime MTR_PROVISIONALLY_AVAILABLE = 0x4, - MTRColorControlUpdateFlagsBitmapUpdateStartHue MTR_PROVISIONALLY_AVAILABLE = 0x8, -} MTR_PROVISIONALLY_AVAILABLE; + MTRColorControlUpdateFlagsBitmapUpdateAction MTR_NEWLY_AVAILABLE = 0x1, + MTRColorControlUpdateFlagsBitmapUpdateDirection MTR_NEWLY_AVAILABLE = 0x2, + MTRColorControlUpdateFlagsBitmapUpdateTime MTR_NEWLY_AVAILABLE = 0x4, + MTRColorControlUpdateFlagsBitmapUpdateStartHue MTR_NEWLY_AVAILABLE = 0x8, +} MTR_NEWLY_AVAILABLE; + +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"); typedef NS_OPTIONS(uint8_t, MTRBallastConfigurationBallastStatusBitmap) { MTRBallastConfigurationBallastStatusBitmapBallastNonOperational MTR_PROVISIONALLY_AVAILABLE = 0x1, From dd8b002e7e65d3f6b1f1a95ef8a740607202ea38 Mon Sep 17 00:00:00 2001 From: Sharad Binjola <31142146+sharadb-amazon@users.noreply.github.com> Date: Wed, 21 Aug 2024 17:01:20 -0700 Subject: [PATCH 135/165] Re-route deprecated android casting APIs to new ones (#35136) --- .../android/App/app/build.gradle | 4 +- .../com/chip/casting/app/CastingContext.java | 2 + .../chip/casting/app/CertTestFragment.java | 12 +- .../app/CommissionerDiscoveryFragment.java | 6 +- .../chip/casting/app/ConnectionFragment.java | 10 +- .../casting/app/ContentLauncherFragment.java | 6 +- .../casting/app/MediaPlaybackFragment.java | 6 +- .../casting/app/SelectClusterFragment.java | 6 +- .../chip/casting/util/DACProviderStub.java | 2 + .../casting/util/GlobalCastingConstants.java | 11 + .../jni/com/chip/casting/AppParameters.java | 2 + .../chip/casting/CommissioningCallbacks.java | 2 + .../jni/com/chip/casting/ContentApp.java | 37 + .../chip/casting/ContentLauncherTypes.java | 2 + .../jni/com/chip/casting/DACProvider.java | 2 + .../com/chip/casting/DiscoveredNodeData.java | 26 +- .../jni/com/chip/casting/FailureCallback.java | 6 +- .../chip/casting/MatterCallbackHandler.java | 6 +- .../jni/com/chip/casting/MatterError.java | 9 + .../com/chip/casting/MediaPlaybackTypes.java | 2 + .../SubscriptionEstablishedCallback.java | 2 + .../jni/com/chip/casting/SuccessCallback.java | 2 + .../chip/casting/TargetNavigatorTypes.java | 2 + .../jni/com/chip/casting/TvCastingApp.java | 1327 ++++++++++ .../jni/com/chip/casting/VideoPlayer.java | 62 +- .../App/app/src/main/AndroidManifest.xml | 4 +- .../casting/util/GlobalCastingConstants.java | 11 - .../casting}/ChipTvCastingApplication.java | 2 +- .../app => matter/casting}/MainActivity.java | 16 +- .../chip/casting/NsdDiscoveryListener.java | 128 - .../com/chip/casting/NsdResolveListener.java | 165 -- .../jni/com/chip/casting/TvCastingApp.java | 608 ----- .../matter/casting/support/DataProvider.java | 4 +- .../App/app/src/main/jni/cpp/Constants.h | 74 - .../app/src/main/jni/cpp/ConversionUtils.cpp | 410 ---- .../app/src/main/jni/cpp/ConversionUtils.h | 36 - .../jni/cpp/MatterCallbackHandler-JNI.cpp | 419 ---- .../main/jni/cpp/MatterCallbackHandler-JNI.h | 293 --- .../app/src/main/jni/cpp/TvCastingApp-JNI.cpp | 2129 ----------------- .../app/src/main/jni/cpp/TvCastingApp-JNI.h | 162 -- .../src/main/jni/cpp/core/CastingApp-JNI.cpp | 15 +- .../cpp/core/CastingPlayerDiscovery-JNI.cpp | 1 - .../jni/cpp/core/MatterCastingPlayer-JNI.cpp | 1 - .../main/jni/cpp/core/MatterEndpoint-JNI.cpp | 1 - .../jni/cpp/{ => support}/JNIDACProvider.cpp | 8 + .../jni/cpp/{ => support}/JNIDACProvider.h | 8 + .../app/src/main/res/layout/activity_main.xml | 2 +- .../CommissionerDiscoveryListenerTest.java | 68 - examples/tv-casting-app/android/BUILD.gn | 46 +- .../tv-casting-common/core/CastingApp.cpp | 2 - 50 files changed, 1566 insertions(+), 4601 deletions(-) rename examples/tv-casting-app/android/App/app/src/{main => compat}/java/com/chip/casting/app/CastingContext.java (87%) rename examples/tv-casting-app/android/App/app/src/{main => compat}/java/com/chip/casting/app/CertTestFragment.java (97%) rename examples/tv-casting-app/android/App/app/src/{main => compat}/java/com/chip/casting/app/CommissionerDiscoveryFragment.java (98%) rename examples/tv-casting-app/android/App/app/src/{main => compat}/java/com/chip/casting/app/ConnectionFragment.java (96%) rename examples/tv-casting-app/android/App/app/src/{main => compat}/java/com/chip/casting/app/ContentLauncherFragment.java (94%) rename examples/tv-casting-app/android/App/app/src/{main => compat}/java/com/chip/casting/app/MediaPlaybackFragment.java (97%) rename examples/tv-casting-app/android/App/app/src/{main => compat}/java/com/chip/casting/app/SelectClusterFragment.java (95%) rename examples/tv-casting-app/android/App/app/src/{main => compat}/java/com/chip/casting/util/DACProviderStub.java (98%) create mode 100644 examples/tv-casting-app/android/App/app/src/compat/java/com/chip/casting/util/GlobalCastingConstants.java rename examples/tv-casting-app/android/App/app/src/{main => compat}/jni/com/chip/casting/AppParameters.java (97%) rename examples/tv-casting-app/android/App/app/src/{main => compat}/jni/com/chip/casting/CommissioningCallbacks.java (97%) rename examples/tv-casting-app/android/App/app/src/{main => compat}/jni/com/chip/casting/ContentApp.java (51%) rename examples/tv-casting-app/android/App/app/src/{main => compat}/jni/com/chip/casting/ContentLauncherTypes.java (96%) rename examples/tv-casting-app/android/App/app/src/{main => compat}/jni/com/chip/casting/DACProvider.java (92%) rename examples/tv-casting-app/android/App/app/src/{main => compat}/jni/com/chip/casting/DiscoveredNodeData.java (88%) rename examples/tv-casting-app/android/App/app/src/{main => compat}/jni/com/chip/casting/FailureCallback.java (85%) rename examples/tv-casting-app/android/App/app/src/{main => compat}/jni/com/chip/casting/MatterCallbackHandler.java (85%) rename examples/tv-casting-app/android/App/app/src/{main => compat}/jni/com/chip/casting/MatterError.java (84%) rename examples/tv-casting-app/android/App/app/src/{main => compat}/jni/com/chip/casting/MediaPlaybackTypes.java (93%) rename examples/tv-casting-app/android/App/app/src/{main => compat}/jni/com/chip/casting/SubscriptionEstablishedCallback.java (91%) rename examples/tv-casting-app/android/App/app/src/{main => compat}/jni/com/chip/casting/SuccessCallback.java (91%) rename examples/tv-casting-app/android/App/app/src/{main => compat}/jni/com/chip/casting/TargetNavigatorTypes.java (93%) create mode 100644 examples/tv-casting-app/android/App/app/src/compat/jni/com/chip/casting/TvCastingApp.java rename examples/tv-casting-app/android/App/app/src/{main => compat}/jni/com/chip/casting/VideoPlayer.java (81%) delete mode 100644 examples/tv-casting-app/android/App/app/src/main/java/com/chip/casting/util/GlobalCastingConstants.java rename examples/tv-casting-app/android/App/app/src/main/java/com/{chip/casting/app => matter/casting}/ChipTvCastingApplication.java (84%) rename examples/tv-casting-app/android/App/app/src/main/java/com/{chip/casting/app => matter/casting}/MainActivity.java (92%) delete mode 100644 examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/NsdDiscoveryListener.java delete mode 100644 examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/NsdResolveListener.java delete mode 100644 examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/TvCastingApp.java delete mode 100644 examples/tv-casting-app/android/App/app/src/main/jni/cpp/Constants.h delete mode 100644 examples/tv-casting-app/android/App/app/src/main/jni/cpp/ConversionUtils.cpp delete mode 100644 examples/tv-casting-app/android/App/app/src/main/jni/cpp/ConversionUtils.h delete mode 100644 examples/tv-casting-app/android/App/app/src/main/jni/cpp/MatterCallbackHandler-JNI.cpp delete mode 100644 examples/tv-casting-app/android/App/app/src/main/jni/cpp/MatterCallbackHandler-JNI.h delete mode 100644 examples/tv-casting-app/android/App/app/src/main/jni/cpp/TvCastingApp-JNI.cpp delete mode 100644 examples/tv-casting-app/android/App/app/src/main/jni/cpp/TvCastingApp-JNI.h rename examples/tv-casting-app/android/App/app/src/main/jni/cpp/{ => support}/JNIDACProvider.cpp (98%) rename examples/tv-casting-app/android/App/app/src/main/jni/cpp/{ => support}/JNIDACProvider.h (94%) delete mode 100644 examples/tv-casting-app/android/App/app/src/test/java/com/chip/casting/dnssd/CommissionerDiscoveryListenerTest.java diff --git a/examples/tv-casting-app/android/App/app/build.gradle b/examples/tv-casting-app/android/App/app/build.gradle index 3dcdad715e..757e6a6522 100644 --- a/examples/tv-casting-app/android/App/app/build.gradle +++ b/examples/tv-casting-app/android/App/app/build.gradle @@ -7,7 +7,7 @@ android { defaultConfig { applicationId "com.chip.casting" - minSdk 24 + minSdk 26 targetSdk 30 versionCode 1 versionName "1.0" @@ -47,6 +47,8 @@ android { java.srcDirs = [ 'src/main/java', 'src/main/jni', + 'src/compat/java', + 'src/compat/jni', ] // uncomment this code to debug diff --git a/examples/tv-casting-app/android/App/app/src/main/java/com/chip/casting/app/CastingContext.java b/examples/tv-casting-app/android/App/app/src/compat/java/com/chip/casting/app/CastingContext.java similarity index 87% rename from examples/tv-casting-app/android/App/app/src/main/java/com/chip/casting/app/CastingContext.java rename to examples/tv-casting-app/android/App/app/src/compat/java/com/chip/casting/app/CastingContext.java index acab829034..b089e92b8f 100644 --- a/examples/tv-casting-app/android/App/app/src/main/java/com/chip/casting/app/CastingContext.java +++ b/examples/tv-casting-app/android/App/app/src/compat/java/com/chip/casting/app/CastingContext.java @@ -5,6 +5,8 @@ import androidx.fragment.app.FragmentActivity; import com.R; +/** @deprecated Use the APIs described in /examples/tv-casting-app/APIs.md instead. */ +@Deprecated public class CastingContext { private FragmentActivity fragmentActivity; diff --git a/examples/tv-casting-app/android/App/app/src/main/java/com/chip/casting/app/CertTestFragment.java b/examples/tv-casting-app/android/App/app/src/compat/java/com/chip/casting/app/CertTestFragment.java similarity index 97% rename from examples/tv-casting-app/android/App/app/src/main/java/com/chip/casting/app/CertTestFragment.java rename to examples/tv-casting-app/android/App/app/src/compat/java/com/chip/casting/app/CertTestFragment.java index 7ee9fa3c46..27f00aab8e 100644 --- a/examples/tv-casting-app/android/App/app/src/main/java/com/chip/casting/app/CertTestFragment.java +++ b/examples/tv-casting-app/android/App/app/src/compat/java/com/chip/casting/app/CertTestFragment.java @@ -313,7 +313,17 @@ private void runCertTests(Activity activity) { "messages_presentMessages", successFailureCallback, () -> { - tvCastingApp.messages_presentMessages(kTVApp, "CastingAppTestMessage", callback); + final byte[] messageID = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5}; + tvCastingApp.messages_presentMessages( + kTVApp, + messageID, + 0, + 0, + (long) 0, + (long) 60 * 1000, + "CastingAppTestMessage", + Optional.empty(), + callback); }); runAndWait( diff --git a/examples/tv-casting-app/android/App/app/src/main/java/com/chip/casting/app/CommissionerDiscoveryFragment.java b/examples/tv-casting-app/android/App/app/src/compat/java/com/chip/casting/app/CommissionerDiscoveryFragment.java similarity index 98% rename from examples/tv-casting-app/android/App/app/src/main/java/com/chip/casting/app/CommissionerDiscoveryFragment.java rename to examples/tv-casting-app/android/App/app/src/compat/java/com/chip/casting/app/CommissionerDiscoveryFragment.java index 3a119940b6..c7aa931d9f 100644 --- a/examples/tv-casting-app/android/App/app/src/main/java/com/chip/casting/app/CommissionerDiscoveryFragment.java +++ b/examples/tv-casting-app/android/App/app/src/compat/java/com/chip/casting/app/CommissionerDiscoveryFragment.java @@ -28,7 +28,11 @@ import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; -/** A {@link Fragment} to discover commissioners on the network */ +/** + * @deprecated Refer to com.matter.casting.DiscoveryExampleFragment. + *

A {@link Fragment} to discover commissioners on the network + */ +@Deprecated public class CommissionerDiscoveryFragment extends Fragment { private static final String TAG = CommissionerDiscoveryFragment.class.getSimpleName(); private static final long DISCOVERY_POLL_INTERVAL_MS = 15000; diff --git a/examples/tv-casting-app/android/App/app/src/main/java/com/chip/casting/app/ConnectionFragment.java b/examples/tv-casting-app/android/App/app/src/compat/java/com/chip/casting/app/ConnectionFragment.java similarity index 96% rename from examples/tv-casting-app/android/App/app/src/main/java/com/chip/casting/app/ConnectionFragment.java rename to examples/tv-casting-app/android/App/app/src/compat/java/com/chip/casting/app/ConnectionFragment.java index 09ba31b2c8..dcd681d7cb 100644 --- a/examples/tv-casting-app/android/App/app/src/main/java/com/chip/casting/app/ConnectionFragment.java +++ b/examples/tv-casting-app/android/App/app/src/compat/java/com/chip/casting/app/ConnectionFragment.java @@ -21,9 +21,14 @@ import com.chip.casting.util.GlobalCastingConstants; import java.util.concurrent.Executors; -/** A {@link Fragment} to get the TV Casting App commissioned / connected. */ +/** + * @deprecated Refer to com.matter.casting.ConnectionExampleFragment. + *

A {@link Fragment} to get the TV Casting App commissioned / connected + */ +@Deprecated public class ConnectionFragment extends Fragment { private static final String TAG = ConnectionFragment.class.getSimpleName(); + private static final Integer targetContentAppVendorId = 65521; private final TvCastingApp tvCastingApp; private final DiscoveredNodeData selectedCommissioner; @@ -189,7 +194,8 @@ public void handle(MatterError error) { + " port: " + selectedCommissioner.getPort()); - this.sendUdcSuccess = tvCastingApp.sendCommissioningRequest(selectedCommissioner); + this.sendUdcSuccess = + tvCastingApp.sendCommissioningRequest(selectedCommissioner, targetContentAppVendorId); updateUiOnConnectionSuccess(); } } else { diff --git a/examples/tv-casting-app/android/App/app/src/main/java/com/chip/casting/app/ContentLauncherFragment.java b/examples/tv-casting-app/android/App/app/src/compat/java/com/chip/casting/app/ContentLauncherFragment.java similarity index 94% rename from examples/tv-casting-app/android/App/app/src/main/java/com/chip/casting/app/ContentLauncherFragment.java rename to examples/tv-casting-app/android/App/app/src/compat/java/com/chip/casting/app/ContentLauncherFragment.java index d1c3c9f957..14bcfcae15 100644 --- a/examples/tv-casting-app/android/App/app/src/main/java/com/chip/casting/app/ContentLauncherFragment.java +++ b/examples/tv-casting-app/android/App/app/src/compat/java/com/chip/casting/app/ContentLauncherFragment.java @@ -15,7 +15,11 @@ import com.chip.casting.MatterError; import com.chip.casting.TvCastingApp; -/** A {@link Fragment} to send Content Launcher commands from the TV Casting App. */ +/** + * @deprecated Refer to com.matter.casting.ContentLauncherLaunchURLExampleFragment. + *

A {@link Fragment} to send Content Launcher commands from the TV Casting App. + */ +@Deprecated public class ContentLauncherFragment extends Fragment { private static final String TAG = ContentLauncherFragment.class.getSimpleName(); diff --git a/examples/tv-casting-app/android/App/app/src/main/java/com/chip/casting/app/MediaPlaybackFragment.java b/examples/tv-casting-app/android/App/app/src/compat/java/com/chip/casting/app/MediaPlaybackFragment.java similarity index 97% rename from examples/tv-casting-app/android/App/app/src/main/java/com/chip/casting/app/MediaPlaybackFragment.java rename to examples/tv-casting-app/android/App/app/src/compat/java/com/chip/casting/app/MediaPlaybackFragment.java index a9c38443a7..b48dcd2771 100644 --- a/examples/tv-casting-app/android/App/app/src/main/java/com/chip/casting/app/MediaPlaybackFragment.java +++ b/examples/tv-casting-app/android/App/app/src/compat/java/com/chip/casting/app/MediaPlaybackFragment.java @@ -18,7 +18,11 @@ import com.chip.casting.SuccessCallback; import com.chip.casting.TvCastingApp; -/** A {@link Fragment} for the Media Playback cluster */ +/** + * @deprecated Refer to com.matter.casting.MediaPlaybackSubscribeToCurrentStateExampleFragment. + *

A {@link Fragment} for the Media Playback cluster + */ +@Deprecated public class MediaPlaybackFragment extends Fragment { private static final String TAG = MediaPlaybackFragment.class.getSimpleName(); diff --git a/examples/tv-casting-app/android/App/app/src/main/java/com/chip/casting/app/SelectClusterFragment.java b/examples/tv-casting-app/android/App/app/src/compat/java/com/chip/casting/app/SelectClusterFragment.java similarity index 95% rename from examples/tv-casting-app/android/App/app/src/main/java/com/chip/casting/app/SelectClusterFragment.java rename to examples/tv-casting-app/android/App/app/src/compat/java/com/chip/casting/app/SelectClusterFragment.java index f89fc36009..47cc4728f9 100644 --- a/examples/tv-casting-app/android/App/app/src/main/java/com/chip/casting/app/SelectClusterFragment.java +++ b/examples/tv-casting-app/android/App/app/src/compat/java/com/chip/casting/app/SelectClusterFragment.java @@ -10,7 +10,11 @@ import com.R; import com.chip.casting.TvCastingApp; -/** An interstitial {@link Fragment} to select one of the supported media actions to perform */ +/** + * @deprecated Refer to com.matter.casting.ActionSelectorFragment. + *

An interstitial {@link Fragment} to select one of the supported media actions to perform + */ +@Deprecated public class SelectClusterFragment extends Fragment { private static final String TAG = SelectClusterFragment.class.getSimpleName(); diff --git a/examples/tv-casting-app/android/App/app/src/main/java/com/chip/casting/util/DACProviderStub.java b/examples/tv-casting-app/android/App/app/src/compat/java/com/chip/casting/util/DACProviderStub.java similarity index 98% rename from examples/tv-casting-app/android/App/app/src/main/java/com/chip/casting/util/DACProviderStub.java rename to examples/tv-casting-app/android/App/app/src/compat/java/com/chip/casting/util/DACProviderStub.java index 9dbae27c6e..2a91c055dc 100644 --- a/examples/tv-casting-app/android/App/app/src/main/java/com/chip/casting/util/DACProviderStub.java +++ b/examples/tv-casting-app/android/App/app/src/compat/java/com/chip/casting/util/DACProviderStub.java @@ -11,6 +11,8 @@ import java.security.spec.ECParameterSpec; import java.security.spec.ECPrivateKeySpec; +/** @deprecated Refer to com.matter.casting.DACProviderStub. */ +@Deprecated public class DACProviderStub implements DACProvider { private String kDevelopmentDAC_Cert_FFF1_8001 = diff --git a/examples/tv-casting-app/android/App/app/src/compat/java/com/chip/casting/util/GlobalCastingConstants.java b/examples/tv-casting-app/android/App/app/src/compat/java/com/chip/casting/util/GlobalCastingConstants.java new file mode 100644 index 0000000000..526bbb0740 --- /dev/null +++ b/examples/tv-casting-app/android/App/app/src/compat/java/com/chip/casting/util/GlobalCastingConstants.java @@ -0,0 +1,11 @@ +package com.chip.casting.util; + +public class GlobalCastingConstants { + public static final int CommissioningWindowDurationSecs = 3 * 60; + public static final int SetupPasscode = 20202021; + public static final int Discriminator = 0xF00; + + // set to true, to demo the simplified casting APIs. + // Otherwise, the deprecated casting APIs are invoked + public static final boolean ChipCastingSimplified = true; +} diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/AppParameters.java b/examples/tv-casting-app/android/App/app/src/compat/jni/com/chip/casting/AppParameters.java similarity index 97% rename from examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/AppParameters.java rename to examples/tv-casting-app/android/App/app/src/compat/jni/com/chip/casting/AppParameters.java index 18c9a351f0..3d72b38f72 100644 --- a/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/AppParameters.java +++ b/examples/tv-casting-app/android/App/app/src/compat/jni/com/chip/casting/AppParameters.java @@ -22,6 +22,8 @@ import java.math.BigInteger; import java.util.Arrays; +/** @deprecated Use the APIs described in /examples/tv-casting-app/APIs.md instead. */ +@Deprecated public class AppParameters { private static final String TAG = AppParameters.class.getSimpleName(); public static final int MIN_ROTATING_DEVICE_ID_UNIQUE_ID_LENGTH = 16; diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/CommissioningCallbacks.java b/examples/tv-casting-app/android/App/app/src/compat/jni/com/chip/casting/CommissioningCallbacks.java similarity index 97% rename from examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/CommissioningCallbacks.java rename to examples/tv-casting-app/android/App/app/src/compat/jni/com/chip/casting/CommissioningCallbacks.java index 9a44aba792..20599a4f07 100644 --- a/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/CommissioningCallbacks.java +++ b/examples/tv-casting-app/android/App/app/src/compat/jni/com/chip/casting/CommissioningCallbacks.java @@ -17,6 +17,8 @@ */ package com.chip.casting; +/** @deprecated Use the APIs described in /examples/tv-casting-app/APIs.md instead. */ +@Deprecated public class CommissioningCallbacks { /** * This is called when the PBKDFParamRequest is received and indicates the start of the session diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/ContentApp.java b/examples/tv-casting-app/android/App/app/src/compat/jni/com/chip/casting/ContentApp.java similarity index 51% rename from examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/ContentApp.java rename to examples/tv-casting-app/android/App/app/src/compat/jni/com/chip/casting/ContentApp.java index 80efc22ef5..1c20a40b66 100644 --- a/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/ContentApp.java +++ b/examples/tv-casting-app/android/App/app/src/compat/jni/com/chip/casting/ContentApp.java @@ -17,10 +17,16 @@ */ package com.chip.casting; +import chip.devicecontroller.ChipClusters; +import com.matter.casting.core.Endpoint; +import java.util.ArrayList; import java.util.List; import java.util.Objects; +/** @deprecated Use the APIs described in /examples/tv-casting-app/APIs.md instead. */ +@Deprecated public class ContentApp { + private Endpoint endpoint; private short endpointId; private List clusterIds; @@ -32,6 +38,33 @@ public ContentApp(short endpointId, List clusterIds) { this.isInitialized = true; } + ContentApp(Endpoint endpoint) { + this.endpoint = endpoint; + this.endpointId = (short) endpoint.getId(); + this.clusterIds = new ArrayList<>(); + if (endpoint.getCluster(ChipClusters.ApplicationBasicCluster.class) != null) { + this.clusterIds.add((int) ChipClusters.ApplicationBasicCluster.CLUSTER_ID); + } + if (endpoint.getCluster(ChipClusters.ApplicationLauncherCluster.class) != null) { + this.clusterIds.add((int) ChipClusters.ApplicationLauncherCluster.CLUSTER_ID); + } + if (endpoint.getCluster(ChipClusters.ContentLauncherCluster.class) != null) { + this.clusterIds.add((int) ChipClusters.ContentLauncherCluster.CLUSTER_ID); + } + if (endpoint.getCluster(ChipClusters.KeypadInputCluster.class) != null) { + this.clusterIds.add((int) ChipClusters.KeypadInputCluster.CLUSTER_ID); + } + if (endpoint.getCluster(ChipClusters.MediaPlaybackCluster.class) != null) { + this.clusterIds.add((int) ChipClusters.MediaPlaybackCluster.CLUSTER_ID); + } + if (endpoint.getCluster(ChipClusters.OnOffCluster.class) != null) { + this.clusterIds.add((int) ChipClusters.OnOffCluster.CLUSTER_ID); + } + if (endpoint.getCluster(ChipClusters.TargetNavigatorCluster.class) != null) { + this.clusterIds.add((int) ChipClusters.TargetNavigatorCluster.CLUSTER_ID); + } + } + public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; @@ -49,6 +82,10 @@ public java.lang.String toString() { return "endpointId=" + endpointId; } + Endpoint getEndpoint() { + return endpoint; + } + public short getEndpointId() { return endpointId; } diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/ContentLauncherTypes.java b/examples/tv-casting-app/android/App/app/src/compat/jni/com/chip/casting/ContentLauncherTypes.java similarity index 96% rename from examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/ContentLauncherTypes.java rename to examples/tv-casting-app/android/App/app/src/compat/jni/com/chip/casting/ContentLauncherTypes.java index bc4ee6a6a2..b6d7c34029 100644 --- a/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/ContentLauncherTypes.java +++ b/examples/tv-casting-app/android/App/app/src/compat/jni/com/chip/casting/ContentLauncherTypes.java @@ -20,6 +20,8 @@ import java.util.ArrayList; import java.util.Optional; +/** @deprecated Use the APIs described in /examples/tv-casting-app/APIs.md instead. */ +@Deprecated public class ContentLauncherTypes { public static class AdditionalInfo { public String name; diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/DACProvider.java b/examples/tv-casting-app/android/App/app/src/compat/jni/com/chip/casting/DACProvider.java similarity index 92% rename from examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/DACProvider.java rename to examples/tv-casting-app/android/App/app/src/compat/jni/com/chip/casting/DACProvider.java index c49d73ab98..7c6ac281e6 100644 --- a/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/DACProvider.java +++ b/examples/tv-casting-app/android/App/app/src/compat/jni/com/chip/casting/DACProvider.java @@ -17,6 +17,8 @@ */ package com.chip.casting; +/** @deprecated Use the APIs described in /examples/tv-casting-app/APIs.md instead. */ +@Deprecated public interface DACProvider { byte[] GetCertificationDeclaration(); diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/DiscoveredNodeData.java b/examples/tv-casting-app/android/App/app/src/compat/jni/com/chip/casting/DiscoveredNodeData.java similarity index 88% rename from examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/DiscoveredNodeData.java rename to examples/tv-casting-app/android/App/app/src/compat/jni/com/chip/casting/DiscoveredNodeData.java index a66d48a57c..39b9113c94 100644 --- a/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/DiscoveredNodeData.java +++ b/examples/tv-casting-app/android/App/app/src/compat/jni/com/chip/casting/DiscoveredNodeData.java @@ -19,6 +19,7 @@ import android.net.nsd.NsdServiceInfo; import android.util.Log; +import com.matter.casting.core.CastingPlayer; import java.net.InetAddress; import java.nio.charset.StandardCharsets; import java.util.Arrays; @@ -26,15 +27,18 @@ import java.util.Map; import java.util.Objects; +/** @deprecated Use the APIs described in /examples/tv-casting-app/APIs.md instead. */ +@Deprecated public class DiscoveredNodeData { private static final String TAG = DiscoveredNodeData.class.getSimpleName(); - private static final int MAX_IP_ADDRESSES = 5; private static final int MAX_ROTATING_ID_LEN = 50; private static final String KEY_DEVICE_NAME = "DN"; private static final String KEY_DEVICE_TYPE = "DT"; private static final String KEY_VENDOR_PRODUCT = "VP"; + private CastingPlayer castingPlayer; + private String hostName; private String instanceName; private long longDiscriminator; @@ -119,10 +123,30 @@ public DiscoveredNodeData(VideoPlayer player) { this.port = player.getPort(); } + DiscoveredNodeData(CastingPlayer castingPlayer) { + this.castingPlayer = castingPlayer; + this.deviceName = castingPlayer.getDeviceName(); + this.ipAddresses = castingPlayer.getIpAddresses(); + this.numIPs = + castingPlayer.getIpAddresses() != null ? castingPlayer.getIpAddresses().size() : 0; + this.deviceType = castingPlayer.getDeviceType(); + this.hostName = castingPlayer.getHostName(); + this.vendorId = castingPlayer.getVendorId(); + this.productId = castingPlayer.getProductId(); + this.instanceName = castingPlayer.getInstanceName(); + if (castingPlayer.isConnected()) { + this.connectableVideoPlayer = new VideoPlayer(castingPlayer); + } + } + void setConnectableVideoPlayer(VideoPlayer videoPlayer) { this.connectableVideoPlayer = videoPlayer; } + CastingPlayer getCastingPlayer() { + return castingPlayer; + } + public boolean isPreCommissioned() { return connectableVideoPlayer != null; } diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/FailureCallback.java b/examples/tv-casting-app/android/App/app/src/compat/jni/com/chip/casting/FailureCallback.java similarity index 85% rename from examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/FailureCallback.java rename to examples/tv-casting-app/android/App/app/src/compat/jni/com/chip/casting/FailureCallback.java index 2ad3b9fc72..5e07e9d526 100644 --- a/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/FailureCallback.java +++ b/examples/tv-casting-app/android/App/app/src/compat/jni/com/chip/casting/FailureCallback.java @@ -19,14 +19,16 @@ import android.util.Log; +/** @deprecated Use the APIs described in /examples/tv-casting-app/APIs.md instead. */ +@Deprecated public abstract class FailureCallback { private static final String TAG = FailureCallback.class.getSimpleName(); public abstract void handle(MatterError err); - protected final void handleInternal(int errorCode, String errorMessage) { + protected final void handleInternal(MatterError err) { try { - handle(new MatterError(errorCode, errorMessage)); + handle(err); } catch (Throwable t) { Log.e(TAG, "FailureCallback::Caught an unhandled Throwable from the client: " + t); } diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/MatterCallbackHandler.java b/examples/tv-casting-app/android/App/app/src/compat/jni/com/chip/casting/MatterCallbackHandler.java similarity index 85% rename from examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/MatterCallbackHandler.java rename to examples/tv-casting-app/android/App/app/src/compat/jni/com/chip/casting/MatterCallbackHandler.java index 493635beb6..7f1efd056e 100644 --- a/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/MatterCallbackHandler.java +++ b/examples/tv-casting-app/android/App/app/src/compat/jni/com/chip/casting/MatterCallbackHandler.java @@ -19,14 +19,16 @@ import android.util.Log; +/** @deprecated Use the APIs described in /examples/tv-casting-app/APIs.md instead. */ +@Deprecated public abstract class MatterCallbackHandler { private static final String TAG = MatterCallbackHandler.class.getSimpleName(); public abstract void handle(MatterError err); - protected final void handleInternal(int errorCode, String errorMessage) { + protected final void handleInternal(MatterError err) { try { - handle(new MatterError(errorCode, errorMessage)); + handle(err); } catch (Throwable t) { Log.e(TAG, "MatterCallbackHandler::Caught an unhandled Throwable from the client: " + t); } diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/MatterError.java b/examples/tv-casting-app/android/App/app/src/compat/jni/com/chip/casting/MatterError.java similarity index 84% rename from examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/MatterError.java rename to examples/tv-casting-app/android/App/app/src/compat/jni/com/chip/casting/MatterError.java index ac12eaccd2..e281bdd8b6 100644 --- a/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/MatterError.java +++ b/examples/tv-casting-app/android/App/app/src/compat/jni/com/chip/casting/MatterError.java @@ -19,6 +19,8 @@ import java.util.Objects; +/** @deprecated Use the APIs described in /examples/tv-casting-app/APIs.md instead. */ +@Deprecated public class MatterError { private long errorCode; private String errorMessage; @@ -26,8 +28,15 @@ public class MatterError { public static final MatterError DISCOVERY_SERVICE_LOST = new MatterError(4L, "Discovery service was lost."); + public static final MatterError MATTER_INTERNAL_ERROR = new MatterError(0xac, "Internal error."); + public static final MatterError NO_ERROR = new MatterError(0, null); + MatterError(com.matter.casting.support.MatterError err) { + this.errorCode = err.getErrorCode(); + this.errorMessage = err.getErrorMessage(); + } + public MatterError(long errorCode, String errorMessage) { this.errorCode = errorCode; this.errorMessage = errorMessage; diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/MediaPlaybackTypes.java b/examples/tv-casting-app/android/App/app/src/compat/jni/com/chip/casting/MediaPlaybackTypes.java similarity index 93% rename from examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/MediaPlaybackTypes.java rename to examples/tv-casting-app/android/App/app/src/compat/jni/com/chip/casting/MediaPlaybackTypes.java index 7bf37b5d1c..fc01b02dea 100644 --- a/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/MediaPlaybackTypes.java +++ b/examples/tv-casting-app/android/App/app/src/compat/jni/com/chip/casting/MediaPlaybackTypes.java @@ -17,6 +17,8 @@ */ package com.chip.casting; +/** @deprecated Use the APIs described in /examples/tv-casting-app/APIs.md instead. */ +@Deprecated public class MediaPlaybackTypes { public enum PlaybackStateEnum { Playing, diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/SubscriptionEstablishedCallback.java b/examples/tv-casting-app/android/App/app/src/compat/jni/com/chip/casting/SubscriptionEstablishedCallback.java similarity index 91% rename from examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/SubscriptionEstablishedCallback.java rename to examples/tv-casting-app/android/App/app/src/compat/jni/com/chip/casting/SubscriptionEstablishedCallback.java index aab9dcd930..dd5eab2ec6 100644 --- a/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/SubscriptionEstablishedCallback.java +++ b/examples/tv-casting-app/android/App/app/src/compat/jni/com/chip/casting/SubscriptionEstablishedCallback.java @@ -19,6 +19,8 @@ import android.util.Log; +/** @deprecated Use the APIs described in /examples/tv-casting-app/APIs.md instead. */ +@Deprecated public abstract class SubscriptionEstablishedCallback { private static final String TAG = SubscriptionEstablishedCallback.class.getSimpleName(); diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/SuccessCallback.java b/examples/tv-casting-app/android/App/app/src/compat/jni/com/chip/casting/SuccessCallback.java similarity index 91% rename from examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/SuccessCallback.java rename to examples/tv-casting-app/android/App/app/src/compat/jni/com/chip/casting/SuccessCallback.java index b82845567d..d1194d46f3 100644 --- a/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/SuccessCallback.java +++ b/examples/tv-casting-app/android/App/app/src/compat/jni/com/chip/casting/SuccessCallback.java @@ -19,6 +19,8 @@ import android.util.Log; +/** @deprecated Use the APIs described in /examples/tv-casting-app/APIs.md instead. */ +@Deprecated public abstract class SuccessCallback { private static final String TAG = SuccessCallback.class.getSimpleName(); diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/TargetNavigatorTypes.java b/examples/tv-casting-app/android/App/app/src/compat/jni/com/chip/casting/TargetNavigatorTypes.java similarity index 93% rename from examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/TargetNavigatorTypes.java rename to examples/tv-casting-app/android/App/app/src/compat/jni/com/chip/casting/TargetNavigatorTypes.java index 88f71bb796..832101c956 100644 --- a/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/TargetNavigatorTypes.java +++ b/examples/tv-casting-app/android/App/app/src/compat/jni/com/chip/casting/TargetNavigatorTypes.java @@ -17,6 +17,8 @@ */ package com.chip.casting; +/** @deprecated Use the APIs described in /examples/tv-casting-app/APIs.md instead. */ +@Deprecated public class TargetNavigatorTypes { public static class TargetInfo { public Integer identifier; diff --git a/examples/tv-casting-app/android/App/app/src/compat/jni/com/chip/casting/TvCastingApp.java b/examples/tv-casting-app/android/App/app/src/compat/jni/com/chip/casting/TvCastingApp.java new file mode 100644 index 0000000000..cd96590506 --- /dev/null +++ b/examples/tv-casting-app/android/App/app/src/compat/jni/com/chip/casting/TvCastingApp.java @@ -0,0 +1,1327 @@ +/* + * Copyright (c) 2022 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. + * + */ +package com.chip.casting; + +import android.content.Context; +import android.util.Log; +import androidx.annotation.Nullable; +import chip.devicecontroller.ChipClusters; +import chip.devicecontroller.ChipStructs; +import com.matter.casting.core.CastingApp; +import com.matter.casting.core.CastingPlayer; +import com.matter.casting.core.CastingPlayerDiscovery; +import com.matter.casting.core.Endpoint; +import com.matter.casting.core.MatterCastingPlayerDiscovery; +import com.matter.casting.support.AppParameters; +import com.matter.casting.support.CommissionableData; +import com.matter.casting.support.ConnectionCallbacks; +import com.matter.casting.support.DACProvider; +import com.matter.casting.support.IdentificationDeclarationOptions; +import com.matter.casting.support.MatterCallback; +import com.matter.casting.support.MatterError; +import com.matter.casting.support.TargetAppInfo; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +/** @deprecated Use the APIs described in /examples/tv-casting-app/APIs.md instead. */ +@Deprecated +public class TvCastingApp { + private static final String TAG = TvCastingApp.class.getSimpleName(); + + private com.chip.casting.AppParameters appParametersCompat; + private int commissioningWindowTimeout; + private CommissioningCallbacks commissioningCallbacks; + private SuccessCallback onConnectionSuccess; + private FailureCallback onConnectionFailure; + private SuccessCallback onNewOrUpdatedEndpointCallback; + private CastingPlayer targetCastingPlayer; + + private abstract class CastingPlayerChangeListenerAdapter + extends CastingPlayerDiscovery.CastingPlayerChangeListener { + public abstract void initialize(SuccessCallback discoverySuccessCallback); + } + + private CastingPlayerChangeListenerAdapter castingPlayerDiscoveryChangeListener = + new CastingPlayerChangeListenerAdapter() { + private SuccessCallback discoverySuccessCallbackCompat; + + @Override + public void initialize(SuccessCallback discoverySuccessCallback) { + this.discoverySuccessCallbackCompat = discoverySuccessCallback; + } + + @Override + public void onAdded(CastingPlayer castingPlayer) { + if (discoverySuccessCallbackCompat == null) { + Log.e(TAG, "discoverySuccessCallbackCompat not set"); + return; + } + discoverySuccessCallbackCompat.handleInternal(new DiscoveredNodeData((castingPlayer))); + } + + @Override + public void onChanged(CastingPlayer castingPlayer) { + if (discoverySuccessCallbackCompat == null) { + Log.e(TAG, "discoverySuccessCallbackCompat not set"); + return; + } + discoverySuccessCallbackCompat.handleInternal(new DiscoveredNodeData((castingPlayer))); + } + + @Override + public void onRemoved(CastingPlayer castingPlayer) { + Log.e(TAG, "CastingPlayerChangeListener.onRemoved() not implemented"); + } + }; + + private interface DACProviderAdapter extends DACProvider { + void initialize(com.chip.casting.DACProvider dacProviderCompat); + } + + private DACProviderAdapter dacProvider = + new DACProviderAdapter() { + private com.chip.casting.DACProvider dacProviderCompat; + + public void initialize(com.chip.casting.DACProvider dacProviderCompat) { + this.dacProviderCompat = dacProviderCompat; + } + + @Override + public byte[] GetCertificationDeclaration() { + if (dacProviderCompat == null) { + Log.e(TAG, "dacProviderCompat not set"); + return null; + } + return dacProviderCompat.GetCertificationDeclaration(); + } + + @Override + public byte[] GetFirmwareInformation() { + if (dacProviderCompat == null) { + Log.e(TAG, "dacProviderCompat not set"); + return null; + } + return dacProviderCompat.GetFirmwareInformation(); + } + + @Override + public byte[] GetDeviceAttestationCert() { + if (dacProviderCompat == null) { + Log.e(TAG, "dacProviderCompat not set"); + return null; + } + return dacProviderCompat.GetDeviceAttestationCert(); + } + + @Override + public byte[] GetProductAttestationIntermediateCert() { + if (dacProviderCompat == null) { + Log.e(TAG, "dacProviderCompat not set"); + return null; + } + return dacProviderCompat.GetProductAttestationIntermediateCert(); + } + + @Override + public byte[] SignWithDeviceAttestationKey(byte[] message) { + if (dacProviderCompat == null) { + Log.e(TAG, "dacProviderCompat not set"); + return null; + } + return dacProviderCompat.SignWithDeviceAttestationKey(message); + } + }; + + private static final List DISCOVERY_TARGET_DEVICE_TYPE_FILTER = + Arrays.asList(35L); // Matter Casting Video player = 35; + + private static TvCastingApp sInstance; + + private TvCastingApp() {} + + public static TvCastingApp getInstance() { + if (sInstance == null) { + sInstance = new TvCastingApp(); + } + return sInstance; + } + + public boolean initApp( + Context applicationContext, com.chip.casting.AppParameters appParametersCompat) { + if (applicationContext == null + || appParametersCompat == null + || appParametersCompat.getConfigurationManager() == null) { + return false; + } + + this.appParametersCompat = appParametersCompat; + + AppParameters appParameters = + new AppParameters( + applicationContext, + () -> appParametersCompat.getConfigurationManager(), + () -> appParametersCompat.getRotatingDeviceIdUniqueId(), + () -> { + CommissionableData commissionableData = + new CommissionableData( + appParametersCompat.getSetupPasscode(), + appParametersCompat.getDiscriminator()); + commissionableData.setSpake2pIterationCount( + appParametersCompat.getSpake2pIterationCount()); + commissionableData.setSpake2pSaltBase64(appParametersCompat.getSpake2pSaltBase64()); + commissionableData.setSpake2pVerifierBase64( + appParametersCompat.getSpake2pVerifierBase64()); + return commissionableData; + }, + this.dacProvider); + + // Initialize the SDK using the appParameters and check if it returns successfully + MatterError err = CastingApp.getInstance().initialize(appParameters); + if (err.hasError()) { + Log.e(TAG, "Failed to initialize Matter CastingApp. Err: " + err); + return false; + } + + err = CastingApp.getInstance().start(); + if (err.hasError()) { + Log.e(TAG, "Failed to start Matter CastingApp. Err: " + err); + return false; + } + return true; + } + + public void setDACProvider(com.chip.casting.DACProvider dacProviderCompat) { + this.dacProvider.initialize(dacProviderCompat); + } + + public void discoverVideoPlayerCommissioners( + SuccessCallback discoverySuccessCallback, + FailureCallback discoveryFailureCallback) { + + // stop before starting another discovery session + stopVideoPlayerDiscovery(); + + castingPlayerDiscoveryChangeListener.initialize(discoverySuccessCallback); + MatterError err = + MatterCastingPlayerDiscovery.getInstance() + .addCastingPlayerChangeListener(castingPlayerDiscoveryChangeListener); + if (err.hasError()) { + Log.e(TAG, "addCastingPlayerChangeListener before starting discovery failed. Err: " + err); + discoveryFailureCallback.handleInternal(new com.chip.casting.MatterError(err)); + return; + } + + err = + MatterCastingPlayerDiscovery.getInstance() + .startDiscovery(DISCOVERY_TARGET_DEVICE_TYPE_FILTER.get(0)); + if (err.hasError()) { + Log.e(TAG, "startDiscovery failed. Err: " + err); + discoveryFailureCallback.handleInternal(new com.chip.casting.MatterError(err)); + } + } + + public void stopVideoPlayerDiscovery() { + MatterError err = MatterCastingPlayerDiscovery.getInstance().stopDiscovery(); + if (err.hasError()) { + Log.e(TAG, "stopDiscovery failed. Err: " + err); + return; + } + + err = + MatterCastingPlayerDiscovery.getInstance() + .removeCastingPlayerChangeListener(castingPlayerDiscoveryChangeListener); + if (err.hasError()) { + Log.e(TAG, "removeCastingPlayerChangeListener failed. Err: " + err); + } + } + + public boolean openBasicCommissioningWindow( + int commissioningWindowTimeout, + CommissioningCallbacks commissioningCallbacks, + SuccessCallback onConnectionSuccess, + FailureCallback onConnectionFailure, + SuccessCallback onNewOrUpdatedEndpointCallback) { + this.commissioningWindowTimeout = commissioningWindowTimeout; + this.commissioningCallbacks = commissioningCallbacks; + this.onConnectionSuccess = onConnectionSuccess; + this.onConnectionFailure = onConnectionFailure; + this.onNewOrUpdatedEndpointCallback = onNewOrUpdatedEndpointCallback; + return true; + } + + public boolean sendCommissioningRequest(DiscoveredNodeData commissioner, Integer vendorId) { + if (commissioningCallbacks == null + || onConnectionSuccess == null + || onConnectionFailure == null + || onNewOrUpdatedEndpointCallback == null) { + Log.e(TAG, "Commissioning/connection callbacks not set"); + return false; + } + + this.targetCastingPlayer = commissioner.getCastingPlayer(); + + IdentificationDeclarationOptions idOptions = new IdentificationDeclarationOptions(); + idOptions.addTargetAppInfo(new TargetAppInfo(vendorId, null)); + + MatterError err = + targetCastingPlayer.verifyOrEstablishConnection( + new ConnectionCallbacks( + new MatterCallback() { + @Override + public void handle(Void response) { + ((MatterCallbackHandler) commissioningCallbacks.getCommissioningComplete()) + .handleInternal(com.chip.casting.MatterError.NO_ERROR); + onConnectionSuccess.handleInternal(new VideoPlayer(targetCastingPlayer)); + + List endpoints = targetCastingPlayer.getEndpoints(); + if (endpoints != null) { + for (Endpoint endpoint : endpoints) { + onNewOrUpdatedEndpointCallback.handleInternal(new ContentApp(endpoint)); + } + } + } + }, + new MatterCallback() { + @Override + public void handle(MatterError err) { + onConnectionFailure.handleInternal(new com.chip.casting.MatterError(err)); + } + }, + null), + (short) this.commissioningWindowTimeout, + idOptions); + + if (err.hasError()) { + Log.e( + TAG, "sendCommissioningRequest failed to call verifyOrEstablishConnection. Err: " + err); + return false; + } + + return true; + } + + public boolean verifyOrEstablishConnection( + VideoPlayer targetVideoPlayer, + SuccessCallback onConnectionSuccess, + FailureCallback onConnectionFailure, + SuccessCallback onNewOrUpdatedEndpointCallback) { + Log.e(TAG, "verifyOrEstablishConnection is unsupported"); + return false; + } + + public void shutdownAllSubscriptions() { + MatterError err = CastingApp.getInstance().shutdownAllSubscriptions(); + if (err.hasError()) { + Log.e(TAG, "shutdownAllSubscriptions failed. Err: " + err); + } + } + + public void disconnect() { + if (targetCastingPlayer != null) { + targetCastingPlayer.disconnect(); + } + } + + public boolean purgeCache() { + MatterError err = CastingApp.getInstance().clearCache(); + if (err.hasError()) { + Log.e(TAG, "purgeCache failed. Err: " + err); + return false; + } + return true; + } + + private Endpoint getTargetEndpoint(ContentApp contentApp) { + if (targetCastingPlayer == null || targetCastingPlayer.getEndpoints() == null) { + return null; + } + + for (Endpoint endpoint : targetCastingPlayer.getEndpoints()) { + if (endpoint.getId() == contentApp.getEndpointId()) { + return endpoint; + } + } + + return null; + } + + public boolean contentLauncherLaunchURL( + ContentApp contentApp, String contentUrl, String contentDisplayStr, Object responseHandler) { + + Endpoint endpoint = getTargetEndpoint(contentApp); + ChipClusters.ContentLauncherCluster cluster = + endpoint != null ? endpoint.getCluster(ChipClusters.ContentLauncherCluster.class) : null; + if (cluster == null) { + Log.e(TAG, "Cluster not found"); + return false; + } + + cluster.launchURL( + new ChipClusters.ContentLauncherCluster.LauncherResponseCallback() { + @Override + public void onSuccess(Integer status, Optional data) { + ((MatterCallbackHandler) responseHandler) + .handleInternal(com.chip.casting.MatterError.NO_ERROR); + } + + @Override + public void onError(Exception error) { + Log.e(TAG, "LauncherResponseCallback.onError: " + error); + ((MatterCallbackHandler) responseHandler) + .handleInternal(com.chip.casting.MatterError.MATTER_INTERNAL_ERROR); + } + }, + contentUrl, + Optional.of(contentDisplayStr), + Optional.empty()); + + return true; + } + + public boolean contentLauncher_launchContent( + ContentApp contentApp, + ContentLauncherTypes.ContentSearch searchCompat, + boolean autoPlay, + String data, + Object responseHandler) { + + Endpoint endpoint = getTargetEndpoint(contentApp); + ChipClusters.ContentLauncherCluster cluster = + endpoint != null ? endpoint.getCluster(ChipClusters.ContentLauncherCluster.class) : null; + if (cluster == null) { + Log.e(TAG, "Cluster not found"); + return false; + } + + // translate searchCompat + ArrayList parameterList = null; + if (searchCompat.parameterList != null) { + parameterList = new ArrayList<>(); + for (ContentLauncherTypes.Parameter parameterCompat : searchCompat.parameterList) { + ArrayList externalIDList = null; + if (parameterCompat.externalIDList != null && parameterCompat.externalIDList.isPresent()) { + externalIDList = new ArrayList<>(); + for (ContentLauncherTypes.AdditionalInfo additionalInfoCompat : + parameterCompat.externalIDList.get()) { + externalIDList.add( + new ChipStructs.ContentLauncherClusterAdditionalInfoStruct( + additionalInfoCompat.name, additionalInfoCompat.value)); + } + } + parameterList.add( + new ChipStructs.ContentLauncherClusterParameterStruct( + parameterCompat.type, + parameterCompat.value, + externalIDList != null ? Optional.of(externalIDList) : Optional.empty())); + } + } + ChipStructs.ContentLauncherClusterContentSearchStruct search = + new ChipStructs.ContentLauncherClusterContentSearchStruct(parameterList); + + cluster.launchContent( + new ChipClusters.ContentLauncherCluster.LauncherResponseCallback() { + @Override + public void onSuccess(Integer status, Optional data) { + ((MatterCallbackHandler) responseHandler) + .handleInternal(com.chip.casting.MatterError.NO_ERROR); + } + + @Override + public void onError(Exception error) { + Log.e(TAG, "LauncherResponseCallback.onError: " + error); + ((MatterCallbackHandler) responseHandler) + .handleInternal(com.chip.casting.MatterError.MATTER_INTERNAL_ERROR); + } + }, + search, + autoPlay, + data != null ? Optional.of(data) : Optional.empty(), + Optional.empty(), + Optional.empty()); + return true; + } + + public boolean mediaPlayback_play(ContentApp contentApp, Object responseHandler) { + + Endpoint endpoint = getTargetEndpoint(contentApp); + ChipClusters.MediaPlaybackCluster cluster = + endpoint != null ? endpoint.getCluster(ChipClusters.MediaPlaybackCluster.class) : null; + if (cluster == null) { + Log.e(TAG, "Cluster not found"); + return false; + } + + cluster.play( + new ChipClusters.MediaPlaybackCluster.PlaybackResponseCallback() { + @Override + public void onSuccess(Integer status, Optional data) { + ((MatterCallbackHandler) responseHandler) + .handleInternal(com.chip.casting.MatterError.NO_ERROR); + } + + @Override + public void onError(Exception error) { + Log.e(TAG, "PlaybackResponseCallback.onError: " + error); + ((MatterCallbackHandler) responseHandler) + .handleInternal(com.chip.casting.MatterError.MATTER_INTERNAL_ERROR); + } + }); + return true; + } + + public boolean mediaPlayback_pause(ContentApp contentApp, Object responseHandler) { + + Endpoint endpoint = getTargetEndpoint(contentApp); + ChipClusters.MediaPlaybackCluster cluster = + endpoint != null ? endpoint.getCluster(ChipClusters.MediaPlaybackCluster.class) : null; + if (cluster == null) { + Log.e(TAG, "Cluster not found"); + return false; + } + + cluster.pause( + new ChipClusters.MediaPlaybackCluster.PlaybackResponseCallback() { + @Override + public void onSuccess(Integer status, Optional data) { + ((MatterCallbackHandler) responseHandler) + .handleInternal(com.chip.casting.MatterError.NO_ERROR); + } + + @Override + public void onError(Exception error) { + Log.e(TAG, "PlaybackResponseCallback.onError: " + error); + ((MatterCallbackHandler) responseHandler) + .handleInternal(com.chip.casting.MatterError.MATTER_INTERNAL_ERROR); + } + }); + return true; + } + + public boolean mediaPlayback_stopPlayback(ContentApp contentApp, Object responseHandler) { + + Endpoint endpoint = getTargetEndpoint(contentApp); + ChipClusters.MediaPlaybackCluster cluster = + endpoint != null ? endpoint.getCluster(ChipClusters.MediaPlaybackCluster.class) : null; + if (cluster == null) { + Log.e(TAG, "Cluster not found"); + return false; + } + + cluster.stop( + new ChipClusters.MediaPlaybackCluster.PlaybackResponseCallback() { + @Override + public void onSuccess(Integer status, Optional data) { + ((MatterCallbackHandler) responseHandler) + .handleInternal(com.chip.casting.MatterError.NO_ERROR); + } + + @Override + public void onError(Exception error) { + Log.e(TAG, "PlaybackResponseCallback.onError: " + error); + ((MatterCallbackHandler) responseHandler) + .handleInternal(com.chip.casting.MatterError.MATTER_INTERNAL_ERROR); + } + }); + return true; + } + + public boolean mediaPlayback_next(ContentApp contentApp, Object responseHandler) { + + Endpoint endpoint = getTargetEndpoint(contentApp); + ChipClusters.MediaPlaybackCluster cluster = + endpoint != null ? endpoint.getCluster(ChipClusters.MediaPlaybackCluster.class) : null; + if (cluster == null) { + Log.e(TAG, "Cluster not found"); + return false; + } + + cluster.next( + new ChipClusters.MediaPlaybackCluster.PlaybackResponseCallback() { + @Override + public void onSuccess(Integer status, Optional data) { + ((MatterCallbackHandler) responseHandler) + .handleInternal(com.chip.casting.MatterError.NO_ERROR); + } + + @Override + public void onError(Exception error) { + Log.e(TAG, "PlaybackResponseCallback.onError: " + error); + ((MatterCallbackHandler) responseHandler) + .handleInternal(com.chip.casting.MatterError.MATTER_INTERNAL_ERROR); + } + }); + return true; + } + + public boolean mediaPlayback_previous(ContentApp contentApp, Object responseHandler) { + + Endpoint endpoint = getTargetEndpoint(contentApp); + ChipClusters.MediaPlaybackCluster cluster = + endpoint != null ? endpoint.getCluster(ChipClusters.MediaPlaybackCluster.class) : null; + + if (cluster == null) { + Log.e(TAG, "Cluster not found"); + return false; + } + + cluster.previous( + new ChipClusters.MediaPlaybackCluster.PlaybackResponseCallback() { + @Override + public void onSuccess(Integer status, Optional data) { + ((MatterCallbackHandler) responseHandler) + .handleInternal(com.chip.casting.MatterError.NO_ERROR); + } + + @Override + public void onError(Exception error) { + Log.e(TAG, "PlaybackResponseCallback.onError: " + error); + ((MatterCallbackHandler) responseHandler) + .handleInternal(com.chip.casting.MatterError.MATTER_INTERNAL_ERROR); + } + }); + return true; + } + + public boolean mediaPlayback_rewind(ContentApp contentApp, Object responseHandler) { + + Endpoint endpoint = getTargetEndpoint(contentApp); + ChipClusters.MediaPlaybackCluster cluster = + endpoint != null ? endpoint.getCluster(ChipClusters.MediaPlaybackCluster.class) : null; + if (cluster == null) { + Log.e(TAG, "Cluster not found"); + return false; + } + + cluster.rewind( + new ChipClusters.MediaPlaybackCluster.PlaybackResponseCallback() { + @Override + public void onSuccess(Integer status, Optional data) { + ((MatterCallbackHandler) responseHandler) + .handleInternal(com.chip.casting.MatterError.NO_ERROR); + } + + @Override + public void onError(Exception error) { + Log.e(TAG, "PlaybackResponseCallback.onError: " + error); + ((MatterCallbackHandler) responseHandler) + .handleInternal(com.chip.casting.MatterError.MATTER_INTERNAL_ERROR); + } + }, + Optional.empty()); + return true; + } + + public boolean mediaPlayback_fastForward(ContentApp contentApp, Object responseHandler) { + + Endpoint endpoint = getTargetEndpoint(contentApp); + ChipClusters.MediaPlaybackCluster cluster = + endpoint != null ? endpoint.getCluster(ChipClusters.MediaPlaybackCluster.class) : null; + if (cluster == null) { + Log.e(TAG, "Cluster not found"); + return false; + } + + cluster.fastForward( + new ChipClusters.MediaPlaybackCluster.PlaybackResponseCallback() { + @Override + public void onSuccess(Integer status, Optional data) { + ((MatterCallbackHandler) responseHandler) + .handleInternal(com.chip.casting.MatterError.NO_ERROR); + } + + @Override + public void onError(Exception error) { + Log.e(TAG, "PlaybackResponseCallback.onError: " + error); + ((MatterCallbackHandler) responseHandler) + .handleInternal(com.chip.casting.MatterError.MATTER_INTERNAL_ERROR); + } + }, + Optional.empty()); + return true; + } + + public boolean mediaPlayback_startOver(ContentApp contentApp, Object responseHandler) { + + Endpoint endpoint = getTargetEndpoint(contentApp); + ChipClusters.MediaPlaybackCluster cluster = + endpoint != null ? endpoint.getCluster(ChipClusters.MediaPlaybackCluster.class) : null; + if (cluster == null) { + Log.e(TAG, "Cluster not found"); + return false; + } + + cluster.startOver( + new ChipClusters.MediaPlaybackCluster.PlaybackResponseCallback() { + @Override + public void onSuccess(Integer status, Optional data) { + ((MatterCallbackHandler) responseHandler) + .handleInternal(com.chip.casting.MatterError.NO_ERROR); + } + + @Override + public void onError(Exception error) { + Log.e(TAG, "PlaybackResponseCallback.onError: " + error); + ((MatterCallbackHandler) responseHandler) + .handleInternal(com.chip.casting.MatterError.MATTER_INTERNAL_ERROR); + } + }); + return true; + } + + public boolean mediaPlayback_seek(ContentApp contentApp, long position, Object responseHandler) { + + Endpoint endpoint = getTargetEndpoint(contentApp); + ChipClusters.MediaPlaybackCluster cluster = + endpoint != null ? endpoint.getCluster(ChipClusters.MediaPlaybackCluster.class) : null; + if (cluster == null) { + Log.e(TAG, "Cluster not found"); + return false; + } + + cluster.seek( + new ChipClusters.MediaPlaybackCluster.PlaybackResponseCallback() { + @Override + public void onSuccess(Integer status, Optional data) { + ((MatterCallbackHandler) responseHandler) + .handleInternal(com.chip.casting.MatterError.NO_ERROR); + } + + @Override + public void onError(Exception error) { + Log.e(TAG, "PlaybackResponseCallback.onError: " + error); + ((MatterCallbackHandler) responseHandler) + .handleInternal(com.chip.casting.MatterError.MATTER_INTERNAL_ERROR); + } + }, + position); + return true; + } + + public boolean mediaPlayback_skipForward( + ContentApp contentApp, long deltaPositionMilliseconds, Object responseHandler) { + + Endpoint endpoint = getTargetEndpoint(contentApp); + ChipClusters.MediaPlaybackCluster cluster = + endpoint != null ? endpoint.getCluster(ChipClusters.MediaPlaybackCluster.class) : null; + if (cluster == null) { + Log.e(TAG, "Cluster not found"); + return false; + } + + cluster.skipForward( + new ChipClusters.MediaPlaybackCluster.PlaybackResponseCallback() { + @Override + public void onSuccess(Integer status, Optional data) { + ((MatterCallbackHandler) responseHandler) + .handleInternal(com.chip.casting.MatterError.NO_ERROR); + } + + @Override + public void onError(Exception error) { + Log.e(TAG, "PlaybackResponseCallback.onError: " + error); + ((MatterCallbackHandler) responseHandler) + .handleInternal(com.chip.casting.MatterError.MATTER_INTERNAL_ERROR); + } + }, + deltaPositionMilliseconds); + return true; + } + + public boolean mediaPlayback_skipBackward( + ContentApp contentApp, long deltaPositionMilliseconds, Object responseHandler) { + + Endpoint endpoint = getTargetEndpoint(contentApp); + ChipClusters.MediaPlaybackCluster cluster = + endpoint != null ? endpoint.getCluster(ChipClusters.MediaPlaybackCluster.class) : null; + if (cluster == null) { + Log.e(TAG, "Cluster not found"); + return false; + } + + cluster.skipBackward( + new ChipClusters.MediaPlaybackCluster.PlaybackResponseCallback() { + @Override + public void onSuccess(Integer status, Optional data) { + ((MatterCallbackHandler) responseHandler) + .handleInternal(com.chip.casting.MatterError.NO_ERROR); + } + + @Override + public void onError(Exception error) { + Log.e(TAG, "PlaybackResponseCallback.onError: " + error); + ((MatterCallbackHandler) responseHandler) + .handleInternal(com.chip.casting.MatterError.MATTER_INTERNAL_ERROR); + } + }, + deltaPositionMilliseconds); + return true; + } + + public boolean mediaPlayback_subscribeToCurrentState( + ContentApp contentApp, + SuccessCallback readSuccessHandler, + FailureCallback readFailureHandler, + int minInterval, + int maxInterval, + SubscriptionEstablishedCallback subscriptionEstablishedHandler) { + + Endpoint endpoint = getTargetEndpoint(contentApp); + ChipClusters.MediaPlaybackCluster cluster = + endpoint != null ? endpoint.getCluster(ChipClusters.MediaPlaybackCluster.class) : null; + if (cluster == null) { + Log.e(TAG, "Cluster not found"); + return false; + } + + cluster.subscribeCurrentStateAttribute( + new ChipClusters.IntegerAttributeCallback() { + @Override + public void onSuccess(int value) { + readSuccessHandler.handleInternal(MediaPlaybackTypes.PlaybackStateEnum.values()[value]); + } + + @Override + public void onError(Exception error) { + Log.e(TAG, "IntegerAttributeCallback.onError: " + error); + readFailureHandler.handleInternal(com.chip.casting.MatterError.MATTER_INTERNAL_ERROR); + } + + @Override + public void onSubscriptionEstablished(long subscriptionId) { + subscriptionEstablishedHandler.handleInternal(); + } + }, + minInterval, + maxInterval); + return true; + } + + public boolean applicationLauncher_launchApp( + ContentApp contentApp, + short catalogVendorId, + String applicationId, + byte[] data, + Object responseHandler) { + + Endpoint endpoint = getTargetEndpoint(contentApp); + ChipClusters.ApplicationLauncherCluster cluster = + endpoint != null + ? endpoint.getCluster(ChipClusters.ApplicationLauncherCluster.class) + : null; + if (cluster == null) { + Log.e(TAG, "Cluster not found"); + return false; + } + + // translate to application + Optional application = + Optional.empty(); + if (applicationId != null) { + application = + Optional.of( + new ChipStructs.ApplicationLauncherClusterApplicationStruct( + (int) catalogVendorId, applicationId)); + } + + cluster.launchApp( + new ChipClusters.ApplicationLauncherCluster.LauncherResponseCallback() { + @Override + public void onSuccess(Integer status, Optional data) { + ((MatterCallbackHandler) responseHandler) + .handleInternal(com.chip.casting.MatterError.NO_ERROR); + } + + @Override + public void onError(Exception error) { + Log.e(TAG, "LauncherResponseCallback.onError: " + error); + ((MatterCallbackHandler) responseHandler) + .handleInternal(com.chip.casting.MatterError.MATTER_INTERNAL_ERROR); + } + }, + application, + data != null ? Optional.of(data) : Optional.empty()); + return true; + } + + public boolean applicationLauncher_stopApp( + ContentApp contentApp, short catalogVendorId, String applicationId, Object responseHandler) { + + Endpoint endpoint = getTargetEndpoint(contentApp); + ChipClusters.ApplicationLauncherCluster cluster = + endpoint != null + ? endpoint.getCluster(ChipClusters.ApplicationLauncherCluster.class) + : null; + if (cluster == null) { + Log.e(TAG, "Cluster not found"); + return false; + } + + // translate to application + Optional application = + Optional.empty(); + if (applicationId != null) { + application = + Optional.of( + new ChipStructs.ApplicationLauncherClusterApplicationStruct( + (int) catalogVendorId, applicationId)); + } + + cluster.stopApp( + new ChipClusters.ApplicationLauncherCluster.LauncherResponseCallback() { + @Override + public void onSuccess(Integer status, Optional data) { + ((MatterCallbackHandler) responseHandler) + .handleInternal(com.chip.casting.MatterError.NO_ERROR); + } + + @Override + public void onError(Exception error) { + Log.e(TAG, "LauncherResponseCallback.onError: " + error); + ((MatterCallbackHandler) responseHandler) + .handleInternal(com.chip.casting.MatterError.MATTER_INTERNAL_ERROR); + } + }, + application); + return true; + } + + public boolean applicationLauncher_hideApp( + ContentApp contentApp, short catalogVendorId, String applicationId, Object responseHandler) { + + Endpoint endpoint = getTargetEndpoint(contentApp); + ChipClusters.ApplicationLauncherCluster cluster = + endpoint != null + ? endpoint.getCluster(ChipClusters.ApplicationLauncherCluster.class) + : null; + if (cluster == null) { + Log.e(TAG, "Cluster not found"); + return false; + } + + // translate to application + Optional application = + Optional.empty(); + if (applicationId != null) { + application = + Optional.of( + new ChipStructs.ApplicationLauncherClusterApplicationStruct( + (int) catalogVendorId, applicationId)); + } + + cluster.hideApp( + new ChipClusters.ApplicationLauncherCluster.LauncherResponseCallback() { + @Override + public void onSuccess(Integer status, Optional data) { + ((MatterCallbackHandler) responseHandler) + .handleInternal(com.chip.casting.MatterError.NO_ERROR); + } + + @Override + public void onError(Exception error) { + Log.e(TAG, "LauncherResponseCallback.onError: " + error); + ((MatterCallbackHandler) responseHandler) + .handleInternal(com.chip.casting.MatterError.MATTER_INTERNAL_ERROR); + } + }, + application); + return true; + } + + public boolean targetNavigator_navigateTarget( + ContentApp contentApp, byte target, String data, Object responseHandler) { + + Endpoint endpoint = getTargetEndpoint(contentApp); + ChipClusters.TargetNavigatorCluster cluster = + endpoint != null ? endpoint.getCluster(ChipClusters.TargetNavigatorCluster.class) : null; + if (cluster == null) { + Log.e(TAG, "Cluster not found"); + return false; + } + + cluster.navigateTarget( + new ChipClusters.TargetNavigatorCluster.NavigateTargetResponseCallback() { + @Override + public void onSuccess(Integer status, Optional data) { + ((MatterCallbackHandler) responseHandler) + .handleInternal(com.chip.casting.MatterError.NO_ERROR); + } + + @Override + public void onError(Exception error) { + Log.e(TAG, "NavigateTargetResponseCallback.onError: " + error); + ((MatterCallbackHandler) responseHandler) + .handleInternal(com.chip.casting.MatterError.MATTER_INTERNAL_ERROR); + } + }, + (int) target, + data != null ? Optional.of(data) : Optional.empty()); + return true; + } + + public boolean targetNavigator_subscribeToTargetList( + ContentApp contentApp, + SuccessCallback readSuccessHandler, + FailureCallback readFailureHandler, + int minInterval, + int maxInterval, + SubscriptionEstablishedCallback subscriptionEstablishedHandler) { + + Endpoint endpoint = getTargetEndpoint(contentApp); + ChipClusters.TargetNavigatorCluster cluster = + endpoint != null ? endpoint.getCluster(ChipClusters.TargetNavigatorCluster.class) : null; + if (cluster == null) { + Log.e(TAG, "Cluster not found"); + return false; + } + + cluster.subscribeTargetListAttribute( + new ChipClusters.TargetNavigatorCluster.TargetListAttributeCallback() { + @Override + public void onSuccess( + List targetInfoList) { + List targetInfoListCompat = null; + if (targetInfoList != null) { + targetInfoListCompat = new ArrayList<>(); + for (ChipStructs.TargetNavigatorClusterTargetInfoStruct targetInfo : targetInfoList) { + targetInfoListCompat.add( + new TargetNavigatorTypes.TargetInfo(targetInfo.identifier, targetInfo.name)); + } + } + readSuccessHandler.handleInternal(targetInfoListCompat); + } + + @Override + public void onError(Exception error) { + Log.e(TAG, "TargetListAttributeCallback.onError: " + error); + readFailureHandler.handleInternal(com.chip.casting.MatterError.MATTER_INTERNAL_ERROR); + } + + @Override + public void onSubscriptionEstablished(long subscriptionId) { + subscriptionEstablishedHandler.handleInternal(); + } + }, + minInterval, + maxInterval); + return true; + } + + public boolean keypadInput_sendKey(ContentApp contentApp, byte keyCode, Object responseHandler) { + + Endpoint endpoint = getTargetEndpoint(contentApp); + ChipClusters.KeypadInputCluster cluster = + endpoint != null ? endpoint.getCluster(ChipClusters.KeypadInputCluster.class) : null; + if (cluster == null) { + Log.e(TAG, "Cluster not found"); + return false; + } + + cluster.sendKey( + new ChipClusters.KeypadInputCluster.SendKeyResponseCallback() { + @Override + public void onSuccess(Integer status) { + ((MatterCallbackHandler) responseHandler) + .handleInternal(com.chip.casting.MatterError.NO_ERROR); + } + + @Override + public void onError(Exception error) { + Log.e(TAG, "LauncherResponseCallback.onError: " + error); + ((MatterCallbackHandler) responseHandler) + .handleInternal(com.chip.casting.MatterError.MATTER_INTERNAL_ERROR); + } + }, + (int) keyCode); + return true; + } + + public boolean applicationBasic_readVendorName( + ContentApp contentApp, + SuccessCallback readSuccessHandler, + FailureCallback readFailureHandler) { + + Endpoint endpoint = getTargetEndpoint(contentApp); + ChipClusters.ApplicationBasicCluster cluster = + endpoint != null ? endpoint.getCluster(ChipClusters.ApplicationBasicCluster.class) : null; + if (cluster == null) { + Log.e(TAG, "Cluster not found"); + return false; + } + + cluster.readVendorNameAttribute( + new ChipClusters.CharStringAttributeCallback() { + @Override + public void onSuccess(String value) { + readSuccessHandler.handleInternal(value); + } + + @Override + public void onError(Exception error) { + Log.e(TAG, "CharStringAttributeCallback.onError: " + error); + readFailureHandler.handleInternal(com.chip.casting.MatterError.MATTER_INTERNAL_ERROR); + } + }); + return true; + } + + public boolean applicationBasic_readVendorID( + ContentApp contentApp, + SuccessCallback readSuccessHandler, + FailureCallback readFailureHandler) { + + Endpoint endpoint = getTargetEndpoint(contentApp); + ChipClusters.ApplicationBasicCluster cluster = + endpoint != null ? endpoint.getCluster(ChipClusters.ApplicationBasicCluster.class) : null; + if (cluster == null) { + Log.e(TAG, "Cluster not found"); + return false; + } + + cluster.readVendorIDAttribute( + new ChipClusters.IntegerAttributeCallback() { + @Override + public void onSuccess(int value) { + readSuccessHandler.handleInternal(value); + } + + @Override + public void onError(Exception error) { + Log.e(TAG, "IntegerAttributeCallback.onError: " + error); + readFailureHandler.handleInternal(com.chip.casting.MatterError.MATTER_INTERNAL_ERROR); + } + }); + return true; + } + + public boolean applicationBasic_readApplicationName( + ContentApp contentApp, + SuccessCallback readSuccessHandler, + FailureCallback readFailureHandler) { + + Endpoint endpoint = getTargetEndpoint(contentApp); + ChipClusters.ApplicationBasicCluster cluster = + endpoint != null ? endpoint.getCluster(ChipClusters.ApplicationBasicCluster.class) : null; + if (cluster == null) { + Log.e(TAG, "Cluster not found"); + return false; + } + + cluster.readApplicationNameAttribute( + new ChipClusters.CharStringAttributeCallback() { + @Override + public void onSuccess(String value) { + readSuccessHandler.handleInternal(value); + } + + @Override + public void onError(Exception error) { + Log.e(TAG, "CharStringAttributeCallback.onError: " + error); + readFailureHandler.handleInternal(com.chip.casting.MatterError.MATTER_INTERNAL_ERROR); + } + }); + return true; + } + + public boolean applicationBasic_readProductID( + ContentApp contentApp, + SuccessCallback readSuccessHandler, + FailureCallback readFailureHandler) { + + Endpoint endpoint = getTargetEndpoint(contentApp); + ChipClusters.ApplicationBasicCluster cluster = + endpoint != null ? endpoint.getCluster(ChipClusters.ApplicationBasicCluster.class) : null; + if (cluster == null) { + Log.e(TAG, "Cluster not found"); + return false; + } + + cluster.readProductIDAttribute( + new ChipClusters.IntegerAttributeCallback() { + @Override + public void onSuccess(int value) { + readSuccessHandler.handleInternal(value); + } + + @Override + public void onError(Exception error) { + Log.e(TAG, "IntegerAttributeCallback.onError: " + error); + readFailureHandler.handleInternal(com.chip.casting.MatterError.MATTER_INTERNAL_ERROR); + } + }); + return true; + } + + public boolean applicationBasic_readApplicationVersion( + ContentApp contentApp, + SuccessCallback readSuccessHandler, + FailureCallback readFailureHandler) { + + Endpoint endpoint = getTargetEndpoint(contentApp); + ChipClusters.ApplicationBasicCluster cluster = + endpoint != null ? endpoint.getCluster(ChipClusters.ApplicationBasicCluster.class) : null; + if (cluster == null) { + Log.e(TAG, "Cluster not found"); + return false; + } + + cluster.readApplicationVersionAttribute( + new ChipClusters.CharStringAttributeCallback() { + @Override + public void onSuccess(String value) { + readSuccessHandler.handleInternal(value); + } + + @Override + public void onError(Exception error) { + Log.e(TAG, "CharStringAttributeCallback.onError: " + error); + readFailureHandler.handleInternal(com.chip.casting.MatterError.MATTER_INTERNAL_ERROR); + } + }); + return true; + } + + public boolean onOff_on(ContentApp contentApp, Object responseHandler) { + + Endpoint endpoint = getTargetEndpoint(contentApp); + ChipClusters.OnOffCluster cluster = + endpoint != null ? endpoint.getCluster(ChipClusters.OnOffCluster.class) : null; + if (cluster == null) { + Log.e(TAG, "Cluster not found"); + return false; + } + + cluster.on( + new ChipClusters.DefaultClusterCallback() { + @Override + public void onSuccess() { + ((MatterCallbackHandler) responseHandler) + .handleInternal(com.chip.casting.MatterError.NO_ERROR); + } + + @Override + public void onError(Exception error) { + Log.e(TAG, "DefaultClusterCallback.onError: " + error); + ((MatterCallbackHandler) responseHandler) + .handleInternal(com.chip.casting.MatterError.MATTER_INTERNAL_ERROR); + } + }); + return true; + } + + public boolean onOff_off(ContentApp contentApp, Object responseHandler) { + + Endpoint endpoint = getTargetEndpoint(contentApp); + ChipClusters.OnOffCluster cluster = + endpoint != null ? endpoint.getCluster(ChipClusters.OnOffCluster.class) : null; + if (cluster == null) { + Log.e(TAG, "Cluster not found"); + return false; + } + + cluster.off( + new ChipClusters.DefaultClusterCallback() { + @Override + public void onSuccess() { + ((MatterCallbackHandler) responseHandler) + .handleInternal(com.chip.casting.MatterError.NO_ERROR); + } + + @Override + public void onError(Exception error) { + Log.e(TAG, "DefaultClusterCallback.onError: " + error); + ((MatterCallbackHandler) responseHandler) + .handleInternal(com.chip.casting.MatterError.MATTER_INTERNAL_ERROR); + } + }); + return true; + } + + public boolean onOff_toggle(ContentApp contentApp, Object responseHandler) { + + Endpoint endpoint = getTargetEndpoint(contentApp); + ChipClusters.OnOffCluster cluster = + endpoint != null ? endpoint.getCluster(ChipClusters.OnOffCluster.class) : null; + if (cluster == null) { + Log.e(TAG, "Cluster not found"); + return false; + } + + cluster.toggle( + new ChipClusters.DefaultClusterCallback() { + @Override + public void onSuccess() { + ((MatterCallbackHandler) responseHandler) + .handleInternal(com.chip.casting.MatterError.NO_ERROR); + } + + @Override + public void onError(Exception error) { + Log.e(TAG, "DefaultClusterCallback.onError: " + error); + ((MatterCallbackHandler) responseHandler) + .handleInternal(com.chip.casting.MatterError.MATTER_INTERNAL_ERROR); + } + }); + return true; + } + + public boolean messages_presentMessages( + ContentApp contentApp, + byte[] messageID, + Integer priority, + Integer messageControl, + @Nullable Long startTime, + @Nullable Long duration, + String messageText, + Optional> responses, + Object responseHandler) { + + Endpoint endpoint = getTargetEndpoint(contentApp); + ChipClusters.MessagesCluster cluster = + endpoint != null ? endpoint.getCluster(ChipClusters.MessagesCluster.class) : null; + if (cluster == null) { + Log.e(TAG, "Cluster not found"); + return false; + } + + cluster.presentMessagesRequest( + new ChipClusters.DefaultClusterCallback() { + @Override + public void onSuccess() { + ((MatterCallbackHandler) responseHandler) + .handleInternal(com.chip.casting.MatterError.NO_ERROR); + } + + @Override + public void onError(Exception error) { + Log.e(TAG, "DefaultClusterCallback.onError: " + error); + ((MatterCallbackHandler) responseHandler) + .handleInternal(com.chip.casting.MatterError.MATTER_INTERNAL_ERROR); + } + }, + messageID, + priority, + messageControl, + startTime, + duration, + messageText, + responses); + return true; + } +} diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/VideoPlayer.java b/examples/tv-casting-app/android/App/app/src/compat/jni/com/chip/casting/VideoPlayer.java similarity index 81% rename from examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/VideoPlayer.java rename to examples/tv-casting-app/android/App/app/src/compat/jni/com/chip/casting/VideoPlayer.java index fab9b027a7..1933e28979 100644 --- a/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/VideoPlayer.java +++ b/examples/tv-casting-app/android/App/app/src/compat/jni/com/chip/casting/VideoPlayer.java @@ -17,15 +17,19 @@ */ package com.chip.casting; +import com.matter.casting.core.CastingPlayer; +import com.matter.casting.core.Endpoint; import java.net.InetAddress; -import java.util.HashSet; +import java.util.ArrayList; import java.util.List; import java.util.Objects; -import java.util.Set; +/** @deprecated Use the APIs described in /examples/tv-casting-app/APIs.md instead. */ +@Deprecated public class VideoPlayer { private static final String TAG = VideoPlayer.class.getSimpleName(); + private CastingPlayer castingPlayer; private long nodeId; private byte fabricIndex; private String deviceName; @@ -82,41 +86,25 @@ public VideoPlayer( this.isInitialized = true; } - public boolean isSameAs(DiscoveredNodeData discoveredNodeData) { - // return false because 'this' VideoPlayer is not null - if (discoveredNodeData == null) { - return false; - } - - // return true if hostNames match - if (Objects.equals(hostName, discoveredNodeData.getHostName())) { - return true; - } - - // return false because deviceNames are different - if (Objects.equals(deviceName, discoveredNodeData.getDeviceName()) == false) { - return false; - } - - // return false because not even a single IP Address matches - if (ipAddresses != null) { - boolean matchFound = false; - Set discoveredNodeDataIpAddressSet = - new HashSet(discoveredNodeData.getIpAddresses()); - for (InetAddress videoPlayerIpAddress : ipAddresses) { - if (discoveredNodeDataIpAddressSet.contains(videoPlayerIpAddress)) { - matchFound = true; - break; - } - } - - if (!matchFound) { - return false; + public VideoPlayer(CastingPlayer castingPlayer) { + this.castingPlayer = castingPlayer; + this.deviceType = (int) castingPlayer.getDeviceType(); + this.deviceName = castingPlayer.getDeviceName(); + this.hostName = castingPlayer.getHostName(); + this.ipAddresses = castingPlayer.getIpAddresses(); + this.numIPs = + castingPlayer.getIpAddresses() != null ? castingPlayer.getIpAddresses().size() : 0; + this.isConnected = castingPlayer.isConnected(); + this.productId = castingPlayer.getProductId(); + this.vendorId = castingPlayer.getVendorId(); + List endpoints = castingPlayer.getEndpoints(); + if (endpoints != null) { + this.contentApps = new ArrayList<>(); + for (Endpoint endpoint : endpoints) { + contentApps.add(new ContentApp(endpoint)); } } - - // otherwise, return true - return true; + this.isInitialized = true; } public boolean equals(Object object) { @@ -175,6 +163,10 @@ public String toString() { + '}'; } + CastingPlayer getCastingPlayer() { + return castingPlayer; + } + public long getNodeId() { return nodeId; } diff --git a/examples/tv-casting-app/android/App/app/src/main/AndroidManifest.xml b/examples/tv-casting-app/android/App/app/src/main/AndroidManifest.xml index e551de818e..b47ec80a86 100644 --- a/examples/tv-casting-app/android/App/app/src/main/AndroidManifest.xml +++ b/examples/tv-casting-app/android/App/app/src/main/AndroidManifest.xml @@ -18,9 +18,9 @@ android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" - android:name=".chip.casting.app.ChipTvCastingApplication" + android:name=".matter.casting.ChipTvCastingApplication" android:theme="@style/Theme.CHIPTVCastingApp"> - diff --git a/examples/tv-casting-app/android/App/app/src/main/java/com/chip/casting/util/GlobalCastingConstants.java b/examples/tv-casting-app/android/App/app/src/main/java/com/chip/casting/util/GlobalCastingConstants.java deleted file mode 100644 index 483f1efedb..0000000000 --- a/examples/tv-casting-app/android/App/app/src/main/java/com/chip/casting/util/GlobalCastingConstants.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.chip.casting.util; - -public class GlobalCastingConstants { - public static final String CommissionerServiceType = "_matterd._udp."; - public static final int CommissioningWindowDurationSecs = 3 * 60; - public static final int SetupPasscode = 20202021; - public static final int Discriminator = 0xF00; - public static final boolean ChipCastingSimplified = - true; // set to true, to demo the simplified casting APIs. Otherwise, the older deprecated - // APIs are invoked -} diff --git a/examples/tv-casting-app/android/App/app/src/main/java/com/chip/casting/app/ChipTvCastingApplication.java b/examples/tv-casting-app/android/App/app/src/main/java/com/matter/casting/ChipTvCastingApplication.java similarity index 84% rename from examples/tv-casting-app/android/App/app/src/main/java/com/chip/casting/app/ChipTvCastingApplication.java rename to examples/tv-casting-app/android/App/app/src/main/java/com/matter/casting/ChipTvCastingApplication.java index 4986cc28e4..bea5b88a31 100644 --- a/examples/tv-casting-app/android/App/app/src/main/java/com/chip/casting/app/ChipTvCastingApplication.java +++ b/examples/tv-casting-app/android/App/app/src/main/java/com/matter/casting/ChipTvCastingApplication.java @@ -1,4 +1,4 @@ -package com.chip.casting.app; +package com.matter.casting; import android.app.Application; diff --git a/examples/tv-casting-app/android/App/app/src/main/java/com/chip/casting/app/MainActivity.java b/examples/tv-casting-app/android/App/app/src/main/java/com/matter/casting/MainActivity.java similarity index 92% rename from examples/tv-casting-app/android/App/app/src/main/java/com/chip/casting/app/MainActivity.java rename to examples/tv-casting-app/android/App/app/src/main/java/com/matter/casting/MainActivity.java index 685dbf2fb6..53908322d1 100644 --- a/examples/tv-casting-app/android/App/app/src/main/java/com/chip/casting/app/MainActivity.java +++ b/examples/tv-casting-app/android/App/app/src/main/java/com/matter/casting/MainActivity.java @@ -1,4 +1,4 @@ -package com.chip.casting.app; +package com.matter.casting; import android.os.Bundle; import android.util.Log; @@ -9,15 +9,13 @@ import com.chip.casting.AppParameters; import com.chip.casting.DiscoveredNodeData; import com.chip.casting.TvCastingApp; +import com.chip.casting.app.CertTestFragment; +import com.chip.casting.app.CommissionerDiscoveryFragment; +import com.chip.casting.app.ConnectionFragment; +import com.chip.casting.app.ContentLauncherFragment; +import com.chip.casting.app.MediaPlaybackFragment; +import com.chip.casting.app.SelectClusterFragment; import com.chip.casting.util.GlobalCastingConstants; -import com.matter.casting.ActionSelectorFragment; -import com.matter.casting.ApplicationBasicReadVendorIDExampleFragment; -import com.matter.casting.ConnectionExampleFragment; -import com.matter.casting.ContentLauncherLaunchURLExampleFragment; -import com.matter.casting.DiscoveryExampleFragment; -import com.matter.casting.InitializationExample; -import com.matter.casting.MediaPlaybackSubscribeToCurrentStateExampleFragment; -import com.matter.casting.PreferencesConfigurationManager; import com.matter.casting.core.CastingPlayer; import java.util.Random; diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/NsdDiscoveryListener.java b/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/NsdDiscoveryListener.java deleted file mode 100644 index 1a9556e5fd..0000000000 --- a/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/NsdDiscoveryListener.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright (c) 2022 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. - * - */ -package com.chip.casting; - -import android.net.nsd.NsdManager; -import android.net.nsd.NsdServiceInfo; -import android.util.Log; -import chip.platform.NsdManagerServiceResolver; -import java.util.List; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -public class NsdDiscoveryListener implements NsdManager.DiscoveryListener { - private static final String TAG = NsdDiscoveryListener.class.getSimpleName(); - - private final NsdManager nsdManager; - private final String targetServiceType; - private final List deviceTypeFilter; - private final List preCommissionedVideoPlayers; - private final SuccessCallback successCallback; - private final FailureCallback failureCallback; - private final NsdManagerServiceResolver.NsdManagerResolverAvailState nsdManagerResolverAvailState; - private final ExecutorService resolutionExecutor; - - public NsdDiscoveryListener( - NsdManager nsdManager, - String targetServiceType, - List deviceTypeFilter, - List preCommissionedVideoPlayers, - SuccessCallback successCallback, - FailureCallback failureCallback, - NsdManagerServiceResolver.NsdManagerResolverAvailState nsdManagerResolverAvailState) { - this.nsdManager = nsdManager; - this.targetServiceType = targetServiceType; - this.deviceTypeFilter = deviceTypeFilter; - this.preCommissionedVideoPlayers = preCommissionedVideoPlayers; - this.successCallback = successCallback; - this.failureCallback = failureCallback; - this.nsdManagerResolverAvailState = nsdManagerResolverAvailState; - this.resolutionExecutor = Executors.newSingleThreadExecutor(); - } - - @Override - public void onDiscoveryStarted(String regType) { - Log.d(TAG, "Service discovery started. regType: " + regType); - } - - @Override - public void onServiceFound(NsdServiceInfo service) { - this.resolutionExecutor.execute( - new Runnable() { - @Override - public void run() { - Log.d(TAG, "Service discovery success. " + service); - if (service.getServiceType().equals(targetServiceType)) { - if (nsdManagerResolverAvailState != null) { - nsdManagerResolverAvailState.acquireResolver(); - } - - Log.d(TAG, "Calling NsdManager.resolveService for " + service); - nsdManager.resolveService( - service, - new NsdResolveListener( - nsdManager, - deviceTypeFilter, - preCommissionedVideoPlayers, - successCallback, - failureCallback, - nsdManagerResolverAvailState, - 1)); - } else { - Log.d(TAG, "Ignoring discovered service: " + service.toString()); - } - } - }); - } - - @Override - public void onServiceLost(NsdServiceInfo service) { - // When the network service is no longer available. - // Internal bookkeeping code goes here. - Log.e(TAG, "Service lost: " + service); - failureCallback.handle(MatterError.DISCOVERY_SERVICE_LOST); - } - - @Override - public void onDiscoveryStopped(String serviceType) { - Log.i(TAG, "Discovery stopped: " + serviceType); - if (nsdManagerResolverAvailState != null) { - nsdManagerResolverAvailState.signalFree(); - } - } - - @Override - public void onStartDiscoveryFailed(String serviceType, int errorCode) { - Log.e(TAG, "Discovery failed to start: Error code:" + errorCode); - TvCastingApp.getInstance().resetDiscoveryState(); - failureCallback.handle( - new MatterError( - 3, "NsdDiscoveryListener Discovery failed to start: Nsd Error code:" + errorCode)); - } - - @Override - public void onStopDiscoveryFailed(String serviceType, int errorCode) { - Log.e(TAG, "Discovery failed to stop: Error code:" + errorCode); - if (nsdManagerResolverAvailState != null) { - nsdManagerResolverAvailState.signalFree(); - } - failureCallback.handle( - new MatterError( - 3, "NsdDiscoveryListener Discovery failed to stop: Nsd Error code:" + errorCode)); - } -} diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/NsdResolveListener.java b/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/NsdResolveListener.java deleted file mode 100644 index 638425675d..0000000000 --- a/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/NsdResolveListener.java +++ /dev/null @@ -1,165 +0,0 @@ -/* - * Copyright (c) 2022 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. - * - */ -package com.chip.casting; - -import android.net.nsd.NsdManager; -import android.net.nsd.NsdServiceInfo; -import android.util.Log; -import chip.platform.NsdManagerServiceResolver; -import java.util.List; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; - -public class NsdResolveListener implements NsdManager.ResolveListener { - - private static final String TAG = NsdResolveListener.class.getSimpleName(); - - private static final int MAX_RESOLUTION_ATTEMPTS = 5; - private static final int RESOLUTION_ATTEMPT_DELAY_SECS = 1; - - private final NsdManager nsdManager; - private final List deviceTypeFilter; - private final List preCommissionedVideoPlayers; - private final SuccessCallback successCallback; - private final FailureCallback failureCallback; - private final NsdManagerServiceResolver.NsdManagerResolverAvailState nsdManagerResolverAvailState; - private final int resolutionAttemptNumber; - - public NsdResolveListener( - NsdManager nsdManager, - List deviceTypeFilter, - List preCommissionedVideoPlayers, - SuccessCallback successCallback, - FailureCallback failureCallback, - NsdManagerServiceResolver.NsdManagerResolverAvailState nsdManagerResolverAvailState, - int resolutionAttemptNumber) { - this.nsdManager = nsdManager; - this.deviceTypeFilter = deviceTypeFilter; - this.preCommissionedVideoPlayers = preCommissionedVideoPlayers; - if (preCommissionedVideoPlayers != null) { - for (VideoPlayer videoPlayer : preCommissionedVideoPlayers) { - Log.d(TAG, "Precommissioned video player: " + videoPlayer); - } - } - this.successCallback = successCallback; - this.failureCallback = failureCallback; - this.nsdManagerResolverAvailState = nsdManagerResolverAvailState; - this.resolutionAttemptNumber = resolutionAttemptNumber; - } - - @Override - public void onServiceResolved(NsdServiceInfo serviceInfo) { - DiscoveredNodeData discoveredNodeData = new DiscoveredNodeData(serviceInfo); - Log.d(TAG, "DiscoveredNodeData resolved: " + discoveredNodeData); - - if (nsdManagerResolverAvailState != null) { - nsdManagerResolverAvailState.signalFree(); - } - - if (isPassingDeviceTypeFilter(discoveredNodeData)) { - addCommissioningInfo(discoveredNodeData); - successCallback.handle(discoveredNodeData); - } else { - Log.d( - TAG, - "DiscoveredNodeData ignored because it did not pass the device type filter " - + discoveredNodeData); - } - } - - @Override - public void onResolveFailed(NsdServiceInfo serviceInfo, int errorCode) { - if (nsdManagerResolverAvailState != null) { - if (errorCode != NsdManager.FAILURE_ALREADY_ACTIVE - || resolutionAttemptNumber >= MAX_RESOLUTION_ATTEMPTS) { - nsdManagerResolverAvailState.signalFree(); - } - } - - switch (errorCode) { - case NsdManager.FAILURE_ALREADY_ACTIVE: - Log.e(TAG, "NsdResolveListener FAILURE_ALREADY_ACTIVE - Service: " + serviceInfo); - if (resolutionAttemptNumber < MAX_RESOLUTION_ATTEMPTS) { - Log.d(TAG, "NsdResolveListener Scheduling a retry to resolve service " + serviceInfo); - Executors.newSingleThreadScheduledExecutor() - .schedule( - new Runnable() { - @Override - public void run() { - nsdManager.resolveService( - serviceInfo, - new NsdResolveListener( - nsdManager, - deviceTypeFilter, - preCommissionedVideoPlayers, - successCallback, - failureCallback, - nsdManagerResolverAvailState, - resolutionAttemptNumber + 1)); - } - }, - RESOLUTION_ATTEMPT_DELAY_SECS, - TimeUnit.SECONDS); - } else { // giving up - failureCallback.handle( - new MatterError( - 3, "NsdResolveListener FAILURE_ALREADY_ACTIVE - Service: " + serviceInfo)); - } - break; - case NsdManager.FAILURE_INTERNAL_ERROR: - Log.e(TAG, "NsdResolveListener FAILURE_INTERNAL_ERROR - Service: " + serviceInfo); - failureCallback.handle( - new MatterError( - 3, "NsdResolveListener FAILURE_INTERNAL_ERROR - Service: " + serviceInfo)); - break; - case NsdManager.FAILURE_MAX_LIMIT: - Log.e(TAG, "NsdResolveListener FAILURE_MAX_LIMIT - Service: " + serviceInfo); - failureCallback.handle( - new MatterError(19, "NsdResolveListener FAILURE_MAX_LIMIT - Service: " + serviceInfo)); - break; - } - } - - private boolean isPassingDeviceTypeFilter(DiscoveredNodeData discoveredNodeData) { - return deviceTypeFilter == null - || deviceTypeFilter.isEmpty() - || deviceTypeFilter.contains(discoveredNodeData.getDeviceType()); - } - - private void addCommissioningInfo(DiscoveredNodeData discoveredNodeData) { - if (preCommissionedVideoPlayers != null) { - long currentUnixTimeMS = System.currentTimeMillis(); - for (VideoPlayer videoPlayer : preCommissionedVideoPlayers) { - if (videoPlayer.isSameAs(discoveredNodeData)) { - Log.d( - TAG, - "Matching Video Player with the following information found for DiscoveredNodeData" - + videoPlayer); - Log.d(TAG, "Updating discovery timestamp for VideoPlayer to " + currentUnixTimeMS); - videoPlayer.setLastDiscoveredMs(currentUnixTimeMS); - discoveredNodeData.setConnectableVideoPlayer(videoPlayer); - return; - } - } - } - Log.d( - TAG, - "No matching VideoPlayers found from the cache for new DiscoveredNodeData: " - + discoveredNodeData); - } -} diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/TvCastingApp.java b/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/TvCastingApp.java deleted file mode 100644 index 9dd0fa500d..0000000000 --- a/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/TvCastingApp.java +++ /dev/null @@ -1,608 +0,0 @@ -/* - * Copyright (c) 2022 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. - * - */ -package com.chip.casting; - -import android.content.Context; -import android.net.nsd.NsdManager; -import android.net.wifi.WifiManager; -import android.util.Log; -import chip.appserver.ChipAppServer; -import chip.platform.AndroidBleManager; -import chip.platform.AndroidChipPlatform; -import chip.platform.ChipMdnsCallbackImpl; -import chip.platform.DiagnosticDataProviderImpl; -import chip.platform.NsdManagerServiceBrowser; -import chip.platform.NsdManagerServiceResolver; -import chip.platform.PreferencesKeyValueStoreManager; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeUnit; -import java.util.function.Predicate; - -public class TvCastingApp { - private static final String TAG = TvCastingApp.class.getSimpleName(); - private static final String DISCOVERY_TARGET_SERVICE_TYPE = "_matterd._udp."; - private static final List DISCOVERY_TARGET_DEVICE_TYPE_FILTER = - Arrays.asList(35L); // Video player = 35; - - // delay before which we assume undiscovered cached players may be in STR mode - private static final long CHIP_DEVICE_CONFIG_STR_DISCOVERY_DELAY_SEC = 5; - - private static TvCastingApp sInstance; - private Context applicationContext; - private ChipAppServer chipAppServer; - private NsdManagerServiceResolver.NsdManagerResolverAvailState nsdManagerResolverAvailState; - private boolean discoveryStarted = false; - private Object discoveryLock = new Object(); - - private List discoveredPlayers; - private ScheduledFuture reportSleepingVideoPlayerCommissionersFuture; - - private WifiManager.MulticastLock multicastLock; - private NsdManager nsdManager; - private NsdDiscoveryListener nsdDiscoveryListener; - - private TvCastingApp() {} - - public static TvCastingApp getInstance() { - if (sInstance == null) { - sInstance = new TvCastingApp(); - } - return sInstance; - } - - public boolean initApp(Context applicationContext, AppParameters appParameters) { - if (applicationContext == null - || appParameters == null - || appParameters.getConfigurationManager() == null) { - return false; - } - - this.applicationContext = applicationContext; - nsdManagerResolverAvailState = new NsdManagerServiceResolver.NsdManagerResolverAvailState(); - NsdManagerServiceResolver nsdManagerServiceResolver = - new NsdManagerServiceResolver(applicationContext, nsdManagerResolverAvailState); - - AndroidChipPlatform chipPlatform = - new AndroidChipPlatform( - new AndroidBleManager(), - new PreferencesKeyValueStoreManager(applicationContext), - appParameters.getConfigurationManager(), - nsdManagerServiceResolver, - new NsdManagerServiceBrowser(applicationContext), - new ChipMdnsCallbackImpl(), - new DiagnosticDataProviderImpl(applicationContext)); - - boolean ret = - chipPlatform.updateCommissionableDataProviderData( - appParameters.getSpake2pVerifierBase64(), - appParameters.getSpake2pSaltBase64(), - appParameters.getSpake2pIterationCount(), - appParameters.getSetupPasscode(), - appParameters.getDiscriminator()); - if (!ret) { - Log.e( - TAG, - "TvCastingApp.initApp failed to updateCommissionableDataProviderData on chipPlatform"); - return ret; - } - - ret = preInitJni(appParameters); - if (!ret) { - Log.e(TAG, "TvCastingApp.initApp failed in preInitJni"); - return ret; - } - - chipAppServer = new ChipAppServer(); - ret = chipAppServer.startApp(); - if (!ret) { - Log.e(TAG, "TvCastingApp.initApp failed in start chipAppServer"); - return ret; - } - - return initJni(appParameters); - } - - public native void setDACProvider(DACProvider provider); - - private native boolean preInitJni(AppParameters appParameters); - - private native boolean initJni(AppParameters appParameters); - - public void discoverVideoPlayerCommissioners( - SuccessCallback discoverySuccessCallback, - FailureCallback discoveryFailureCallback) { - synchronized (discoveryLock) { - Log.d(TAG, "TvCastingApp.discoverVideoPlayerCommissioners called"); - - if (this.discoveryStarted) { - Log.d(TAG, "Discovery already started, stopping before starting again"); - stopVideoPlayerDiscovery(); - } - - List preCommissionedVideoPlayers = readCachedVideoPlayers(); - - WifiManager wifiManager = - (WifiManager) applicationContext.getSystemService(Context.WIFI_SERVICE); - multicastLock = wifiManager.createMulticastLock("multicastLock"); - multicastLock.setReferenceCounted(true); - multicastLock.acquire(); - - nsdManager = (NsdManager) applicationContext.getSystemService(Context.NSD_SERVICE); - discoveredPlayers = new ArrayList<>(); - nsdDiscoveryListener = - new NsdDiscoveryListener( - nsdManager, - DISCOVERY_TARGET_SERVICE_TYPE, - DISCOVERY_TARGET_DEVICE_TYPE_FILTER, - preCommissionedVideoPlayers, - new SuccessCallback() { - @Override - public void handle(DiscoveredNodeData commissioner) { - Log.d(TAG, "Discovered commissioner added " + commissioner); - discoveredPlayers.add(commissioner); - discoverySuccessCallback.handle(commissioner); - } - }, - discoveryFailureCallback, - nsdManagerResolverAvailState); - - nsdManager.discoverServices( - DISCOVERY_TARGET_SERVICE_TYPE, NsdManager.PROTOCOL_DNS_SD, nsdDiscoveryListener); - Log.d(TAG, "TvCastingApp.discoverVideoPlayerCommissioners started"); - - /** - * Surface players (as DiscoveredNodeData objects on discoverySuccessCallback) that we - * previously connected to and received their WakeOnLAN MACAddress, but could not discover - * over DNS-SD this time in CHIP_DEVICE_CONFIG_STR_DISCOVERY_DELAY_SEC. This API will also - * ensure that the reported players were previously discoverable within - * CHIP_DEVICE_CONFIG_STR_CACHE_LAST_DISCOVERED_HOURS. - * - *

The DiscoveredNodeData object for such players will have the IsAsleep attribute set to - * true, which can optionally be used for any special UX treatment when displaying them. - * - *

Surfacing such players as discovered will allow displaying them to the user, who may - * want to cast to them. In such a case, the VerifyOrEstablishConnection API will turn them on - * over WakeOnLan. - */ - this.reportSleepingVideoPlayerCommissionersFuture = - Executors.newScheduledThreadPool(1) - .schedule( - () -> { - Log.d( - TAG, - "Scheduling reportSleepingCommissioners with commissioner count " - + (preCommissionedVideoPlayers != null - ? preCommissionedVideoPlayers.size() - : 0)); - reportSleepingVideoPlayerCommissioners( - preCommissionedVideoPlayers, discoverySuccessCallback); - }, - CHIP_DEVICE_CONFIG_STR_DISCOVERY_DELAY_SEC * 1000, - TimeUnit.MILLISECONDS); - - this.discoveryStarted = true; - } - } - - private void reportSleepingVideoPlayerCommissioners( - List cachedVideoPlayers, - SuccessCallback discoverySuccessCallback) { - Log.d( - TAG, - "TvCastingApp.reportSleepingVideoPlayerCommissioners called with commissioner count " - + (cachedVideoPlayers != null ? cachedVideoPlayers.size() : 0)); - if (cachedVideoPlayers == null) { - Log.d(TAG, "No cached video players available."); - return; - } - - for (VideoPlayer player : cachedVideoPlayers) { - Log.d(TAG, "Cached Video Player: " + player); - // do NOT surface this cached Player if we don't have its MACAddress - if (player.getMACAddress() == null) { - Log.d( - TAG, - "TvCastingApp.reportSleepingVideoPlayerCommissioners Skipping Player with hostName" - + player.getHostName() - + " but no MACAddress"); - continue; - } - - // do NOT surface this cached Player if it has not been discoverable recently (in - // CHIP_DEVICE_CONFIG_STR_CACHE_LAST_DISCOVERED_HOURS) - if (!WasRecentlyDiscoverable(player)) { - Log.d( - TAG, - "TvCastingApp.reportSleepingVideoPlayerCommissioners Skipping Player with hostName" - + player.getHostName() - + " that has not been discovered recently"); - continue; - } - - // do NOT surface this cached Player if it was just discovered right now (in this discovery - // call) - boolean justDiscovered = - discoveredPlayers - .stream() - .anyMatch( - new Predicate() { - @Override - public boolean test(DiscoveredNodeData discoveredNodeData) { - return player.getHostName().equals(discoveredNodeData.getHostName()); - } - }); - if (justDiscovered) { - Log.d( - TAG, - "TvCastingApp.reportSleepingVideoPlayerCommissioners Skipping Player with hostName" - + player.getHostName() - + " that was just discovered"); - continue; - } - - // DO surface this cached Player (as asleep) - Log.d(TAG, "Reporting sleeping player with hostName " + player.getHostName()); - player.setIsAsleep(true); - discoverySuccessCallback.handle(new DiscoveredNodeData(player)); - } - } - - private native boolean WasRecentlyDiscoverable(VideoPlayer player); - - public void stopVideoPlayerDiscovery() { - synchronized (discoveryLock) { - Log.d(TAG, "TvCastingApp trying to stop video player discovery"); - if (this.discoveryStarted - && nsdManager != null - && multicastLock != null - && nsdDiscoveryListener != null) { - Log.d(TAG, "TvCastingApp stopping Video Player commissioner discovery"); - try { - nsdManager.stopServiceDiscovery(nsdDiscoveryListener); - } catch (IllegalArgumentException e) { - Log.w( - TAG, - "TvCastingApp received exception on calling nsdManager.stopServiceDiscovery() " - + e.getMessage()); - } - - if (multicastLock.isHeld()) { - multicastLock.release(); - } - - if (reportSleepingVideoPlayerCommissionersFuture != null) { - reportSleepingVideoPlayerCommissionersFuture.cancel(false); - } - this.discoveryStarted = false; - } - } - } - - void resetDiscoveryState() { - synchronized (discoveryLock) { - Log.d(TAG, "TvCastingApp resetting discovery state"); - this.discoveryStarted = false; - this.nsdDiscoveryListener = null; - if (multicastLock != null && multicastLock.isHeld()) { - multicastLock.release(); - } - } - } - - public native boolean openBasicCommissioningWindow( - int duration, - CommissioningCallbacks commissioningCallbacks, - SuccessCallback onConnectionSuccess, - FailureCallback onConnectionFailure, - SuccessCallback onNewOrUpdatedEndpointCallback); - - public native boolean sendCommissioningRequest(DiscoveredNodeData commissioner); - - /** @Deprecated Use sendCommissioningRequest(DiscoveredNodeData) instead */ - private native boolean sendUserDirectedCommissioningRequest(String address, int port); - - public native List readCachedVideoPlayers(); - - public native boolean verifyOrEstablishConnection( - VideoPlayer targetVideoPlayer, - SuccessCallback onConnectionSuccess, - FailureCallback onConnectionFailure, - SuccessCallback onNewOrUpdatedEndpointCallback); - - public native void shutdownAllSubscriptions(); - - public native void disconnect(); - - public native List getActiveTargetVideoPlayers(); - - public native boolean purgeCache(); - - /* - * CONTENT LAUNCHER CLUSTER - * - * TODO: Add API to subscribe to AcceptHeader - */ - public native boolean contentLauncherLaunchURL( - ContentApp contentApp, String contentUrl, String contentDisplayStr, Object launchURLHandler); - - public native boolean contentLauncher_launchContent( - ContentApp contentApp, - ContentLauncherTypes.ContentSearch search, - boolean autoPlay, - String data, - Object responseHandler); - - public native boolean contentLauncher_subscribeToSupportedStreamingProtocols( - ContentApp contentApp, - SuccessCallback readSuccessHandler, - FailureCallback readFailureHandler, - int minInterval, - int maxInterval, - SubscriptionEstablishedCallback subscriptionEstablishedHandler); - - /* - * LEVEL CONTROL CLUSTER - */ - public native boolean levelControl_step( - ContentApp contentApp, - byte stepMode, - byte stepSize, - short transitionTime, - byte optionMask, - byte optionOverridem, - Object responseHandler); - - public native boolean levelControl_moveToLevel( - ContentApp contentApp, - byte level, - short transitionTime, - byte optionMask, - byte optionOverridem, - Object responseHandler); - - public native boolean levelControl_subscribeToCurrentLevel( - ContentApp contentApp, - SuccessCallback readSuccessHandler, - FailureCallback readFailureHandler, - int minInterval, - int maxInterval, - SubscriptionEstablishedCallback subscriptionEstablishedHandler); - - public native boolean levelControl_subscribeToMinLevel( - ContentApp contentApp, - SuccessCallback readSuccessHandler, - FailureCallback readFailureHandler, - int minInterval, - int maxInterval, - SubscriptionEstablishedCallback subscriptionEstablishedHandler); - - public native boolean levelControl_subscribeToMaxLevel( - ContentApp contentApp, - SuccessCallback readSuccessHandler, - FailureCallback readFailureHandler, - int minInterval, - int maxInterval, - SubscriptionEstablishedCallback subscriptionEstablishedHandler); - - /* - * MEDIA PLAYBACK CLUSTER - */ - public native boolean mediaPlayback_play(ContentApp contentApp, Object responseHandler); - - public native boolean mediaPlayback_pause(ContentApp contentApp, Object responseHandler); - - public native boolean mediaPlayback_stopPlayback(ContentApp contentApp, Object responseHandler); - - public native boolean mediaPlayback_next(ContentApp contentApp, Object responseHandler); - - public native boolean mediaPlayback_previous(ContentApp contentApp, Object responseHandler); - - public native boolean mediaPlayback_rewind(ContentApp contentApp, Object responseHandler); - - public native boolean mediaPlayback_fastForward(ContentApp contentApp, Object responseHandler); - - public native boolean mediaPlayback_startOver(ContentApp contentApp, Object responseHandler); - - public native boolean mediaPlayback_seek( - ContentApp contentApp, long position, Object responseHandler); - - public native boolean mediaPlayback_skipForward( - ContentApp contentApp, long deltaPositionMilliseconds, Object responseHandler); - - public native boolean mediaPlayback_skipBackward( - ContentApp contentApp, long deltaPositionMilliseconds, Object responseHandler); - - public native boolean mediaPlayback_subscribeToCurrentState( - ContentApp contentApp, - SuccessCallback readSuccessHandler, - FailureCallback readFailureHandler, - int minInterval, - int maxInterval, - SubscriptionEstablishedCallback subscriptionEstablishedHandler); - - public native boolean mediaPlayback_subscribeToDuration( - ContentApp contentApp, - SuccessCallback readSuccessHandler, - FailureCallback readFailureHandler, - int minInterval, - int maxInterval, - SubscriptionEstablishedCallback subscriptionEstablishedHandler); - - public native boolean mediaPlayback_subscribeToSampledPosition( - ContentApp contentApp, - SuccessCallback readSuccessHandler, - FailureCallback readFailureHandler, - int minInterval, - int maxInterval, - SubscriptionEstablishedCallback subscriptionEstablishedHandler); - - public native boolean mediaPlayback_subscribeToPlaybackSpeed( - ContentApp contentApp, - SuccessCallback readSuccessHandler, - FailureCallback readFailureHandler, - int minInterval, - int maxInterval, - SubscriptionEstablishedCallback subscriptionEstablishedHandler); - - public native boolean mediaPlayback_subscribeToSeekRangeEnd( - ContentApp contentApp, - SuccessCallback readSuccessHandler, - FailureCallback readFailureHandler, - int minInterval, - int maxInterval, - SubscriptionEstablishedCallback subscriptionEstablishedHandler); - - public native boolean mediaPlayback_subscribeToSeekRangeStart( - ContentApp contentApp, - SuccessCallback readSuccessHandler, - FailureCallback readFailureHandler, - int minInterval, - int maxInterval, - SubscriptionEstablishedCallback subscriptionEstablishedHandler); - - /* - * APPLICATION LAUNCHER CLUSTER - */ - public native boolean applicationLauncher_launchApp( - ContentApp contentApp, - short catalogVendorId, - String applicationId, - byte[] data, - Object responseHandler); - - public native boolean applicationLauncher_stopApp( - ContentApp contentApp, short catalogVendorId, String applicationId, Object responseHandler); - - public native boolean applicationLauncher_hideApp( - ContentApp contentApp, short catalogVendorId, String applicationId, Object responseHandler); - - /* - * TARGET NAVIGATOR CLUSTER - */ - public native boolean targetNavigator_navigateTarget( - ContentApp contentApp, byte target, String data, Object responseHandler); - - public native boolean targetNavigator_subscribeToCurrentTarget( - ContentApp contentApp, - SuccessCallback readSuccessHandler, - FailureCallback readFailureHandler, - int minInterval, - int maxInterval, - SubscriptionEstablishedCallback subscriptionEstablishedHandler); - - public native boolean targetNavigator_subscribeToTargetList( - ContentApp contentApp, - SuccessCallback readSuccessHandler, - FailureCallback readFailureHandler, - int minInterval, - int maxInterval, - SubscriptionEstablishedCallback subscriptionEstablishedHandler); - - /* - * KEYPAD INPUT CLUSTER - */ - public native boolean keypadInput_sendKey( - ContentApp contentApp, byte keyCode, Object responseHandler); - - /** - * APPLICATION BASIC - * - *

TODO: Add APIs to subscribe to & read Application, Status and AllowedVendorList - */ - public native boolean applicationBasic_subscribeToVendorName( - ContentApp contentApp, - SuccessCallback readSuccessHandler, - FailureCallback readFailureHandler, - int minInterval, - int maxInterval, - SubscriptionEstablishedCallback subscriptionEstablishedHandler); - - public native boolean applicationBasic_subscribeToVendorID( - ContentApp contentApp, - SuccessCallback readSuccessHandler, - FailureCallback readFailureHandler, - int minInterval, - int maxInterval, - SubscriptionEstablishedCallback subscriptionEstablishedHandler); - - public native boolean applicationBasic_subscribeToApplicationName( - ContentApp contentApp, - SuccessCallback readSuccessHandler, - FailureCallback readFailureHandler, - int minInterval, - int maxInterval, - SubscriptionEstablishedCallback subscriptionEstablishedHandler); - - public native boolean applicationBasic_subscribeToProductID( - ContentApp contentApp, - SuccessCallback readSuccessHandler, - FailureCallback readFailureHandler, - int minInterval, - int maxInterval, - SubscriptionEstablishedCallback subscriptionEstablishedHandler); - - public native boolean applicationBasic_subscribeToApplicationVersion( - ContentApp contentApp, - SuccessCallback readSuccessHandler, - FailureCallback readFailureHandler, - int minInterval, - int maxInterval, - SubscriptionEstablishedCallback subscriptionEstablishedHandler); - - public native boolean applicationBasic_readVendorName( - ContentApp contentApp, - SuccessCallback readSuccessHandler, - FailureCallback readFailureHandler); - - public native boolean applicationBasic_readVendorID( - ContentApp contentApp, - SuccessCallback readSuccessHandler, - FailureCallback readFailureHandler); - - public native boolean applicationBasic_readApplicationName( - ContentApp contentApp, - SuccessCallback readSuccessHandler, - FailureCallback readFailureHandler); - - public native boolean applicationBasic_readProductID( - ContentApp contentApp, - SuccessCallback readSuccessHandler, - FailureCallback readFailureHandler); - - public native boolean applicationBasic_readApplicationVersion( - ContentApp contentApp, - SuccessCallback readSuccessHandler, - FailureCallback readFailureHandler); - - public native boolean onOff_on(ContentApp contentApp, Object responseHandler); - - public native boolean onOff_off(ContentApp contentApp, Object responseHandler); - - public native boolean onOff_toggle(ContentApp contentApp, Object responseHandler); - - public native boolean messages_presentMessages( - ContentApp contentApp, String messageText, Object responseHandler); - - static { - System.loadLibrary("TvCastingApp"); - } -} diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/com/matter/casting/support/DataProvider.java b/examples/tv-casting-app/android/App/app/src/main/jni/com/matter/casting/support/DataProvider.java index 854cf76ce8..63e8da3d31 100644 --- a/examples/tv-casting-app/android/App/app/src/main/jni/com/matter/casting/support/DataProvider.java +++ b/examples/tv-casting-app/android/App/app/src/main/jni/com/matter/casting/support/DataProvider.java @@ -20,7 +20,7 @@ import android.util.Log; public interface DataProvider { - public static final String TAG = DataProvider.class.getSimpleName(); + String TAG = DataProvider.class.getSimpleName(); default T _get() { T val = null; @@ -32,5 +32,5 @@ default T _get() { return val; } - public abstract T get(); + T get(); } diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/Constants.h b/examples/tv-casting-app/android/App/app/src/main/jni/cpp/Constants.h deleted file mode 100644 index 735cabf237..0000000000 --- a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/Constants.h +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) 2022 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 - -enum MediaCommandName -{ - ContentLauncher_LaunchURL, - ContentLauncher_LaunchContent, - LevelControl_Step, - LevelControl_MoveToLevel, - OnOff_On, - OnOff_Off, - OnOff_Toggle, - MediaPlayback_Play, - MediaPlayback_Pause, - MediaPlayback_StopPlayback, - MediaPlayback_Next, - MediaPlayback_Previous, - MediaPlayback_Rewind, - MediaPlayback_FastForward, - MediaPlayback_StartOver, - MediaPlayback_Seek, - MediaPlayback_SkipForward, - MediaPlayback_SkipBackward, - Messages_PresentMessagesRequest, - ApplicationLauncher_LaunchApp, - ApplicationLauncher_StopApp, - ApplicationLauncher_HideApp, - TargetNavigator_NavigateTarget, - KeypadInput_SendKey, - - MEDIA_COMMAND_COUNT -}; - -enum MediaAttributeName -{ - ContentLauncher_SupportedStreamingProtocols, - ContentLauncher_AcceptHeader, - LevelControl_CurrentLevel, - LevelControl_MinLevel, - LevelControl_MaxLevel, - MediaPlayback_CurrentState, - MediaPlayback_StartTime, - MediaPlayback_Duration, - MediaPlayback_SampledPosition, - MediaPlayback_PlaybackSpeed, - MediaPlayback_SeekRangeEnd, - MediaPlayback_SeekRangeStart, - ApplicationLauncher_CurrentApp, - TargetNavigator_TargetList, - TargetNavigator_CurrentTarget, - ApplicationBasic_VendorName, - ApplicationBasic_VendorID, - ApplicationBasic_ApplicationName, - ApplicationBasic_ProductID, - ApplicationBasic_ApplicationVersion, - - MEDIA_ATTRIBUTE_COUNT -}; diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/ConversionUtils.cpp b/examples/tv-casting-app/android/App/app/src/main/jni/cpp/ConversionUtils.cpp deleted file mode 100644 index c8a38942e6..0000000000 --- a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/ConversionUtils.cpp +++ /dev/null @@ -1,410 +0,0 @@ -/* - * - * Copyright (c) 2021 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 "ConversionUtils.h" - -#include -#include -#include -#include -#include -#include -#include - -CHIP_ERROR convertJAppParametersToCppAppParams(jobject appParameters, AppParams & outAppParams) -{ - ChipLogProgress(AppServer, "convertJAppParametersToCppAppParams called"); - JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread(); - VerifyOrReturnError(appParameters != nullptr, CHIP_ERROR_INVALID_ARGUMENT); - - jclass jAppParametersClass; - ReturnErrorOnFailure( - chip::JniReferences::GetInstance().GetLocalClassRef(env, "com/chip/casting/AppParameters", jAppParametersClass)); - - jmethodID getRotatingDeviceIdUniqueIdMethod = env->GetMethodID(jAppParametersClass, "getRotatingDeviceIdUniqueId", "()[B"); - if (getRotatingDeviceIdUniqueIdMethod == nullptr) - { - ChipLogError(Zcl, "Failed to access AppParameters 'getRotatingDeviceIdUniqueId' method"); - env->ExceptionClear(); - } - - jobject jRotatingDeviceIdUniqueId = (jobject) env->CallObjectMethod(appParameters, getRotatingDeviceIdUniqueIdMethod); - if (env->ExceptionCheck()) - { - ChipLogError(Zcl, "Java exception in AppParameters::getRotatingDeviceIdUniqueId"); - env->ExceptionDescribe(); - env->ExceptionClear(); - return CHIP_ERROR_INCORRECT_STATE; - } - - if (jRotatingDeviceIdUniqueId != nullptr) - { - chip::JniByteArray * jniRotatingDeviceIdUniqueIdByteArray = - new chip::JniByteArray(env, static_cast(jRotatingDeviceIdUniqueId)); - outAppParams.SetRotatingDeviceIdUniqueId(MakeOptional(jniRotatingDeviceIdUniqueIdByteArray->byteSpan())); - } - - return CHIP_NO_ERROR; -} - -CHIP_ERROR convertJContentAppToTargetEndpointInfo(jobject contentApp, TargetEndpointInfo & outTargetEndpointInfo) -{ - ChipLogProgress(AppServer, "convertJContentAppToTargetEndpointInfo called"); - VerifyOrReturnError(contentApp != nullptr, CHIP_ERROR_INVALID_ARGUMENT); - JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread(); - - jclass jContentAppClass; - ReturnErrorOnFailure(chip::JniReferences::GetInstance().GetLocalClassRef(env, "com/chip/casting/ContentApp", jContentAppClass)); - - jfieldID jEndpointIdField = env->GetFieldID(jContentAppClass, "endpointId", "S"); - jshort jEndpointId = env->GetShortField(contentApp, jEndpointIdField); - outTargetEndpointInfo.Initialize(static_cast(jEndpointId)); - - jfieldID jclusterIdsField = env->GetFieldID(jContentAppClass, "clusterIds", "Ljava/util/List;"); - jobject jClusterIds = env->GetObjectField(contentApp, jclusterIdsField); - if (jClusterIds == nullptr) - { - return CHIP_NO_ERROR; - } - - jobject jIterator = env->CallObjectMethod( - jClusterIds, env->GetMethodID(env->GetObjectClass(jClusterIds), "iterator", "()Ljava/util/Iterator;")); - jmethodID jNextMid = env->GetMethodID(env->GetObjectClass(jIterator), "next", "()Ljava/lang/Object;"); - jmethodID jHasNextMid = env->GetMethodID(env->GetObjectClass(jIterator), "hasNext", "()Z"); - - while (env->CallBooleanMethod(jIterator, jHasNextMid)) - { - jobject jClusterId = env->CallObjectMethod(jIterator, jNextMid); - jclass jIntegerClass = env->FindClass("java/lang/Integer"); - jmethodID jIntValueMid = env->GetMethodID(jIntegerClass, "intValue", "()I"); - outTargetEndpointInfo.AddCluster(static_cast(env->CallIntMethod(jClusterId, jIntValueMid))); - } - - return CHIP_NO_ERROR; -} - -CHIP_ERROR convertTargetEndpointInfoToJContentApp(TargetEndpointInfo * targetEndpointInfo, jobject & outContentApp) -{ - ChipLogProgress(AppServer, "convertTargetEndpointInfoToJContentApp called"); - if (targetEndpointInfo != nullptr && targetEndpointInfo->IsInitialized()) - { - JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread(); - - jclass jContentAppClass; - ReturnErrorOnFailure( - chip::JniReferences::GetInstance().GetLocalClassRef(env, "com/chip/casting/ContentApp", jContentAppClass)); - jmethodID jContentAppConstructor = env->GetMethodID(jContentAppClass, "", "(SLjava/util/List;)V"); - chip::ClusterId * clusters = targetEndpointInfo->GetClusters(); - jobject jClustersArrayList = nullptr; - if (clusters != nullptr) - { - chip::JniReferences::GetInstance().CreateArrayList(jClustersArrayList); - for (size_t i = 0; i < kMaxNumberOfClustersPerEndpoint && clusters[i] != chip::kInvalidClusterId; i++) - { - jobject jCluster = nullptr; - jint jniclusterId = static_cast(clusters[i]); - chip::JniReferences::GetInstance().CreateBoxedObject("java/lang/Integer", "(I)V", jniclusterId, jCluster); - chip::JniReferences::GetInstance().AddToList(jClustersArrayList, jCluster); - } - } - outContentApp = - env->NewObject(jContentAppClass, jContentAppConstructor, targetEndpointInfo->GetEndpointId(), jClustersArrayList); - } - return CHIP_NO_ERROR; -} - -CHIP_ERROR convertJVideoPlayerToTargetVideoPlayerInfo(jobject videoPlayer, TargetVideoPlayerInfo & outTargetVideoPlayerInfo) -{ - ChipLogProgress(AppServer, "convertJVideoPlayerToTargetVideoPlayerInfo called"); - VerifyOrReturnError(videoPlayer != nullptr, CHIP_ERROR_INVALID_ARGUMENT); - JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread(); - - jclass jVideoPlayerClass; - ReturnErrorOnFailure( - chip::JniReferences::GetInstance().GetLocalClassRef(env, "com/chip/casting/VideoPlayer", jVideoPlayerClass)); - - jfieldID jNodeIdField = env->GetFieldID(jVideoPlayerClass, "nodeId", "J"); - chip::NodeId nodeId = static_cast(env->GetLongField(videoPlayer, jNodeIdField)); - - jfieldID jFabricIndexField = env->GetFieldID(jVideoPlayerClass, "fabricIndex", "B"); - chip::FabricIndex fabricIndex = static_cast(env->GetByteField(videoPlayer, jFabricIndexField)); - - jfieldID jVendorIdField = env->GetFieldID(jVideoPlayerClass, "vendorId", "I"); - uint16_t vendorId = static_cast(env->GetIntField(videoPlayer, jVendorIdField)); - - jfieldID jProductIdField = env->GetFieldID(jVideoPlayerClass, "productId", "I"); - uint16_t productId = static_cast(env->GetIntField(videoPlayer, jProductIdField)); - - jfieldID jDeviceType = env->GetFieldID(jVideoPlayerClass, "deviceType", "I"); - uint16_t deviceType = static_cast(env->GetIntField(videoPlayer, jDeviceType)); - - jfieldID getDeviceNameField = env->GetFieldID(jVideoPlayerClass, "deviceName", "Ljava/lang/String;"); - jstring jDeviceName = static_cast(env->GetObjectField(videoPlayer, getDeviceNameField)); - const char * deviceName = env->GetStringUTFChars(jDeviceName, 0); - - jfieldID getHostNameField = env->GetFieldID(jVideoPlayerClass, "hostName", "Ljava/lang/String;"); - jstring jHostName = static_cast(env->GetObjectField(videoPlayer, getHostNameField)); - const char * hostName = env->GetStringUTFChars(jHostName, 0); - - jfieldID jPort = env->GetFieldID(jVideoPlayerClass, "port", "I"); - uint16_t port = static_cast(env->GetIntField(videoPlayer, jPort)); - - jfieldID getInstanceNameField = env->GetFieldID(jVideoPlayerClass, "instanceName", "Ljava/lang/String;"); - jstring jInstanceName = static_cast(env->GetObjectField(videoPlayer, getInstanceNameField)); - const char * instanceName = {}; - if (jInstanceName != nullptr) - { - instanceName = env->GetStringUTFChars(jInstanceName, 0); - } - - jfieldID jLastDiscoveredMs = env->GetFieldID(jVideoPlayerClass, "lastDiscoveredMs", "J"); - long lastDiscoveredMs = static_cast(env->GetLongField(videoPlayer, jLastDiscoveredMs)); - - jfieldID getMACAddressField = env->GetFieldID(jVideoPlayerClass, "MACAddress", "Ljava/lang/String;"); - jstring jMACAddress = static_cast(env->GetObjectField(videoPlayer, getMACAddressField)); - const char * MACAddress = jMACAddress == nullptr ? nullptr : env->GetStringUTFChars(jMACAddress, 0); - - jfieldID jIsAsleep = env->GetFieldID(jVideoPlayerClass, "isAsleep", "Z"); - bool isAsleep = static_cast(env->GetBooleanField(videoPlayer, jIsAsleep)); - - outTargetVideoPlayerInfo.Initialize(nodeId, fabricIndex, nullptr, nullptr, vendorId, productId, deviceType, deviceName, - hostName, 0, nullptr, port, instanceName, chip::System::Clock::Timestamp(lastDiscoveredMs)); - - if (MACAddress != nullptr) - { - chip::CharSpan MACAddressSpan(MACAddress, 2 * 2 * chip::DeviceLayer::ConfigurationManager::kPrimaryMACAddressLength); - outTargetVideoPlayerInfo.SetMACAddress(MACAddressSpan); - } - - outTargetVideoPlayerInfo.SetIsAsleep(isAsleep); - - jfieldID jContentAppsField = env->GetFieldID(jVideoPlayerClass, "contentApps", "Ljava/util/List;"); - jobject jContentApps = env->GetObjectField(videoPlayer, jContentAppsField); - if (jContentApps == nullptr) - { - return CHIP_NO_ERROR; - } - - jobject jIterator = env->CallObjectMethod( - jContentApps, env->GetMethodID(env->GetObjectClass(jContentApps), "iterator", "()Ljava/util/Iterator;")); - jmethodID jNextMid = env->GetMethodID(env->GetObjectClass(jIterator), "next", "()Ljava/lang/Object;"); - jmethodID jHasNextMid = env->GetMethodID(env->GetObjectClass(jIterator), "hasNext", "()Z"); - - while (env->CallBooleanMethod(jIterator, jHasNextMid)) - { - jobject jContentApp = env->CallObjectMethod(jIterator, jNextMid); - - jclass jContentAppClass; - ReturnErrorOnFailure( - chip::JniReferences::GetInstance().GetLocalClassRef(env, "com/chip/casting/ContentApp", jContentAppClass)); - jfieldID jEndpointIdField = env->GetFieldID(jContentAppClass, "endpointId", "S"); - chip::EndpointId endpointId = static_cast(env->GetShortField(jContentApp, jEndpointIdField)); - TargetEndpointInfo * endpoint = outTargetVideoPlayerInfo.GetOrAddEndpoint(endpointId); - - ReturnErrorOnFailure(convertJContentAppToTargetEndpointInfo(jContentApp, *endpoint)); - } - - return CHIP_NO_ERROR; -} - -CHIP_ERROR convertTargetVideoPlayerInfoToJVideoPlayer(TargetVideoPlayerInfo * targetVideoPlayerInfo, jobject & outVideoPlayer) -{ - ChipLogProgress(AppServer, "convertTargetVideoPlayerInfoToJVideoPlayer called"); - if (targetVideoPlayerInfo != nullptr && targetVideoPlayerInfo->IsInitialized()) - { - JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread(); - - jclass jVideoPlayerClass; - ReturnErrorOnFailure( - chip::JniReferences::GetInstance().GetLocalClassRef(env, "com/chip/casting/VideoPlayer", jVideoPlayerClass)); - jmethodID jVideoPlayerConstructor = env->GetMethodID(jVideoPlayerClass, "", - "(JBLjava/lang/String;IIILjava/util/List;ILjava/util/List;Ljava/lang/" - "String;Ljava/lang/String;IJLjava/lang/String;ZZ)V"); - - jobject jContentAppList = nullptr; - TargetEndpointInfo * endpoints = targetVideoPlayerInfo->GetEndpoints(); - if (endpoints != nullptr) - { - chip::JniReferences::GetInstance().CreateArrayList(jContentAppList); - for (size_t i = 0; i < kMaxNumberOfEndpoints && endpoints[i].IsInitialized(); i++) - { - jobject contentApp = nullptr; - ReturnErrorOnFailure(convertTargetEndpointInfoToJContentApp(&endpoints[i], contentApp)); - chip::JniReferences::GetInstance().AddToList(jContentAppList, contentApp); - } - } - - jstring deviceName = - targetVideoPlayerInfo->GetDeviceName() == nullptr ? nullptr : env->NewStringUTF(targetVideoPlayerInfo->GetDeviceName()); - - jstring hostName = - targetVideoPlayerInfo->GetHostName() == nullptr ? nullptr : env->NewStringUTF(targetVideoPlayerInfo->GetHostName()); - - jstring instanceName = targetVideoPlayerInfo->GetInstanceName() == nullptr - ? nullptr - : env->NewStringUTF(targetVideoPlayerInfo->GetInstanceName()); - - jstring MACAddress = nullptr; - if (targetVideoPlayerInfo->GetMACAddress() != nullptr && targetVideoPlayerInfo->GetMACAddress()->data() != nullptr) - { - char MACAddressWithNil[2 * chip::DeviceLayer::ConfigurationManager::kPrimaryMACAddressLength + 1]; - memcpy(MACAddressWithNil, targetVideoPlayerInfo->GetMACAddress()->data(), - targetVideoPlayerInfo->GetMACAddress()->size()); - MACAddressWithNil[targetVideoPlayerInfo->GetMACAddress()->size()] = '\0'; - MACAddress = env->NewStringUTF(MACAddressWithNil); - } - - jobject jIPAddressList = nullptr; - const chip::Inet::IPAddress * ipAddresses = targetVideoPlayerInfo->GetIpAddresses(); - if (ipAddresses != nullptr) - { - chip::JniReferences::GetInstance().CreateArrayList(jIPAddressList); - for (size_t i = 0; i < targetVideoPlayerInfo->GetNumIPs() && i < chip::Dnssd::CommonResolutionData::kMaxIPAddresses; - i++) - { - char addrCString[chip::Inet::IPAddress::kMaxStringLength]; - ipAddresses[i].ToString(addrCString, chip::Inet::IPAddress::kMaxStringLength); - jstring jIPAddressStr = env->NewStringUTF(addrCString); - - jclass jIPAddressClass; - ReturnErrorOnFailure( - chip::JniReferences::GetInstance().GetLocalClassRef(env, "java/net/InetAddress", jIPAddressClass)); - jmethodID jGetByNameMid = - env->GetStaticMethodID(jIPAddressClass, "getByName", "(Ljava/lang/String;)Ljava/net/InetAddress;"); - jobject jIPAddress = env->CallStaticObjectMethod(jIPAddressClass, jGetByNameMid, jIPAddressStr); - - chip::JniReferences::GetInstance().AddToList(jIPAddressList, jIPAddress); - } - } - - outVideoPlayer = env->NewObject( - jVideoPlayerClass, jVideoPlayerConstructor, targetVideoPlayerInfo->GetNodeId(), targetVideoPlayerInfo->GetFabricIndex(), - deviceName, targetVideoPlayerInfo->GetVendorId(), targetVideoPlayerInfo->GetProductId(), - targetVideoPlayerInfo->GetDeviceType(), jContentAppList, targetVideoPlayerInfo->GetNumIPs(), jIPAddressList, hostName, - instanceName, targetVideoPlayerInfo->GetPort(), targetVideoPlayerInfo->GetLastDiscovered().count(), MACAddress, - targetVideoPlayerInfo->IsAsleep(), targetVideoPlayerInfo->GetOperationalDeviceProxy() != nullptr); - } - return CHIP_NO_ERROR; -} - -CHIP_ERROR convertJDiscoveredNodeDataToCppDiscoveredNodeData(jobject jDiscoveredNodeData, - chip::Dnssd::CommissionNodeData & outCppDiscoveredNodeData) -{ - ChipLogProgress(AppServer, "convertJDiscoveredNodeDataToCppDiscoveredNodeData called"); - VerifyOrReturnError(jDiscoveredNodeData != nullptr, CHIP_ERROR_INVALID_ARGUMENT); - - JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread(); - - jclass jDiscoveredNodeDataClass; - ReturnErrorOnFailure( - chip::JniReferences::GetInstance().GetLocalClassRef(env, "com/chip/casting/DiscoveredNodeData", jDiscoveredNodeDataClass)); - - jfieldID getHostNameField = env->GetFieldID(jDiscoveredNodeDataClass, "hostName", "Ljava/lang/String;"); - jstring jHostName = static_cast(env->GetObjectField(jDiscoveredNodeData, getHostNameField)); - if (jHostName != nullptr) - { - chip::Platform::CopyString(outCppDiscoveredNodeData.hostName, chip::Dnssd::kHostNameMaxLength + 1, - env->GetStringUTFChars(jHostName, 0)); - } - - jfieldID getInstanceNameField = env->GetFieldID(jDiscoveredNodeDataClass, "instanceName", "Ljava/lang/String;"); - jstring jInstanceName = static_cast(env->GetObjectField(jDiscoveredNodeData, getInstanceNameField)); - if (jInstanceName != nullptr) - { - chip::Platform::CopyString(outCppDiscoveredNodeData.instanceName, chip::Dnssd::Commission::kInstanceNameMaxLength + 1, - env->GetStringUTFChars(jInstanceName, 0)); - } - - jfieldID jLongDiscriminatorField = env->GetFieldID(jDiscoveredNodeDataClass, "longDiscriminator", "J"); - outCppDiscoveredNodeData.vendorId = static_cast(env->GetLongField(jDiscoveredNodeData, jLongDiscriminatorField)); - - jfieldID jVendorIdField = env->GetFieldID(jDiscoveredNodeDataClass, "vendorId", "J"); - outCppDiscoveredNodeData.vendorId = static_cast(env->GetLongField(jDiscoveredNodeData, jVendorIdField)); - - jfieldID jProductIdField = env->GetFieldID(jDiscoveredNodeDataClass, "productId", "J"); - outCppDiscoveredNodeData.productId = static_cast(env->GetLongField(jDiscoveredNodeData, jProductIdField)); - - jfieldID jCommissioningModeField = env->GetFieldID(jDiscoveredNodeDataClass, "commissioningMode", "B"); - outCppDiscoveredNodeData.commissioningMode = - static_cast(env->GetByteField(jDiscoveredNodeData, jCommissioningModeField)); - - jfieldID jDeviceTypeField = env->GetFieldID(jDiscoveredNodeDataClass, "deviceType", "J"); - outCppDiscoveredNodeData.deviceType = static_cast(env->GetLongField(jDiscoveredNodeData, jDeviceTypeField)); - - jfieldID getDeviceNameField = env->GetFieldID(jDiscoveredNodeDataClass, "deviceName", "Ljava/lang/String;"); - jstring jDeviceName = static_cast(env->GetObjectField(jDiscoveredNodeData, getDeviceNameField)); - if (jDeviceName != nullptr) - { - chip::Platform::CopyString(outCppDiscoveredNodeData.deviceName, chip::Dnssd::kMaxDeviceNameLen + 1, - env->GetStringUTFChars(jDeviceName, 0)); - } - - // TODO: map rotating ID - jfieldID jRotatingIdLenField = env->GetFieldID(jDiscoveredNodeDataClass, "rotatingIdLen", "I"); - outCppDiscoveredNodeData.rotatingIdLen = static_cast(env->GetIntField(jDiscoveredNodeData, jRotatingIdLenField)); - - jfieldID jPairingHintField = env->GetFieldID(jDiscoveredNodeDataClass, "pairingHint", "S"); - outCppDiscoveredNodeData.pairingHint = static_cast(env->GetShortField(jDiscoveredNodeData, jPairingHintField)); - - jfieldID getPairingInstructionField = env->GetFieldID(jDiscoveredNodeDataClass, "pairingInstruction", "Ljava/lang/String;"); - jstring jPairingInstruction = static_cast(env->GetObjectField(jDiscoveredNodeData, getPairingInstructionField)); - if (jPairingInstruction != nullptr) - { - chip::Platform::CopyString(outCppDiscoveredNodeData.pairingInstruction, chip::Dnssd::kMaxPairingInstructionLen + 1, - env->GetStringUTFChars(jPairingInstruction, 0)); - } - - jfieldID jPortField = env->GetFieldID(jDiscoveredNodeDataClass, "port", "I"); - outCppDiscoveredNodeData.port = static_cast(env->GetIntField(jDiscoveredNodeData, jPortField)); - - jfieldID jNumIpsField = env->GetFieldID(jDiscoveredNodeDataClass, "numIPs", "I"); - outCppDiscoveredNodeData.numIPs = static_cast(env->GetIntField(jDiscoveredNodeData, jNumIpsField)); - - jfieldID jIPAddressesField = env->GetFieldID(jDiscoveredNodeDataClass, "ipAddresses", "Ljava/util/List;"); - jobject jIPAddresses = env->GetObjectField(jDiscoveredNodeData, jIPAddressesField); - if (jIPAddresses == nullptr && outCppDiscoveredNodeData.numIPs > 0) - { - return CHIP_ERROR_INVALID_ARGUMENT; - } - - jobject jIterator = env->CallObjectMethod( - jIPAddresses, env->GetMethodID(env->GetObjectClass(jIPAddresses), "iterator", "()Ljava/util/Iterator;")); - jmethodID jNextMid = env->GetMethodID(env->GetObjectClass(jIterator), "next", "()Ljava/lang/Object;"); - jmethodID jHasNextMid = env->GetMethodID(env->GetObjectClass(jIterator), "hasNext", "()Z"); - - size_t ipAddressCount = 0; - while (env->CallBooleanMethod(jIterator, jHasNextMid)) - { - jobject jIPAddress = env->CallObjectMethod(jIterator, jNextMid); - jclass jIPAddressClass; - ReturnErrorOnFailure(chip::JniReferences::GetInstance().GetLocalClassRef(env, "java/net/InetAddress", jIPAddressClass)); - jmethodID jGetHostAddressMid = env->GetMethodID(jIPAddressClass, "getHostAddress", "()Ljava/lang/String;"); - jstring jIPAddressStr = static_cast(env->CallObjectMethod(jIPAddress, jGetHostAddressMid)); - - chip::Inet::IPAddress addressInet; - chip::JniUtfString addressJniString(env, jIPAddressStr); - VerifyOrReturnError(chip::Inet::IPAddress::FromString(addressJniString.c_str(), addressInet), CHIP_ERROR_INVALID_ARGUMENT); - outCppDiscoveredNodeData.ipAddress[ipAddressCount] = addressInet; - - if (ipAddressCount == 0) - { - outCppDiscoveredNodeData.interfaceId = chip::Inet::InterfaceId::FromIPAddress(addressInet); - } - ipAddressCount++; - } - - return CHIP_NO_ERROR; -} diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/ConversionUtils.h b/examples/tv-casting-app/android/App/app/src/main/jni/cpp/ConversionUtils.h deleted file mode 100644 index 28f5a1abd2..0000000000 --- a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/ConversionUtils.h +++ /dev/null @@ -1,36 +0,0 @@ -/* - * - * Copyright (c) 2021 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 "AppParams.h" -#include "TargetEndpointInfo.h" -#include "TargetVideoPlayerInfo.h" - -#include - -CHIP_ERROR convertJAppParametersToCppAppParams(jobject appParameters, AppParams & outAppParams); - -CHIP_ERROR convertJContentAppToTargetEndpointInfo(jobject contentApp, TargetEndpointInfo & outTargetEndpointInfo); - -CHIP_ERROR convertTargetEndpointInfoToJContentApp(TargetEndpointInfo * targetEndpointInfo, jobject & outContentApp); - -CHIP_ERROR convertJVideoPlayerToTargetVideoPlayerInfo(jobject videoPlayer, TargetVideoPlayerInfo & targetVideoPlayerInfo); - -CHIP_ERROR convertTargetVideoPlayerInfoToJVideoPlayer(TargetVideoPlayerInfo * targetVideoPlayerInfo, jobject & outVideoPlayer); - -CHIP_ERROR convertJDiscoveredNodeDataToCppDiscoveredNodeData(jobject jDiscoveredNodeData, - chip::Dnssd::CommissionNodeData & cppDiscoveredNodeData); diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/MatterCallbackHandler-JNI.cpp b/examples/tv-casting-app/android/App/app/src/main/jni/cpp/MatterCallbackHandler-JNI.cpp deleted file mode 100644 index ca62ba5f37..0000000000 --- a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/MatterCallbackHandler-JNI.cpp +++ /dev/null @@ -1,419 +0,0 @@ -/* - * - * Copyright (c) 2022 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 "MatterCallbackHandler-JNI.h" - -#include - -using namespace chip; - -CHIP_ERROR CallbackBaseJNI::SetUp(JNIEnv * env, jobject inHandler) -{ - ChipLogProgress(AppServer, "CallbackBaseJNI::SetUp called"); - CHIP_ERROR err = CHIP_NO_ERROR; - - VerifyOrExit(mObject.Init(inHandler) == CHIP_NO_ERROR, ChipLogError(AppServer, "Failed to Init mObject")); - - mClazz = env->GetObjectClass(mObject.ObjectRef()); - VerifyOrExit(mClazz != nullptr, ChipLogError(AppServer, "Failed to get handler Java class")); - - mSuperClazz = env->GetSuperclass(mClazz); - VerifyOrExit(mSuperClazz != nullptr, ChipLogError(AppServer, "Failed to get handler's parent's Java class")); - - mMethod = env->GetMethodID(mSuperClazz, "handleInternal", mMethodSignature); - if (mMethod == nullptr) - { - ChipLogError(AppServer, "Failed to access 'handleInternal' method with signature %s", mMethodSignature); - env->ExceptionClear(); - } - -exit: - if (err != CHIP_NO_ERROR) - { - ChipLogError(AppServer, "CallbackBaseJNI::SetUp error: %s", err.AsString()); - return err; - } - - return err; -} - -void FailureHandlerJNI::Handle(CHIP_ERROR callbackErr) -{ - ChipLogProgress(AppServer, "Handle(CHIP_ERROR) called"); - - JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - UtfString jniCallbackErrString(env, callbackErr.AsString()); - - chip::DeviceLayer::StackUnlock unlock; - CHIP_ERROR err = CHIP_NO_ERROR; - VerifyOrExit(mObject.HasValidObjectRef(), err = CHIP_ERROR_INCORRECT_STATE); - VerifyOrExit(mMethod != nullptr, err = CHIP_ERROR_INCORRECT_STATE); - env->CallVoidMethod(mObject.ObjectRef(), mMethod, static_cast(callbackErr.AsInteger()), jniCallbackErrString.jniValue()); -exit: - if (err != CHIP_NO_ERROR) - { - ChipLogError(AppServer, "Handle(CHIP_ERROR) status error: %s", err.AsString()); - } -} - -void SubscriptionEstablishedHandlerJNI::Handle() -{ - ChipLogProgress(AppServer, "SubscriptionEstablishedHandlerJNI::Handle called"); - - JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - - chip::DeviceLayer::StackUnlock unlock; - CHIP_ERROR err = CHIP_NO_ERROR; - VerifyOrExit(mObject.HasValidObjectRef(), err = CHIP_ERROR_INCORRECT_STATE); - VerifyOrExit(mMethod != nullptr, err = CHIP_ERROR_INCORRECT_STATE); - - env->CallVoidMethod(mObject.ObjectRef(), mMethod); -exit: - if (err != CHIP_NO_ERROR) - { - ChipLogError(AppServer, "SubscriptionEstablishedHandlerJNI::Handle status error: %s", err.AsString()); - } -} - -jobject ConvertToLongJObject(uint64_t responseData) -{ - JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - - jclass responseTypeClass = env->FindClass("java/lang/Long"); - if (responseTypeClass == nullptr) - { - ChipLogError(AppServer, "ConvertToJObject: Class for Response Type not found!"); - return nullptr; - } - - jmethodID constructor = env->GetMethodID(responseTypeClass, "", "(J)V"); - return env->NewObject(responseTypeClass, constructor, responseData); -} - -jobject ConvertToFloatJObject(float responseData) -{ - JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - - jclass responseTypeClass = env->FindClass("java/lang/Float"); - if (responseTypeClass == nullptr) - { - ChipLogError(AppServer, "ConvertToJObject: Class for Response Type not found!"); - return nullptr; - } - - jmethodID constructor = env->GetMethodID(responseTypeClass, "", "(F)V"); - return env->NewObject(responseTypeClass, constructor, responseData); -} - -jobject ConvertToShortJObject(uint16_t responseData) -{ - JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - - jclass responseTypeClass = env->FindClass("java/lang/Short"); - if (responseTypeClass == nullptr) - { - ChipLogError(AppServer, "ConvertToJObject: Class for Response Type not found!"); - return nullptr; - } - - jmethodID constructor = env->GetMethodID(responseTypeClass, "", "(S)V"); - return env->NewObject(responseTypeClass, constructor, responseData); -} - -jobject ConvertToByteJObject(uint8_t responseData) -{ - JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - - jclass responseTypeClass = env->FindClass("java/lang/Byte"); - if (responseTypeClass == nullptr) - { - ChipLogError(AppServer, "ConvertToJObject: Class for Response Type not found!"); - return nullptr; - } - - jmethodID constructor = env->GetMethodID(responseTypeClass, "", "(B)V"); - return env->NewObject(responseTypeClass, constructor, responseData); -} - -jstring ConvertToJString(chip::CharSpan responseData) -{ - JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - - return env->NewStringUTF(std::string(responseData.data(), responseData.size()).c_str()); -} - -jobject ConvertToIntegerJObject(uint32_t responseData) -{ - JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - - jclass responseTypeClass = env->FindClass("java/lang/Integer"); - if (responseTypeClass == nullptr) - { - ChipLogError(AppServer, "ConvertToJObject: Class for Response Type not found!"); - return nullptr; - } - - jmethodID constructor = env->GetMethodID(responseTypeClass, "", "(I)V"); - return env->NewObject(responseTypeClass, constructor, responseData); -} - -// COMMISSIONING AND CONNECTION -jobject OnConnectionSuccessHandlerJNI::ConvertToJObject(TargetVideoPlayerInfo * targetVideoPlayerInfo) -{ - ChipLogProgress(AppServer, "OnConnectionSuccessHandlerJNI::ConvertToJObject called"); - jobject videoPlayer = nullptr; - CHIP_ERROR err = convertTargetVideoPlayerInfoToJVideoPlayer(targetVideoPlayerInfo, videoPlayer); - if (err != CHIP_NO_ERROR) - { - ChipLogError(AppServer, "OnConnectionSuccessHandlerJNI::ConvertToJObject failed with %" CHIP_ERROR_FORMAT, err.Format()); - } - return videoPlayer; -} - -jobject OnNewOrUpdatedEndpointHandlerJNI::ConvertToJObject(TargetEndpointInfo * targetEndpointInfo) -{ - ChipLogProgress(AppServer, "OnNewOrUpdatedEndpointHandlerJNI::ConvertToJObject called"); - jobject contentApp = nullptr; - CHIP_ERROR err = convertTargetEndpointInfoToJContentApp(targetEndpointInfo, contentApp); - if (err != CHIP_NO_ERROR) - { - ChipLogError(AppServer, "OnNewOrUpdatedEndpointHandlerJNI::ConvertToJObject failed with %" CHIP_ERROR_FORMAT, err.Format()); - } - return contentApp; -} - -// MEDIA PLAYBACK -jobject CurrentStateSuccessHandlerJNI::ConvertToJObject( - chip::app::Clusters::MediaPlayback::Attributes::CurrentState::TypeInfo::DecodableArgType responseData) -{ - ChipLogProgress(AppServer, "CurrentStateSuccessHandlerJNI::ConvertToJObject called"); - JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - VerifyOrReturnValue(env != nullptr, nullptr); - JniLocalReferenceScope scope(env); - - jclass enumClass = nullptr; - CHIP_ERROR err = - JniReferences::GetInstance().GetLocalClassRef(env, "com/chip/casting/MediaPlaybackTypes$PlaybackStateEnum", enumClass); - if (err != CHIP_NO_ERROR) - { - ChipLogError(AppServer, "ConvertToJObject: Class for Response Type not found!"); - return nullptr; - } - - jfieldID enumType = nullptr; - switch (responseData) - { - case chip::app::Clusters::MediaPlayback::PlaybackStateEnum::kPlaying: - enumType = env->GetStaticFieldID(enumClass, "Playing", "Lcom/chip/casting/MediaPlaybackTypes$PlaybackStateEnum;"); - break; - case chip::app::Clusters::MediaPlayback::PlaybackStateEnum::kPaused: - enumType = env->GetStaticFieldID(enumClass, "Paused", "Lcom/chip/casting/MediaPlaybackTypes$PlaybackStateEnum;"); - break; - case chip::app::Clusters::MediaPlayback::PlaybackStateEnum::kNotPlaying: - enumType = env->GetStaticFieldID(enumClass, "NotPlaying", "Lcom/chip/casting/MediaPlaybackTypes$PlaybackStateEnum;"); - break; - case chip::app::Clusters::MediaPlayback::PlaybackStateEnum::kBuffering: - enumType = env->GetStaticFieldID(enumClass, "Buffering", "Lcom/chip/casting/MediaPlaybackTypes$PlaybackStateEnum;"); - break; - default: - enumType = env->GetStaticFieldID(enumClass, "Unknown", "Lcom/chip/casting/MediaPlaybackTypes$PlaybackStateEnum;"); - break; - } - - if (enumType != nullptr) - { - return env->GetStaticObjectField(enumClass, enumType); - } - return nullptr; -} - -jobject DurationSuccessHandlerJNI::ConvertToJObject( - chip::app::Clusters::MediaPlayback::Attributes::Duration::TypeInfo::DecodableArgType responseData) -{ - ChipLogProgress(AppServer, "DurationSuccessHandlerJNI::ConvertToJObject called"); - return responseData.IsNull() ? nullptr : ConvertToLongJObject(responseData.Value()); -} - -jobject SampledPositionSuccessHandlerJNI::ConvertToJObject( - chip::app::Clusters::MediaPlayback::Attributes::SampledPosition::TypeInfo::DecodableArgType responseData) -{ - ChipLogProgress(AppServer, "SampledPositionSuccessHandlerJNI::ConvertToJObject called"); - JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - VerifyOrReturnValue(env != nullptr, nullptr); - JniLocalReferenceScope scope(env); - - jobject jSampledPosition = nullptr; - if (!responseData.IsNull()) - { - const chip::app::Clusters::MediaPlayback::Structs::PlaybackPositionStruct::DecodableType & playbackPosition = - responseData.Value(); - - jclass responseTypeClass = nullptr; - CHIP_ERROR err = JniReferences::GetInstance().GetLocalClassRef( - env, "com/chip/casting/MediaPlaybackTypes$PlaybackPositionStruct", responseTypeClass); - if (err != CHIP_NO_ERROR) - { - ChipLogError(AppServer, "ConvertToJObject: Class for Response Type not found!"); - return nullptr; - } - - if (playbackPosition.position.IsNull()) - { - jmethodID constructor = env->GetMethodID(responseTypeClass, "", "(Ljava/lang/Long;)V"); - jSampledPosition = env->NewObject(responseTypeClass, constructor, playbackPosition.updatedAt); - } - else - { - jmethodID constructor = env->GetMethodID(responseTypeClass, "", "(Ljava/lang/Long;java/lang/Long;)V"); - jSampledPosition = - env->NewObject(responseTypeClass, constructor, playbackPosition.updatedAt, playbackPosition.position.Value()); - } - } - - return jSampledPosition; -} - -jobject PlaybackSpeedSuccessHandlerJNI::ConvertToJObject( - chip::app::Clusters::MediaPlayback::Attributes::PlaybackSpeed::TypeInfo::DecodableArgType responseData) -{ - ChipLogProgress(AppServer, "PlaybackSpeedSuccessHandlerJNI::ConvertToJObject called"); - return ConvertToFloatJObject(responseData); -} - -jobject SeekRangeEndSuccessHandlerJNI::ConvertToJObject( - chip::app::Clusters::MediaPlayback::Attributes::SeekRangeEnd::TypeInfo::DecodableArgType responseData) -{ - ChipLogProgress(AppServer, "SeekRangeEndSuccessHandlerJNI::ConvertToJObject called"); - return responseData.IsNull() ? nullptr : ConvertToLongJObject(responseData.Value()); -} - -jobject SeekRangeStartSuccessHandlerJNI::ConvertToJObject( - chip::app::Clusters::MediaPlayback::Attributes::SeekRangeStart::TypeInfo::DecodableArgType responseData) -{ - ChipLogProgress(AppServer, "SeekRangeStartSuccessHandlerJNI::ConvertToJObject called"); - return responseData.IsNull() ? nullptr : ConvertToLongJObject(responseData.Value()); -} - -// TARGET NAVIGATOR -jobject CurrentTargetSuccessHandlerJNI::ConvertToJObject( - chip::app::Clusters::TargetNavigator::Attributes::CurrentTarget::TypeInfo::DecodableArgType responseData) -{ - ChipLogProgress(AppServer, "CurrentTargetSuccessHandlerJNI::ConvertToJObject called"); - return ConvertToByteJObject(responseData); -} - -jobject TargetListSuccessHandlerJNI::ConvertToJObject( - chip::app::Clusters::TargetNavigator::Attributes::TargetList::TypeInfo::DecodableArgType responseData) -{ - ChipLogProgress(AppServer, "TargetListSuccessHandlerJNI::ConvertToJObject called"); - - JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - VerifyOrReturnValue(env != nullptr, nullptr); - JniLocalReferenceScope scope(env); - - jobject jArrayList; - chip::JniReferences::GetInstance().CreateArrayList(jArrayList); - auto iter = responseData.begin(); - while (iter.Next()) - { - const chip::app::Clusters::TargetNavigator::Structs::TargetInfoStruct::DecodableType & targetInfo = iter.GetValue(); - - jclass responseTypeClass = nullptr; - CHIP_ERROR err = JniReferences::GetInstance().GetLocalClassRef(env, "com/chip/casting/TargetNavigatorTypes$TargetInfo", - responseTypeClass); - if (err != CHIP_NO_ERROR) - { - ChipLogError(AppServer, "ConvertToJObject: Class for Response Type not found!"); - return nullptr; - } - - jmethodID constructor = env->GetMethodID(responseTypeClass, "", "(Ljava/lang/Integer;Ljava/lang/String;)V"); - chip::UtfString targetInfoName(env, targetInfo.name); - jobject jTargetInfo = env->NewObject(responseTypeClass, constructor, ConvertToIntegerJObject(targetInfo.identifier), - targetInfoName.jniValue()); - - chip::JniReferences::GetInstance().AddToList(jArrayList, jTargetInfo); - } - return jArrayList; -} - -// LEVEL CONTROL -jobject CurrentLevelSuccessHandlerJNI::ConvertToJObject( - chip::app::Clusters::LevelControl::Attributes::CurrentLevel::TypeInfo::DecodableArgType responseData) -{ - ChipLogProgress(AppServer, "CurrentLevelSuccessHandlerJNI::ConvertToJObject called"); - return responseData.IsNull() ? nullptr : ConvertToByteJObject(responseData.Value()); -} - -jobject MinLevelSuccessHandlerJNI::ConvertToJObject( - chip::app::Clusters::LevelControl::Attributes::MinLevel::TypeInfo::DecodableArgType responseData) -{ - ChipLogProgress(AppServer, "MinLevelSuccessHandlerJNI::ConvertToJObject called"); - return ConvertToByteJObject(responseData); -} - -jobject MaxLevelSuccessHandlerJNI::ConvertToJObject( - chip::app::Clusters::LevelControl::Attributes::MaxLevel::TypeInfo::DecodableArgType responseData) -{ - ChipLogProgress(AppServer, "MaxLevelSuccessHandlerJNI::ConvertToJObject called"); - return ConvertToByteJObject(responseData); -} - -// CONTENT LAUNCHER -jobject SupportedStreamingProtocolsSuccessHandlerJNI::ConvertToJObject( - chip::app::Clusters::ContentLauncher::Attributes::SupportedStreamingProtocols::TypeInfo::DecodableArgType responseData) -{ - ChipLogProgress(AppServer, "SupportedStreamingProtocolsSuccessHandlerJNI::ConvertToJObject called"); - return ConvertToIntegerJObject(responseData.Raw()); -} - -// APPLICATION BASIC -jobject VendorNameSuccessHandlerJNI::ConvertToJObject( - chip::app::Clusters::ApplicationBasic::Attributes::VendorName::TypeInfo::DecodableArgType responseData) -{ - ChipLogProgress(AppServer, "VendorNameSuccessHandlerJNI::ConvertToJObject called"); - return ConvertToJString(responseData); -} - -jobject VendorIDSuccessHandlerJNI::ConvertToJObject( - chip::app::Clusters::ApplicationBasic::Attributes::VendorID::TypeInfo::DecodableArgType responseData) -{ - ChipLogProgress(AppServer, "VendorIDSuccessHandlerJNI::ConvertToJObject called"); - return ConvertToIntegerJObject(responseData); -} - -jobject ApplicationNameSuccessHandlerJNI::ConvertToJObject( - chip::app::Clusters::ApplicationBasic::Attributes::ApplicationName::TypeInfo::DecodableArgType responseData) -{ - ChipLogProgress(AppServer, "ApplicationNameSuccessHandlerJNI::ConvertToJObject called"); - return ConvertToJString(responseData); -} - -jobject ProductIDSuccessHandlerJNI::ConvertToJObject( - chip::app::Clusters::ApplicationBasic::Attributes::ProductID::TypeInfo::DecodableArgType responseData) -{ - ChipLogProgress(AppServer, "ProductIDSuccessHandlerJNI::ConvertToJObject called"); - return ConvertToIntegerJObject(responseData); -} - -jobject ApplicationVersionSuccessHandlerJNI::ConvertToJObject( - chip::app::Clusters::ApplicationBasic::Attributes::ApplicationVersion::TypeInfo::DecodableArgType responseData) -{ - ChipLogProgress(AppServer, "ApplicationVersionSuccessHandlerJNI::ConvertToJObject called"); - return ConvertToJString(responseData); -} diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/MatterCallbackHandler-JNI.h b/examples/tv-casting-app/android/App/app/src/main/jni/cpp/MatterCallbackHandler-JNI.h deleted file mode 100644 index 152dac5973..0000000000 --- a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/MatterCallbackHandler-JNI.h +++ /dev/null @@ -1,293 +0,0 @@ -/* - * - * Copyright (c) 2022 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 "ConversionUtils.h" -#include "TargetEndpointInfo.h" -#include "TargetVideoPlayerInfo.h" - -#include -#include -#include -#include -#include - -#include - -class CallbackBaseJNI -{ -public: - CallbackBaseJNI(const char * methodSignature) { mMethodSignature = methodSignature; } - CHIP_ERROR SetUp(JNIEnv * env, jobject inHandler); - -protected: - chip::JniGlobalReference mObject; - jclass mClazz = nullptr; - jclass mSuperClazz = nullptr; - jmethodID mMethod = nullptr; - const char * mMethodSignature = nullptr; -}; - -class FailureHandlerJNI : public CallbackBaseJNI -{ -public: - FailureHandlerJNI() : CallbackBaseJNI("(ILjava/lang/String;)V") {} - void Handle(CHIP_ERROR err); -}; - -class MatterCallbackHandlerJNI : public FailureHandlerJNI -{ -}; - -class SubscriptionEstablishedHandlerJNI : public CallbackBaseJNI -{ -public: - SubscriptionEstablishedHandlerJNI() : CallbackBaseJNI("()V") {} - void Handle(); -}; - -// helper functions for conversions -jobject ConvertToLongJObject(uint64_t responseData); -jobject ConvertToFloatJObject(float responseData); -jobject ConvertToShortJObject(uint8_t responseData); -jobject ConvertToByteJObject(uint8_t responseData); -jobject ConvertToIntegerJObject(uint32_t responseData); -jstring ConvertToJString(chip::CharSpan responseData); - -template -class SuccessHandlerJNI : public CallbackBaseJNI -{ -public: - SuccessHandlerJNI(const char * methodSignature) : CallbackBaseJNI(methodSignature) {} - - virtual ~SuccessHandlerJNI() = 0; - - virtual jobject ConvertToJObject(T responseData) = 0; - - void Handle(T responseData) - { - ChipLogProgress(AppServer, "SuccessHandlerJNI::Handle called"); - - JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread(); - jobject jResponseData = ConvertToJObject(responseData); - - chip::DeviceLayer::StackUnlock unlock; - CHIP_ERROR err = CHIP_NO_ERROR; - VerifyOrExit(mObject.HasValidObjectRef(), err = CHIP_ERROR_INCORRECT_STATE); - VerifyOrExit(mMethod != nullptr, err = CHIP_ERROR_INCORRECT_STATE); - env->CallVoidMethod(mObject.ObjectRef(), mMethod, jResponseData); - exit: - if (err != CHIP_NO_ERROR) - { - ChipLogError(AppServer, "SuccessHandlerJNI::Handle status error: %s", err.AsString()); - } - } -}; - -template -SuccessHandlerJNI::~SuccessHandlerJNI(){}; - -// COMMISSIONING AND CONNECTION -class SessionEstablishmentStartedHandlerJNI : public SuccessHandlerJNI -{ -public: - SessionEstablishmentStartedHandlerJNI() : SuccessHandlerJNI("(Ljava/lang/Object;)V") {} - jobject ConvertToJObject(void * responseData) - { - // return nullptr because the Java callback extends SuccessCallback and its handle() expects a Void param. - // It expects a Void becauase no value is passed as part of this callback. - return nullptr; - } -}; - -class SessionEstablishedHandlerJNI : public SuccessHandlerJNI -{ -public: - SessionEstablishedHandlerJNI() : SuccessHandlerJNI("(Ljava/lang/Object;)V") {} - jobject ConvertToJObject(void * responseData) - { - // return nullptr because the Java callback extends SuccessCallback and its handle() expects a Void param. - // It expects a Void becauase no value is passed as part of this callback. - return nullptr; - } -}; - -class OnConnectionSuccessHandlerJNI : public SuccessHandlerJNI -{ -public: - OnConnectionSuccessHandlerJNI() : SuccessHandlerJNI("(Ljava/lang/Object;)V") {} - jobject ConvertToJObject(TargetVideoPlayerInfo * responseData); -}; - -class OnNewOrUpdatedEndpointHandlerJNI : public SuccessHandlerJNI -{ -public: - OnNewOrUpdatedEndpointHandlerJNI() : SuccessHandlerJNI("(Ljava/lang/Object;)V") {} - jobject ConvertToJObject(TargetEndpointInfo * responseData); -}; - -// MEDIA PLAYBACK -class CurrentStateSuccessHandlerJNI - : public SuccessHandlerJNI -{ -public: - CurrentStateSuccessHandlerJNI() : SuccessHandlerJNI("(Ljava/lang/Object;)V") {} - jobject ConvertToJObject(chip::app::Clusters::MediaPlayback::Attributes::CurrentState::TypeInfo::DecodableArgType responseData); -}; - -class DurationSuccessHandlerJNI - : public SuccessHandlerJNI -{ -public: - DurationSuccessHandlerJNI() : SuccessHandlerJNI("(Ljava/lang/Long;)V") {} - jobject ConvertToJObject(chip::app::Clusters::MediaPlayback::Attributes::Duration::TypeInfo::DecodableArgType responseData); -}; - -class SampledPositionSuccessHandlerJNI - : public SuccessHandlerJNI -{ -public: - SampledPositionSuccessHandlerJNI() : SuccessHandlerJNI("(Ljava/lang/Object;)V") {} - jobject - ConvertToJObject(chip::app::Clusters::MediaPlayback::Attributes::SampledPosition::TypeInfo::DecodableArgType responseData); -}; - -class PlaybackSpeedSuccessHandlerJNI - : public SuccessHandlerJNI -{ -public: - PlaybackSpeedSuccessHandlerJNI() : SuccessHandlerJNI("(Ljava/lang/Float;)V") {} - jobject - ConvertToJObject(chip::app::Clusters::MediaPlayback::Attributes::PlaybackSpeed::TypeInfo::DecodableArgType responseData); -}; - -class SeekRangeEndSuccessHandlerJNI - : public SuccessHandlerJNI -{ -public: - SeekRangeEndSuccessHandlerJNI() : SuccessHandlerJNI("(Ljava/lang/Long;)V") {} - jobject ConvertToJObject(chip::app::Clusters::MediaPlayback::Attributes::SeekRangeEnd::TypeInfo::DecodableArgType responseData); -}; - -class SeekRangeStartSuccessHandlerJNI - : public SuccessHandlerJNI -{ -public: - SeekRangeStartSuccessHandlerJNI() : SuccessHandlerJNI("(Ljava/lang/Long;)V") {} - jobject - ConvertToJObject(chip::app::Clusters::MediaPlayback::Attributes::SeekRangeStart::TypeInfo::DecodableArgType responseData); -}; - -// TARGET NAVIGATOR -class CurrentTargetSuccessHandlerJNI - : public SuccessHandlerJNI -{ -public: - CurrentTargetSuccessHandlerJNI() : SuccessHandlerJNI("(Ljava/lang/Byte;)V") {} - jobject - ConvertToJObject(chip::app::Clusters::TargetNavigator::Attributes::CurrentTarget::TypeInfo::DecodableArgType responseData); -}; - -class TargetListSuccessHandlerJNI - : public SuccessHandlerJNI -{ -public: - TargetListSuccessHandlerJNI() : SuccessHandlerJNI("(Ljava/lang/Object;)V") {} - jobject ConvertToJObject(chip::app::Clusters::TargetNavigator::Attributes::TargetList::TypeInfo::DecodableArgType responseData); -}; - -// LEVEL CONTROL -class CurrentLevelSuccessHandlerJNI - : public SuccessHandlerJNI -{ -public: - CurrentLevelSuccessHandlerJNI() : SuccessHandlerJNI("(Ljava/lang/Byte;)V") {} - jobject ConvertToJObject(chip::app::Clusters::LevelControl::Attributes::CurrentLevel::TypeInfo::DecodableArgType responseData); -}; - -class MinLevelSuccessHandlerJNI - : public SuccessHandlerJNI -{ -public: - MinLevelSuccessHandlerJNI() : SuccessHandlerJNI("(Ljava/lang/Byte;)V") {} - jobject ConvertToJObject(chip::app::Clusters::LevelControl::Attributes::MinLevel::TypeInfo::DecodableArgType responseData); -}; - -class MaxLevelSuccessHandlerJNI - : public SuccessHandlerJNI -{ -public: - MaxLevelSuccessHandlerJNI() : SuccessHandlerJNI("(Ljava/lang/Byte;)V") {} - jobject ConvertToJObject(chip::app::Clusters::LevelControl::Attributes::MaxLevel::TypeInfo::DecodableArgType responseData); -}; - -// CONTENT LAUNCHER -class SupportedStreamingProtocolsSuccessHandlerJNI - : public SuccessHandlerJNI< - chip::app::Clusters::ContentLauncher::Attributes::SupportedStreamingProtocols::TypeInfo::DecodableArgType> -{ -public: - SupportedStreamingProtocolsSuccessHandlerJNI() : SuccessHandlerJNI("(Ljava/lang/Integer;)V") {} - jobject ConvertToJObject( - chip::app::Clusters::ContentLauncher::Attributes::SupportedStreamingProtocols::TypeInfo::DecodableArgType responseData); -}; - -// APPLICATION BASIC -class VendorNameSuccessHandlerJNI - : public SuccessHandlerJNI -{ -public: - VendorNameSuccessHandlerJNI() : SuccessHandlerJNI("(Ljava/lang/String;)V") {} - jobject - ConvertToJObject(chip::app::Clusters::ApplicationBasic::Attributes::VendorName::TypeInfo::DecodableArgType responseData); -}; - -class VendorIDSuccessHandlerJNI - : public SuccessHandlerJNI -{ -public: - VendorIDSuccessHandlerJNI() : SuccessHandlerJNI("(Ljava/lang/Integer;)V") {} - jobject ConvertToJObject(chip::app::Clusters::ApplicationBasic::Attributes::VendorID::TypeInfo::DecodableArgType responseData); -}; - -class ApplicationNameSuccessHandlerJNI - : public SuccessHandlerJNI -{ -public: - ApplicationNameSuccessHandlerJNI() : SuccessHandlerJNI("(Ljava/lang/String;)V") {} - jobject - ConvertToJObject(chip::app::Clusters::ApplicationBasic::Attributes::ApplicationName::TypeInfo::DecodableArgType responseData); -}; - -class ProductIDSuccessHandlerJNI - : public SuccessHandlerJNI -{ -public: - ProductIDSuccessHandlerJNI() : SuccessHandlerJNI("(Ljava/lang/Integer;)V") {} - jobject ConvertToJObject(chip::app::Clusters::ApplicationBasic::Attributes::ProductID::TypeInfo::DecodableArgType responseData); -}; - -class ApplicationVersionSuccessHandlerJNI - : public SuccessHandlerJNI -{ -public: - ApplicationVersionSuccessHandlerJNI() : SuccessHandlerJNI("(Ljava/lang/String;)V") {} - jobject ConvertToJObject( - chip::app::Clusters::ApplicationBasic::Attributes::ApplicationVersion::TypeInfo::DecodableArgType responseData); -}; diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/TvCastingApp-JNI.cpp b/examples/tv-casting-app/android/App/app/src/main/jni/cpp/TvCastingApp-JNI.cpp deleted file mode 100644 index f2e0d5b79f..0000000000 --- a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/TvCastingApp-JNI.cpp +++ /dev/null @@ -1,2129 +0,0 @@ -/* - * Copyright (c) 2022 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 "TvCastingApp-JNI.h" -#include "CastingServer.h" -#include "Constants.h" -#include "ConversionUtils.h" -#include "JNIDACProvider.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace chip; - -#define JNI_METHOD(RETURN, METHOD_NAME) extern "C" JNIEXPORT RETURN JNICALL Java_com_chip_casting_TvCastingApp_##METHOD_NAME - -TvCastingAppJNI TvCastingAppJNI::sInstance; - -jint JNI_OnLoad(JavaVM * jvm, void * reserved) -{ - return AndroidAppServerJNI_OnLoad(jvm, reserved); -} - -void JNI_OnUnload(JavaVM * jvm, void * reserved) -{ - return AndroidAppServerJNI_OnUnload(jvm, reserved); -} - -JNI_METHOD(jboolean, preInitJni)(JNIEnv *, jobject, jobject jAppParameters) -{ - chip::DeviceLayer::StackLock lock; - ChipLogProgress(AppServer, "JNI_METHOD preInitJni called"); - - CHIP_ERROR err = CHIP_NO_ERROR; - if (jAppParameters == nullptr) - { - err = CastingServer::GetInstance()->PreInit(); - } - else - { - AppParams appParams; - err = convertJAppParametersToCppAppParams(jAppParameters, appParams); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogError(AppServer, "Conversion of AppParameters from jobject to Cpp type failed: %" CHIP_ERROR_FORMAT, - err.Format())); - err = CastingServer::GetInstance()->PreInit(&appParams); - } - VerifyOrExit( - err == CHIP_NO_ERROR, - ChipLogError(AppServer, "Call to CastingServer::GetInstance()->PreInit() failed: %" CHIP_ERROR_FORMAT, err.Format())); -exit: - return (err == CHIP_NO_ERROR); -} - -JNI_METHOD(jboolean, initJni)(JNIEnv *, jobject, jobject jAppParameters) -{ - chip::DeviceLayer::StackLock lock; - ChipLogProgress(AppServer, "JNI_METHOD initJni called"); - - CHIP_ERROR err = CHIP_NO_ERROR; - if (jAppParameters == nullptr) - { - err = CastingServer::GetInstance()->Init(); - } - else - { - AppParams appParams; - err = convertJAppParametersToCppAppParams(jAppParameters, appParams); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogError(AppServer, "Conversion of AppParameters from jobject to Cpp type failed: %" CHIP_ERROR_FORMAT, - err.Format())); - err = CastingServer::GetInstance()->Init(&appParams); - } - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogError(AppServer, "Call to CastingServer::GetInstance()->Init() failed: %" CHIP_ERROR_FORMAT, err.Format())); -exit: - return (err == CHIP_NO_ERROR); -} - -JNI_METHOD(void, setDACProvider)(JNIEnv *, jobject, jobject provider) -{ - chip::DeviceLayer::StackLock lock; - ChipLogProgress(AppServer, "JNI_METHOD setDACProvider called"); - - JNIDACProvider * p = new JNIDACProvider(provider); - chip::Credentials::SetDeviceAttestationCredentialsProvider(p); -} - -JNI_METHOD(jboolean, openBasicCommissioningWindow) -(JNIEnv * env, jobject, jint duration, jobject jCommissioningCallbacks, jobject jOnConnectionSuccessHandler, - jobject jOnConnectionFailureHandler, jobject jOnNewOrUpdatedEndpointHandler) -{ - chip::DeviceLayer::StackLock lock; - - ChipLogProgress(AppServer, "JNI_METHOD openBasicCommissioningWindow called with duration %d", duration); - - CHIP_ERROR err = CHIP_NO_ERROR; - - CommissioningCallbacks commissioningCallbacks; - jclass jCommissioningCallbacksClass; - chip::JniReferences::GetInstance().GetLocalClassRef(env, "com/chip/casting/CommissioningCallbacks", - jCommissioningCallbacksClass); - - jfieldID jCommissioningCompleteField = - env->GetFieldID(jCommissioningCallbacksClass, "commissioningComplete", "Ljava/lang/Object;"); - jobject jCommissioningComplete = env->GetObjectField(jCommissioningCallbacks, jCommissioningCompleteField); - if (jCommissioningComplete != nullptr) - { - err = TvCastingAppJNIMgr().getCommissioningCompleteHandler().SetUp(env, jCommissioningComplete); - VerifyOrReturnValue(err == CHIP_NO_ERROR, false, - ChipLogError(AppServer, "MatterCallbackHandlerJNI::SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - commissioningCallbacks.commissioningComplete = [](CHIP_ERROR err) { - TvCastingAppJNIMgr().getCommissioningCompleteHandler().Handle(err); - }; - } - - jfieldID jSessionEstablishmentStartedField = - env->GetFieldID(jCommissioningCallbacksClass, "sessionEstablishmentStarted", "Lcom/chip/casting/SuccessCallback;"); - jobject jSessionEstablishmentStarted = env->GetObjectField(jCommissioningCallbacks, jSessionEstablishmentStartedField); - if (jSessionEstablishmentStarted != nullptr) - { - err = TvCastingAppJNIMgr().getSessionEstablishmentStartedHandler().SetUp(env, jSessionEstablishmentStarted); - VerifyOrReturnValue( - err == CHIP_NO_ERROR, false, - ChipLogError(AppServer, "SessionEstablishmentStartedHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - commissioningCallbacks.sessionEstablishmentStarted = []() { - TvCastingAppJNIMgr().getSessionEstablishmentStartedHandler().Handle(nullptr); - }; - } - - jfieldID jSessionEstablishedField = - env->GetFieldID(jCommissioningCallbacksClass, "sessionEstablished", "Lcom/chip/casting/SuccessCallback;"); - jobject jSessionEstablished = env->GetObjectField(jCommissioningCallbacks, jSessionEstablishedField); - if (jSessionEstablished != nullptr) - { - err = TvCastingAppJNIMgr().getSessionEstablishedHandler().SetUp(env, jSessionEstablished); - VerifyOrReturnValue(err == CHIP_NO_ERROR, false, - ChipLogError(AppServer, "SessionEstablishedHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - commissioningCallbacks.sessionEstablished = []() { TvCastingAppJNIMgr().getSessionEstablishedHandler().Handle(nullptr); }; - } - - jfieldID jSessionEstablishmentErrorField = - env->GetFieldID(jCommissioningCallbacksClass, "sessionEstablishmentError", "Lcom/chip/casting/FailureCallback;"); - jobject jSessionEstablishmentError = env->GetObjectField(jCommissioningCallbacks, jSessionEstablishmentErrorField); - if (jSessionEstablishmentError != nullptr) - { - err = TvCastingAppJNIMgr().getSessionEstablishmentErrorHandler().SetUp(env, jSessionEstablishmentError); - VerifyOrReturnValue(err == CHIP_NO_ERROR, false); - commissioningCallbacks.sessionEstablishmentError = [](CHIP_ERROR err) { - TvCastingAppJNIMgr().getSessionEstablishmentErrorHandler().Handle(err); - }; - } - - jfieldID jSessionEstablishmentStoppedField = - env->GetFieldID(jCommissioningCallbacksClass, "sessionEstablishmentStopped", "Lcom/chip/casting/FailureCallback;"); - jobject jSessionEstablishmentStopped = env->GetObjectField(jCommissioningCallbacks, jSessionEstablishmentStoppedField); - if (jSessionEstablishmentStopped != nullptr) - { - err = TvCastingAppJNIMgr().getSessionEstablishmentStoppedHandler().SetUp(env, jSessionEstablishmentStopped); - VerifyOrReturnValue( - err == CHIP_NO_ERROR, false, - ChipLogError(AppServer, "SessionEstablishmentStoppedHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - commissioningCallbacks.sessionEstablishmentStopped = []() { - TvCastingAppJNIMgr().getSessionEstablishmentStoppedHandler().Handle(CHIP_NO_ERROR); - }; - } - - err = TvCastingAppJNIMgr().getOnConnectionSuccessHandler(false).SetUp(env, jOnConnectionSuccessHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "OnConnectionSuccessHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = TvCastingAppJNIMgr().getOnConnectionFailureHandler(false).SetUp(env, jOnConnectionFailureHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "OnConnectionFailureHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = TvCastingAppJNIMgr().getOnNewOrUpdatedEndpointHandler(false).SetUp(env, jOnNewOrUpdatedEndpointHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "OnNewOrUpdatedEndpointHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = CastingServer::GetInstance()->OpenBasicCommissioningWindow( - commissioningCallbacks, - [](TargetVideoPlayerInfo * videoPlayer) { TvCastingAppJNIMgr().getOnConnectionSuccessHandler(false).Handle(videoPlayer); }, - [](CHIP_ERROR err) { TvCastingAppJNIMgr().getOnConnectionFailureHandler(false).Handle(err); }, - [](TargetEndpointInfo * endpoint) { TvCastingAppJNIMgr().getOnNewOrUpdatedEndpointHandler(false).Handle(endpoint); }); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "CastingServer::OpenBasicCommissioningWindow failed: %" CHIP_ERROR_FORMAT, err.Format())); - -exit: - return (err == CHIP_NO_ERROR); -} - -JNI_METHOD(jobject, readCachedVideoPlayers)(JNIEnv * env, jobject) -{ - chip::DeviceLayer::StackLock lock; - - ChipLogProgress(AppServer, "JNI_METHOD readCachedVideoPlayers called"); - - jobject jVideoPlayerList = nullptr; - TargetVideoPlayerInfo * targetVideoPlayerInfoList = CastingServer::GetInstance()->ReadCachedTargetVideoPlayerInfos(); - if (targetVideoPlayerInfoList != nullptr) - { - chip::JniReferences::GetInstance().CreateArrayList(jVideoPlayerList); - for (size_t i = 0; targetVideoPlayerInfoList[i].IsInitialized(); i++) - { - jobject jVideoPlayer = nullptr; - CHIP_ERROR err = convertTargetVideoPlayerInfoToJVideoPlayer(&targetVideoPlayerInfoList[i], jVideoPlayer); - if (err != CHIP_NO_ERROR) - { - ChipLogError(AppServer, - "Conversion from TargetVideoPlayerInfo * to jobject VideoPlayer failed: %" CHIP_ERROR_FORMAT, - err.Format()); - continue; - } - chip::JniReferences::GetInstance().AddToList(jVideoPlayerList, jVideoPlayer); - } - } - - return jVideoPlayerList; -} - -JNI_METHOD(jboolean, verifyOrEstablishConnection) -(JNIEnv * env, jobject, jobject videoPlayer, jobject jOnConnectionSuccessHandler, jobject jOnConnectionFailureHandler, - jobject jOnNewOrUpdatedEndpointHandler) -{ - chip::DeviceLayer::StackLock lock; - - ChipLogProgress(AppServer, "JNI_METHOD verifyOrEstablishConnection called"); - - TargetVideoPlayerInfo targetVideoPlayerInfo; - CHIP_ERROR err = convertJVideoPlayerToTargetVideoPlayerInfo(videoPlayer, targetVideoPlayerInfo); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogError(AppServer, - "Conversion from jobject VideoPlayer to TargetVideoPlayerInfo * failed: %" CHIP_ERROR_FORMAT, - err.Format())); - - err = TvCastingAppJNIMgr().getOnConnectionSuccessHandler(true).SetUp(env, jOnConnectionSuccessHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "OnConnectionSuccessHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = TvCastingAppJNIMgr().getOnConnectionFailureHandler(true).SetUp(env, jOnConnectionFailureHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "OnConnectionFailureHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = TvCastingAppJNIMgr().getOnNewOrUpdatedEndpointHandler(true).SetUp(env, jOnNewOrUpdatedEndpointHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "OnNewOrUpdatedEndpointHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = CastingServer::GetInstance()->VerifyOrEstablishConnection( - targetVideoPlayerInfo, - [](TargetVideoPlayerInfo * videoPlayer) { TvCastingAppJNIMgr().getOnConnectionSuccessHandler(true).Handle(videoPlayer); }, - [](CHIP_ERROR err) { TvCastingAppJNIMgr().getOnConnectionFailureHandler(true).Handle(err); }, - [](TargetEndpointInfo * endpoint) { TvCastingAppJNIMgr().getOnNewOrUpdatedEndpointHandler(true).Handle(endpoint); }); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "CastingServer::verifyOrEstablishConnection failed: %" CHIP_ERROR_FORMAT, err.Format())); - -exit: - return (err == CHIP_NO_ERROR); -} - -JNI_METHOD(jboolean, WasRecentlyDiscoverable) -(JNIEnv * env, jobject, jobject videoPlayer) -{ - chip::DeviceLayer::StackLock lock; - - ChipLogProgress(AppServer, "JNI_METHOD WasRecentlyDiscoverable called"); - - TargetVideoPlayerInfo targetVideoPlayerInfo; - CHIP_ERROR err = convertJVideoPlayerToTargetVideoPlayerInfo(videoPlayer, targetVideoPlayerInfo); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogError(AppServer, - "Conversion from jobject VideoPlayer to TargetVideoPlayerInfo * failed: %" CHIP_ERROR_FORMAT, - err.Format())); - return targetVideoPlayerInfo.WasRecentlyDiscoverable(); - -exit: - return false; // default to false -} - -JNI_METHOD(void, shutdownAllSubscriptions)(JNIEnv * env, jobject) -{ - chip::DeviceLayer::StackLock lock; - ChipLogProgress(AppServer, "JNI_METHOD shutdownAllSubscriptions called"); - - CastingServer::GetInstance()->ShutdownAllSubscriptions(); -} - -JNI_METHOD(void, disconnect)(JNIEnv * env, jobject) -{ - chip::DeviceLayer::StackLock lock; - ChipLogProgress(AppServer, "JNI_METHOD disconnect called"); - CastingServer::GetInstance()->Disconnect(); -} - -JNI_METHOD(jobject, getActiveTargetVideoPlayers)(JNIEnv * env, jobject) -{ - chip::DeviceLayer::StackLock lock; - - ChipLogProgress(AppServer, "JNI_METHOD getActiveTargetVideoPlayers called"); - - jobject jVideoPlayerList = nullptr; - TargetVideoPlayerInfo * targetVideoPlayerInfo = CastingServer::GetInstance()->GetActiveTargetVideoPlayer(); - if (targetVideoPlayerInfo != nullptr) - { - chip::JniReferences::GetInstance().CreateArrayList(jVideoPlayerList); - jobject jVideoPlayer = nullptr; - CHIP_ERROR err = convertTargetVideoPlayerInfoToJVideoPlayer(targetVideoPlayerInfo, jVideoPlayer); - if (err != CHIP_NO_ERROR) - { - ChipLogError(AppServer, "Conversion from TargetVideoPlayerInfo * to jobject VideoPlayer failed: %" CHIP_ERROR_FORMAT, - err.Format()); - } - else - { - chip::JniReferences::GetInstance().AddToList(jVideoPlayerList, jVideoPlayer); - } - } - return jVideoPlayerList; -} - -JNI_METHOD(jboolean, sendUserDirectedCommissioningRequest)(JNIEnv * env, jobject, jstring addressJStr, jint port) -{ - chip::DeviceLayer::StackLock lock; - ChipLogProgress(AppServer, "JNI_METHOD sendUserDirectedCommissioningRequest called with port %d", port); - Inet::IPAddress addressInet; - JniUtfString addressJniString(env, addressJStr); - if (Inet::IPAddress::FromString(addressJniString.c_str(), addressInet) == false) - { - ChipLogError(AppServer, "Failed to parse IP address"); - return false; - } - - chip::Inet::InterfaceId interfaceId = chip::Inet::InterfaceId::FromIPAddress(addressInet); - chip::Transport::PeerAddress peerAddress = - chip::Transport::PeerAddress::UDP(addressInet, static_cast(port), interfaceId); - CHIP_ERROR err = CastingServer::GetInstance()->SendUserDirectedCommissioningRequest(peerAddress); - if (err != CHIP_NO_ERROR) - { - ChipLogError(AppServer, "TVCastingApp-JNI::sendUserDirectedCommissioningRequest failed: %" CHIP_ERROR_FORMAT, err.Format()); - return false; - } - return true; -} - -JNI_METHOD(jboolean, sendCommissioningRequest)(JNIEnv * env, jobject, jobject jDiscoveredNodeData) -{ - chip::DeviceLayer::StackLock lock; - ChipLogProgress(AppServer, "JNI_METHOD sendCommissioningRequest called"); - - chip::Dnssd::CommissionNodeData commissioner; - CHIP_ERROR err = convertJDiscoveredNodeDataToCppDiscoveredNodeData(jDiscoveredNodeData, commissioner); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogError(AppServer, - "Conversion from jobject DiscoveredNodeData to Cpp DiscoveredNodeData failed: %" CHIP_ERROR_FORMAT, - err.Format())); - - err = CastingServer::GetInstance()->SendUserDirectedCommissioningRequest(&commissioner); - -exit: - if (err != CHIP_NO_ERROR) - { - ChipLogError(AppServer, "TVCastingApp-JNI::sendCommissioningRequest failed: %" CHIP_ERROR_FORMAT, err.Format()); - return false; - } - return true; -} - -JNI_METHOD(jboolean, purgeCache)(JNIEnv * env, jobject) -{ - chip::DeviceLayer::StackLock lock; - ChipLogProgress(AppServer, "JNI_METHOD purgeCache called"); - - CHIP_ERROR err = CastingServer::GetInstance()->PurgeCache(); - if (err != CHIP_NO_ERROR) - { - ChipLogError(AppServer, "TVCastingApp-JNI::purgeCache failed: %" CHIP_ERROR_FORMAT, err.Format()); - return false; - } - return true; -} - -JNI_METHOD(jboolean, contentLauncherLaunchURL) -(JNIEnv * env, jobject, jobject contentApp, jstring contentUrl, jstring contentDisplayStr, jobject jResponseHandler) -{ - chip::DeviceLayer::StackLock lock; - - ChipLogProgress(AppServer, "JNI_METHOD contentLauncherLaunchURL called"); - const char * nativeContentUrl = env->GetStringUTFChars(contentUrl, 0); - const char * nativeContentDisplayStr = env->GetStringUTFChars(contentDisplayStr, 0); - - TargetEndpointInfo endpoint; - CHIP_ERROR err = convertJContentAppToTargetEndpointInfo(contentApp, endpoint); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogError(AppServer, "Conversion from jobject contentApp to TargetEndpointInfo * failed: %" CHIP_ERROR_FORMAT, - err.Format())); - - err = TvCastingAppJNIMgr().getMediaCommandResponseHandler(ContentLauncher_LaunchURL).SetUp(env, jResponseHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "MatterCallbackHandlerJNI::SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = CastingServer::GetInstance()->ContentLauncherLaunchURL( - &endpoint, nativeContentUrl, nativeContentDisplayStr, - [](CHIP_ERROR err) { TvCastingAppJNIMgr().getMediaCommandResponseHandler(ContentLauncher_LaunchURL).Handle(err); }); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "CastingServer::ContentLauncherLaunchURL failed %" CHIP_ERROR_FORMAT, err.Format())); - - env->ReleaseStringUTFChars(contentUrl, nativeContentUrl); - env->ReleaseStringUTFChars(contentDisplayStr, nativeContentDisplayStr); - -exit: - return (err == CHIP_NO_ERROR); -} - -CHIP_ERROR CreateParameter(JNIEnv * env, jobject jParameter, - chip::app::Clusters::ContentLauncher::Structs::ParameterStruct::Type & parameter) -{ - jclass jParameterClass = env->GetObjectClass(jParameter); - - jfieldID jTypeField = env->GetFieldID(jParameterClass, "type", "Ljava/lang/Integer;"); - jobject jTypeObj = env->GetObjectField(jParameter, jTypeField); - jclass jIntegerClass = env->FindClass("java/lang/Integer"); - jmethodID jIntValueMid = env->GetMethodID(jIntegerClass, "intValue", "()I"); - parameter.type = static_cast(env->CallIntMethod(jTypeObj, jIntValueMid)); - - jfieldID jValueField = env->GetFieldID(jParameterClass, "value", "Ljava/lang/String;"); - jstring jValueObj = (jstring) env->GetObjectField(jParameter, jValueField); - const char * nativeValue = env->GetStringUTFChars(jValueObj, 0); - parameter.value = CharSpan::fromCharString(nativeValue); - return CHIP_NO_ERROR; -} - -CHIP_ERROR CreateContentSearch(JNIEnv * env, jobject jSearch, - chip::app::Clusters::ContentLauncher::Structs::ContentSearchStruct::Type & search, - ListFreer & listFreer) -{ - jclass jContentSearchClass; - ReturnErrorOnFailure(JniReferences::GetInstance().GetLocalClassRef(env, "com/chip/casting/ContentLauncherTypes$ContentSearch", - jContentSearchClass)); - - jfieldID jParameterListField = env->GetFieldID(jContentSearchClass, "parameterList", "Ljava/util/ArrayList;"); - jobject jParameterList = env->GetObjectField(jSearch, jParameterListField); - ReturnErrorOnFailure(jParameterList != nullptr ? CHIP_NO_ERROR : CHIP_ERROR_INVALID_ARGUMENT); - - jclass jArrayListClass = env->FindClass("java/util/ArrayList"); - jmethodID sizeMid = env->GetMethodID(jArrayListClass, "size", "()I"); - size_t parameterListSize = static_cast(env->CallIntMethod(jParameterList, sizeMid)); - - jobject jIterator = env->CallObjectMethod( - jParameterList, env->GetMethodID(env->GetObjectClass(jParameterList), "iterator", "()Ljava/util/Iterator;")); - jmethodID jNextMid = env->GetMethodID(env->GetObjectClass(jIterator), "next", "()Ljava/lang/Object;"); - jmethodID jHasNextMid = env->GetMethodID(env->GetObjectClass(jIterator), "hasNext", "()Z"); - - auto * parameterListHolder = - new ListHolder(parameterListSize); - listFreer.add(parameterListHolder); - int parameterIndex = 0; - while (env->CallBooleanMethod(jIterator, jHasNextMid)) - { - jobject jParameter = env->CallObjectMethod(jIterator, jNextMid); - chip::app::Clusters::ContentLauncher::Structs::ParameterStruct::Type parameter; - ReturnErrorOnFailure(CreateParameter(env, jParameter, parameter)); - parameterListHolder->mList[parameterIndex].type = parameter.type; - parameterListHolder->mList[parameterIndex].value = parameter.value; - parameterListHolder->mList[parameterIndex].externalIDList = parameter.externalIDList; - parameterIndex++; - } - search.parameterList = chip::app::DataModel::List( - parameterListHolder->mList, parameterListSize); - - return CHIP_NO_ERROR; -} - -JNI_METHOD(jboolean, contentLauncher_1launchContent) -(JNIEnv * env, jobject, jobject contentApp, jobject jSearch, jboolean jAutoplay, jstring jData, jobject jResponseHandler) -{ - chip::DeviceLayer::StackLock lock; - - ChipLogProgress(AppServer, "JNI_METHOD contentLauncher_1launchContent called"); - - // prepare arguments - bool autoplay = static_cast(jAutoplay); - - const char * nativeData = env->GetStringUTFChars(jData, 0); - chip::Optional data = MakeOptional(CharSpan::fromCharString(nativeData)); - - ListFreer listFreer; - chip::app::Clusters::ContentLauncher::Structs::ContentSearchStruct::Type search; - CHIP_ERROR err = CreateContentSearch(env, jSearch, search, listFreer); - - TargetEndpointInfo endpoint; - err = convertJContentAppToTargetEndpointInfo(contentApp, endpoint); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogError(AppServer, "Conversion from jobject contentApp to TargetEndpointInfo * failed: %" CHIP_ERROR_FORMAT, - err.Format())); - - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, - "contentLauncher_1launchContent::Could not create ContentSearch object %" CHIP_ERROR_FORMAT, - err.Format())); - - err = TvCastingAppJNIMgr().getMediaCommandResponseHandler(ContentLauncher_LaunchContent).SetUp(env, jResponseHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "MatterCallbackHandlerJNI::SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = CastingServer::GetInstance()->ContentLauncher_LaunchContent(&endpoint, search, autoplay, data, [](CHIP_ERROR err) { - TvCastingAppJNIMgr().getMediaCommandResponseHandler(ContentLauncher_LaunchContent).Handle(err); - }); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "CastingServer::ContentLauncher_LaunchContent failed %" CHIP_ERROR_FORMAT, err.Format())); - - env->ReleaseStringUTFChars(jData, nativeData); - -exit: - return (err == CHIP_NO_ERROR); -} - -JNI_METHOD(jboolean, contentLauncher_1subscribeToSupportedStreamingProtocols) -(JNIEnv * env, jobject, jobject contentApp, jobject jReadSuccessHandler, jobject jReadFailureHandler, jint minInterval, - jint maxInterval, jobject jSubscriptionEstablishedHandler) -{ - chip::DeviceLayer::StackLock lock; - - ChipLogProgress(AppServer, "JNI_METHOD ContentLauncher_subscribeToSupportedStreamingProtocols called"); - - TargetEndpointInfo endpoint; - CHIP_ERROR err = convertJContentAppToTargetEndpointInfo(contentApp, endpoint); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogError(AppServer, "Conversion from jobject contentApp to TargetEndpointInfo * failed: %" CHIP_ERROR_FORMAT, - err.Format())); - - err = TvCastingAppJNIMgr().getSupportedStreamingProtocolsSuccessHandler().SetUp(env, jReadSuccessHandler); - VerifyOrExit(CHIP_NO_ERROR == err, ChipLogError(AppServer, "SuccessHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = TvCastingAppJNIMgr() - .getSubscriptionReadFailureHandler(ContentLauncher_SupportedStreamingProtocols) - .SetUp(env, jReadFailureHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "SubscriptionReadFailureHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = TvCastingAppJNIMgr() - .getSubscriptionEstablishedHandler(ContentLauncher_SupportedStreamingProtocols) - .SetUp(env, jSubscriptionEstablishedHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "SubscriptionEstablishedHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = CastingServer::GetInstance()->ContentLauncher_SubscribeToSupportedStreamingProtocols( - &endpoint, nullptr, - [](void * context, - chip::app::Clusters::ContentLauncher::Attributes::SupportedStreamingProtocols::TypeInfo::DecodableArgType responseData) { - TvCastingAppJNIMgr().getSupportedStreamingProtocolsSuccessHandler().Handle(responseData); - }, - [](void * context, CHIP_ERROR err) { - TvCastingAppJNIMgr().getSubscriptionReadFailureHandler(ContentLauncher_SupportedStreamingProtocols).Handle(err); - }, - static_cast(minInterval), static_cast(maxInterval), - [](void * context, chip::SubscriptionId) { - TvCastingAppJNIMgr().getSubscriptionEstablishedHandler(ContentLauncher_SupportedStreamingProtocols).Handle(); - }); - - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, - "CastingServer.ContentLauncher_SubscribeToSupportedStreamingProtocols failed %" CHIP_ERROR_FORMAT, - err.Format())); - -exit: - return (err == CHIP_NO_ERROR); -} - -JNI_METHOD(jboolean, levelControl_1step) -(JNIEnv * env, jobject, jobject contentApp, jbyte stepMode, jbyte stepSize, jshort transitionTime, jbyte optionMask, - jbyte optionOverride, jobject jResponseHandler) -{ - chip::DeviceLayer::StackLock lock; - - ChipLogProgress(AppServer, "JNI_METHOD levelControl_step called"); - - TargetEndpointInfo endpoint; - CHIP_ERROR err = convertJContentAppToTargetEndpointInfo(contentApp, endpoint); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogError(AppServer, "Conversion from jobject contentApp to TargetEndpointInfo * failed: %" CHIP_ERROR_FORMAT, - err.Format())); - - err = TvCastingAppJNIMgr().getMediaCommandResponseHandler(LevelControl_Step).SetUp(env, jResponseHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "MatterCallbackHandlerJNI.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = CastingServer::GetInstance()->LevelControl_Step( - &endpoint, static_cast(stepMode), static_cast(stepSize), - static_cast(transitionTime), static_cast(optionMask), static_cast(optionOverride), - [](CHIP_ERROR err) { TvCastingAppJNIMgr().getMediaCommandResponseHandler(LevelControl_Step).Handle(err); }); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "CastingServer.LevelControl_Step failed %" CHIP_ERROR_FORMAT, err.Format())); - -exit: - return (err == CHIP_NO_ERROR); -} - -JNI_METHOD(jboolean, levelControl_1moveToLevel) -(JNIEnv * env, jobject, jobject contentApp, jbyte level, jshort transitionTime, jbyte optionMask, jbyte optionOverride, - jobject jResponseHandler) -{ - chip::DeviceLayer::StackLock lock; - - ChipLogProgress(AppServer, "JNI_METHOD levelControl_moveToLevel called"); - - TargetEndpointInfo endpoint; - CHIP_ERROR err = convertJContentAppToTargetEndpointInfo(contentApp, endpoint); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogError(AppServer, "Conversion from jobject contentApp to TargetEndpointInfo * failed: %" CHIP_ERROR_FORMAT, - err.Format())); - - err = TvCastingAppJNIMgr().getMediaCommandResponseHandler(LevelControl_MoveToLevel).SetUp(env, jResponseHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "MatterCallbackHandlerJNI.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = CastingServer::GetInstance()->LevelControl_MoveToLevel( - &endpoint, static_cast(level), static_cast(transitionTime), static_cast(optionMask), - static_cast(optionOverride), - [](CHIP_ERROR err) { TvCastingAppJNIMgr().getMediaCommandResponseHandler(LevelControl_MoveToLevel).Handle(err); }); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "CastingServer.LevelControl_MoveToLevel failed %" CHIP_ERROR_FORMAT, err.Format())); - -exit: - return (err == CHIP_NO_ERROR); -} - -JNI_METHOD(jboolean, levelControl_1subscribeToCurrentLevel) -(JNIEnv * env, jobject, jobject contentApp, jobject jReadSuccessHandler, jobject jReadFailureHandler, jint minInterval, - jint maxInterval, jobject jSubscriptionEstablishedHandler) -{ - chip::DeviceLayer::StackLock lock; - - ChipLogProgress(AppServer, "JNI_METHOD levelControl_subscribeToCurrentLevel called"); - - TargetEndpointInfo endpoint; - CHIP_ERROR err = convertJContentAppToTargetEndpointInfo(contentApp, endpoint); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogError(AppServer, "Conversion from jobject contentApp to TargetEndpointInfo * failed: %" CHIP_ERROR_FORMAT, - err.Format())); - - err = TvCastingAppJNIMgr().getCurrentLevelSuccessHandler().SetUp(env, jReadSuccessHandler); - VerifyOrExit(CHIP_NO_ERROR == err, ChipLogError(AppServer, "SuccessHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = TvCastingAppJNIMgr().getSubscriptionReadFailureHandler(LevelControl_CurrentLevel).SetUp(env, jReadFailureHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "SubscriptionReadFailureHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = TvCastingAppJNIMgr() - .getSubscriptionEstablishedHandler(LevelControl_CurrentLevel) - .SetUp(env, jSubscriptionEstablishedHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "SubscriptionEstablishedHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = CastingServer::GetInstance()->LevelControl_SubscribeToCurrentLevel( - &endpoint, nullptr, - [](void * context, chip::app::Clusters::LevelControl::Attributes::CurrentLevel::TypeInfo::DecodableArgType responseData) { - TvCastingAppJNIMgr().getCurrentLevelSuccessHandler().Handle(responseData); - }, - [](void * context, CHIP_ERROR err) { - TvCastingAppJNIMgr().getSubscriptionReadFailureHandler(LevelControl_CurrentLevel).Handle(err); - }, - static_cast(minInterval), static_cast(maxInterval), - [](void * context, chip::SubscriptionId) { - TvCastingAppJNIMgr().getSubscriptionEstablishedHandler(LevelControl_CurrentLevel).Handle(); - }); - - VerifyOrExit( - CHIP_NO_ERROR == err, - ChipLogError(AppServer, "CastingServer.LevelControl_SubscribeToCurrentLevel failed %" CHIP_ERROR_FORMAT, err.Format())); - -exit: - return (err == CHIP_NO_ERROR); -} - -JNI_METHOD(jboolean, levelControl_1subscribeToMinLevel) -(JNIEnv * env, jobject, jobject contentApp, jobject jReadSuccessHandler, jobject jReadFailureHandler, jint minInterval, - jint maxInterval, jobject jSubscriptionEstablishedHandler) -{ - chip::DeviceLayer::StackLock lock; - - ChipLogProgress(AppServer, "JNI_METHOD levelControl_subscribeToMinLevel called"); - - TargetEndpointInfo endpoint; - CHIP_ERROR err = convertJContentAppToTargetEndpointInfo(contentApp, endpoint); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogError(AppServer, "Conversion from jobject contentApp to TargetEndpointInfo * failed: %" CHIP_ERROR_FORMAT, - err.Format())); - - err = TvCastingAppJNIMgr().getMinLevelSuccessHandler().SetUp(env, jReadSuccessHandler); - VerifyOrExit(CHIP_NO_ERROR == err, ChipLogError(AppServer, "SuccessHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = TvCastingAppJNIMgr().getSubscriptionReadFailureHandler(LevelControl_MinLevel).SetUp(env, jReadFailureHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "SubscriptionReadFailureHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = TvCastingAppJNIMgr().getSubscriptionEstablishedHandler(LevelControl_MinLevel).SetUp(env, jSubscriptionEstablishedHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "SubscriptionEstablishedHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = CastingServer::GetInstance()->LevelControl_SubscribeToMinLevel( - &endpoint, nullptr, - [](void * context, chip::app::Clusters::LevelControl::Attributes::MinLevel::TypeInfo::DecodableArgType responseData) { - TvCastingAppJNIMgr().getMinLevelSuccessHandler().Handle(responseData); - }, - [](void * context, CHIP_ERROR err) { - TvCastingAppJNIMgr().getSubscriptionReadFailureHandler(LevelControl_MinLevel).Handle(err); - }, - static_cast(minInterval), static_cast(maxInterval), - [](void * context, chip::SubscriptionId) { - TvCastingAppJNIMgr().getSubscriptionEstablishedHandler(LevelControl_MinLevel).Handle(); - }); - - VerifyOrExit( - CHIP_NO_ERROR == err, - ChipLogError(AppServer, "CastingServer.LevelControl_SubscribeToMinLevel failed %" CHIP_ERROR_FORMAT, err.Format())); - -exit: - return (err == CHIP_NO_ERROR); -} - -JNI_METHOD(jboolean, levelControl_1subscribeToMaxLevel) -(JNIEnv * env, jobject, jobject contentApp, jobject jReadSuccessHandler, jobject jReadFailureHandler, jint minInterval, - jint maxInterval, jobject jSubscriptionEstablishedHandler) -{ - chip::DeviceLayer::StackLock lock; - - ChipLogProgress(AppServer, "JNI_METHOD levelControl_subscribeToMaxLevel called"); - - TargetEndpointInfo endpoint; - CHIP_ERROR err = convertJContentAppToTargetEndpointInfo(contentApp, endpoint); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogError(AppServer, "Conversion from jobject contentApp to TargetEndpointInfo * failed: %" CHIP_ERROR_FORMAT, - err.Format())); - - err = TvCastingAppJNIMgr().getMaxLevelSuccessHandler().SetUp(env, jReadSuccessHandler); - VerifyOrExit(CHIP_NO_ERROR == err, ChipLogError(AppServer, "SuccessHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = TvCastingAppJNIMgr().getSubscriptionReadFailureHandler(LevelControl_MaxLevel).SetUp(env, jReadFailureHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "SubscriptionReadFailureHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = TvCastingAppJNIMgr().getSubscriptionEstablishedHandler(LevelControl_MaxLevel).SetUp(env, jSubscriptionEstablishedHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "SubscriptionEstablishedHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = CastingServer::GetInstance()->LevelControl_SubscribeToMaxLevel( - &endpoint, nullptr, - [](void * context, chip::app::Clusters::LevelControl::Attributes::MaxLevel::TypeInfo::DecodableArgType responseData) { - TvCastingAppJNIMgr().getMaxLevelSuccessHandler().Handle(responseData); - }, - [](void * context, CHIP_ERROR err) { - TvCastingAppJNIMgr().getSubscriptionReadFailureHandler(LevelControl_MaxLevel).Handle(err); - }, - static_cast(minInterval), static_cast(maxInterval), - [](void * context, chip::SubscriptionId) { - TvCastingAppJNIMgr().getSubscriptionEstablishedHandler(LevelControl_MaxLevel).Handle(); - }); - - VerifyOrExit( - CHIP_NO_ERROR == err, - ChipLogError(AppServer, "CastingServer.LevelControl_SubscribeToMaxLevel failed %" CHIP_ERROR_FORMAT, err.Format())); - -exit: - return (err == CHIP_NO_ERROR); -} - -JNI_METHOD(jboolean, onOff_1on) -(JNIEnv * env, jobject, jobject contentApp, jobject jResponseHandler) -{ - chip::DeviceLayer::StackLock lock; - - ChipLogProgress(AppServer, "JNI_METHOD onOff_on called"); - - TargetEndpointInfo endpoint; - CHIP_ERROR err = convertJContentAppToTargetEndpointInfo(contentApp, endpoint); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogError(AppServer, "Conversion from jobject contentApp to TargetEndpointInfo * failed: %" CHIP_ERROR_FORMAT, - err.Format())); - - err = TvCastingAppJNIMgr().getMediaCommandResponseHandler(OnOff_On).SetUp(env, jResponseHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "MatterCallbackHandlerJNI.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = CastingServer::GetInstance()->OnOff_On( - &endpoint, [](CHIP_ERROR err) { TvCastingAppJNIMgr().getMediaCommandResponseHandler(OnOff_On).Handle(err); }); - VerifyOrExit(CHIP_NO_ERROR == err, ChipLogError(AppServer, "CastingServer.OnOff_On failed %" CHIP_ERROR_FORMAT, err.Format())); - -exit: - return (err == CHIP_NO_ERROR); -} - -JNI_METHOD(jboolean, onOff_1off) -(JNIEnv * env, jobject, jobject contentApp, jobject jResponseHandler) -{ - chip::DeviceLayer::StackLock lock; - - ChipLogProgress(AppServer, "JNI_METHOD onOff_off called"); - - TargetEndpointInfo endpoint; - CHIP_ERROR err = convertJContentAppToTargetEndpointInfo(contentApp, endpoint); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogError(AppServer, "Conversion from jobject contentApp to TargetEndpointInfo * failed: %" CHIP_ERROR_FORMAT, - err.Format())); - - err = TvCastingAppJNIMgr().getMediaCommandResponseHandler(OnOff_Off).SetUp(env, jResponseHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "MatterCallbackHandlerJNI.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = CastingServer::GetInstance()->OnOff_Off( - &endpoint, [](CHIP_ERROR err) { TvCastingAppJNIMgr().getMediaCommandResponseHandler(OnOff_Off).Handle(err); }); - VerifyOrExit(CHIP_NO_ERROR == err, ChipLogError(AppServer, "CastingServer.OnOff_Off failed %" CHIP_ERROR_FORMAT, err.Format())); - -exit: - return (err == CHIP_NO_ERROR); -} - -JNI_METHOD(jboolean, onOff_1toggle) -(JNIEnv * env, jobject, jobject contentApp, jobject jResponseHandler) -{ - chip::DeviceLayer::StackLock lock; - - ChipLogProgress(AppServer, "JNI_METHOD onOff_toggle called"); - - TargetEndpointInfo endpoint; - CHIP_ERROR err = convertJContentAppToTargetEndpointInfo(contentApp, endpoint); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogError(AppServer, "Conversion from jobject contentApp to TargetEndpointInfo * failed: %" CHIP_ERROR_FORMAT, - err.Format())); - - err = TvCastingAppJNIMgr().getMediaCommandResponseHandler(OnOff_Toggle).SetUp(env, jResponseHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "MatterCallbackHandlerJNI.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = CastingServer::GetInstance()->OnOff_Toggle( - &endpoint, [](CHIP_ERROR err) { TvCastingAppJNIMgr().getMediaCommandResponseHandler(OnOff_Toggle).Handle(err); }); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "CastingServer.OnOff_Toggle failed %" CHIP_ERROR_FORMAT, err.Format())); - -exit: - return (err == CHIP_NO_ERROR); -} - -JNI_METHOD(jboolean, messages_1presentMessages) -(JNIEnv * env, jobject, jobject contentApp, jstring messageText, jobject jResponseHandler) -{ - chip::DeviceLayer::StackLock lock; - - ChipLogProgress(AppServer, "JNI_METHOD messages_presentMessages called"); - const char * nativeMessageText = env->GetStringUTFChars(messageText, 0); - - TargetEndpointInfo endpoint; - CHIP_ERROR err = convertJContentAppToTargetEndpointInfo(contentApp, endpoint); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogError(AppServer, "Conversion from jobject contentApp to TargetEndpointInfo * failed: %" CHIP_ERROR_FORMAT, - err.Format())); - - err = TvCastingAppJNIMgr().getMediaCommandResponseHandler(Messages_PresentMessagesRequest).SetUp(env, jResponseHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "MatterCallbackHandlerJNI.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = CastingServer::GetInstance()->Messages_PresentMessagesRequest(&endpoint, nativeMessageText, [](CHIP_ERROR err) { - TvCastingAppJNIMgr().getMediaCommandResponseHandler(Messages_PresentMessagesRequest).Handle(err); - }); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "CastingServer.Messages_PresentMessagesRequest failed %" CHIP_ERROR_FORMAT, err.Format())); - - env->ReleaseStringUTFChars(messageText, nativeMessageText); - -exit: - return (err == CHIP_NO_ERROR); -} - -JNI_METHOD(jboolean, mediaPlayback_1play) -(JNIEnv * env, jobject, jobject contentApp, jobject jResponseHandler) -{ - chip::DeviceLayer::StackLock lock; - - ChipLogProgress(AppServer, "JNI_METHOD mediaPlayback_play called"); - - TargetEndpointInfo endpoint; - CHIP_ERROR err = convertJContentAppToTargetEndpointInfo(contentApp, endpoint); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogError(AppServer, "Conversion from jobject contentApp to TargetEndpointInfo * failed: %" CHIP_ERROR_FORMAT, - err.Format())); - - err = TvCastingAppJNIMgr().getMediaCommandResponseHandler(MediaPlayback_Play).SetUp(env, jResponseHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "MatterCallbackHandlerJNI.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = CastingServer::GetInstance()->MediaPlayback_Play( - &endpoint, [](CHIP_ERROR err) { TvCastingAppJNIMgr().getMediaCommandResponseHandler(MediaPlayback_Play).Handle(err); }); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "CastingServer.MediaPlayback_Play failed %" CHIP_ERROR_FORMAT, err.Format())); - -exit: - return (err == CHIP_NO_ERROR); -} - -JNI_METHOD(jboolean, mediaPlayback_1pause) -(JNIEnv * env, jobject, jobject contentApp, jobject jResponseHandler) -{ - chip::DeviceLayer::StackLock lock; - - ChipLogProgress(AppServer, "JNI_METHOD mediaPlayback_pause called"); - - TargetEndpointInfo endpoint; - CHIP_ERROR err = convertJContentAppToTargetEndpointInfo(contentApp, endpoint); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogError(AppServer, "Conversion from jobject contentApp to TargetEndpointInfo * failed: %" CHIP_ERROR_FORMAT, - err.Format())); - - err = TvCastingAppJNIMgr().getMediaCommandResponseHandler(MediaPlayback_Pause).SetUp(env, jResponseHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "MatterCallbackHandlerJNI.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = CastingServer::GetInstance()->MediaPlayback_Pause( - &endpoint, [](CHIP_ERROR err) { TvCastingAppJNIMgr().getMediaCommandResponseHandler(MediaPlayback_Pause).Handle(err); }); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "CastingServer.MediaPlayback_Pause failed %" CHIP_ERROR_FORMAT, err.Format())); - -exit: - return (err == CHIP_NO_ERROR); -} - -JNI_METHOD(jboolean, mediaPlayback_1stopPlayback) -(JNIEnv * env, jobject, jobject contentApp, jobject jResponseHandler) -{ - chip::DeviceLayer::StackLock lock; - - ChipLogProgress(AppServer, "JNI_METHOD mediaPlayback_stopPlayback called"); - - TargetEndpointInfo endpoint; - CHIP_ERROR err = convertJContentAppToTargetEndpointInfo(contentApp, endpoint); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogError(AppServer, "Conversion from jobject contentApp to TargetEndpointInfo * failed: %" CHIP_ERROR_FORMAT, - err.Format())); - - err = TvCastingAppJNIMgr().getMediaCommandResponseHandler(MediaPlayback_StopPlayback).SetUp(env, jResponseHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "MatterCallbackHandlerJNI.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = CastingServer::GetInstance()->MediaPlayback_StopPlayback(&endpoint, [](CHIP_ERROR err) { - TvCastingAppJNIMgr().getMediaCommandResponseHandler(MediaPlayback_StopPlayback).Handle(err); - }); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "CastingServer.MediaPlayback_StopPlayback failed %" CHIP_ERROR_FORMAT, err.Format())); - -exit: - return (err == CHIP_NO_ERROR); -} - -JNI_METHOD(jboolean, mediaPlayback_1next) -(JNIEnv * env, jobject, jobject contentApp, jobject jResponseHandler) -{ - chip::DeviceLayer::StackLock lock; - - ChipLogProgress(AppServer, "JNI_METHOD mediaPlayback_next called"); - - TargetEndpointInfo endpoint; - CHIP_ERROR err = convertJContentAppToTargetEndpointInfo(contentApp, endpoint); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogError(AppServer, "Conversion from jobject contentApp to TargetEndpointInfo * failed: %" CHIP_ERROR_FORMAT, - err.Format())); - - err = TvCastingAppJNIMgr().getMediaCommandResponseHandler(MediaPlayback_Next).SetUp(env, jResponseHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "MatterCallbackHandlerJNI.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = CastingServer::GetInstance()->MediaPlayback_Next( - &endpoint, [](CHIP_ERROR err) { TvCastingAppJNIMgr().getMediaCommandResponseHandler(MediaPlayback_Next).Handle(err); }); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "CastingServer.MediaPlayback_Next failed %" CHIP_ERROR_FORMAT, err.Format())); - -exit: - return (err == CHIP_NO_ERROR); -} - -JNI_METHOD(jboolean, mediaPlayback_1seek) -(JNIEnv * env, jobject, jobject contentApp, jlong position, jobject jResponseHandler) -{ - chip::DeviceLayer::StackLock lock; - - ChipLogProgress(AppServer, "JNI_METHOD mediaPlayback_seek called"); - - TargetEndpointInfo endpoint; - CHIP_ERROR err = convertJContentAppToTargetEndpointInfo(contentApp, endpoint); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogError(AppServer, "Conversion from jobject contentApp to TargetEndpointInfo * failed: %" CHIP_ERROR_FORMAT, - err.Format())); - - err = TvCastingAppJNIMgr().getMediaCommandResponseHandler(MediaPlayback_Seek).SetUp(env, jResponseHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "MatterCallbackHandlerJNI.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = CastingServer::GetInstance()->MediaPlayback_Seek(&endpoint, static_cast(position), [](CHIP_ERROR err) { - TvCastingAppJNIMgr().getMediaCommandResponseHandler(MediaPlayback_Seek).Handle(err); - }); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "CastingServer.MediaPlayback_Seek failed %" CHIP_ERROR_FORMAT, err.Format())); - -exit: - return (err == CHIP_NO_ERROR); -} - -JNI_METHOD(jboolean, mediaPlayback_1skipForward) -(JNIEnv * env, jobject, jobject contentApp, jlong deltaPositionMilliseconds, jobject jResponseHandler) -{ - chip::DeviceLayer::StackLock lock; - - ChipLogProgress(AppServer, "JNI_METHOD mediaPlayback_skipForward called"); - - TargetEndpointInfo endpoint; - CHIP_ERROR err = convertJContentAppToTargetEndpointInfo(contentApp, endpoint); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogError(AppServer, "Conversion from jobject contentApp to TargetEndpointInfo * failed: %" CHIP_ERROR_FORMAT, - err.Format())); - - err = TvCastingAppJNIMgr().getMediaCommandResponseHandler(MediaPlayback_SkipForward).SetUp(env, jResponseHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "MatterCallbackHandlerJNI.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = CastingServer::GetInstance()->MediaPlayback_SkipForward( - &endpoint, static_cast(deltaPositionMilliseconds), - [](CHIP_ERROR err) { TvCastingAppJNIMgr().getMediaCommandResponseHandler(MediaPlayback_SkipForward).Handle(err); }); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "CastingServer.MediaPlayback_SkipForward failed %" CHIP_ERROR_FORMAT, err.Format())); - -exit: - return (err == CHIP_NO_ERROR); -} - -JNI_METHOD(jboolean, mediaPlayback_1skipBackward) -(JNIEnv * env, jobject, jobject contentApp, jlong deltaPositionMilliseconds, jobject jResponseHandler) -{ - chip::DeviceLayer::StackLock lock; - - ChipLogProgress(AppServer, "JNI_METHOD mediaPlayback_skipBackward called"); - - TargetEndpointInfo endpoint; - CHIP_ERROR err = convertJContentAppToTargetEndpointInfo(contentApp, endpoint); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogError(AppServer, "Conversion from jobject contentApp to TargetEndpointInfo * failed: %" CHIP_ERROR_FORMAT, - err.Format())); - - err = TvCastingAppJNIMgr().getMediaCommandResponseHandler(MediaPlayback_SkipBackward).SetUp(env, jResponseHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "MatterCallbackHandlerJNI.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = CastingServer::GetInstance()->MediaPlayback_SkipBackward( - &endpoint, static_cast(deltaPositionMilliseconds), - [](CHIP_ERROR err) { TvCastingAppJNIMgr().getMediaCommandResponseHandler(MediaPlayback_SkipBackward).Handle(err); }); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "CastingServer.MediaPlayback_SkipBackward failed %" CHIP_ERROR_FORMAT, err.Format())); - -exit: - return (err == CHIP_NO_ERROR); -} - -JNI_METHOD(jboolean, mediaPlayback_1previous) -(JNIEnv * env, jobject, jobject contentApp, jobject jResponseHandler) -{ - return TvCastingAppJNIMgr().runCastingServerCommand( - env, contentApp, jResponseHandler, "MediaPlayback_Previous", MediaPlayback_Previous, - [](TargetEndpointInfo endpoint) -> CHIP_ERROR { - return CastingServer::GetInstance()->MediaPlayback_Previous(&endpoint, [](CHIP_ERROR err) { - TvCastingAppJNIMgr().getMediaCommandResponseHandler(MediaPlayback_Previous).Handle(err); - }); - }); -} - -JNI_METHOD(jboolean, mediaPlayback_1rewind) -(JNIEnv * env, jobject, jobject contentApp, jobject jResponseHandler) -{ - return TvCastingAppJNIMgr().runCastingServerCommand( - env, contentApp, jResponseHandler, "MediaPlayback_Rewind", MediaPlayback_Rewind, - [](TargetEndpointInfo endpoint) -> CHIP_ERROR { - return CastingServer::GetInstance()->MediaPlayback_Rewind(&endpoint, [](CHIP_ERROR err) { - TvCastingAppJNIMgr().getMediaCommandResponseHandler(MediaPlayback_Rewind).Handle(err); - }); - }); -} - -JNI_METHOD(jboolean, mediaPlayback_1fastForward) -(JNIEnv * env, jobject, jobject contentApp, jobject jResponseHandler) -{ - return TvCastingAppJNIMgr().runCastingServerCommand( - env, contentApp, jResponseHandler, "MediaPlayback_FastForward", MediaPlayback_FastForward, - [](TargetEndpointInfo endpoint) -> CHIP_ERROR { - return CastingServer::GetInstance()->MediaPlayback_FastForward(&endpoint, [](CHIP_ERROR err) { - TvCastingAppJNIMgr().getMediaCommandResponseHandler(MediaPlayback_FastForward).Handle(err); - }); - }); -} - -JNI_METHOD(jboolean, mediaPlayback_1startOver) -(JNIEnv * env, jobject, jobject contentApp, jobject jResponseHandler) -{ - return TvCastingAppJNIMgr().runCastingServerCommand( - env, contentApp, jResponseHandler, "MediaPlayback_StartOver", MediaPlayback_StartOver, - [](TargetEndpointInfo endpoint) -> CHIP_ERROR { - return CastingServer::GetInstance()->MediaPlayback_StartOver(&endpoint, [](CHIP_ERROR err) { - TvCastingAppJNIMgr().getMediaCommandResponseHandler(MediaPlayback_StartOver).Handle(err); - }); - }); -} - -jboolean TvCastingAppJNI::runCastingServerCommand(JNIEnv * env, jobject contentApp, jobject jResponseHandler, - const char * commandName, MediaCommandName command, - const std::function & commandRunner) -{ - chip::DeviceLayer::StackLock lock; - - ChipLogProgress(AppServer, "JNI_METHOD %s called", commandName); - - TargetEndpointInfo endpoint; - CHIP_ERROR err = convertJContentAppToTargetEndpointInfo(contentApp, endpoint); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogError(AppServer, "Conversion from jobject contentApp to TargetEndpointInfo * failed: %" CHIP_ERROR_FORMAT, - err.Format())); - - err = TvCastingAppJNIMgr().getMediaCommandResponseHandler(command).SetUp(env, jResponseHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "MatterCallbackHandlerJNI.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = commandRunner(endpoint); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "CastingServer.%s failed %" CHIP_ERROR_FORMAT, commandName, err.Format())); - -exit: - return (err == CHIP_NO_ERROR); -} - -JNI_METHOD(jboolean, mediaPlayback_1subscribeToCurrentState) -(JNIEnv * env, jobject, jobject contentApp, jobject jReadSuccessHandler, jobject jReadFailureHandler, jint minInterval, - jint maxInterval, jobject jSubscriptionEstablishedHandler) -{ - chip::DeviceLayer::StackLock lock; - - ChipLogProgress(AppServer, "JNI_METHOD mediaPlayback_subscribeToCurrentState called"); - - TargetEndpointInfo endpoint; - CHIP_ERROR err = convertJContentAppToTargetEndpointInfo(contentApp, endpoint); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogError(AppServer, "Conversion from jobject contentApp to TargetEndpointInfo * failed: %" CHIP_ERROR_FORMAT, - err.Format())); - - err = TvCastingAppJNIMgr().getCurrentStateSuccessHandler().SetUp(env, jReadSuccessHandler); - VerifyOrExit(CHIP_NO_ERROR == err, ChipLogError(AppServer, "SuccessHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = TvCastingAppJNIMgr().getSubscriptionReadFailureHandler(MediaPlayback_CurrentState).SetUp(env, jReadFailureHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "SubscriptionReadFailureHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = TvCastingAppJNIMgr() - .getSubscriptionEstablishedHandler(MediaPlayback_CurrentState) - .SetUp(env, jSubscriptionEstablishedHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "SubscriptionEstablishedHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = CastingServer::GetInstance()->MediaPlayback_SubscribeToCurrentState( - &endpoint, nullptr, - [](void * context, chip::app::Clusters::MediaPlayback::Attributes::CurrentState::TypeInfo::DecodableArgType responseData) { - TvCastingAppJNIMgr().getCurrentStateSuccessHandler().Handle(responseData); - }, - [](void * context, CHIP_ERROR err) { - TvCastingAppJNIMgr().getSubscriptionReadFailureHandler(MediaPlayback_CurrentState).Handle(err); - }, - static_cast(minInterval), static_cast(maxInterval), - [](void * context, chip::SubscriptionId) { - TvCastingAppJNIMgr().getSubscriptionEstablishedHandler(MediaPlayback_CurrentState).Handle(); - }); - - VerifyOrExit( - CHIP_NO_ERROR == err, - ChipLogError(AppServer, "CastingServer.MediaPlayback_SubscribeToCurrentState failed %" CHIP_ERROR_FORMAT, err.Format())); - -exit: - return (err == CHIP_NO_ERROR); -} - -JNI_METHOD(jboolean, mediaPlayback_1subscribeToDuration) -(JNIEnv * env, jobject, jobject contentApp, jobject jReadSuccessHandler, jobject jReadFailureHandler, jint minInterval, - jint maxInterval, jobject jSubscriptionEstablishedHandler) -{ - chip::DeviceLayer::StackLock lock; - - ChipLogProgress(AppServer, "JNI_METHOD mediaPlayback_1subscribeToDuration called"); - - TargetEndpointInfo endpoint; - CHIP_ERROR err = convertJContentAppToTargetEndpointInfo(contentApp, endpoint); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogError(AppServer, "Conversion from jobject contentApp to TargetEndpointInfo * failed: %" CHIP_ERROR_FORMAT, - err.Format())); - - err = TvCastingAppJNIMgr().getDurationSuccessHandler().SetUp(env, jReadSuccessHandler); - VerifyOrExit(CHIP_NO_ERROR == err, ChipLogError(AppServer, "SuccessHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = TvCastingAppJNIMgr().getSubscriptionReadFailureHandler(MediaPlayback_Duration).SetUp(env, jReadFailureHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "SubscriptionReadFailureHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = - TvCastingAppJNIMgr().getSubscriptionEstablishedHandler(MediaPlayback_Duration).SetUp(env, jSubscriptionEstablishedHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "SubscriptionEstablishedHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = CastingServer::GetInstance()->MediaPlayback_SubscribeToDuration( - &endpoint, nullptr, - [](void * context, chip::app::Clusters::MediaPlayback::Attributes::Duration::TypeInfo::DecodableArgType responseData) { - TvCastingAppJNIMgr().getDurationSuccessHandler().Handle(responseData); - }, - [](void * context, CHIP_ERROR err) { - TvCastingAppJNIMgr().getSubscriptionReadFailureHandler(MediaPlayback_Duration).Handle(err); - }, - static_cast(minInterval), static_cast(maxInterval), - [](void * context, chip::SubscriptionId) { - TvCastingAppJNIMgr().getSubscriptionEstablishedHandler(MediaPlayback_Duration).Handle(); - }); - - VerifyOrExit( - CHIP_NO_ERROR == err, - ChipLogError(AppServer, "CastingServer.mediaPlayback_subscribeToDuration failed %" CHIP_ERROR_FORMAT, err.Format())); - -exit: - return (err == CHIP_NO_ERROR); -} - -JNI_METHOD(jboolean, mediaPlayback_1subscribeToSampledPosition) -(JNIEnv * env, jobject, jobject contentApp, jobject jReadSuccessHandler, jobject jReadFailureHandler, jint minInterval, - jint maxInterval, jobject jSubscriptionEstablishedHandler) -{ - chip::DeviceLayer::StackLock lock; - - ChipLogProgress(AppServer, "JNI_METHOD mediaPlayback_1subscribeToSampledPosition called"); - - TargetEndpointInfo endpoint; - CHIP_ERROR err = convertJContentAppToTargetEndpointInfo(contentApp, endpoint); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogError(AppServer, "Conversion from jobject contentApp to TargetEndpointInfo * failed: %" CHIP_ERROR_FORMAT, - err.Format())); - - err = TvCastingAppJNIMgr().getSampledPositionSuccessHandler().SetUp(env, jReadSuccessHandler); - VerifyOrExit(CHIP_NO_ERROR == err, ChipLogError(AppServer, "SuccessHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = TvCastingAppJNIMgr().getSubscriptionReadFailureHandler(MediaPlayback_SampledPosition).SetUp(env, jReadFailureHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "SubscriptionReadFailureHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = TvCastingAppJNIMgr() - .getSubscriptionEstablishedHandler(MediaPlayback_SampledPosition) - .SetUp(env, jSubscriptionEstablishedHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "SubscriptionEstablishedHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = CastingServer::GetInstance()->MediaPlayback_SubscribeToSampledPosition( - &endpoint, nullptr, - [](void * context, - chip::app::Clusters::MediaPlayback::Attributes::SampledPosition::TypeInfo::DecodableArgType responseData) { - TvCastingAppJNIMgr().getSampledPositionSuccessHandler().Handle(responseData); - }, - [](void * context, CHIP_ERROR err) { - TvCastingAppJNIMgr().getSubscriptionReadFailureHandler(MediaPlayback_SampledPosition).Handle(err); - }, - static_cast(minInterval), static_cast(maxInterval), - [](void * context, chip::SubscriptionId) { - TvCastingAppJNIMgr().getSubscriptionEstablishedHandler(MediaPlayback_SampledPosition).Handle(); - }); - - VerifyOrExit( - CHIP_NO_ERROR == err, - ChipLogError(AppServer, "CastingServer.mediaPlayback_subscribeToSampledPosition failed %" CHIP_ERROR_FORMAT, err.Format())); - -exit: - return (err == CHIP_NO_ERROR); -} - -JNI_METHOD(jboolean, mediaPlayback_1subscribeToPlaybackSpeed) -(JNIEnv * env, jobject, jobject contentApp, jobject jReadSuccessHandler, jobject jReadFailureHandler, jint minInterval, - jint maxInterval, jobject jSubscriptionEstablishedHandler) -{ - chip::DeviceLayer::StackLock lock; - - ChipLogProgress(AppServer, "JNI_METHOD mediaPlayback_1subscribeToPlaybackSpeed called"); - - TargetEndpointInfo endpoint; - CHIP_ERROR err = convertJContentAppToTargetEndpointInfo(contentApp, endpoint); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogError(AppServer, "Conversion from jobject contentApp to TargetEndpointInfo * failed: %" CHIP_ERROR_FORMAT, - err.Format())); - - err = TvCastingAppJNIMgr().getPlaybackSpeedSuccessHandler().SetUp(env, jReadSuccessHandler); - VerifyOrExit(CHIP_NO_ERROR == err, ChipLogError(AppServer, "SuccessHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = TvCastingAppJNIMgr().getSubscriptionReadFailureHandler(MediaPlayback_PlaybackSpeed).SetUp(env, jReadFailureHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "SubscriptionReadFailureHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = TvCastingAppJNIMgr() - .getSubscriptionEstablishedHandler(MediaPlayback_PlaybackSpeed) - .SetUp(env, jSubscriptionEstablishedHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "SubscriptionEstablishedHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = CastingServer::GetInstance()->MediaPlayback_SubscribeToPlaybackSpeed( - &endpoint, nullptr, - [](void * context, chip::app::Clusters::MediaPlayback::Attributes::PlaybackSpeed::TypeInfo::DecodableArgType responseData) { - TvCastingAppJNIMgr().getPlaybackSpeedSuccessHandler().Handle(responseData); - }, - [](void * context, CHIP_ERROR err) { - TvCastingAppJNIMgr().getSubscriptionReadFailureHandler(MediaPlayback_PlaybackSpeed).Handle(err); - }, - static_cast(minInterval), static_cast(maxInterval), - [](void * context, chip::SubscriptionId) { - TvCastingAppJNIMgr().getSubscriptionEstablishedHandler(MediaPlayback_PlaybackSpeed).Handle(); - }); - - VerifyOrExit( - CHIP_NO_ERROR == err, - ChipLogError(AppServer, "CastingServer.mediaPlayback_subscribeToPlaybackSpeed failed %" CHIP_ERROR_FORMAT, err.Format())); - -exit: - return (err == CHIP_NO_ERROR); -} - -JNI_METHOD(jboolean, mediaPlayback_1subscribeToSeekRangeEnd) -(JNIEnv * env, jobject, jobject contentApp, jobject jReadSuccessHandler, jobject jReadFailureHandler, jint minInterval, - jint maxInterval, jobject jSubscriptionEstablishedHandler) -{ - chip::DeviceLayer::StackLock lock; - - ChipLogProgress(AppServer, "JNI_METHOD mediaPlayback_1subscribeToSeekRangeEnd called"); - - TargetEndpointInfo endpoint; - CHIP_ERROR err = convertJContentAppToTargetEndpointInfo(contentApp, endpoint); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogError(AppServer, "Conversion from jobject contentApp to TargetEndpointInfo * failed: %" CHIP_ERROR_FORMAT, - err.Format())); - - err = TvCastingAppJNIMgr().getSeekRangeEndSuccessHandler().SetUp(env, jReadSuccessHandler); - VerifyOrExit(CHIP_NO_ERROR == err, ChipLogError(AppServer, "SuccessHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = TvCastingAppJNIMgr().getSubscriptionReadFailureHandler(MediaPlayback_SeekRangeEnd).SetUp(env, jReadFailureHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "SubscriptionReadFailureHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = TvCastingAppJNIMgr() - .getSubscriptionEstablishedHandler(MediaPlayback_SeekRangeEnd) - .SetUp(env, jSubscriptionEstablishedHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "SubscriptionEstablishedHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = CastingServer::GetInstance()->MediaPlayback_SubscribeToSeekRangeEnd( - &endpoint, nullptr, - [](void * context, chip::app::Clusters::MediaPlayback::Attributes::SeekRangeEnd::TypeInfo::DecodableArgType responseData) { - TvCastingAppJNIMgr().getSeekRangeEndSuccessHandler().Handle(responseData); - }, - [](void * context, CHIP_ERROR err) { - TvCastingAppJNIMgr().getSubscriptionReadFailureHandler(MediaPlayback_SeekRangeEnd).Handle(err); - }, - static_cast(minInterval), static_cast(maxInterval), - [](void * context, chip::SubscriptionId) { - TvCastingAppJNIMgr().getSubscriptionEstablishedHandler(MediaPlayback_SeekRangeEnd).Handle(); - }); - - VerifyOrExit( - CHIP_NO_ERROR == err, - ChipLogError(AppServer, "CastingServer.mediaPlayback_subscribeToSeekRangeEnd failed %" CHIP_ERROR_FORMAT, err.Format())); - -exit: - return (err == CHIP_NO_ERROR); -} - -JNI_METHOD(jboolean, mediaPlayback_1subscribeToSeekRangeStart) -(JNIEnv * env, jobject, jobject contentApp, jobject jReadSuccessHandler, jobject jReadFailureHandler, jint minInterval, - jint maxInterval, jobject jSubscriptionEstablishedHandler) -{ - chip::DeviceLayer::StackLock lock; - - ChipLogProgress(AppServer, "JNI_METHOD mediaPlayback_1subscribeToSeekRangeStart called"); - - TargetEndpointInfo endpoint; - CHIP_ERROR err = convertJContentAppToTargetEndpointInfo(contentApp, endpoint); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogError(AppServer, "Conversion from jobject contentApp to TargetEndpointInfo * failed: %" CHIP_ERROR_FORMAT, - err.Format())); - - err = TvCastingAppJNIMgr().getSeekRangeStartSuccessHandler().SetUp(env, jReadSuccessHandler); - VerifyOrExit(CHIP_NO_ERROR == err, ChipLogError(AppServer, "SuccessHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = TvCastingAppJNIMgr().getSubscriptionReadFailureHandler(MediaPlayback_SeekRangeStart).SetUp(env, jReadFailureHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "SubscriptionReadFailureHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = TvCastingAppJNIMgr() - .getSubscriptionEstablishedHandler(MediaPlayback_SeekRangeStart) - .SetUp(env, jSubscriptionEstablishedHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "SubscriptionEstablishedHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = CastingServer::GetInstance()->MediaPlayback_SubscribeToSeekRangeStart( - &endpoint, nullptr, - [](void * context, - chip::app::Clusters::MediaPlayback::Attributes::SeekRangeStart::TypeInfo::DecodableArgType responseData) { - TvCastingAppJNIMgr().getSeekRangeStartSuccessHandler().Handle(responseData); - }, - [](void * context, CHIP_ERROR err) { - TvCastingAppJNIMgr().getSubscriptionReadFailureHandler(MediaPlayback_SeekRangeStart).Handle(err); - }, - static_cast(minInterval), static_cast(maxInterval), - [](void * context, chip::SubscriptionId) { - TvCastingAppJNIMgr().getSubscriptionEstablishedHandler(MediaPlayback_SeekRangeStart).Handle(); - }); - - VerifyOrExit( - CHIP_NO_ERROR == err, - ChipLogError(AppServer, "CastingServer.mediaPlayback_subscribeToSeekRangeStart failed %" CHIP_ERROR_FORMAT, err.Format())); - -exit: - return (err == CHIP_NO_ERROR); -} - -JNI_METHOD(jboolean, applicationLauncher_1launchApp) -(JNIEnv * env, jobject, jobject contentApp, jshort catalogVendorId, jstring applicationId, jbyteArray data, - jobject jResponseHandler) -{ - chip::DeviceLayer::StackLock lock; - - ChipLogProgress(AppServer, "JNI_METHOD applicationLauncher_launchApp called"); - - chip::app::Clusters::ApplicationLauncher::Structs::ApplicationStruct::Type application; - application.catalogVendorID = static_cast(catalogVendorId); - const char * nativeApplicationId = env->GetStringUTFChars(applicationId, 0); - application.applicationID = CharSpan::fromCharString(nativeApplicationId); - JniByteArray dataByteArray(env, data); - - TargetEndpointInfo endpoint; - CHIP_ERROR err = convertJContentAppToTargetEndpointInfo(contentApp, endpoint); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogError(AppServer, "Conversion from jobject contentApp to TargetEndpointInfo * failed: %" CHIP_ERROR_FORMAT, - err.Format())); - - err = TvCastingAppJNIMgr().getMediaCommandResponseHandler(ApplicationLauncher_LaunchApp).SetUp(env, jResponseHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "MatterCallbackHandlerJNI.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = CastingServer::GetInstance()->ApplicationLauncher_LaunchApp( - &endpoint, application, chip::MakeOptional(dataByteArray.byteSpan()), - [](CHIP_ERROR err) { TvCastingAppJNIMgr().getMediaCommandResponseHandler(ApplicationLauncher_LaunchApp).Handle(err); }); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "CastingServer.ApplicationLauncher_LaunchApp failed %" CHIP_ERROR_FORMAT, err.Format())); - - env->ReleaseStringUTFChars(applicationId, nativeApplicationId); -exit: - return (err == CHIP_NO_ERROR); -} - -JNI_METHOD(jboolean, applicationLauncher_1stopApp) -(JNIEnv * env, jobject, jobject contentApp, jshort catalogVendorId, jstring applicationId, jobject jResponseHandler) -{ - chip::DeviceLayer::StackLock lock; - - ChipLogProgress(AppServer, "JNI_METHOD applicationLauncher_stopApp called"); - - chip::app::Clusters::ApplicationLauncher::Structs::ApplicationStruct::Type application; - application.catalogVendorID = static_cast(catalogVendorId); - const char * nativeApplicationId = env->GetStringUTFChars(applicationId, 0); - application.applicationID = CharSpan::fromCharString(nativeApplicationId); - - TargetEndpointInfo endpoint; - CHIP_ERROR err = convertJContentAppToTargetEndpointInfo(contentApp, endpoint); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogError(AppServer, "Conversion from jobject contentApp to TargetEndpointInfo * failed: %" CHIP_ERROR_FORMAT, - err.Format())); - - err = TvCastingAppJNIMgr().getMediaCommandResponseHandler(ApplicationLauncher_StopApp).SetUp(env, jResponseHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "MatterCallbackHandlerJNI.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = CastingServer::GetInstance()->ApplicationLauncher_StopApp(&endpoint, application, [&](CHIP_ERROR err) { - TvCastingAppJNIMgr().getMediaCommandResponseHandler(ApplicationLauncher_StopApp).Handle(err); - }); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "CastingServer.ApplicationLauncher_StopApp failed %" CHIP_ERROR_FORMAT, err.Format())); - - env->ReleaseStringUTFChars(applicationId, nativeApplicationId); -exit: - return (err == CHIP_NO_ERROR); -} - -JNI_METHOD(jboolean, applicationLauncher_1hideApp) -(JNIEnv * env, jobject, jobject contentApp, jshort catalogVendorId, jstring applicationId, jobject jResponseHandler) -{ - chip::DeviceLayer::StackLock lock; - - ChipLogProgress(AppServer, "JNI_METHOD applicationLauncher_hideApp called"); - - chip::app::Clusters::ApplicationLauncher::Structs::ApplicationStruct::Type application; - application.catalogVendorID = static_cast(catalogVendorId); - const char * nativeApplicationId = env->GetStringUTFChars(applicationId, 0); - application.applicationID = CharSpan::fromCharString(nativeApplicationId); - - TargetEndpointInfo endpoint; - CHIP_ERROR err = convertJContentAppToTargetEndpointInfo(contentApp, endpoint); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogError(AppServer, "Conversion from jobject contentApp to TargetEndpointInfo * failed: %" CHIP_ERROR_FORMAT, - err.Format())); - - err = TvCastingAppJNIMgr().getMediaCommandResponseHandler(ApplicationLauncher_HideApp).SetUp(env, jResponseHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "MatterCallbackHandlerJNI.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = CastingServer::GetInstance()->ApplicationLauncher_HideApp(&endpoint, application, [](CHIP_ERROR err) { - TvCastingAppJNIMgr().getMediaCommandResponseHandler(ApplicationLauncher_HideApp).Handle(err); - }); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "CastingServer.ApplicationLauncher_HideApp failed %" CHIP_ERROR_FORMAT, err.Format())); - - env->ReleaseStringUTFChars(applicationId, nativeApplicationId); -exit: - return (err == CHIP_NO_ERROR); -} - -JNI_METHOD(jboolean, targetNavigator_1navigateTarget) -(JNIEnv * env, jobject, jobject contentApp, jbyte target, jstring data, jobject jResponseHandler) -{ - chip::DeviceLayer::StackLock lock; - - ChipLogProgress(AppServer, "JNI_METHOD targetNavigator_navigateTarget called"); - - const char * nativeData = (data != nullptr ? env->GetStringUTFChars(data, 0) : nullptr); - - TargetEndpointInfo endpoint; - CHIP_ERROR err = convertJContentAppToTargetEndpointInfo(contentApp, endpoint); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogError(AppServer, "Conversion from jobject contentApp to TargetEndpointInfo * failed: %" CHIP_ERROR_FORMAT, - err.Format())); - - err = TvCastingAppJNIMgr().getMediaCommandResponseHandler(TargetNavigator_NavigateTarget).SetUp(env, jResponseHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "MatterCallbackHandlerJNI.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = CastingServer::GetInstance()->TargetNavigator_NavigateTarget( - &endpoint, static_cast(target), - (nativeData != nullptr ? chip::MakeOptional(CharSpan::fromCharString(nativeData)) : chip::NullOptional), - [](CHIP_ERROR err) { TvCastingAppJNIMgr().getMediaCommandResponseHandler(TargetNavigator_NavigateTarget).Handle(err); }); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "CastingServer.TargetNavigator_NavigateTarget failed %" CHIP_ERROR_FORMAT, err.Format())); - - if (nativeData != nullptr) - { - env->ReleaseStringUTFChars(data, nativeData); - } -exit: - return (err == CHIP_NO_ERROR); -} - -JNI_METHOD(jboolean, targetNavigator_1subscribeToCurrentTarget) -(JNIEnv * env, jobject, jobject contentApp, jobject jReadSuccessHandler, jobject jReadFailureHandler, jint minInterval, - jint maxInterval, jobject jSubscriptionEstablishedHandler) -{ - chip::DeviceLayer::StackLock lock; - - ChipLogProgress(AppServer, "JNI_METHOD targetNavigator_1subscribeToCurrentTarget called"); - - TargetEndpointInfo endpoint; - CHIP_ERROR err = convertJContentAppToTargetEndpointInfo(contentApp, endpoint); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogError(AppServer, "Conversion from jobject contentApp to TargetEndpointInfo * failed: %" CHIP_ERROR_FORMAT, - err.Format())); - - err = TvCastingAppJNIMgr().getCurrentTargetSuccessHandler().SetUp(env, jReadSuccessHandler); - VerifyOrExit(CHIP_NO_ERROR == err, ChipLogError(AppServer, "SuccessHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = TvCastingAppJNIMgr().getSubscriptionReadFailureHandler(TargetNavigator_CurrentTarget).SetUp(env, jReadFailureHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "SubscriptionReadFailureHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = TvCastingAppJNIMgr() - .getSubscriptionEstablishedHandler(TargetNavigator_CurrentTarget) - .SetUp(env, jSubscriptionEstablishedHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "SubscriptionEstablishedHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = CastingServer::GetInstance()->TargetNavigator_SubscribeToCurrentTarget( - &endpoint, nullptr, - [](void * context, - chip::app::Clusters::TargetNavigator::Attributes::CurrentTarget::TypeInfo::DecodableArgType responseData) { - TvCastingAppJNIMgr().getCurrentTargetSuccessHandler().Handle(responseData); - }, - [](void * context, CHIP_ERROR err) { - TvCastingAppJNIMgr().getSubscriptionReadFailureHandler(TargetNavigator_CurrentTarget).Handle(err); - }, - static_cast(minInterval), static_cast(maxInterval), - [](void * context, chip::SubscriptionId) { - TvCastingAppJNIMgr().getSubscriptionEstablishedHandler(TargetNavigator_CurrentTarget).Handle(); - }); - - VerifyOrExit( - CHIP_NO_ERROR == err, - ChipLogError(AppServer, "CastingServer.targetNavigator_subscribeToCurrentTarget failed %" CHIP_ERROR_FORMAT, err.Format())); - -exit: - return (err == CHIP_NO_ERROR); -} - -JNI_METHOD(jboolean, targetNavigator_1subscribeToTargetList) -(JNIEnv * env, jobject, jobject contentApp, jobject jReadSuccessHandler, jobject jReadFailureHandler, jint minInterval, - jint maxInterval, jobject jSubscriptionEstablishedHandler) -{ - chip::DeviceLayer::StackLock lock; - - ChipLogProgress(AppServer, "JNI_METHOD targetNavigator_1subscribeToTargetList called"); - - TargetEndpointInfo endpoint; - CHIP_ERROR err = convertJContentAppToTargetEndpointInfo(contentApp, endpoint); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogError(AppServer, "Conversion from jobject contentApp to TargetEndpointInfo * failed: %" CHIP_ERROR_FORMAT, - err.Format())); - - err = TvCastingAppJNIMgr().getTargetListSuccessHandler().SetUp(env, jReadSuccessHandler); - VerifyOrExit(CHIP_NO_ERROR == err, ChipLogError(AppServer, "SuccessHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = TvCastingAppJNIMgr().getSubscriptionReadFailureHandler(TargetNavigator_TargetList).SetUp(env, jReadFailureHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "SubscriptionReadFailureHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = TvCastingAppJNIMgr() - .getSubscriptionEstablishedHandler(TargetNavigator_TargetList) - .SetUp(env, jSubscriptionEstablishedHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "SubscriptionEstablishedHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = CastingServer::GetInstance()->TargetNavigator_SubscribeToTargetList( - &endpoint, nullptr, - [](void * context, chip::app::Clusters::TargetNavigator::Attributes::TargetList::TypeInfo::DecodableArgType responseData) { - TvCastingAppJNIMgr().getTargetListSuccessHandler().Handle(responseData); - }, - [](void * context, CHIP_ERROR err) { - TvCastingAppJNIMgr().getSubscriptionReadFailureHandler(TargetNavigator_TargetList).Handle(err); - }, - static_cast(minInterval), static_cast(maxInterval), - [](void * context, chip::SubscriptionId) { - TvCastingAppJNIMgr().getSubscriptionEstablishedHandler(TargetNavigator_TargetList).Handle(); - }); - - VerifyOrExit( - CHIP_NO_ERROR == err, - ChipLogError(AppServer, "CastingServer.targetNavigator_subscribeToTargetList failed %" CHIP_ERROR_FORMAT, err.Format())); - -exit: - return (err == CHIP_NO_ERROR); -} - -JNI_METHOD(jboolean, keypadInput_1sendKey) -(JNIEnv * env, jobject, jobject contentApp, jbyte keyCode, jobject jResponseHandler) -{ - chip::DeviceLayer::StackLock lock; - - ChipLogProgress(AppServer, "JNI_METHOD keypadInput_sendKey called"); - - TargetEndpointInfo endpoint; - CHIP_ERROR err = convertJContentAppToTargetEndpointInfo(contentApp, endpoint); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogError(AppServer, "Conversion from jobject contentApp to TargetEndpointInfo * failed: %" CHIP_ERROR_FORMAT, - err.Format())); - - err = TvCastingAppJNIMgr().getMediaCommandResponseHandler(KeypadInput_SendKey).SetUp(env, jResponseHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "MatterCallbackHandlerJNI.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = CastingServer::GetInstance()->KeypadInput_SendKey( - &endpoint, static_cast(keyCode), - [](CHIP_ERROR err) { TvCastingAppJNIMgr().getMediaCommandResponseHandler(KeypadInput_SendKey).Handle(err); }); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "CastingServer.KeypadInput_SendKey failed %" CHIP_ERROR_FORMAT, err.Format())); - -exit: - return (err == CHIP_NO_ERROR); -} - -// APPLICATION BASIC -JNI_METHOD(jboolean, applicationBasic_1subscribeToVendorName) -(JNIEnv * env, jobject, jobject contentApp, jobject jReadSuccessHandler, jobject jReadFailureHandler, jint minInterval, - jint maxInterval, jobject jSubscriptionEstablishedHandler) -{ - chip::DeviceLayer::StackLock lock; - - ChipLogProgress(AppServer, "JNI_METHOD applicationBasic_1subscribeToVendorName called"); - - TargetEndpointInfo endpoint; - CHIP_ERROR err = convertJContentAppToTargetEndpointInfo(contentApp, endpoint); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogError(AppServer, "Conversion from jobject contentApp to TargetEndpointInfo * failed: %" CHIP_ERROR_FORMAT, - err.Format())); - - err = TvCastingAppJNIMgr().getVendorNameSuccessHandler().SetUp(env, jReadSuccessHandler); - VerifyOrExit(CHIP_NO_ERROR == err, ChipLogError(AppServer, "SuccessHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = TvCastingAppJNIMgr().getSubscriptionReadFailureHandler(ApplicationBasic_VendorName).SetUp(env, jReadFailureHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "SubscriptionReadFailureHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = TvCastingAppJNIMgr() - .getSubscriptionEstablishedHandler(ApplicationBasic_VendorName) - .SetUp(env, jSubscriptionEstablishedHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "SubscriptionEstablishedHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = CastingServer::GetInstance()->ApplicationBasic_SubscribeToVendorName( - &endpoint, nullptr, - [](void * context, chip::app::Clusters::ApplicationBasic::Attributes::VendorName::TypeInfo::DecodableArgType responseData) { - TvCastingAppJNIMgr().getVendorNameSuccessHandler().Handle(responseData); - }, - [](void * context, CHIP_ERROR err) { - TvCastingAppJNIMgr().getSubscriptionReadFailureHandler(ApplicationBasic_VendorName).Handle(err); - }, - static_cast(minInterval), static_cast(maxInterval), - [](void * context, chip::SubscriptionId) { - TvCastingAppJNIMgr().getSubscriptionEstablishedHandler(ApplicationBasic_VendorName).Handle(); - }); - - VerifyOrExit( - CHIP_NO_ERROR == err, - ChipLogError(AppServer, "CastingServer.applicationBasic_subscribeToVendorName failed %" CHIP_ERROR_FORMAT, err.Format())); - -exit: - return (err == CHIP_NO_ERROR); -} - -JNI_METHOD(jboolean, applicationBasic_1subscribeToVendorID) -(JNIEnv * env, jobject, jobject contentApp, jobject jReadSuccessHandler, jobject jReadFailureHandler, jint minInterval, - jint maxInterval, jobject jSubscriptionEstablishedHandler) -{ - chip::DeviceLayer::StackLock lock; - - ChipLogProgress(AppServer, "JNI_METHOD applicationBasic_1subscribeToVendorID called"); - - TargetEndpointInfo endpoint; - CHIP_ERROR err = convertJContentAppToTargetEndpointInfo(contentApp, endpoint); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogError(AppServer, "Conversion from jobject contentApp to TargetEndpointInfo * failed: %" CHIP_ERROR_FORMAT, - err.Format())); - - err = TvCastingAppJNIMgr().getVendorIDSuccessHandler().SetUp(env, jReadSuccessHandler); - VerifyOrExit(CHIP_NO_ERROR == err, ChipLogError(AppServer, "SuccessHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = TvCastingAppJNIMgr().getSubscriptionReadFailureHandler(ApplicationBasic_VendorID).SetUp(env, jReadFailureHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "SubscriptionReadFailureHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = TvCastingAppJNIMgr() - .getSubscriptionEstablishedHandler(ApplicationBasic_VendorID) - .SetUp(env, jSubscriptionEstablishedHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "SubscriptionEstablishedHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = CastingServer::GetInstance()->ApplicationBasic_SubscribeToVendorID( - &endpoint, nullptr, - [](void * context, chip::app::Clusters::ApplicationBasic::Attributes::VendorID::TypeInfo::DecodableArgType responseData) { - TvCastingAppJNIMgr().getVendorIDSuccessHandler().Handle(responseData); - }, - [](void * context, CHIP_ERROR err) { - TvCastingAppJNIMgr().getSubscriptionReadFailureHandler(ApplicationBasic_VendorID).Handle(err); - }, - static_cast(minInterval), static_cast(maxInterval), - [](void * context, chip::SubscriptionId) { - TvCastingAppJNIMgr().getSubscriptionEstablishedHandler(ApplicationBasic_VendorID).Handle(); - }); - - VerifyOrExit( - CHIP_NO_ERROR == err, - ChipLogError(AppServer, "CastingServer.applicationBasic_subscribeToVendorID failed %" CHIP_ERROR_FORMAT, err.Format())); - -exit: - return (err == CHIP_NO_ERROR); -} - -JNI_METHOD(jboolean, applicationBasic_1subscribeToApplicationName) -(JNIEnv * env, jobject, jobject contentApp, jobject jReadSuccessHandler, jobject jReadFailureHandler, jint minInterval, - jint maxInterval, jobject jSubscriptionEstablishedHandler) -{ - chip::DeviceLayer::StackLock lock; - - ChipLogProgress(AppServer, "JNI_METHOD applicationBasic_1subscribeToApplicationName called"); - - TargetEndpointInfo endpoint; - CHIP_ERROR err = convertJContentAppToTargetEndpointInfo(contentApp, endpoint); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogError(AppServer, "Conversion from jobject contentApp to TargetEndpointInfo * failed: %" CHIP_ERROR_FORMAT, - err.Format())); - - err = TvCastingAppJNIMgr().getApplicationNameSuccessHandler().SetUp(env, jReadSuccessHandler); - VerifyOrExit(CHIP_NO_ERROR == err, ChipLogError(AppServer, "SuccessHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = TvCastingAppJNIMgr().getSubscriptionReadFailureHandler(ApplicationBasic_ApplicationName).SetUp(env, jReadFailureHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "SubscriptionReadFailureHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = TvCastingAppJNIMgr() - .getSubscriptionEstablishedHandler(ApplicationBasic_ApplicationName) - .SetUp(env, jSubscriptionEstablishedHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "SubscriptionEstablishedHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = CastingServer::GetInstance()->ApplicationBasic_SubscribeToApplicationName( - &endpoint, nullptr, - [](void * context, - chip::app::Clusters::ApplicationBasic::Attributes::ApplicationName::TypeInfo::DecodableArgType responseData) { - TvCastingAppJNIMgr().getApplicationNameSuccessHandler().Handle(responseData); - }, - [](void * context, CHIP_ERROR err) { - TvCastingAppJNIMgr().getSubscriptionReadFailureHandler(ApplicationBasic_ApplicationName).Handle(err); - }, - static_cast(minInterval), static_cast(maxInterval), - [](void * context, chip::SubscriptionId) { - TvCastingAppJNIMgr().getSubscriptionEstablishedHandler(ApplicationBasic_ApplicationName).Handle(); - }); - - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "CastingServer.applicationBasic_subscribeToApplicationName failed %" CHIP_ERROR_FORMAT, - err.Format())); - -exit: - return (err == CHIP_NO_ERROR); -} - -JNI_METHOD(jboolean, applicationBasic_1subscribeToProductID) -(JNIEnv * env, jobject, jobject contentApp, jobject jReadSuccessHandler, jobject jReadFailureHandler, jint minInterval, - jint maxInterval, jobject jSubscriptionEstablishedHandler) -{ - chip::DeviceLayer::StackLock lock; - - ChipLogProgress(AppServer, "JNI_METHOD applicationBasic_1subscribeToProductID called"); - - TargetEndpointInfo endpoint; - CHIP_ERROR err = convertJContentAppToTargetEndpointInfo(contentApp, endpoint); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogError(AppServer, "Conversion from jobject contentApp to TargetEndpointInfo * failed: %" CHIP_ERROR_FORMAT, - err.Format())); - - err = TvCastingAppJNIMgr().getProductIDSuccessHandler().SetUp(env, jReadSuccessHandler); - VerifyOrExit(CHIP_NO_ERROR == err, ChipLogError(AppServer, "SuccessHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = TvCastingAppJNIMgr().getSubscriptionReadFailureHandler(ApplicationBasic_ProductID).SetUp(env, jReadFailureHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "SubscriptionReadFailureHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = TvCastingAppJNIMgr() - .getSubscriptionEstablishedHandler(ApplicationBasic_ProductID) - .SetUp(env, jSubscriptionEstablishedHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "SubscriptionEstablishedHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = CastingServer::GetInstance()->ApplicationBasic_SubscribeToProductID( - &endpoint, nullptr, - [](void * context, chip::app::Clusters::ApplicationBasic::Attributes::ProductID::TypeInfo::DecodableArgType responseData) { - TvCastingAppJNIMgr().getProductIDSuccessHandler().Handle(responseData); - }, - [](void * context, CHIP_ERROR err) { - TvCastingAppJNIMgr().getSubscriptionReadFailureHandler(ApplicationBasic_ProductID).Handle(err); - }, - static_cast(minInterval), static_cast(maxInterval), - [](void * context, chip::SubscriptionId) { - TvCastingAppJNIMgr().getSubscriptionEstablishedHandler(ApplicationBasic_ProductID).Handle(); - }); - - VerifyOrExit( - CHIP_NO_ERROR == err, - ChipLogError(AppServer, "CastingServer.applicationBasic_subscribeToProductID failed %" CHIP_ERROR_FORMAT, err.Format())); - -exit: - return (err == CHIP_NO_ERROR); -} - -JNI_METHOD(jboolean, applicationBasic_1subscribeToApplicationVersion) -(JNIEnv * env, jobject, jobject contentApp, jobject jReadSuccessHandler, jobject jReadFailureHandler, jint minInterval, - jint maxInterval, jobject jSubscriptionEstablishedHandler) -{ - chip::DeviceLayer::StackLock lock; - - ChipLogProgress(AppServer, "JNI_METHOD applicationBasic_1subscribeToApplicationVersion called"); - - TargetEndpointInfo endpoint; - CHIP_ERROR err = convertJContentAppToTargetEndpointInfo(contentApp, endpoint); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogError(AppServer, "Conversion from jobject contentApp to TargetEndpointInfo * failed: %" CHIP_ERROR_FORMAT, - err.Format())); - - err = TvCastingAppJNIMgr().getApplicationVersionSuccessHandler().SetUp(env, jReadSuccessHandler); - VerifyOrExit(CHIP_NO_ERROR == err, ChipLogError(AppServer, "SuccessHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = - TvCastingAppJNIMgr().getSubscriptionReadFailureHandler(ApplicationBasic_ApplicationVersion).SetUp(env, jReadFailureHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "SubscriptionReadFailureHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = TvCastingAppJNIMgr() - .getSubscriptionEstablishedHandler(ApplicationBasic_ApplicationVersion) - .SetUp(env, jSubscriptionEstablishedHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "SubscriptionEstablishedHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = CastingServer::GetInstance()->ApplicationBasic_SubscribeToApplicationVersion( - &endpoint, nullptr, - [](void * context, - chip::app::Clusters::ApplicationBasic::Attributes::ApplicationVersion::TypeInfo::DecodableArgType responseData) { - TvCastingAppJNIMgr().getApplicationVersionSuccessHandler().Handle(responseData); - }, - [](void * context, CHIP_ERROR err) { - TvCastingAppJNIMgr().getSubscriptionReadFailureHandler(ApplicationBasic_ApplicationVersion).Handle(err); - }, - static_cast(minInterval), static_cast(maxInterval), - [](void * context, chip::SubscriptionId) { - TvCastingAppJNIMgr().getSubscriptionEstablishedHandler(ApplicationBasic_ApplicationVersion).Handle(); - }); - - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "CastingServer.applicationBasic_subscribeToApplicationVersion failed %" CHIP_ERROR_FORMAT, - err.Format())); - -exit: - return (err == CHIP_NO_ERROR); -} - -JNI_METHOD(jboolean, applicationBasic_1readVendorName) -(JNIEnv * env, jobject, jobject contentApp, jobject jReadSuccessHandler, jobject jReadFailureHandler) -{ - chip::DeviceLayer::StackLock lock; - - ChipLogProgress(AppServer, "JNI_METHOD applicationBasic_1readVendorName called"); - - TargetEndpointInfo endpoint; - CHIP_ERROR err = convertJContentAppToTargetEndpointInfo(contentApp, endpoint); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogError(AppServer, "Conversion from jobject contentApp to TargetEndpointInfo * failed: %" CHIP_ERROR_FORMAT, - err.Format())); - - err = TvCastingAppJNIMgr().getReadVendorNameSuccessHandler().SetUp(env, jReadSuccessHandler); - VerifyOrExit(CHIP_NO_ERROR == err, ChipLogError(AppServer, "SuccessHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = TvCastingAppJNIMgr().getReadFailureHandler(ApplicationBasic_VendorName).SetUp(env, jReadFailureHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "ReadFailureHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = CastingServer::GetInstance()->ApplicationBasic_ReadVendorName( - &endpoint, nullptr, - [](void * context, chip::app::Clusters::ApplicationBasic::Attributes::VendorName::TypeInfo::DecodableArgType responseData) { - TvCastingAppJNIMgr().getReadVendorNameSuccessHandler().Handle(responseData); - }, - [](void * context, CHIP_ERROR err) { - TvCastingAppJNIMgr().getReadFailureHandler(ApplicationBasic_VendorName).Handle(err); - }); - - VerifyOrExit( - CHIP_NO_ERROR == err, - ChipLogError(AppServer, "CastingServer.applicationBasic_1readVendorName failed %" CHIP_ERROR_FORMAT, err.Format())); - -exit: - return (err == CHIP_NO_ERROR); -} - -JNI_METHOD(jboolean, applicationBasic_1readVendorID) -(JNIEnv * env, jobject, jobject contentApp, jobject jReadSuccessHandler, jobject jReadFailureHandler) -{ - chip::DeviceLayer::StackLock lock; - - ChipLogProgress(AppServer, "JNI_METHOD applicationBasic_1readVendorID called"); - - TargetEndpointInfo endpoint; - CHIP_ERROR err = convertJContentAppToTargetEndpointInfo(contentApp, endpoint); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogError(AppServer, "Conversion from jobject contentApp to TargetEndpointInfo * failed: %" CHIP_ERROR_FORMAT, - err.Format())); - - err = TvCastingAppJNIMgr().getReadVendorIDSuccessHandler().SetUp(env, jReadSuccessHandler); - VerifyOrExit(CHIP_NO_ERROR == err, ChipLogError(AppServer, "SuccessHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = TvCastingAppJNIMgr().getReadFailureHandler(ApplicationBasic_VendorID).SetUp(env, jReadFailureHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "ReadFailureHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = CastingServer::GetInstance()->ApplicationBasic_ReadVendorID( - &endpoint, nullptr, - [](void * context, chip::app::Clusters::ApplicationBasic::Attributes::VendorID::TypeInfo::DecodableArgType responseData) { - TvCastingAppJNIMgr().getReadVendorIDSuccessHandler().Handle(responseData); - }, - [](void * context, CHIP_ERROR err) { TvCastingAppJNIMgr().getReadFailureHandler(ApplicationBasic_VendorID).Handle(err); }); - - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "CastingServer.applicationBasic_ReadVendorID failed %" CHIP_ERROR_FORMAT, err.Format())); - -exit: - return (err == CHIP_NO_ERROR); -} - -JNI_METHOD(jboolean, applicationBasic_1readApplicationName) -(JNIEnv * env, jobject, jobject contentApp, jobject jReadSuccessHandler, jobject jReadFailureHandler) -{ - chip::DeviceLayer::StackLock lock; - - ChipLogProgress(AppServer, "JNI_METHOD applicationBasic_1readApplicationName called"); - - TargetEndpointInfo endpoint; - CHIP_ERROR err = convertJContentAppToTargetEndpointInfo(contentApp, endpoint); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogError(AppServer, "Conversion from jobject contentApp to TargetEndpointInfo * failed: %" CHIP_ERROR_FORMAT, - err.Format())); - - err = TvCastingAppJNIMgr().getReadApplicationNameSuccessHandler().SetUp(env, jReadSuccessHandler); - VerifyOrExit(CHIP_NO_ERROR == err, ChipLogError(AppServer, "SuccessHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = TvCastingAppJNIMgr().getReadFailureHandler(ApplicationBasic_ApplicationName).SetUp(env, jReadFailureHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "ReadFailureHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = CastingServer::GetInstance()->ApplicationBasic_ReadApplicationName( - &endpoint, nullptr, - [](void * context, - chip::app::Clusters::ApplicationBasic::Attributes::ApplicationName::TypeInfo::DecodableArgType responseData) { - TvCastingAppJNIMgr().getReadApplicationNameSuccessHandler().Handle(responseData); - }, - [](void * context, CHIP_ERROR err) { - TvCastingAppJNIMgr().getReadFailureHandler(ApplicationBasic_ApplicationName).Handle(err); - }); - - VerifyOrExit( - CHIP_NO_ERROR == err, - ChipLogError(AppServer, "CastingServer.applicationBasic_ReadApplicationName failed %" CHIP_ERROR_FORMAT, err.Format())); - -exit: - return (err == CHIP_NO_ERROR); -} - -JNI_METHOD(jboolean, applicationBasic_1readProductID) -(JNIEnv * env, jobject, jobject contentApp, jobject jReadSuccessHandler, jobject jReadFailureHandler) -{ - chip::DeviceLayer::StackLock lock; - - ChipLogProgress(AppServer, "JNI_METHOD applicationBasic_1readProductID called"); - - TargetEndpointInfo endpoint; - CHIP_ERROR err = convertJContentAppToTargetEndpointInfo(contentApp, endpoint); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogError(AppServer, "Conversion from jobject contentApp to TargetEndpointInfo * failed: %" CHIP_ERROR_FORMAT, - err.Format())); - - err = TvCastingAppJNIMgr().getReadProductIDSuccessHandler().SetUp(env, jReadSuccessHandler); - VerifyOrExit(CHIP_NO_ERROR == err, ChipLogError(AppServer, "SuccessHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = TvCastingAppJNIMgr().getReadFailureHandler(ApplicationBasic_ProductID).SetUp(env, jReadFailureHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "ReadFailureHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = CastingServer::GetInstance()->ApplicationBasic_ReadProductID( - &endpoint, nullptr, - [](void * context, chip::app::Clusters::ApplicationBasic::Attributes::ProductID::TypeInfo::DecodableArgType responseData) { - TvCastingAppJNIMgr().getReadProductIDSuccessHandler().Handle(responseData); - }, - [](void * context, CHIP_ERROR err) { TvCastingAppJNIMgr().getReadFailureHandler(ApplicationBasic_ProductID).Handle(err); }); - - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "CastingServer.applicationBasic_ReadProductID failed %" CHIP_ERROR_FORMAT, err.Format())); - -exit: - return (err == CHIP_NO_ERROR); -} - -JNI_METHOD(jboolean, applicationBasic_1readApplicationVersion) -(JNIEnv * env, jobject, jobject contentApp, jobject jReadSuccessHandler, jobject jReadFailureHandler) -{ - chip::DeviceLayer::StackLock lock; - - ChipLogProgress(AppServer, "JNI_METHOD applicationBasic_1readApplicationVersion called"); - - TargetEndpointInfo endpoint; - CHIP_ERROR err = convertJContentAppToTargetEndpointInfo(contentApp, endpoint); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogError(AppServer, "Conversion from jobject contentApp to TargetEndpointInfo * failed: %" CHIP_ERROR_FORMAT, - err.Format())); - - err = TvCastingAppJNIMgr().getReadApplicationVersionSuccessHandler().SetUp(env, jReadSuccessHandler); - VerifyOrExit(CHIP_NO_ERROR == err, ChipLogError(AppServer, "SuccessHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = TvCastingAppJNIMgr().getReadFailureHandler(ApplicationBasic_ApplicationVersion).SetUp(env, jReadFailureHandler); - VerifyOrExit(CHIP_NO_ERROR == err, - ChipLogError(AppServer, "ReadFailureHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - - err = CastingServer::GetInstance()->ApplicationBasic_ReadApplicationVersion( - &endpoint, nullptr, - [](void * context, - chip::app::Clusters::ApplicationBasic::Attributes::ApplicationVersion::TypeInfo::DecodableArgType responseData) { - TvCastingAppJNIMgr().getReadApplicationVersionSuccessHandler().Handle(responseData); - }, - [](void * context, CHIP_ERROR err) { - TvCastingAppJNIMgr().getReadFailureHandler(ApplicationBasic_ApplicationVersion).Handle(err); - }); - - VerifyOrExit( - CHIP_NO_ERROR == err, - ChipLogError(AppServer, "CastingServer.applicationBasic_ReadApplicationVersion failed %" CHIP_ERROR_FORMAT, err.Format())); - -exit: - return (err == CHIP_NO_ERROR); -} diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/TvCastingApp-JNI.h b/examples/tv-casting-app/android/App/app/src/main/jni/cpp/TvCastingApp-JNI.h deleted file mode 100644 index 863e2691c4..0000000000 --- a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/TvCastingApp-JNI.h +++ /dev/null @@ -1,162 +0,0 @@ -/* - * - * Copyright (c) 2022 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 "Constants.h" -#include "MatterCallbackHandler-JNI.h" - -class TvCastingAppJNI -{ -public: - MatterCallbackHandlerJNI & getCommissioningCompleteHandler() { return mCommissioningCompleteHandler; } - - SessionEstablishmentStartedHandlerJNI & getSessionEstablishmentStartedHandler() { return mSessionEstablishmentStartedHandler; } - - SessionEstablishedHandlerJNI & getSessionEstablishedHandler() { return mSessionEstablishedHandler; } - - FailureHandlerJNI & getSessionEstablishmentErrorHandler() { return mSessionEstablishmentErrorHandler; } - - FailureHandlerJNI & getSessionEstablishmentStoppedHandler() { return mSessionEstablishmentStoppedHandler; } - - OnConnectionSuccessHandlerJNI & getOnConnectionSuccessHandler(bool preCommissioned) - { - return preCommissioned ? mPreCommissionedOnConnectionSuccessHandler : mCommissioningOnConnectionSuccessHandler; - } - - FailureHandlerJNI & getOnConnectionFailureHandler(bool preCommissioned) - { - return preCommissioned ? mPreCommissionedOnConnectionFailureHandler : mCommissioningOnConnectionFailureHandler; - } - OnNewOrUpdatedEndpointHandlerJNI & getOnNewOrUpdatedEndpointHandler(bool preCommissioned) - { - return preCommissioned ? mPreCommissionedOnNewOrUpdatedEndpointHandler : mCommissioningOnNewOrUpdatedEndpointHandler; - } - - MatterCallbackHandlerJNI & getMediaCommandResponseHandler(enum MediaCommandName name) - { - return mMediaCommandResponseHandler[name]; - } - - FailureHandlerJNI & getReadFailureHandler(enum MediaAttributeName name) { return mReadFailureHandler[name]; } - - FailureHandlerJNI & getSubscriptionReadFailureHandler(enum MediaAttributeName name) - { - return mSubscriptionReadFailureHandler[name]; - } - - SubscriptionEstablishedHandlerJNI & getSubscriptionEstablishedHandler(enum MediaAttributeName name) - { - return mSubscriptionEstablishedHandler[name]; - } - - CurrentStateSuccessHandlerJNI & getCurrentStateSuccessHandler() { return mCurrentStateSuccessHandlerJNI; } - DurationSuccessHandlerJNI & getDurationSuccessHandler() { return mDurationSuccessHandlerJNI; } - SampledPositionSuccessHandlerJNI & getSampledPositionSuccessHandler() { return mSampledPositionSuccessHandlerJNI; } - PlaybackSpeedSuccessHandlerJNI & getPlaybackSpeedSuccessHandler() { return mPlaybackSpeedSuccessHandlerJNI; } - SeekRangeEndSuccessHandlerJNI & getSeekRangeEndSuccessHandler() { return mSeekRangeEndSuccessHandlerJNI; } - SeekRangeStartSuccessHandlerJNI & getSeekRangeStartSuccessHandler() { return mSeekRangeStartSuccessHandlerJNI; } - - CurrentTargetSuccessHandlerJNI & getCurrentTargetSuccessHandler() { return mCurrentTargetSuccessHandlerJNI; } - TargetListSuccessHandlerJNI & getTargetListSuccessHandler() { return mTargetListSuccessHandlerJNI; } - - CurrentLevelSuccessHandlerJNI & getCurrentLevelSuccessHandler() { return mCurrentLevelSuccessHandlerJNI; } - MinLevelSuccessHandlerJNI & getMinLevelSuccessHandler() { return mMinLevelSuccessHandlerJNI; } - MaxLevelSuccessHandlerJNI & getMaxLevelSuccessHandler() { return mMaxLevelSuccessHandlerJNI; } - - SupportedStreamingProtocolsSuccessHandlerJNI & getSupportedStreamingProtocolsSuccessHandler() - { - return mSupportedStreamingProtocolsSuccessHandlerJNI; - } - - VendorNameSuccessHandlerJNI & getVendorNameSuccessHandler() { return mVendorNameSuccessHandlerJNI; } - VendorIDSuccessHandlerJNI & getVendorIDSuccessHandler() { return mVendorIDSuccessHandlerJNI; } - ApplicationNameSuccessHandlerJNI & getApplicationNameSuccessHandler() { return mApplicationNameSuccessHandlerJNI; } - ProductIDSuccessHandlerJNI & getProductIDSuccessHandler() { return mProductIDSuccessHandlerJNI; } - ApplicationVersionSuccessHandlerJNI & getApplicationVersionSuccessHandler() { return mApplicationVersionSuccessHandlerJNI; } - - VendorNameSuccessHandlerJNI & getReadVendorNameSuccessHandler() { return mReadVendorNameSuccessHandlerJNI; } - VendorIDSuccessHandlerJNI & getReadVendorIDSuccessHandler() { return mReadVendorIDSuccessHandlerJNI; } - ApplicationNameSuccessHandlerJNI & getReadApplicationNameSuccessHandler() { return mReadApplicationNameSuccessHandlerJNI; } - ProductIDSuccessHandlerJNI & getReadProductIDSuccessHandler() { return mReadProductIDSuccessHandlerJNI; } - ApplicationVersionSuccessHandlerJNI & getReadApplicationVersionSuccessHandler() - { - return mReadApplicationVersionSuccessHandlerJNI; - } - - jboolean runCastingServerCommand(JNIEnv * env, jobject contentApp, jobject jResponseHandler, const char * commandName, - MediaCommandName command, const std::function & commandRunner); - -private: - friend TvCastingAppJNI & TvCastingAppJNIMgr(); - - static TvCastingAppJNI sInstance; - - MatterCallbackHandlerJNI mCommissioningCompleteHandler; - SessionEstablishmentStartedHandlerJNI mSessionEstablishmentStartedHandler; - SessionEstablishedHandlerJNI mSessionEstablishedHandler; - FailureHandlerJNI mSessionEstablishmentErrorHandler; - FailureHandlerJNI mSessionEstablishmentStoppedHandler; - OnConnectionSuccessHandlerJNI mCommissioningOnConnectionSuccessHandler; - FailureHandlerJNI mCommissioningOnConnectionFailureHandler; - OnNewOrUpdatedEndpointHandlerJNI mCommissioningOnNewOrUpdatedEndpointHandler; - - OnConnectionSuccessHandlerJNI mPreCommissionedOnConnectionSuccessHandler; - FailureHandlerJNI mPreCommissionedOnConnectionFailureHandler; - OnNewOrUpdatedEndpointHandlerJNI mPreCommissionedOnNewOrUpdatedEndpointHandler; - - MatterCallbackHandlerJNI mMediaCommandResponseHandler[MEDIA_COMMAND_COUNT]; - FailureHandlerJNI mSubscriptionReadFailureHandler[MEDIA_ATTRIBUTE_COUNT]; - SubscriptionEstablishedHandlerJNI mSubscriptionEstablishedHandler[MEDIA_ATTRIBUTE_COUNT]; - FailureHandlerJNI mReadFailureHandler[MEDIA_ATTRIBUTE_COUNT]; - - CurrentStateSuccessHandlerJNI mCurrentStateSuccessHandlerJNI; - DurationSuccessHandlerJNI mDurationSuccessHandlerJNI; - SampledPositionSuccessHandlerJNI mSampledPositionSuccessHandlerJNI; - PlaybackSpeedSuccessHandlerJNI mPlaybackSpeedSuccessHandlerJNI; - SeekRangeEndSuccessHandlerJNI mSeekRangeEndSuccessHandlerJNI; - SeekRangeStartSuccessHandlerJNI mSeekRangeStartSuccessHandlerJNI; - - CurrentTargetSuccessHandlerJNI mCurrentTargetSuccessHandlerJNI; - TargetListSuccessHandlerJNI mTargetListSuccessHandlerJNI; - - CurrentLevelSuccessHandlerJNI mCurrentLevelSuccessHandlerJNI; - MinLevelSuccessHandlerJNI mMinLevelSuccessHandlerJNI; - MaxLevelSuccessHandlerJNI mMaxLevelSuccessHandlerJNI; - - SupportedStreamingProtocolsSuccessHandlerJNI mSupportedStreamingProtocolsSuccessHandlerJNI; - - VendorNameSuccessHandlerJNI mVendorNameSuccessHandlerJNI; - VendorIDSuccessHandlerJNI mVendorIDSuccessHandlerJNI; - ApplicationNameSuccessHandlerJNI mApplicationNameSuccessHandlerJNI; - ProductIDSuccessHandlerJNI mProductIDSuccessHandlerJNI; - ApplicationVersionSuccessHandlerJNI mApplicationVersionSuccessHandlerJNI; - - VendorNameSuccessHandlerJNI mReadVendorNameSuccessHandlerJNI; - VendorIDSuccessHandlerJNI mReadVendorIDSuccessHandlerJNI; - ApplicationNameSuccessHandlerJNI mReadApplicationNameSuccessHandlerJNI; - ProductIDSuccessHandlerJNI mReadProductIDSuccessHandlerJNI; - ApplicationVersionSuccessHandlerJNI mReadApplicationVersionSuccessHandlerJNI; -}; - -inline class TvCastingAppJNI & TvCastingAppJNIMgr() -{ - return TvCastingAppJNI::sInstance; -} diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/core/CastingApp-JNI.cpp b/examples/tv-casting-app/android/App/app/src/main/jni/cpp/core/CastingApp-JNI.cpp index ce8e8c0e1b..2242619df2 100644 --- a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/core/CastingApp-JNI.cpp +++ b/examples/tv-casting-app/android/App/app/src/main/jni/cpp/core/CastingApp-JNI.cpp @@ -18,8 +18,8 @@ #include "CastingApp-JNI.h" -#include "../JNIDACProvider.h" #include "../support/Converters-JNI.h" +#include "../support/JNIDACProvider.h" #include "../support/RotatingDeviceIdUniqueIdProvider-JNI.h" // from tv-casting-common @@ -29,6 +29,7 @@ #include #include +#include #include #include #include @@ -37,6 +38,16 @@ using namespace chip; #define JNI_METHOD(RETURN, METHOD_NAME) extern "C" JNIEXPORT RETURN JNICALL Java_com_matter_casting_core_CastingApp_##METHOD_NAME +jint JNI_OnLoad(JavaVM * jvm, void * reserved) +{ + return AndroidAppServerJNI_OnLoad(jvm, reserved); +} + +void JNI_OnUnload(JavaVM * jvm, void * reserved) +{ + return AndroidAppServerJNI_OnUnload(jvm, reserved); +} + namespace matter { namespace casting { namespace core { @@ -73,7 +84,7 @@ JNI_METHOD(jobject, finishInitialization)(JNIEnv *, jobject, jobject jAppParamet VerifyOrReturnValue(jDACProvider != nullptr, support::convertMatterErrorFromCppToJava(CHIP_ERROR_INCORRECT_STATE)); // set the DACProvider - JNIDACProvider * dacProvider = new JNIDACProvider(jDACProvider); + support::JNIDACProvider * dacProvider = new support::JNIDACProvider(jDACProvider); chip::Credentials::SetDeviceAttestationCredentialsProvider(dacProvider); return support::convertMatterErrorFromCppToJava(CHIP_NO_ERROR); diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/core/CastingPlayerDiscovery-JNI.cpp b/examples/tv-casting-app/android/App/app/src/main/jni/cpp/core/CastingPlayerDiscovery-JNI.cpp index 26526dfdac..0dd0a351b7 100644 --- a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/core/CastingPlayerDiscovery-JNI.cpp +++ b/examples/tv-casting-app/android/App/app/src/main/jni/cpp/core/CastingPlayerDiscovery-JNI.cpp @@ -18,7 +18,6 @@ #include "CastingPlayerDiscovery-JNI.h" -#include "../JNIDACProvider.h" #include "../support/Converters-JNI.h" #include "../support/RotatingDeviceIdUniqueIdProvider-JNI.h" #include "core/CastingApp.h" // from tv-casting-common diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/core/MatterCastingPlayer-JNI.cpp b/examples/tv-casting-app/android/App/app/src/main/jni/cpp/core/MatterCastingPlayer-JNI.cpp index b718682a17..5219dbca3a 100644 --- a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/core/MatterCastingPlayer-JNI.cpp +++ b/examples/tv-casting-app/android/App/app/src/main/jni/cpp/core/MatterCastingPlayer-JNI.cpp @@ -18,7 +18,6 @@ #include "MatterCastingPlayer-JNI.h" -#include "../JNIDACProvider.h" #include "../support/Converters-JNI.h" #include "../support/RotatingDeviceIdUniqueIdProvider-JNI.h" #include "core/CastingApp.h" // from tv-casting-common diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/core/MatterEndpoint-JNI.cpp b/examples/tv-casting-app/android/App/app/src/main/jni/cpp/core/MatterEndpoint-JNI.cpp index e0c41ebc92..685be54985 100644 --- a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/core/MatterEndpoint-JNI.cpp +++ b/examples/tv-casting-app/android/App/app/src/main/jni/cpp/core/MatterEndpoint-JNI.cpp @@ -18,7 +18,6 @@ #include "MatterEndpoint-JNI.h" -#include "../JNIDACProvider.h" #include "../support/MatterCallback-JNI.h" #include "../support/RotatingDeviceIdUniqueIdProvider-JNI.h" #include "clusters/Clusters.h" // from tv-casting-common diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/JNIDACProvider.cpp b/examples/tv-casting-app/android/App/app/src/main/jni/cpp/support/JNIDACProvider.cpp similarity index 98% rename from examples/tv-casting-app/android/App/app/src/main/jni/cpp/JNIDACProvider.cpp rename to examples/tv-casting-app/android/App/app/src/main/jni/cpp/support/JNIDACProvider.cpp index 363a629db2..1fbbfd1402 100644 --- a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/JNIDACProvider.cpp +++ b/examples/tv-casting-app/android/App/app/src/main/jni/cpp/support/JNIDACProvider.cpp @@ -29,6 +29,10 @@ using namespace chip; +namespace matter { +namespace casting { +namespace support { + JNIDACProvider::JNIDACProvider(jobject provider) { JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); @@ -174,3 +178,7 @@ CHIP_ERROR JNIDACProvider::SignWithDeviceAttestationKey(const ByteSpan & message return chip::Crypto::EcdsaAsn1SignatureToRaw(32, ByteSpan(asn1_signature_buffer.data(), asn1_signature_buffer.size()), out_signature_buffer); } + +}; // namespace support +}; // namespace casting +}; // namespace matter diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/JNIDACProvider.h b/examples/tv-casting-app/android/App/app/src/main/jni/cpp/support/JNIDACProvider.h similarity index 94% rename from examples/tv-casting-app/android/App/app/src/main/jni/cpp/JNIDACProvider.h rename to examples/tv-casting-app/android/App/app/src/main/jni/cpp/support/JNIDACProvider.h index d8d774f41f..bb7902f600 100644 --- a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/JNIDACProvider.h +++ b/examples/tv-casting-app/android/App/app/src/main/jni/cpp/support/JNIDACProvider.h @@ -21,6 +21,10 @@ #include #include +namespace matter { +namespace casting { +namespace support { + class JNIDACProvider : public chip::Credentials::DeviceAttestationCredentialsProvider { public: @@ -42,3 +46,7 @@ class JNIDACProvider : public chip::Credentials::DeviceAttestationCredentialsPro jmethodID mGetProductAttestationIntermediateCertMethod = nullptr; jmethodID mSignWithDeviceAttestationKeyMethod = nullptr; }; + +}; // namespace support +}; // namespace casting +}; // namespace matter diff --git a/examples/tv-casting-app/android/App/app/src/main/res/layout/activity_main.xml b/examples/tv-casting-app/android/App/app/src/main/res/layout/activity_main.xml index ff56873cb2..8e3724ec39 100644 --- a/examples/tv-casting-app/android/App/app/src/main/res/layout/activity_main.xml +++ b/examples/tv-casting-app/android/App/app/src/main/res/layout/activity_main.xml @@ -4,7 +4,7 @@ xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" - tools:context=".chip.casting.app.MainActivity"> + tools:context=".matter.casting.MainActivity"> ShutdownAllSubscriptions(); return CHIP_NO_ERROR; From 4aac314416bc579e1d3aa89128fed7ccbe96974f Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Thu, 22 Aug 2024 00:16:07 -0400 Subject: [PATCH 136/165] Remove subscription establishment bits from the MTRDevice base class. (#35139) _setupSubscriptionWithReason was only called from _reattemptSubscriptionNowIfNeededWithReason. _reattemptSubscriptionNowIfNeededWithReason was only called from: * _handleUnsolicitedMessageFromPublisher, which is only called in callbacks set up by _setupSubscriptionWithReason. * _triggerResubscribeWithReason, which only calls it when _reattemptingSubscription is YES. But that's only set to YES in _doHandleSubscriptionReset, see next item. * _doHandleSubscriptionReset, called from: * _handleSubscriptionReset: only called from callbacks set up by _setupSubscriptionWithReason. * _resetSubscriptionWithReasonString: called from unitTestResetSubscription and us detecting persisted data corruption in _clusterDataForPath. But we don't actually have persisted data in the MTRDevice base class anymore, so that's not reachable. So _setupSubscriptionWithReason is not reachable and can be removed. And unitTestResetSubscription can be made a no-op on the base MTRDevice. And we can remove the _resetSubscriptionWithReasonString call in _clusterDataForPath. Once those are done, the following become unreachable: * _handleSubscriptionReset * _handleSubscriptionError * Writing a nonzero value to _unitTestAttributesReportedSinceLastCheck * _markDeviceAsUnreachableIfNeverSubscribed * _handleResubscriptionNeededWithDelay * _handleSubscriptionEstablished * _handleUnsolicitedMessageFromPublisher * _createDataVersionFilterListFromDictionary * _setupConnectivityMonitoring * _resetSubscriptionWithReasonString Once those have been removed, the following become unreachable: * HadSubscriptionEstablishedOnce * _stopConnectivityMonitoring * _doHandleSubscriptionError * _doHandleSubscriptionReset Once those have been removed, the following become unreachable: * _setLastSubscriptionAttemptWait * Setting _lastSubscriptionFailureTime to non-nil * _clearSubscriptionPoolWork * _scheduleSubscriptionPoolWork * Use of _initialSubscribeStart * _storePersistedDeviceData * Use of _connectivityMonitor * Use of _lastSubscriptionFailureTimeForDescription * Any code depending on reattemptingSubscription being YES. * Use of _lastSubscriptionAttemptWait * Use of _lastSubscriptionAttemptWaitForDescription Once those have been removed, _reattemptSubscriptionNowIfNeededWithReason is unreachable and can be removed. At this point _currentReadClient and _currentSubscriptionCallback are always nil, so all code conditioned on those can be removed. Once that's done, _triggerResubscribeWithReason is a no-op, so it and all calls to it can be removed. Since _lastSubscriptionFailureTime is always nil, all code guarded on it not being nil can be removed, so _readThroughSkipped becomes a no-op and _lastSubscriptionFailureTime can be removed. At this point, the following are not reachable: * NeedToStartSubscriptionSetup * _changeInternalState Once those are removed, _internalDeviceStateForDescription is unused, and _internalDeviceState is always MTRInternalDeviceStateUnsubscribed. So HaveSubscriptionEstablishedRightNow() always returns NO and can be removed. At this point SubscriptionCallback is unused and can also be removed. --- src/darwin/Framework/CHIP/MTRDevice.mm | 1044 +----------------------- 1 file changed, 4 insertions(+), 1040 deletions(-) diff --git a/src/darwin/Framework/CHIP/MTRDevice.mm b/src/darwin/Framework/CHIP/MTRDevice.mm index f17e6d5c90..d4027f7725 100644 --- a/src/darwin/Framework/CHIP/MTRDevice.mm +++ b/src/darwin/Framework/CHIP/MTRDevice.mm @@ -22,7 +22,6 @@ #import "MTRAttributeSpecifiedCheck.h" #import "MTRBaseClusters.h" #import "MTRBaseDevice_Internal.h" -#import "MTRBaseSubscriptionCallback.h" #import "MTRCluster.h" #import "MTRClusterConstants.h" #import "MTRCommandTimedCheck.h" @@ -43,16 +42,8 @@ #import "zap-generated/MTRCommandPayloads_Internal.h" #import "lib/core/CHIPError.h" -#import "lib/core/DataModelTypes.h" -#import -#import - -#import -#import -#import -#import + #import -#import typedef void (^MTRDeviceAttributeReportHandler)(NSArray * _Nonnull); @@ -113,68 +104,13 @@ - (void)_deviceInternalStateChanged:(MTRDevice *)device; /* END DRAGONS */ -#pragma mark - SubscriptionCallback class declaration using namespace chip; using namespace chip::app; using namespace chip::Protocols::InteractionModel; using namespace chip::Tracing::DarwinFramework; -typedef void (^FirstReportHandler)(void); - -namespace { - -class SubscriptionCallback final : public MTRBaseSubscriptionCallback { -public: - SubscriptionCallback(DataReportCallback attributeReportCallback, DataReportCallback eventReportCallback, - ErrorCallback errorCallback, MTRDeviceResubscriptionScheduledHandler resubscriptionCallback, - SubscriptionEstablishedHandler subscriptionEstablishedHandler, OnDoneHandler onDoneHandler, - UnsolicitedMessageFromPublisherHandler unsolicitedMessageFromPublisherHandler, ReportBeginHandler reportBeginHandler, - ReportEndHandler reportEndHandler) - : MTRBaseSubscriptionCallback(attributeReportCallback, eventReportCallback, errorCallback, resubscriptionCallback, - subscriptionEstablishedHandler, onDoneHandler, unsolicitedMessageFromPublisherHandler, reportBeginHandler, - reportEndHandler) - { - } - - // Used to reset Resubscription backoff on events that indicate likely availability of device to come back online - void ResetResubscriptionBackoff() { mResubscriptionNumRetries = 0; } - -private: - void OnEventData(const EventHeader & aEventHeader, TLV::TLVReader * apData, const StatusIB * apStatus) override; - - void OnAttributeData(const ConcreteDataAttributePath & aPath, TLV::TLVReader * apData, const StatusIB & aStatus) override; - - CHIP_ERROR OnResubscriptionNeeded(chip::app::ReadClient * apReadClient, CHIP_ERROR aTerminationCause) override; - - // Copied from ReadClient and customized for MTRDevice resubscription time reset - uint32_t ComputeTimeTillNextSubscription(); - uint32_t mResubscriptionNumRetries = 0; -}; - -} // anonymous namespace - #pragma mark - MTRDevice -// Utility methods for working with MTRInternalDeviceState, located near the -// enum so it's easier to notice that they need to stay in sync. -namespace { -bool HadSubscriptionEstablishedOnce(MTRInternalDeviceState state) -{ - return state >= MTRInternalDeviceStateInitialSubscriptionEstablished; -} - -bool NeedToStartSubscriptionSetup(MTRInternalDeviceState state) -{ - return state <= MTRInternalDeviceStateUnsubscribed; -} - -bool HaveSubscriptionEstablishedRightNow(MTRInternalDeviceState state) -{ - return state == MTRInternalDeviceStateInitialSubscriptionEstablished || state == MTRInternalDeviceStateLaterSubscriptionEstablished; -} - -} // anonymous namespace - typedef NS_ENUM(NSUInteger, MTRDeviceExpectedValueFieldIndex) { MTRDeviceExpectedValueFieldExpirationTimeIndex = 0, MTRDeviceExpectedValueFieldValueIndex = 1, @@ -338,13 +274,6 @@ @interface MTRDevice () #define MTRDEVICE_SUBSCRIPTION_ATTEMPT_MAX_WAIT_SECONDS (3600) @property (nonatomic) uint32_t lastSubscriptionAttemptWait; -/** - * If reattemptingSubscription is true, that means that we have failed to get a - * CASE session for the publisher and are now waiting to try again. In this - * state we never have subscriptionActive true or a non-null currentReadClient. - */ -@property (nonatomic) BOOL reattemptingSubscription; - // Expected value cache is attributePath => NSArray of [NSDate of expiration time, NSDictionary of value, expected value ID] // - See MTRDeviceExpectedValueFieldIndex for the definitions of indices into this array. // See MTRDeviceResponseHandler definition for value dictionary details. @@ -362,14 +291,6 @@ @interface MTRDevice () @property (nonatomic) NSMutableDictionary * temporaryMetaDataCache; -/** - * If currentReadClient is non-null, that means that we successfully - * called SendAutoResubscribeRequest on the ReadClient and have not yet gotten - * an OnDone for that ReadClient. - */ -@property (nonatomic) ReadClient * currentReadClient; -@property (nonatomic) SubscriptionCallback * currentSubscriptionCallback; // valid when and only when currentReadClient is valid - @end // Declaring selector so compiler won't complain about testing and calling it in _handleReportEnd @@ -389,10 +310,6 @@ - (BOOL)unitTestSuppressTimeBasedReachabilityChanges:(MTRDevice *)device; #endif @implementation MTRDevice { -#ifdef DEBUG - NSUInteger _unitTestAttributesReportedSinceLastCheck; -#endif - // _deviceCachePrimed is true if we have the data that comes from an initial // subscription priming report (whether it came from storage or from our // subscription). @@ -410,26 +327,10 @@ @implementation MTRDevice { // right now (because they have been evicted). NSMutableSet * _persistedClusters; - // When we last failed to subscribe to the device (either via - // _setupSubscriptionWithReason or via the auto-resubscribe behavior - // of the ReadClient). Nil if we have had no such failures. - NSDate * _Nullable _lastSubscriptionFailureTime; - MTRDeviceConnectivityMonitor * _connectivityMonitor; - // This boolean keeps track of any device configuration changes received in an attribute report. // If this is true when the report ends, we notify the delegate. BOOL _deviceConfigurationChanged; - // The completion block is set when the subscription / resubscription work is enqueued, and called / cleared when any of the following happen: - // 1. Subscription establishes - // 2. OnResubscriptionNeeded is called - // 3. Subscription reset (including when getSessionForNode fails) - MTRAsyncWorkCompletionBlock _subscriptionPoolWorkCompletionBlock; - - // Tracking of initial subscribe latency. When _initialSubscribeStart is - // nil, we are not tracking the latency. - NSDate * _Nullable _initialSubscribeStart; - // Storage behavior configuration and variables to keep track of the logic // _clusterDataPersistenceFirstScheduledTime is used to track the start time of the delay between // report and persistence. @@ -459,14 +360,8 @@ @implementation MTRDevice { // _allNetworkFeatures is a bitwise or of the feature maps of all network commissioning clusters // present on the device, or nil if there aren't any. NSNumber * _Nullable _allNetworkFeatures; - // Copy of _internalDeviceState that is safe to use in description. - MTRInternalDeviceState _internalDeviceStateForDescription; - // Copy of _lastSubscriptionAttemptWait that is safe to use in description. - uint32_t _lastSubscriptionAttemptWaitForDescription; // Most recent entry in _mostRecentReportTimes, if any. NSDate * _Nullable _mostRecentReportTimeForDescription; - // Copy of _lastSubscriptionFailureTime that is safe to use in description. - NSDate * _Nullable _lastSubscriptionFailureTimeForDescription; } - (instancetype)initForSubclassesWithNodeID:(NSNumber *)nodeID controller:(MTRDeviceController *)controller @@ -496,7 +391,6 @@ - (instancetype)initWithNodeID:(NSNumber *)nodeID controller:(MTRDeviceControlle _asyncWorkQueue = [[MTRAsyncWorkQueue alloc] initWithContext:self]; _state = MTRDeviceStateUnknown; _internalDeviceState = MTRInternalDeviceStateUnsubscribed; - _internalDeviceStateForDescription = MTRInternalDeviceStateUnsubscribed; if (controller.controllerDataStore) { _persistedClusterData = [[NSCache alloc] init]; } else { @@ -861,51 +755,6 @@ - (void)nodeMayBeAdvertisingOperational assertChipStackLockedByCurrentThread(); MTR_LOG("%@ saw new operational advertisement", self); - - [self _triggerResubscribeWithReason:@"operational advertisement seen" - nodeLikelyReachable:YES]; -} - -// Trigger a resubscribe as needed. nodeLikelyReachable should be YES if we -// have reason to suspect the node is now reachable, NO if we have no idea -// whether it might be. -- (void)_triggerResubscribeWithReason:(NSString *)reason nodeLikelyReachable:(BOOL)nodeLikelyReachable -{ - MTR_LOG("%@ _triggerResubscribeWithReason called with reason %@", self, reason); - assertChipStackLockedByCurrentThread(); - - // We might want to trigger a resubscribe on our existing ReadClient. Do - // that outside the scope of our lock, so we're not calling arbitrary code - // we don't control with the lock held. This is safe, because we are - // running on he Matter queue and the ReadClient can't get destroyed while - // we are on that queue. - ReadClient * readClientToResubscribe = nullptr; - SubscriptionCallback * subscriptionCallback = nullptr; - - os_unfair_lock_lock(&self->_lock); - - // Don't change state to MTRDeviceStateReachable, since the device might not - // in fact be reachable yet; we won't know until we have managed to - // establish a CASE session. And at that point, our subscription will - // trigger the state change as needed. - if (self.reattemptingSubscription) { - [self _reattemptSubscriptionNowIfNeededWithReason:reason]; - } else { - readClientToResubscribe = self->_currentReadClient; - subscriptionCallback = self->_currentSubscriptionCallback; - } - os_unfair_lock_unlock(&self->_lock); - - if (readClientToResubscribe) { - if (nodeLikelyReachable) { - // If we have reason to suspect the node is now reachable, reset the - // backoff timer, so that if this attempt fails we'll try again - // quickly; it's possible we'll just catch the node at a bad time - // here (e.g. still booting up), but should try again reasonably quickly. - subscriptionCallback->ResetResubscriptionBackoff(); - } - readClientToResubscribe->TriggerResubscribeIfScheduled(reason.UTF8String); - } } // Return YES if we are in a state where, apart from communication issues with @@ -941,41 +790,6 @@ - (BOOL)_subscriptionAbleToReport // Notification that read-through was skipped for an attribute read. - (void)_readThroughSkipped { - std::lock_guard lock(_lock); - if (_state == MTRDeviceStateReachable) { - // We're getting reports from the device, so there's nothing else to be - // done here. We could skip this check, because our "try to - // resubscribe" code would be a no-op in this case, but then we'd have - // an extra dispatch in the common case of read-while-subscribed, which - // is not great for peformance. - return; - } - - if (_lastSubscriptionFailureTime == nil) { - // No need to try to do anything here, because we have never failed a - // subscription attempt (so we might be in the middle of one now, and no - // need to prod things along). - return; - } - - if ([[NSDate now] timeIntervalSinceDate:_lastSubscriptionFailureTime] < MTRDEVICE_MIN_RESUBSCRIBE_DUE_TO_READ_INTERVAL_SECONDS) { - // Not enough time has passed since we last tried. Don't create extra - // network traffic. - // - // TODO: Do we need to worry about this being too spammy in the log if - // we keep getting reads while not subscribed? We could add another - // backoff timer or counter for the log line... - MTR_LOG_DEBUG("%@ skipping resubscribe from skipped read-through: not enough time has passed since %@", self, _lastSubscriptionFailureTime); - return; - } - - // Do the remaining work on the Matter queue, because we may want to touch - // ReadClient in there. If the dispatch fails, that's fine; it means our - // controller has shut down, so nothing to be done. - [_deviceController asyncDispatchToMatterQueue:^{ - [self _triggerResubscribeWithReason:@"read-through skipped while not subscribed" nodeLikelyReachable:NO]; - } - errorHandler:nil]; } - (BOOL)_delegateExists @@ -1090,29 +904,6 @@ - (void)_changeState:(MTRDeviceState)state } } -- (void)_changeInternalState:(MTRInternalDeviceState)state -{ - os_unfair_lock_assert_owner(&self->_lock); - MTRInternalDeviceState lastState = _internalDeviceState; - _internalDeviceState = state; - { - std::lock_guard lock(_descriptionLock); - _internalDeviceStateForDescription = _internalDeviceState; - } - if (lastState != state) { - MTR_LOG("%@ internal state change %lu => %lu", self, static_cast(lastState), static_cast(state)); - - /* BEGIN DRAGONS: This is a huge hack for a specific use case, do not rename, remove or modify behavior here */ - // TODO: This should only be called for thread devices - [self _callDelegatesWithBlock:^(id delegate) { - if ([delegate respondsToSelector:@selector(_deviceInternalStateChanged:)]) { - [delegate _deviceInternalStateChanged:self]; - } - }]; - /* END DRAGONS */ - } -} - #ifdef DEBUG - (MTRInternalDeviceState)_getInternalState { @@ -1121,71 +912,6 @@ - (MTRInternalDeviceState)_getInternalState } #endif -// First Time Sync happens 2 minutes after reachability (this can be changed in the future) -#define MTR_DEVICE_TIME_UPDATE_INITIAL_WAIT_TIME_SEC (60 * 2) -- (void)_handleSubscriptionEstablished -{ - os_unfair_lock_lock(&self->_lock); - - // If subscription had reset since this handler was scheduled, do not execute "established" logic below - if (!HaveSubscriptionEstablishedRightNow(_internalDeviceState)) { - MTR_LOG("%@ _handleSubscriptionEstablished run with internal state %lu - skipping subscription establishment logic", self, static_cast(_internalDeviceState)); - return; - } - - // We have completed the subscription work - remove from the subscription pool. - [self _clearSubscriptionPoolWork]; - - // No need to monitor connectivity after subscription establishment - [self _stopConnectivityMonitoring]; - - // reset subscription attempt wait time when subscription succeeds - [self _setLastSubscriptionAttemptWait:0]; - - auto initialSubscribeStart = _initialSubscribeStart; - // We no longer need to track subscribe latency for this device. - _initialSubscribeStart = nil; - - if (initialSubscribeStart != nil) { - // We want time interval from initialSubscribeStart to now, not the other - // way around. - NSTimeInterval subscriptionLatency = -[initialSubscribeStart timeIntervalSinceNow]; - if (_estimatedSubscriptionLatency == nil) { - _estimatedSubscriptionLatency = @(subscriptionLatency); - } else { - NSTimeInterval newSubscriptionLatencyEstimate = MTRDEVICE_SUBSCRIPTION_LATENCY_NEW_VALUE_WEIGHT * subscriptionLatency + (1 - MTRDEVICE_SUBSCRIPTION_LATENCY_NEW_VALUE_WEIGHT) * _estimatedSubscriptionLatency.doubleValue; - _estimatedSubscriptionLatency = @(newSubscriptionLatencyEstimate); - } - [self _storePersistedDeviceData]; - } - - os_unfair_lock_unlock(&self->_lock); - - os_unfair_lock_lock(&self->_timeSyncLock); - - if (!self.timeUpdateScheduled) { - [self _scheduleNextUpdate:MTR_DEVICE_TIME_UPDATE_INITIAL_WAIT_TIME_SEC]; - } - - os_unfair_lock_unlock(&self->_timeSyncLock); -} - -- (void)_handleSubscriptionError:(NSError *)error -{ - std::lock_guard lock(_lock); - [self _doHandleSubscriptionError:error]; -} - -- (void)_doHandleSubscriptionError:(NSError *)error -{ - os_unfair_lock_assert_owner(&_lock); - - [self _changeInternalState:MTRInternalDeviceStateUnsubscribed]; - _unreportedEvents = nil; - - [self _changeState:MTRDeviceStateUnreachable]; -} - - (BOOL)deviceUsesThread { std::lock_guard lock(_lock); @@ -1229,253 +955,6 @@ - (BOOL)_deviceUsesThread return (networkCommissioningClusterFeatureMapValue & MTRNetworkCommissioningFeatureThreadNetworkInterface) != 0 ? YES : NO; } -- (void)_clearSubscriptionPoolWork -{ - os_unfair_lock_assert_owner(&self->_lock); - MTRAsyncWorkCompletionBlock completion = self->_subscriptionPoolWorkCompletionBlock; - if (completion) { -#ifdef DEBUG - [self _callDelegatesWithBlock:^(id testDelegate) { - if ([testDelegate respondsToSelector:@selector(unitTestSubscriptionPoolWorkComplete:)]) { - [testDelegate unitTestSubscriptionPoolWorkComplete:self]; - } - }]; -#endif - self->_subscriptionPoolWorkCompletionBlock = nil; - completion(MTRAsyncWorkComplete); - } -} - -- (void)_scheduleSubscriptionPoolWork:(dispatch_block_t)workBlock inNanoseconds:(int64_t)inNanoseconds description:(NSString *)description -{ - os_unfair_lock_assert_owner(&self->_lock); - - // Sanity check we are not scheduling for this device multiple times in the pool - if (_subscriptionPoolWorkCompletionBlock) { - MTR_LOG("%@ already scheduled in subscription pool for this device - ignoring: %@", self, description); - return; - } - - // Wait the required amount of time, then put it in the subscription pool to wait additionally for a spot, if needed - dispatch_after(dispatch_time(DISPATCH_TIME_NOW, inNanoseconds), dispatch_get_main_queue(), ^{ - // In the case where a resubscription triggering event happened and already established, running the work block should result in a no-op - MTRAsyncWorkItem * workItem = [[MTRAsyncWorkItem alloc] initWithQueue:self.queue]; - [workItem setReadyHandler:^(id _Nonnull context, NSInteger retryCount, MTRAsyncWorkCompletionBlock _Nonnull completion) { - MTR_LOG("%@ - work item is ready to attempt pooled subscription", self); - os_unfair_lock_lock(&self->_lock); -#ifdef DEBUG - [self _callDelegatesWithBlock:^(id testDelegate) { - if ([testDelegate respondsToSelector:@selector(unitTestSubscriptionPoolDequeue:)]) { - [testDelegate unitTestSubscriptionPoolDequeue:self]; - } - }]; -#endif - if (self->_subscriptionPoolWorkCompletionBlock) { - // This means a resubscription triggering event happened and is now in-progress - MTR_LOG("%@ timer fired but already running in subscription pool - ignoring: %@", self, description); - os_unfair_lock_unlock(&self->_lock); - - // call completion as complete to remove from queue - completion(MTRAsyncWorkComplete); - return; - } - - // Otherwise, save the completion block - self->_subscriptionPoolWorkCompletionBlock = completion; - os_unfair_lock_unlock(&self->_lock); - - workBlock(); - }]; - [self->_deviceController.concurrentSubscriptionPool enqueueWorkItem:workItem description:description]; - MTR_LOG("%@ - enqueued in the subscription pool", self); - }); -} - -- (void)_handleResubscriptionNeededWithDelay:(NSNumber *)resubscriptionDelayMs -{ - BOOL deviceUsesThread; - - os_unfair_lock_lock(&self->_lock); - - [self _changeState:MTRDeviceStateUnknown]; - [self _changeInternalState:MTRInternalDeviceStateResubscribing]; - - // If we are here, then the ReadClient either just detected a subscription - // drop or just tried again and failed. Either way, count it as "tried and - // failed to subscribe": in the latter case it's actually true, and in the - // former case we recently had a subscription and do not want to be forcing - // retries immediately. - _lastSubscriptionFailureTime = [NSDate now]; - { - std::lock_guard lock(_descriptionLock); - _lastSubscriptionFailureTimeForDescription = _lastSubscriptionFailureTime; - } - - deviceUsesThread = [self _deviceUsesThread]; - - // If a previous resubscription failed, remove the item from the subscription pool. - [self _clearSubscriptionPoolWork]; - - os_unfair_lock_unlock(&self->_lock); - - // Use the existing _triggerResubscribeWithReason mechanism, which does the right checks when - // this block is run -- if other triggering events had happened, this would become a no-op. - auto resubscriptionBlock = ^{ - [self->_deviceController asyncDispatchToMatterQueue:^{ - [self _triggerResubscribeWithReason:@"ResubscriptionNeeded timer fired" nodeLikelyReachable:NO]; - } errorHandler:^(NSError * _Nonnull error) { - // If controller is not running, clear work item from the subscription queue - MTR_LOG_ERROR("%@ could not dispatch to matter queue for resubscription - error %@", self, error); - std::lock_guard lock(self->_lock); - [self _clearSubscriptionPoolWork]; - }]; - }; - - int64_t resubscriptionDelayNs = static_cast(resubscriptionDelayMs.unsignedIntValue * NSEC_PER_MSEC); - if (deviceUsesThread) { - std::lock_guard lock(_lock); - // For Thread-enabled devices, schedule the _triggerResubscribeWithReason call to run in the subscription pool - [self _scheduleSubscriptionPoolWork:resubscriptionBlock inNanoseconds:resubscriptionDelayNs description:@"ReadClient resubscription"]; - } else { - // For non-Thread-enabled devices, just call the resubscription block after the specified time - dispatch_after(dispatch_time(DISPATCH_TIME_NOW, resubscriptionDelayNs), self.queue, resubscriptionBlock); - } - - // Set up connectivity monitoring in case network routability changes for the positive, to accelerate resubscription - [self _setupConnectivityMonitoring]; -} - -- (void)_handleSubscriptionReset:(NSNumber * _Nullable)retryDelay -{ - std::lock_guard lock(_lock); - [self _doHandleSubscriptionReset:retryDelay]; -} - -- (void)_setLastSubscriptionAttemptWait:(uint32_t)lastSubscriptionAttemptWait -{ - os_unfair_lock_assert_owner(&_lock); - _lastSubscriptionAttemptWait = lastSubscriptionAttemptWait; - - std::lock_guard lock(_descriptionLock); - _lastSubscriptionAttemptWaitForDescription = lastSubscriptionAttemptWait; -} - -- (void)_doHandleSubscriptionReset:(NSNumber * _Nullable)retryDelay -{ - os_unfair_lock_assert_owner(&_lock); - - // If we are here, then either we failed to establish initial CASE, or we - // failed to send the initial SubscribeRequest message, or our ReadClient - // has given up completely. Those all count as "we have tried and failed to - // subscribe". - _lastSubscriptionFailureTime = [NSDate now]; - { - std::lock_guard lock(_descriptionLock); - _lastSubscriptionFailureTimeForDescription = _lastSubscriptionFailureTime; - } - - // if there is no delegate then also do not retry - if (![self _delegateExists]) { - // NOTE: Do not log anything here: we have been invalidated, and the - // Matter stack might already be torn down. - return; - } - - // don't schedule multiple retries - if (self.reattemptingSubscription) { - return; - } - - self.reattemptingSubscription = YES; - - NSTimeInterval secondsToWait; - if (_lastSubscriptionAttemptWait < MTRDEVICE_SUBSCRIPTION_ATTEMPT_MIN_WAIT_SECONDS) { - _lastSubscriptionAttemptWait = MTRDEVICE_SUBSCRIPTION_ATTEMPT_MIN_WAIT_SECONDS; - secondsToWait = _lastSubscriptionAttemptWait; - } else if (retryDelay != nil) { - // The device responded but is currently busy. Reset our backoff - // counter, so that we don't end up waiting for a long time if the next - // attempt fails for some reason, and retry after whatever time period - // the device told us to use. - [self _setLastSubscriptionAttemptWait:0]; - secondsToWait = retryDelay.doubleValue; - MTR_LOG("%@ resetting resubscribe attempt counter, and delaying by the server-provided delay: %f", - self, secondsToWait); - } else { - auto lastSubscriptionAttemptWait = _lastSubscriptionAttemptWait * 2; - if (lastSubscriptionAttemptWait > MTRDEVICE_SUBSCRIPTION_ATTEMPT_MAX_WAIT_SECONDS) { - lastSubscriptionAttemptWait = MTRDEVICE_SUBSCRIPTION_ATTEMPT_MAX_WAIT_SECONDS; - } - [self _setLastSubscriptionAttemptWait:lastSubscriptionAttemptWait]; - secondsToWait = lastSubscriptionAttemptWait; - } - - MTR_LOG("%@ scheduling to reattempt subscription in %f seconds", self, secondsToWait); - - // If we started subscription or session establishment but failed, remove item from the subscription pool so we can re-queue. - [self _clearSubscriptionPoolWork]; - - // Call _reattemptSubscriptionNowIfNeededWithReason when timer fires - if subscription is - // in a better state at that time this will be a no-op. - auto resubscriptionBlock = ^{ - std::lock_guard lock(self->_lock); - [self _reattemptSubscriptionNowIfNeededWithReason:@"got subscription reset"]; - }; - - int64_t resubscriptionDelayNs = static_cast(secondsToWait * NSEC_PER_SEC); - if ([self _deviceUsesThread]) { - // For Thread-enabled devices, schedule the _reattemptSubscriptionNowIfNeededWithReason call to run in the subscription pool - [self _scheduleSubscriptionPoolWork:resubscriptionBlock inNanoseconds:resubscriptionDelayNs description:@"MTRDevice resubscription"]; - } else { - // For non-Thread-enabled devices, just call the resubscription block after the specified time - dispatch_after(dispatch_time(DISPATCH_TIME_NOW, resubscriptionDelayNs), self.queue, resubscriptionBlock); - } -} - -- (void)_reattemptSubscriptionNowIfNeededWithReason:(NSString *)reason -{ - os_unfair_lock_assert_owner(&self->_lock); - if (!self.reattemptingSubscription) { - return; - } - - MTR_LOG("%@ reattempting subscription with reason %@", self, reason); - self.reattemptingSubscription = NO; - [self _setupSubscriptionWithReason:reason]; -} - -- (void)_handleUnsolicitedMessageFromPublisher -{ - std::lock_guard lock(_lock); - - [self _changeState:MTRDeviceStateReachable]; - - [self _callDelegatesWithBlock:^(id delegate) { - if ([delegate respondsToSelector:@selector(deviceBecameActive:)]) { - [delegate deviceBecameActive:self]; - } - }]; - - // in case this is called during exponential back off of subscription - // reestablishment, this starts the attempt right away - // TODO: This doesn't really make sense. If we _don't_ have a live - // ReadClient how did we get this notification and if we _do_ have an active - // ReadClient, this call or _setupSubscriptionWithReason would be no-ops. - [self _reattemptSubscriptionNowIfNeededWithReason:@"got unsolicited message from publisher"]; -} - -- (void)_markDeviceAsUnreachableIfNeverSubscribed -{ - os_unfair_lock_assert_owner(&self->_lock); - - if (HadSubscriptionEstablishedOnce(_internalDeviceState)) { - return; - } - - MTR_LOG("%@ still not subscribed, marking the device as unreachable", self); - [self _changeState:MTRDeviceStateUnreachable]; -} - - (void)_handleReportBegin { std::lock_guard lock(_lock); @@ -1487,7 +966,7 @@ - (void)_handleReportBegin // If we currently don't have an established subscription, this must be a // priming report. - _receivingPrimingReport = !HaveSubscriptionEstablishedRightNow(_internalDeviceState); + _receivingPrimingReport = YES; } - (NSDictionary *)_clusterDataToPersistSnapshot @@ -2136,8 +1615,6 @@ - (nullable MTRDeviceClusterData *)_clusterDataForPath:(MTRClusterPath *)cluster // First make sure _persistedClusters is consistent with storage, so repeated calls don't immediately re-trigger this [self _reconcilePersistedClustersWithStorage]; - - [self _resetSubscriptionWithReasonString:[NSString stringWithFormat:@"Data store has no data for cluster %@", clusterPath]]; } return data; @@ -2243,352 +1720,16 @@ - (void)_removeCachedAttribute:(NSNumber *)attributeID fromCluster:(MTRClusterPa [clusterData removeValueForAttribute:attributeID]; } -- (void)_createDataVersionFilterListFromDictionary:(NSDictionary *)dataVersions dataVersionFilterList:(DataVersionFilter **)dataVersionFilterList count:(size_t *)count -{ - size_t dataVersionFilterSize = dataVersions.count; - - // Check if any filter list should be generated - if (dataVersionFilterSize == 0) { - *count = 0; - *dataVersionFilterList = nullptr; - return; - } - - DataVersionFilter * dataVersionFilterArray = new DataVersionFilter[dataVersionFilterSize]; - size_t i = 0; - for (MTRClusterPath * path in dataVersions) { - NSNumber * dataVersionNumber = dataVersions[path]; - dataVersionFilterArray[i++] = DataVersionFilter(static_cast(path.endpoint.unsignedShortValue), static_cast(path.cluster.unsignedLongValue), static_cast(dataVersionNumber.unsignedLongValue)); - } - - *dataVersionFilterList = dataVersionFilterArray; - *count = dataVersionFilterSize; -} - -- (void)_setupConnectivityMonitoring -{ -#if ENABLE_CONNECTIVITY_MONITORING - // Dispatch to own queue because we used to need to do that to get the compressedFabricID, but - // at this point that's not really needed anymore. - dispatch_async(self.queue, ^{ - // Get the required info before setting up the connectivity monitor - NSNumber * compressedFabricID = [self->_deviceController compressedFabricID]; - if (!compressedFabricID) { - MTR_LOG_ERROR("%@ could not get compressed fabricID", self); - return; - } - - // Now lock for _connectivityMonitor - std::lock_guard lock(self->_lock); - if (self->_connectivityMonitor) { - // already monitoring - return; - } - - self->_connectivityMonitor = [[MTRDeviceConnectivityMonitor alloc] initWithCompressedFabricID:compressedFabricID nodeID:self.nodeID]; - [self->_connectivityMonitor startMonitoringWithHandler:^{ - [self->_deviceController asyncDispatchToMatterQueue:^{ - [self _triggerResubscribeWithReason:@"device connectivity changed" nodeLikelyReachable:YES]; - } - errorHandler:nil]; - } queue:self.queue]; - }); -#endif -} - -- (void)_stopConnectivityMonitoring -{ - os_unfair_lock_assert_owner(&_lock); - - if (_connectivityMonitor) { - [_connectivityMonitor stopMonitoring]; - _connectivityMonitor = nil; - } -} - -- (void)_resetSubscriptionWithReasonString:(NSString *)reasonString -{ - os_unfair_lock_assert_owner(&self->_lock); - MTR_LOG_ERROR("%@ %@ - resetting subscription", self, reasonString); - - [_deviceController asyncDispatchToMatterQueue:^{ - MTR_LOG("%@ subscription reset disconnecting ReadClient and SubscriptionCallback", self); - - std::lock_guard lock(self->_lock); - self->_currentReadClient = nullptr; - if (self->_currentSubscriptionCallback) { - delete self->_currentSubscriptionCallback; - } - self->_currentSubscriptionCallback = nullptr; - - [self _doHandleSubscriptionError:nil]; - // Use nil reset delay so that this keeps existing backoff timing - [self _doHandleSubscriptionReset:nil]; - } - errorHandler:nil]; -} - #ifdef DEBUG - (void)unitTestResetSubscription { - std::lock_guard lock(self->_lock); - [self _resetSubscriptionWithReasonString:@"Unit test reset subscription"]; } #endif -// assume lock is held -- (void)_setupSubscriptionWithReason:(NSString *)reason -{ - // TODO: XPC: This is not really called anymore in this class. Should - // remove this function and anything only reachable from it. - os_unfair_lock_assert_owner(&self->_lock); - - if (![self _subscriptionsAllowed]) { - MTR_LOG("%@ _setupSubscription: Subscriptions not allowed. Do not set up subscription (reason: %@)", self, reason); - return; - } - -#ifdef DEBUG - __block NSNumber * delegateMin = nil; - Optional maxIntervalOverride; - [self _callFirstDelegateSynchronouslyWithBlock:^(id testDelegate) { - if ([testDelegate respondsToSelector:@selector(unitTestMaxIntervalOverrideForSubscription:)]) { - delegateMin = [testDelegate unitTestMaxIntervalOverrideForSubscription:self]; - } - }]; - if (delegateMin) { - maxIntervalOverride.Emplace(delegateMin.unsignedIntValue); - } -#endif - - // for now just subscribe once - if (!NeedToStartSubscriptionSetup(_internalDeviceState)) { - MTR_LOG("%@ setupSubscription: no need to subscribe due to internal state %lu (reason: %@)", self, static_cast(_internalDeviceState), reason); - return; - } - - [self _changeInternalState:MTRInternalDeviceStateSubscribing]; - - MTR_LOG("%@ setting up subscription with reason: %@", self, reason); - - __block bool markUnreachableAfterWait = true; -#ifdef DEBUG - [self _callFirstDelegateSynchronouslyWithBlock:^(id testDelegate) { - if ([testDelegate respondsToSelector:@selector(unitTestSuppressTimeBasedReachabilityChanges:)]) { - markUnreachableAfterWait = ![testDelegate unitTestSuppressTimeBasedReachabilityChanges:self]; - } - }]; -#endif - - if (markUnreachableAfterWait) { - // Set up a timer to mark as not reachable if it takes too long to set up a subscription - mtr_weakify(self); - dispatch_after(dispatch_time(DISPATCH_TIME_NOW, static_cast(kSecondsToWaitBeforeMarkingUnreachableAfterSettingUpSubscription) * static_cast(NSEC_PER_SEC)), self.queue, ^{ - mtr_strongify(self); - if (self != nil) { - std::lock_guard lock(self->_lock); - [self _markDeviceAsUnreachableIfNeverSubscribed]; - } - }); - } - - // This marks begin of initial subscription to the device (before CASE is established). The end is only marked after successfully setting - // up the subscription since it is always retried as long as the MTRDevice is kept running. - MATTER_LOG_METRIC_BEGIN(kMetricMTRDeviceInitialSubscriptionSetup); - - // Call directlyGetSessionForNode because the subscription setup already goes through the subscription pool queue - [_deviceController - directlyGetSessionForNode:_nodeID.unsignedLongLongValue - completion:^(chip::Messaging::ExchangeManager * _Nullable exchangeManager, - const chip::Optional & session, NSError * _Nullable error, - NSNumber * _Nullable retryDelay) { - if (error != nil) { - MTR_LOG_ERROR("%@ getSessionForNode error %@", self, error); - dispatch_async(self.queue, ^{ - [self _handleSubscriptionError:error]; - [self _handleSubscriptionReset:retryDelay]; - }); - return; - } - - auto callback = std::make_unique( - ^(NSArray * value) { - MTR_LOG("%@ got attribute report %@", self, value); - dispatch_async(self.queue, ^{ - // OnAttributeData - [self _handleAttributeReport:value fromSubscription:YES]; -#ifdef DEBUG - self->_unitTestAttributesReportedSinceLastCheck += value.count; -#endif - }); - }, - ^(NSArray * value) { - MTR_LOG("%@ got event report %@", self, value); - dispatch_async(self.queue, ^{ - // OnEventReport - [self _handleEventReport:value]; - }); - }, - ^(NSError * error) { - MTR_LOG_ERROR("%@ got subscription error %@", self, error); - dispatch_async(self.queue, ^{ - // OnError - [self _handleSubscriptionError:error]; - }); - }, - ^(NSError * error, NSNumber * resubscriptionDelayMs) { - MTR_LOG_ERROR("%@ got resubscription error %@ delay %@", self, error, resubscriptionDelayMs); - dispatch_async(self.queue, ^{ - // OnResubscriptionNeeded - [self _handleResubscriptionNeededWithDelay:resubscriptionDelayMs]; - }); - }, - ^(void) { - MTR_LOG("%@ got subscription established", self); - std::lock_guard lock(self->_lock); - - // First synchronously change state - if (HadSubscriptionEstablishedOnce(self->_internalDeviceState)) { - [self _changeInternalState:MTRInternalDeviceStateLaterSubscriptionEstablished]; - } else { - MATTER_LOG_METRIC_END(kMetricMTRDeviceInitialSubscriptionSetup, CHIP_NO_ERROR); - [self _changeInternalState:MTRInternalDeviceStateInitialSubscriptionEstablished]; - } - - [self _changeState:MTRDeviceStateReachable]; - - // Then async work that shouldn't be performed on the matter queue - dispatch_async(self.queue, ^{ - // OnSubscriptionEstablished - [self _handleSubscriptionEstablished]; - }); - }, - ^(void) { - MTR_LOG("%@ got subscription done", self); - // Drop our pointer to the ReadClient immediately, since - // it's about to be destroyed and we don't want to be - // holding a dangling pointer. - std::lock_guard lock(self->_lock); - self->_currentReadClient = nullptr; - self->_currentSubscriptionCallback = nullptr; - - dispatch_async(self.queue, ^{ - // OnDone - [self _handleSubscriptionReset:nil]; - }); - }, - ^(void) { - MTR_LOG("%@ got unsolicited message from publisher", self); - dispatch_async(self.queue, ^{ - // OnUnsolicitedMessageFromPublisher - [self _handleUnsolicitedMessageFromPublisher]; - }); - }, - ^(void) { - MTR_LOG("%@ got report begin", self); - dispatch_async(self.queue, ^{ - [self _handleReportBegin]; - }); - }, - ^(void) { - MTR_LOG("%@ got report end", self); - dispatch_async(self.queue, ^{ - [self _handleReportEnd]; - }); - }); - - // Set up a cluster state cache. We just want this for the logic it has for - // tracking data versions and event numbers so we minimize the amount of data we - // request on resubscribes, so tell it not to store data. - auto clusterStateCache = std::make_unique(*callback.get(), - /* highestReceivedEventNumber = */ NullOptional, - /* cacheData = */ false); - auto readClient = std::make_unique(InteractionModelEngine::GetInstance(), exchangeManager, - clusterStateCache->GetBufferedCallback(), ReadClient::InteractionType::Subscribe); - - // Wildcard endpoint, cluster, attribute, event. - auto attributePath = std::make_unique(); - auto eventPath = std::make_unique(); - // We want to get event reports at the minInterval, not the maxInterval. - eventPath->mIsUrgentEvent = true; - ReadPrepareParams readParams(session.Value()); - - readParams.mMinIntervalFloorSeconds = 0; - // Select a max interval based on the device's claimed idle sleep interval. - auto idleSleepInterval = std::chrono::duration_cast( - session.Value()->GetRemoteMRPConfig().mIdleRetransTimeout); - - auto maxIntervalCeilingMin = System::Clock::Seconds32(MTR_DEVICE_SUBSCRIPTION_MAX_INTERVAL_MIN); - if (idleSleepInterval < maxIntervalCeilingMin) { - idleSleepInterval = maxIntervalCeilingMin; - } - - auto maxIntervalCeilingMax = System::Clock::Seconds32(MTR_DEVICE_SUBSCRIPTION_MAX_INTERVAL_MAX); - if (idleSleepInterval > maxIntervalCeilingMax) { - idleSleepInterval = maxIntervalCeilingMax; - } -#ifdef DEBUG - if (maxIntervalOverride.HasValue()) { - idleSleepInterval = maxIntervalOverride.Value(); - } -#endif - readParams.mMaxIntervalCeilingSeconds = static_cast(idleSleepInterval.count()); - - readParams.mpAttributePathParamsList = attributePath.get(); - readParams.mAttributePathParamsListSize = 1; - readParams.mpEventPathParamsList = eventPath.get(); - readParams.mEventPathParamsListSize = 1; - readParams.mKeepSubscriptions = true; - readParams.mIsFabricFiltered = false; - - // Subscribe with data version filter list from our cache. - size_t dataVersionFilterListSize = 0; - DataVersionFilter * dataVersionFilterList; - [self _createDataVersionFilterListFromDictionary:[self _getCachedDataVersions] dataVersionFilterList:&dataVersionFilterList count:&dataVersionFilterListSize]; - - readParams.mDataVersionFilterListSize = dataVersionFilterListSize; - readParams.mpDataVersionFilterList = dataVersionFilterList; - attributePath.release(); - eventPath.release(); - - // TODO: Change from local filter list generation to rehydrating ClusterStateCache to take advantage of existing filter list sorting algorithm - - // SendAutoResubscribeRequest cleans up the params, even on failure. - CHIP_ERROR err = readClient->SendAutoResubscribeRequest(std::move(readParams)); - if (err != CHIP_NO_ERROR) { - NSError * error = [MTRError errorForCHIPErrorCode:err logContext:self]; - MTR_LOG_ERROR("%@ SendAutoResubscribeRequest error %@", self, error); - dispatch_async(self.queue, ^{ - [self _handleSubscriptionError:error]; - [self _handleSubscriptionReset:nil]; - }); - - return; - } - - MTR_LOG("%@ Subscribe with data version list size %lu", self, static_cast(dataVersionFilterListSize)); - - // Callback and ClusterStateCache and ReadClient will be deleted - // when OnDone is called. - os_unfair_lock_lock(&self->_lock); - self->_currentReadClient = readClient.get(); - self->_currentSubscriptionCallback = callback.get(); - os_unfair_lock_unlock(&self->_lock); - callback->AdoptReadClient(std::move(readClient)); - callback->AdoptClusterStateCache(std::move(clusterStateCache)); - callback.release(); - }]; - - // Set up connectivity monitoring in case network becomes routable after any part of the subscription process goes into backoff retries. - [self _setupConnectivityMonitoring]; -} - #ifdef DEBUG - (NSUInteger)unitTestAttributesReportedSinceLastCheck { - NSUInteger attributesReportedSinceLastCheck = _unitTestAttributesReportedSinceLastCheck; - _unitTestAttributesReportedSinceLastCheck = 0; - return attributesReportedSinceLastCheck; + return 0; } - (NSUInteger)unitTestNonnullDelegateCount @@ -3472,13 +2613,6 @@ - (void)_pruneEndpointsIn:(MTRDeviceDataValueDictionary)previousPartsListValue } [self _removeClusters:clusterPathsToRemove doRemoveFromDataStore:NO]; [self.deviceController.controllerDataStore clearStoredClusterDataForNodeID:self.nodeID endpointID:endpoint]; - - [_deviceController asyncDispatchToMatterQueue:^{ - std::lock_guard lock(self->_lock); - if (self->_currentSubscriptionCallback) { - self->_currentSubscriptionCallback->ClearCachedAttributeState(static_cast(endpoint.unsignedLongLongValue)); - } - } errorHandler:nil]; } } @@ -3499,17 +2633,6 @@ - (void)_pruneClustersIn:(MTRDeviceDataValueDictionary)previousServerListValue } } [self _removeClusters:clusterPathsToRemove doRemoveFromDataStore:YES]; - - [_deviceController asyncDispatchToMatterQueue:^{ - std::lock_guard lock(self->_lock); - if (self->_currentSubscriptionCallback) { - for (NSNumber * cluster in toBeRemovedClusters) { - ConcreteClusterPath clusterPath(static_cast(endpointID.unsignedLongLongValue), - static_cast(cluster.unsignedLongLongValue)); - self->_currentSubscriptionCallback->ClearCachedAttributeState(clusterPath); - } - } - } errorHandler:nil]; } - (void)_pruneAttributesIn:(MTRDeviceDataValueDictionary)previousAttributeListValue @@ -3523,18 +2646,6 @@ - (void)_pruneAttributesIn:(MTRDeviceDataValueDictionary)previousAttributeListVa [toBeRemovedAttributes minusSet:attributesStillInCluster]; [self _removeAttributes:toBeRemovedAttributes fromCluster:clusterPath]; - - [_deviceController asyncDispatchToMatterQueue:^{ - std::lock_guard lock(self->_lock); - if (self->_currentSubscriptionCallback) { - for (NSNumber * attribute in toBeRemovedAttributes) { - ConcreteAttributePath attributePath(static_cast(clusterPath.endpoint.unsignedLongLongValue), - static_cast(clusterPath.cluster.unsignedLongLongValue), - static_cast(attribute.unsignedLongLongValue)); - self->_currentSubscriptionCallback->ClearCachedAttributeState(attributePath); - } - } - } errorHandler:nil]; } - (void)_pruneStoredDataForPath:(MTRAttributePath *)attributePath @@ -3769,25 +2880,6 @@ - (void)setPersistedDeviceData:(NSDictionary *)data } } -- (void)_storePersistedDeviceData -{ - os_unfair_lock_assert_owner(&self->_lock); - - auto datastore = _deviceController.controllerDataStore; - if (datastore == nil) { - // No way to store. - return; - } - - // For now the only data we have is our initial subscribe latency. - NSMutableDictionary * data = [NSMutableDictionary dictionary]; - if (_estimatedSubscriptionLatency != nil) { - data[sLastInitialSubscribeLatencyKey] = _estimatedSubscriptionLatency; - } - - [datastore storeDeviceData:[data copy] forNodeID:self.nodeID]; -} - #ifdef DEBUG - (MTRDeviceClusterData *)unitTestGetClusterDataForPath:(MTRClusterPath *)path { @@ -4215,20 +3307,11 @@ @implementation MTRDevice (MatterPrivateForInternalDragonsDoNotFeed) - (BOOL)_deviceHasActiveSubscription { - std::lock_guard lock(_lock); - - // TODO: This should always return YES for thread devices - return HaveSubscriptionEstablishedRightNow(_internalDeviceState); + return NO; } - (void)_deviceMayBeReachable { - MTR_LOG("%@ _deviceMayBeReachable called", self); - // TODO: This should only be allowed for thread devices - [_deviceController asyncDispatchToMatterQueue:^{ - [self _triggerResubscribeWithReason:@"SPI client indicated the device may now be reachable" - nodeLikelyReachable:YES]; - } errorHandler:nil]; } /* END DRAGONS */ @@ -4264,122 +3347,3 @@ - (void)invokeCommandWithEndpointID:(NSNumber *)endpointID } @end - -#pragma mark - SubscriptionCallback -namespace { -void SubscriptionCallback::OnEventData(const EventHeader & aEventHeader, TLV::TLVReader * apData, const StatusIB * apStatus) -{ - if (mEventReports == nil) { - // Never got a OnReportBegin? Not much to do other than tear things down. - ReportError(CHIP_ERROR_INCORRECT_STATE); - return; - } - - MTREventPath * eventPath = [[MTREventPath alloc] initWithPath:aEventHeader.mPath]; - if (apStatus != nullptr) { - [mEventReports addObject:@ { MTREventPathKey : eventPath, MTRErrorKey : [MTRError errorForIMStatus:*apStatus] }]; - } else if (apData == nullptr) { - [mEventReports addObject:@ { - MTREventPathKey : eventPath, - MTRErrorKey : [MTRError errorForCHIPErrorCode:CHIP_ERROR_INVALID_ARGUMENT] - }]; - } else { - id value = MTRDecodeDataValueDictionaryFromCHIPTLV(apData); - if (value == nil) { - MTR_LOG_ERROR("Failed to decode event data for path %@", eventPath); - [mEventReports addObject:@ { - MTREventPathKey : eventPath, - MTRErrorKey : [MTRError errorForCHIPErrorCode:CHIP_ERROR_DECODE_FAILED], - }]; - } else { - [mEventReports addObject:[MTRBaseDevice eventReportForHeader:aEventHeader andData:value]]; - } - } - - QueueInterimReport(); -} - -void SubscriptionCallback::OnAttributeData( - const ConcreteDataAttributePath & aPath, TLV::TLVReader * apData, const StatusIB & aStatus) -{ - if (aPath.IsListItemOperation()) { - ReportError(CHIP_ERROR_INCORRECT_STATE); - return; - } - - if (mAttributeReports == nil) { - // Never got a OnReportBegin? Not much to do other than tear things down. - ReportError(CHIP_ERROR_INCORRECT_STATE); - return; - } - - MTRAttributePath * attributePath = [[MTRAttributePath alloc] initWithPath:aPath]; - if (aStatus.mStatus != Status::Success) { - [mAttributeReports addObject:@ { MTRAttributePathKey : attributePath, MTRErrorKey : [MTRError errorForIMStatus:aStatus] }]; - } else if (apData == nullptr) { - [mAttributeReports addObject:@ { - MTRAttributePathKey : attributePath, - MTRErrorKey : [MTRError errorForCHIPErrorCode:CHIP_ERROR_INVALID_ARGUMENT] - }]; - } else { - NSNumber * dataVersionNumber = aPath.mDataVersion.HasValue() ? @(aPath.mDataVersion.Value()) : nil; - NSDictionary * value = MTRDecodeDataValueDictionaryFromCHIPTLV(apData, dataVersionNumber); - if (value == nil) { - MTR_LOG_ERROR("Failed to decode attribute data for path %@", attributePath); - [mAttributeReports addObject:@ { - MTRAttributePathKey : attributePath, - MTRErrorKey : [MTRError errorForCHIPErrorCode:CHIP_ERROR_DECODE_FAILED], - }]; - } else { - [mAttributeReports addObject:@ { MTRAttributePathKey : attributePath, MTRDataKey : value }]; - } - } - - QueueInterimReport(); -} - -uint32_t SubscriptionCallback::ComputeTimeTillNextSubscription() -{ - uint32_t maxWaitTimeInMsec = 0; - uint32_t waitTimeInMsec = 0; - uint32_t minWaitTimeInMsec = 0; - - if (mResubscriptionNumRetries <= CHIP_RESUBSCRIBE_MAX_FIBONACCI_STEP_INDEX) { - maxWaitTimeInMsec = GetFibonacciForIndex(mResubscriptionNumRetries) * CHIP_RESUBSCRIBE_WAIT_TIME_MULTIPLIER_MS; - } else { - maxWaitTimeInMsec = CHIP_RESUBSCRIBE_MAX_RETRY_WAIT_INTERVAL_MS; - } - - if (maxWaitTimeInMsec != 0) { - minWaitTimeInMsec = (CHIP_RESUBSCRIBE_MIN_WAIT_TIME_INTERVAL_PERCENT_PER_STEP * maxWaitTimeInMsec) / 100; - waitTimeInMsec = minWaitTimeInMsec + (Crypto::GetRandU32() % (maxWaitTimeInMsec - minWaitTimeInMsec)); - } - - return waitTimeInMsec; -} - -CHIP_ERROR SubscriptionCallback::OnResubscriptionNeeded(ReadClient * apReadClient, CHIP_ERROR aTerminationCause) -{ - // No need to check ReadClient internal state is Idle because ReadClient only calls OnResubscriptionNeeded after calling ClearActiveSubscriptionState(), which sets the state to Idle. - - // This part is copied from ReadClient's DefaultResubscribePolicy: - auto timeTillNextResubscriptionMs = ComputeTimeTillNextSubscription(); - ChipLogProgress(DataManagement, - "Will try to resubscribe to %02x:" ChipLogFormatX64 " at retry index %" PRIu32 " after %" PRIu32 - "ms due to error %" CHIP_ERROR_FORMAT, - apReadClient->GetFabricIndex(), ChipLogValueX64(apReadClient->GetPeerNodeId()), mResubscriptionNumRetries, timeTillNextResubscriptionMs, - aTerminationCause.Format()); - - // Schedule a maximum time resubscription, to be triggered with TriggerResubscribeIfScheduled after a separate timer. - // This way the aReestablishCASE value is saved, and the sanity checks in ScheduleResubscription are observed and returned. - ReturnErrorOnFailure(apReadClient->ScheduleResubscription(UINT32_MAX, NullOptional, aTerminationCause == CHIP_ERROR_TIMEOUT)); - - // Not as good a place to increment as when resubscription timer fires, but as is, this should be as good, because OnResubscriptionNeeded is only called from ReadClient's Close() while Idle, and nothing should cause this to happen - mResubscriptionNumRetries++; - - auto error = [MTRError errorForCHIPErrorCode:aTerminationCause]; - CallResubscriptionScheduledHandler(error, @(timeTillNextResubscriptionMs)); - - return CHIP_NO_ERROR; -} -} // anonymous namespace From 72ee6eb2973c3b5aecb17e7b92dc90780ec6bf11 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mi=C5=82osz=20Tomkiel?= Date: Thu, 22 Aug 2024 08:51:25 +0200 Subject: [PATCH 137/165] Enhance chip-tool's formatting for some IDs (#35088) * Added logging functions * Modify ZAP template file generation * Updated files for CommandId support * Updated manual tests for the new formatting * Fixed variable name shadowing * Fixed typo * Added logging functions to fabric admin * Restyled by whitespace * Restyled by clang-format * Fixed linking * Fixed typo * Fixed CommandId logging * Updated ZAP generated files * Restyled by clang-format --------- Co-authored-by: Restyled.io --- examples/chip-tool/BUILD.gn | 1 + .../commands/clusters/DataModelLogger.h | 95 + .../logging/DataModelLogger-src.zapt | 12 + .../templates/logging/EntryToText-src.zapt | 84 + .../templates/logging/EntryToText.zapt | 13 + examples/chip-tool/templates/templates.json | 10 + .../commands/clusters/DataModelLogger.h | 95 + .../tv-casting-app/tv-casting-common/BUILD.gn | 1 + .../suites/certification/Test_TC_DEM_1_1.yaml | 54 +- .../certification/Test_TC_DESC_2_1.yaml | 178 +- .../suites/certification/Test_TC_IDM_2_2.yaml | 424 +- .../certification/Test_TC_WAKEONLAN_4_1.yaml | 8 +- .../cluster/logging/DataModelLogger.cpp | 773 +- .../cluster/logging/EntryToText.cpp | 6700 +++++++++++++++++ .../cluster/logging/EntryToText.h | 30 + 15 files changed, 7765 insertions(+), 713 deletions(-) create mode 100644 examples/chip-tool/templates/logging/EntryToText-src.zapt create mode 100644 examples/chip-tool/templates/logging/EntryToText.zapt create mode 100644 zzz_generated/chip-tool/zap-generated/cluster/logging/EntryToText.cpp create mode 100644 zzz_generated/chip-tool/zap-generated/cluster/logging/EntryToText.h diff --git a/examples/chip-tool/BUILD.gn b/examples/chip-tool/BUILD.gn index 94e1eebbde..acacbc70e8 100644 --- a/examples/chip-tool/BUILD.gn +++ b/examples/chip-tool/BUILD.gn @@ -53,6 +53,7 @@ static_library("chip-tool-utils") { "${chip_root}/src/controller/ExamplePersistentStorage.h", "${chip_root}/zzz_generated/chip-tool/zap-generated/cluster/ComplexArgumentParser.cpp", "${chip_root}/zzz_generated/chip-tool/zap-generated/cluster/logging/DataModelLogger.cpp", + "${chip_root}/zzz_generated/chip-tool/zap-generated/cluster/logging/EntryToText.cpp", "commands/clusters/ModelCommand.cpp", "commands/clusters/ModelCommand.h", "commands/common/BDXDiagnosticLogsServerDelegate.cpp", diff --git a/examples/chip-tool/commands/clusters/DataModelLogger.h b/examples/chip-tool/commands/clusters/DataModelLogger.h index 1d9d1e1ccd..7186b833ff 100644 --- a/examples/chip-tool/commands/clusters/DataModelLogger.h +++ b/examples/chip-tool/commands/clusters/DataModelLogger.h @@ -28,6 +28,7 @@ #include #include #include +#include class DataModelLogger { @@ -157,6 +158,100 @@ class DataModelLogger return CHIP_NO_ERROR; } + static CHIP_ERROR LogClusterId(const char * label, size_t indent, + const chip::app::DataModel::DecodableList & value) + { + size_t count = 0; + ReturnErrorOnFailure(value.ComputeSize(&count)); + DataModelLogger::LogString(label, indent, std::to_string(count) + " entries"); + + auto iter = value.begin(); + size_t i = 0; + while (iter.Next()) + { + ++i; + std::string index = std::string("[") + std::to_string(i) + "]"; + std::string item = std::to_string(iter.GetValue()) + " (" + ClusterIdToText(iter.GetValue()) + ")"; + DataModelLogger::LogString(index, indent + 1, item); + } + if (iter.GetStatus() != CHIP_NO_ERROR) + { + DataModelLogger::LogString(indent + 1, "List truncated due to invalid value"); + } + return iter.GetStatus(); + } + + static CHIP_ERROR LogAttributeId(const char * label, size_t indent, + const chip::app::DataModel::DecodableList & value, chip::ClusterId cluster) + { + size_t count = 0; + ReturnErrorOnFailure(value.ComputeSize(&count)); + DataModelLogger::LogString(label, indent, std::to_string(count) + " entries"); + + auto iter = value.begin(); + size_t i = 0; + while (iter.Next()) + { + ++i; + std::string index = std::string("[") + std::to_string(i) + "]"; + std::string item = std::to_string(iter.GetValue()) + " (" + AttributeIdToText(cluster, iter.GetValue()) + ")"; + DataModelLogger::LogString(index, indent + 1, item); + } + if (iter.GetStatus() != CHIP_NO_ERROR) + { + DataModelLogger::LogString(indent + 1, "List truncated due to invalid value"); + } + return iter.GetStatus(); + } + + static CHIP_ERROR LogAcceptedCommandId(const char * label, size_t indent, + const chip::app::DataModel::DecodableList & value, + chip::ClusterId cluster) + { + size_t count = 0; + ReturnErrorOnFailure(value.ComputeSize(&count)); + DataModelLogger::LogString(label, indent, std::to_string(count) + " entries"); + + auto iter = value.begin(); + size_t i = 0; + while (iter.Next()) + { + ++i; + std::string index = std::string("[") + std::to_string(i) + "]"; + std::string item = std::to_string(iter.GetValue()) + " (" + AcceptedCommandIdToText(cluster, iter.GetValue()) + ")"; + DataModelLogger::LogString(index, indent + 1, item); + } + if (iter.GetStatus() != CHIP_NO_ERROR) + { + DataModelLogger::LogString(indent + 1, "List truncated due to invalid value"); + } + return iter.GetStatus(); + } + + static CHIP_ERROR LogGeneratedCommandId(const char * label, size_t indent, + const chip::app::DataModel::DecodableList & value, + chip::ClusterId cluster) + { + size_t count = 0; + ReturnErrorOnFailure(value.ComputeSize(&count)); + DataModelLogger::LogString(label, indent, std::to_string(count) + " entries"); + + auto iter = value.begin(); + size_t i = 0; + while (iter.Next()) + { + ++i; + std::string index = std::string("[") + std::to_string(i) + "]"; + std::string item = std::to_string(iter.GetValue()) + " (" + GeneratedCommandIdToText(cluster, iter.GetValue()) + ")"; + DataModelLogger::LogString(index, indent + 1, item); + } + if (iter.GetStatus() != CHIP_NO_ERROR) + { + DataModelLogger::LogString(indent + 1, "List truncated due to invalid value"); + } + return iter.GetStatus(); + } + #include static void LogString(size_t indent, const std::string string) { LogString("", indent, string); } diff --git a/examples/chip-tool/templates/logging/DataModelLogger-src.zapt b/examples/chip-tool/templates/logging/DataModelLogger-src.zapt index 0f41ff2e16..3f76143ffa 100644 --- a/examples/chip-tool/templates/logging/DataModelLogger-src.zapt +++ b/examples/chip-tool/templates/logging/DataModelLogger-src.zapt @@ -75,7 +75,19 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP { {{zapTypeToDecodableClusterObjectType type ns=parent.name forceNotOptional=true}} value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); +{{#if (isEqual name "ServerList")}} + return DataModelLogger::LogClusterId("{{name}}", 1, value); +{{else if (isEqual name "ClientList")}} + return DataModelLogger::LogClusterId("{{name}}", 1, value); +{{else if (isEqual name "AttributeList")}} + return DataModelLogger::LogAttributeId("{{name}}", 1, value, {{asUpperCamelCase parent.name}}::Id); +{{else if (isEqual name "AcceptedCommandList")}} + return DataModelLogger::LogAcceptedCommandId("{{name}}", 1, value, {{asUpperCamelCase parent.name}}::Id); +{{else if (isEqual name "GeneratedCommandList")}} + return DataModelLogger::LogGeneratedCommandId("{{name}}", 1, value, {{asUpperCamelCase parent.name}}::Id); +{{else}} return DataModelLogger::LogValue("{{name}}", 1, value); +{{/if}} } {{#last}} } diff --git a/examples/chip-tool/templates/logging/EntryToText-src.zapt b/examples/chip-tool/templates/logging/EntryToText-src.zapt new file mode 100644 index 0000000000..646ee2ad87 --- /dev/null +++ b/examples/chip-tool/templates/logging/EntryToText-src.zapt @@ -0,0 +1,84 @@ +{{> header}} + +#include +#include +#include + +char const * ClusterIdToText(chip::ClusterId id) { + switch(id) + { +{{#zcl_clusters}} + case chip::app::Clusters::{{asUpperCamelCase name}}::Id: return "{{asUpperCamelCase name}}"; +{{/zcl_clusters}} + default: return "Unknown"; + } +} + +char const * AttributeIdToText(chip::ClusterId cluster, chip::AttributeId id) { + switch(cluster) + { +{{#zcl_clusters}} +{{#zcl_attributes_server}} +{{#first}} + case chip::app::Clusters::{{asUpperCamelCase parent.name}}::Id: + { + switch(id) + { +{{/first}} + case chip::app::Clusters::{{asUpperCamelCase parent.name}}::Attributes::{{asUpperCamelCase name}}::Id: return "{{asUpperCamelCase name}}"; +{{#last}} + default: return "Unknown"; + } + } +{{/last}} +{{/zcl_attributes_server}} +{{/zcl_clusters}} + default: return "Unknown"; + } +} + +char const * AcceptedCommandIdToText(chip::ClusterId cluster, chip::CommandId id) { + switch(cluster) + { +{{#zcl_clusters}} +{{#zcl_commands_source_client}} +{{#first}} + case chip::app::Clusters::{{asUpperCamelCase parent.name}}::Id: + { + switch(id) + { +{{/first}} + case chip::app::Clusters::{{asUpperCamelCase parent.name}}::Commands::{{asUpperCamelCase name}}::Id: return "{{asUpperCamelCase name}}"; +{{#last}} + default: return "Unknown"; + } + } +{{/last}} +{{/zcl_commands_source_client}} +{{/zcl_clusters}} + default: return "Unknown"; + } +} + +char const * GeneratedCommandIdToText(chip::ClusterId cluster, chip::CommandId id) { + switch(cluster) + { +{{#zcl_clusters}} +{{#zcl_commands_source_server}} +{{#first}} + case chip::app::Clusters::{{asUpperCamelCase parent.name}}::Id: + { + switch(id) + { +{{/first}} + case chip::app::Clusters::{{asUpperCamelCase parent.name}}::Commands::{{asUpperCamelCase name}}::Id: return "{{asUpperCamelCase name}}"; +{{#last}} + default: return "Unknown"; + } + } +{{/last}} +{{/zcl_commands_source_server}} +{{/zcl_clusters}} + default: return "Unknown"; + } +} \ No newline at end of file diff --git a/examples/chip-tool/templates/logging/EntryToText.zapt b/examples/chip-tool/templates/logging/EntryToText.zapt new file mode 100644 index 0000000000..d1a78f84dc --- /dev/null +++ b/examples/chip-tool/templates/logging/EntryToText.zapt @@ -0,0 +1,13 @@ +{{> header}} + +#include +#include +#include + +char const * ClusterIdToText(chip::ClusterId id); + +char const * AttributeIdToText(chip::ClusterId cluster, chip::AttributeId id); + +char const * AcceptedCommandIdToText(chip::ClusterId cluster, chip::CommandId id); + +char const * GeneratedCommandIdToText(chip::ClusterId cluster, chip::CommandId id); \ No newline at end of file diff --git a/examples/chip-tool/templates/templates.json b/examples/chip-tool/templates/templates.json index 528c7d266d..9ced10b137 100644 --- a/examples/chip-tool/templates/templates.json +++ b/examples/chip-tool/templates/templates.json @@ -64,6 +64,16 @@ "path": "ComplexArgumentParser-src.zapt", "name": "Complex Argument Parser", "output": "cluster/ComplexArgumentParser.cpp" + }, + { + "path": "logging/EntryToText.zapt", + "name": "Entry To Text header", + "output": "cluster/logging/EntryToText.h" + }, + { + "path": "logging/EntryToText-src.zapt", + "name": "Entry To Text", + "output": "cluster/logging/EntryToText.cpp" } ] } diff --git a/examples/fabric-admin/commands/clusters/DataModelLogger.h b/examples/fabric-admin/commands/clusters/DataModelLogger.h index ee64975501..36f53ba381 100644 --- a/examples/fabric-admin/commands/clusters/DataModelLogger.h +++ b/examples/fabric-admin/commands/clusters/DataModelLogger.h @@ -28,6 +28,7 @@ #include #include #include +#include class DataModelLogger { @@ -157,6 +158,100 @@ class DataModelLogger return CHIP_NO_ERROR; } + static CHIP_ERROR LogClusterId(const char * label, size_t indent, + const chip::app::DataModel::DecodableList & value) + { + size_t count = 0; + ReturnErrorOnFailure(value.ComputeSize(&count)); + DataModelLogger::LogString(label, indent, std::to_string(count) + " entries"); + + auto iter = value.begin(); + size_t i = 0; + while (iter.Next()) + { + ++i; + std::string index = std::string("[") + std::to_string(i) + "]"; + std::string item = std::to_string(iter.GetValue()) + " (" + ClusterIdToText(iter.GetValue()) + ")"; + DataModelLogger::LogString(index, indent + 1, item); + } + if (iter.GetStatus() != CHIP_NO_ERROR) + { + DataModelLogger::LogString(indent + 1, "List truncated due to invalid value"); + } + return iter.GetStatus(); + } + + static CHIP_ERROR LogAttributeId(const char * label, size_t indent, + const chip::app::DataModel::DecodableList & value, chip::ClusterId cluster) + { + size_t count = 0; + ReturnErrorOnFailure(value.ComputeSize(&count)); + DataModelLogger::LogString(label, indent, std::to_string(count) + " entries"); + + auto iter = value.begin(); + size_t i = 0; + while (iter.Next()) + { + ++i; + std::string index = std::string("[") + std::to_string(i) + "]"; + std::string item = std::to_string(iter.GetValue()) + " (" + AttributeIdToText(cluster, iter.GetValue()) + ")"; + DataModelLogger::LogString(index, indent + 1, item); + } + if (iter.GetStatus() != CHIP_NO_ERROR) + { + DataModelLogger::LogString(indent + 1, "List truncated due to invalid value"); + } + return iter.GetStatus(); + } + + static CHIP_ERROR LogAcceptedCommandId(const char * label, size_t indent, + const chip::app::DataModel::DecodableList & value, + chip::ClusterId cluster) + { + size_t count = 0; + ReturnErrorOnFailure(value.ComputeSize(&count)); + DataModelLogger::LogString(label, indent, std::to_string(count) + " entries"); + + auto iter = value.begin(); + size_t i = 0; + while (iter.Next()) + { + ++i; + std::string index = std::string("[") + std::to_string(i) + "]"; + std::string item = std::to_string(iter.GetValue()) + " (" + AcceptedCommandIdToText(cluster, iter.GetValue()) + ")"; + DataModelLogger::LogString(index, indent + 1, item); + } + if (iter.GetStatus() != CHIP_NO_ERROR) + { + DataModelLogger::LogString(indent + 1, "List truncated due to invalid value"); + } + return iter.GetStatus(); + } + + static CHIP_ERROR LogGeneratedCommandId(const char * label, size_t indent, + const chip::app::DataModel::DecodableList & value, + chip::ClusterId cluster) + { + size_t count = 0; + ReturnErrorOnFailure(value.ComputeSize(&count)); + DataModelLogger::LogString(label, indent, std::to_string(count) + " entries"); + + auto iter = value.begin(); + size_t i = 0; + while (iter.Next()) + { + ++i; + std::string index = std::string("[") + std::to_string(i) + "]"; + std::string item = std::to_string(iter.GetValue()) + " (" + GeneratedCommandIdToText(cluster, iter.GetValue()) + ")"; + DataModelLogger::LogString(index, indent + 1, item); + } + if (iter.GetStatus() != CHIP_NO_ERROR) + { + DataModelLogger::LogString(indent + 1, "List truncated due to invalid value"); + } + return iter.GetStatus(); + } + #include static void LogString(size_t indent, const std::string string) { LogString("", indent, string); } diff --git a/examples/tv-casting-app/tv-casting-common/BUILD.gn b/examples/tv-casting-app/tv-casting-common/BUILD.gn index ee422e1b06..2c30080f02 100644 --- a/examples/tv-casting-app/tv-casting-common/BUILD.gn +++ b/examples/tv-casting-app/tv-casting-common/BUILD.gn @@ -50,6 +50,7 @@ chip_data_model("tv-casting-common") { "${chip_root}/src/controller/ExamplePersistentStorage.h", "${chip_root}/zzz_generated/chip-tool/zap-generated/cluster/ComplexArgumentParser.cpp", "${chip_root}/zzz_generated/chip-tool/zap-generated/cluster/logging/DataModelLogger.cpp", + "${chip_root}/zzz_generated/chip-tool/zap-generated/cluster/logging/EntryToText.cpp", "clusters/content-app-observer/ContentAppObserver.cpp", "clusters/content-app-observer/ContentAppObserver.h", "commands/clusters/ModelCommand.cpp", diff --git a/src/app/tests/suites/certification/Test_TC_DEM_1_1.yaml b/src/app/tests/suites/certification/Test_TC_DEM_1_1.yaml index 4d1a72392a..e69e5a62b0 100644 --- a/src/app/tests/suites/certification/Test_TC_DEM_1_1.yaml +++ b/src/app/tests/suites/certification/Test_TC_DEM_1_1.yaml @@ -62,21 +62,21 @@ tests: - Based on feature support:- 0x0005, 0x0006, 0x0007 Below mentioned log is based on the RPI implementation, Value may vary on real DUT - [1705649142.831039][6212:6214] CHIP:TOO: Endpoint: 1 Cluster: 0x0000_0098 Attribute 0x0000_FFFB DataVersion: 633673396 - [1705649142.831110][6212:6214] CHIP:TOO: AttributeList: 13 entries - [1705649142.831151][6212:6214] CHIP:TOO: [1]: 0 - [1705649142.831174][6212:6214] CHIP:TOO: [2]: 1 - [1705649142.831208][6212:6214] CHIP:TOO: [3]: 2 - [1705649142.831230][6212:6214] CHIP:TOO: [4]: 3 - [1705649142.831261][6212:6214] CHIP:TOO: [5]: 4 - [1705649142.831283][6212:6214] CHIP:TOO: [6]: 5 - [1705649142.831304][6212:6214] CHIP:TOO: [7]: 6 - [1705649142.831336][6212:6214] CHIP:TOO: [8]: 7 - [1705649142.831359][6212:6214] CHIP:TOO: [9]: 65528 - [1705649142.831390][6212:6214] CHIP:TOO: [10]: 65529 - [1705649142.831434][6212:6214] CHIP:TOO: [11]: 65531 - [1705649142.831458][6212:6214] CHIP:TOO: [12]: 65532 - [1705649142.831490][6212:6214] CHIP:TOO: [13]: 65533 + [1723642027.628] [328171:328173] [TOO] Endpoint: 1 Cluster: 0x0000_0098 Attribute 0x0000_FFFB DataVersion: 3122179410 + [1723642027.628] [328171:328173] [TOO] AttributeList: 13 entries + [1723642027.628] [328171:328173] [TOO] [1]: 0 (ESAType) + [1723642027.628] [328171:328173] [TOO] [2]: 1 (ESACanGenerate) + [1723642027.628] [328171:328173] [TOO] [3]: 2 (ESAState) + [1723642027.628] [328171:328173] [TOO] [4]: 3 (AbsMinPower) + [1723642027.628] [328171:328173] [TOO] [5]: 4 (AbsMaxPower) + [1723642027.628] [328171:328173] [TOO] [6]: 5 (PowerAdjustmentCapability) + [1723642027.628] [328171:328173] [TOO] [7]: 6 (Forecast) + [1723642027.628] [328171:328173] [TOO] [8]: 7 (OptOutState) + [1723642027.628] [328171:328173] [TOO] [9]: 65528 (GeneratedCommandList) + [1723642027.628] [328171:328173] [TOO] [10]: 65529 (AcceptedCommandList) + [1723642027.628] [328171:328173] [TOO] [11]: 65531 (AttributeList) + [1723642027.628] [328171:328173] [TOO] [12]: 65532 (FeatureMap) + [1723642027.628] [328171:328173] [TOO] [13]: 65533 (ClusterRevision) disabled: true - label: "Step 5*: TH reads from the DUT the EventList attribute." @@ -100,16 +100,16 @@ tests: On TH(chip-tool), Verify the AcceptedCommandList attribute that contains 7 entries: Below mentioned log is based on the RPI implementation, Value may vary on real DUT - [1705649342.947638][6221:6223] CHIP:TOO: Endpoint: 1 Cluster: 0x0000_0098 Attribute 0x0000_FFF9 DataVersion: 633673396 - [1705649342.947712][6221:6223] CHIP:TOO: AcceptedCommandList: 8 entries - [1705649342.947754][6221:6223] CHIP:TOO: [1]: 0 - [1705649342.947779][6221:6223] CHIP:TOO: [2]: 1 - [1705649342.947802][6221:6223] CHIP:TOO: [3]: 2 - [1705649342.947825][6221:6223] CHIP:TOO: [4]: 3 - [1705649342.947848][6221:6223] CHIP:TOO: [5]: 4 - [1705649342.947871][6221:6223] CHIP:TOO: [6]: 5 - [1705649342.947894][6221:6223] CHIP:TOO: [7]: 6 - [1705649342.947917][6221:6223] CHIP:TOO: [8]: 7 + [1705649342.947638][6221:6223] [TOO] Endpoint: 1 Cluster: 0x0000_0098 Attribute 0x0000_FFF9 DataVersion: 633673396 + [1705649342.947712][6221:6223] [TOO] AcceptedCommandList: 8 entries + [1705649342.947754][6221:6223] [TOO] [1]: 0 (PowerAdjustRequest) + [1705649342.947779][6221:6223] [TOO] [2]: 1 (CancelPowerAdjustRequest) + [1705649342.947802][6221:6223] [TOO] [3]: 2 (StartTimeAdjustRequest) + [1705649342.947825][6221:6223] [TOO] [4]: 3 (PauseRequest) + [1705649342.947848][6221:6223] [TOO] [5]: 4 (ResumeRequest) + [1705649342.947871][6221:6223] [TOO] [6]: 5 (ModifyForecastRequest) + [1705649342.947894][6221:6223] [TOO] [7]: 6 (RequestConstraintBasedForecast) + [1705649342.947917][6221:6223] [TOO] [8]: 7 (CancelRequest) disabled: true - label: "Step 7: TH reads from the DUT the GeneratedCommandList attribute." @@ -118,6 +118,6 @@ tests: On TH(chip-tool), Verify the GeneratedCommandList attribute that contains 1 entries: - [1705567897.076935][7141:7143] CHIP:TOO: Endpoint: 1 Cluster: 0x0000_0098 Attribute 0x0000_FFF8 DataVersion: 1117764527 - [1705567897.076989][7141:7143] CHIP:TOO: GeneratedCommandList: 0 entries + [1705567897.076935][7141:7143] [TOO] Endpoint: 1 Cluster: 0x0000_0098 Attribute 0x0000_FFF8 DataVersion: 1117764527 + [1705567897.076989][7141:7143] [TOO] GeneratedCommandList: 0 entries disabled: true diff --git a/src/app/tests/suites/certification/Test_TC_DESC_2_1.yaml b/src/app/tests/suites/certification/Test_TC_DESC_2_1.yaml index 2ce0e296bb..2afe448fa9 100644 --- a/src/app/tests/suites/certification/Test_TC_DESC_2_1.yaml +++ b/src/app/tests/suites/certification/Test_TC_DESC_2_1.yaml @@ -142,95 +142,95 @@ tests: Verify ServerList entries on the TH (Chip-tool) and below is the sample log provided for the raspi platform, - [1707996554.409850][20755:20757] CHIP:DMG: } - [1707996554.410814][20755:20757] CHIP:TOO: Endpoint: 1 Cluster: 0x0000_001D Attribute 0x0000_0001 DataVersion: 3583190746 - [1707996554.410955][20755:20757] CHIP:TOO: ServerList: 71 entries - [1707996554.410990][20755:20757] CHIP:TOO: [1]: 3 - [1707996554.411002][20755:20757] CHIP:TOO: [2]: 4 - [1707996554.411013][20755:20757] CHIP:TOO: [3]: 6 - [1707996554.411024][20755:20757] CHIP:TOO: [4]: 7 - [1707996554.411034][20755:20757] CHIP:TOO: [5]: 8 - [1707996554.411045][20755:20757] CHIP:TOO: [6]: 15 - [1707996554.411056][20755:20757] CHIP:TOO: [7]: 29 - [1707996554.411067][20755:20757] CHIP:TOO: [8]: 30 - [1707996554.411078][20755:20757] CHIP:TOO: [9]: 37 - [1707996554.411092][20755:20757] CHIP:TOO: [10]: 47 - [1707996554.411103][20755:20757] CHIP:TOO: [11]: 59 - [1707996554.411113][20755:20757] CHIP:TOO: [12]: 64 - [1707996554.411124][20755:20757] CHIP:TOO: [13]: 65 - [1707996554.411135][20755:20757] CHIP:TOO: [14]: 69 - [1707996554.411146][20755:20757] CHIP:TOO: [15]: 72 - [1707996554.411156][20755:20757] CHIP:TOO: [16]: 73 - [1707996554.411167][20755:20757] CHIP:TOO: [17]: 74 - [1707996554.411177][20755:20757] CHIP:TOO: [18]: 80 - [1707996554.411188][20755:20757] CHIP:TOO: [19]: 81 - [1707996554.411199][20755:20757] CHIP:TOO: [20]: 82 - [1707996554.411209][20755:20757] CHIP:TOO: [21]: 83 - [1707996554.411220][20755:20757] CHIP:TOO: [22]: 84 - [1707996554.411231][20755:20757] CHIP:TOO: [23]: 85 - [1707996554.411240][20755:20757] CHIP:TOO: [24]: 86 - [1707996554.411251][20755:20757] CHIP:TOO: [25]: 87 - [1707996554.411261][20755:20757] CHIP:TOO: [26]: 89 - [1707996554.411271][20755:20757] CHIP:TOO: [27]: 91 - [1707996554.411282][20755:20757] CHIP:TOO: [28]: 92 - [1707996554.411293][20755:20757] CHIP:TOO: [29]: 93 - [1707996554.411303][20755:20757] CHIP:TOO: [30]: 94 - [1707996554.411313][20755:20757] CHIP:TOO: [31]: 96 - [1707996554.411323][20755:20757] CHIP:TOO: [32]: 97 - [1707996554.411334][20755:20757] CHIP:TOO: [33]: 98 - [1707996554.411345][20755:20757] CHIP:TOO: [34]: 113 - [1707996554.411355][20755:20757] CHIP:TOO: [35]: 114 - [1707996554.411367][20755:20757] CHIP:TOO: [36]: 128 - [1707996554.411376][20755:20757] CHIP:TOO: [37]: 129 - [1707996554.411387][20755:20757] CHIP:TOO: [38]: 144 - [1707996554.411396][20755:20757] CHIP:TOO: [39]: 145 - [1707996554.411406][20755:20757] CHIP:TOO: [40]: 152 - [1707996554.411417][20755:20757] CHIP:TOO: [41]: 153 - [1707996554.411427][20755:20757] CHIP:TOO: [42]: 157 - [1707996554.411437][20755:20757] CHIP:TOO: [43]: 159 - [1707996554.411449][20755:20757] CHIP:TOO: [44]: 258 - [1707996554.411459][20755:20757] CHIP:TOO: [45]: 259 - [1707996554.411469][20755:20757] CHIP:TOO: [46]: 512 - [1707996554.411480][20755:20757] CHIP:TOO: [47]: 513 - [1707996554.411490][20755:20757] CHIP:TOO: [48]: 514 - [1707996554.411500][20755:20757] CHIP:TOO: [49]: 516 - [1707996554.411511][20755:20757] CHIP:TOO: [50]: 768 - [1707996554.411521][20755:20757] CHIP:TOO: [51]: 769 - [1707996554.411532][20755:20757] CHIP:TOO: [52]: 1024 - [1707996554.411559][20755:20757] CHIP:TOO: [53]: 1026 - [1707996554.411562][20755:20757] CHIP:TOO: [54]: 1027 - [1707996554.411565][20755:20757] CHIP:TOO: [55]: 1028 - [1707996554.411568][20755:20757] CHIP:TOO: [56]: 1029 - [1707996554.411571][20755:20757] CHIP:TOO: [57]: 1030 - [1707996554.411575][20755:20757] CHIP:TOO: [58]: 1036 - [1707996554.411578][20755:20757] CHIP:TOO: [59]: 1037 - [1707996554.411581][20755:20757] CHIP:TOO: [60]: 1043 - [1707996554.411584][20755:20757] CHIP:TOO: [61]: 1045 - [1707996554.411587][20755:20757] CHIP:TOO: [62]: 1066 - [1707996554.411589][20755:20757] CHIP:TOO: [63]: 1067 - [1707996554.411592][20755:20757] CHIP:TOO: [64]: 1068 - [1707996554.411595][20755:20757] CHIP:TOO: [65]: 1069 - [1707996554.411598][20755:20757] CHIP:TOO: [66]: 1070 - [1707996554.411601][20755:20757] CHIP:TOO: [67]: 1071 - [1707996554.411604][20755:20757] CHIP:TOO: [68]: 1283 - [1707996554.411607][20755:20757] CHIP:TOO: [69]: 1288 - [1707996554.411610][20755:20757] CHIP:TOO: [70]: 2820 - [1707996554.411613][20755:20757] CHIP:TOO: [71]: 4294048773 + [1707996554.409850][20755:20757] [DMG] } + [1707996554.410814][20755:20757] [TOO] Endpoint: 1 Cluster: 0x0000_001D Attribute 0x0000_0001 DataVersion: 3583190746 + [1707996554.410955][20755:20757] [TOO] ServerList: 71 entries + [1707996554.410990][20755:20757] [TOO] [1]: 3 (Identify) + [1707996554.411002][20755:20757] [TOO] [2]: 4 (Groups) + [1707996554.411013][20755:20757] [TOO] [3]: 6 (OnOff) + [1707996554.411024][20755:20757] [TOO] [4]: 7 (OnOffSwitchConfiguration) + [1707996554.411034][20755:20757] [TOO] [5]: 8 (LevelControl) + [1707996554.411045][20755:20757] [TOO] [6]: 15 (BinaryInputBasic) + [1707996554.411056][20755:20757] [TOO] [7]: 29 (Descriptor) + [1707996554.411067][20755:20757] [TOO] [8]: 30 (Binding) + [1707996554.411078][20755:20757] [TOO] [9]: 37 (Actions) + [1707996554.411092][20755:20757] [TOO] [10]: 47 (PowerSource) + [1707996554.411103][20755:20757] [TOO] [11]: 59 (Switch) + [1707996554.411113][20755:20757] [TOO] [12]: 64 (FixedLabel) + [1707996554.411124][20755:20757] [TOO] [13]: 65 (UserLabel) + [1707996554.411135][20755:20757] [TOO] [14]: 69 (BooleanState) + [1707996554.411146][20755:20757] [TOO] [15]: 72 (OvenCavityOperationalState) + [1707996554.411156][20755:20757] [TOO] [16]: 73 (OvenMode) + [1707996554.411167][20755:20757] [TOO] [17]: 74 (LaundryDryerControls) + [1707996554.411177][20755:20757] [TOO] [18]: 80 (ModeSelect) + [1707996554.411188][20755:20757] [TOO] [19]: 81 (LaundryWasherMode) + [1707996554.411199][20755:20757] [TOO] [20]: 82 (RefrigeratorAndTemperatureControlledCabinetMode) + [1707996554.411209][20755:20757] [TOO] [21]: 83 (LaundryWasherControls) + [1707996554.411220][20755:20757] [TOO] [22]: 84 (RvcRunMode) + [1707996554.411231][20755:20757] [TOO] [23]: 85 (RvcCleanMode) + [1707996554.411240][20755:20757] [TOO] [24]: 86 (TemperatureControl) + [1707996554.411251][20755:20757] [TOO] [25]: 87 (RefrigeratorAlarm) + [1707996554.411261][20755:20757] [TOO] [26]: 89 (DishwasherMode) + [1707996554.411271][20755:20757] [TOO] [27]: 91 (AirQuality) + [1707996554.411282][20755:20757] [TOO] [28]: 92 (SmokeCoAlarm) + [1707996554.411293][20755:20757] [TOO] [29]: 93 (DishwasherAlarm) + [1707996554.411303][20755:20757] [TOO] [30]: 94 (MicrowaveOvenMode) + [1707996554.411313][20755:20757] [TOO] [31]: 96 (OperationalState) + [1707996554.411323][20755:20757] [TOO] [32]: 97 (RvcOperationalState) + [1707996554.411334][20755:20757] [TOO] [33]: 98 (ScenesManagement) + [1707996554.411345][20755:20757] [TOO] [34]: 113 (HepaFilterMonitoring) + [1707996554.411355][20755:20757] [TOO] [35]: 114 (ActivatedCarbonFilterMonitoring) + [1707996554.411367][20755:20757] [TOO] [36]: 128 (BooleanStateConfiguration) + [1707996554.411376][20755:20757] [TOO] [37]: 129 (ValveConfigurationAndControl) + [1707996554.411387][20755:20757] [TOO] [38]: 144 (ElectricalPowerMeasurement) + [1707996554.411396][20755:20757] [TOO] [39]: 145 (ElectricalEnergyMeasurement) + [1707996554.411406][20755:20757] [TOO] [40]: 152 (DeviceEnergyManagement) + [1707996554.411417][20755:20757] [TOO] [41]: 153 (EnergyEvse) + [1707996554.411427][20755:20757] [TOO] [42]: 157 (EnergyEvseMode) + [1707996554.411437][20755:20757] [TOO] [43]: 159 (DeviceEnergyManagementMode) + [1707996554.411449][20755:20757] [TOO] [44]: 258 (WindowCovering) + [1707996554.411459][20755:20757] [TOO] [45]: 259 (BarrierControl) + [1707996554.411469][20755:20757] [TOO] [46]: 512 (PumpConfigurationAndControl) + [1707996554.411480][20755:20757] [TOO] [47]: 513 (Thermostat) + [1707996554.411490][20755:20757] [TOO] [48]: 514 (FanControl) + [1707996554.411500][20755:20757] [TOO] [49]: 516 (ThermostatUserInterfaceConfiguration) + [1707996554.411511][20755:20757] [TOO] [50]: 768 (ColorControl) + [1707996554.411521][20755:20757] [TOO] [51]: 769 (BallastConfiguration) + [1707996554.411532][20755:20757] [TOO] [52]: 1024 (IlluminanceMeasurement) + [1707996554.411559][20755:20757] [TOO] [53]: 1026 (TemperatureMeasurement) + [1707996554.411562][20755:20757] [TOO] [54]: 1027 (PressureMeasurement) + [1707996554.411565][20755:20757] [TOO] [55]: 1028 (FlowMeasurement) + [1707996554.411568][20755:20757] [TOO] [56]: 1029 (RelativeHumidityMeasurement) + [1707996554.411571][20755:20757] [TOO] [57]: 1030 (OccupancySensing) + [1707996554.411575][20755:20757] [TOO] [58]: 1036 (CarbonMonoxideConcentrationMeasurement) + [1707996554.411578][20755:20757] [TOO] [59]: 1037 (CarbonDioxideConcentrationMeasurement) + [1707996554.411581][20755:20757] [TOO] [60]: 1043 (NitrogenDioxideConcentrationMeasurement) + [1707996554.411584][20755:20757] [TOO] [61]: 1045 (OzoneConcentrationMeasurement) + [1707996554.411587][20755:20757] [TOO] [62]: 1066 (Pm25ConcentrationMeasurement) + [1707996554.411589][20755:20757] [TOO] [63]: 1067 (FormaldehydeConcentrationMeasurement) + [1707996554.411592][20755:20757] [TOO] [64]: 1068 (Pm1ConcentrationMeasurement) + [1707996554.411595][20755:20757] [TOO] [65]: 1069 (Pm10ConcentrationMeasurement) + [1707996554.411598][20755:20757] [TOO] [66]: 1070 (TotalVolatileOrganicCompoundsConcentrationMeasurement) + [1707996554.411601][20755:20757] [TOO] [67]: 1071 (RadonConcentrationMeasurement) + [1707996554.411604][20755:20757] [TOO] [68]: 1283 (WakeOnLan) + [1707996554.411607][20755:20757] [TOO] [69]: 1288 (LowPower) + [1707996554.411610][20755:20757] [TOO] [70]: 2820 (ElectricalMeasurement) + [1707996554.411613][20755:20757] [TOO] [71]: 4294048773 (UnitTesting) ./chip-tool descriptor read server-list 1 2 Verify ServerList entries on TH (Chip-tool) Log and below is the sample log provided for the raspi platform, Here ServerList entries are 7. - [1692618559.962829][31688:31690] CHIP:TOO: Endpoint: 2 Cluster: 0x0000_001D Attribute 0x0000_0001 DataVersion: 1103199808 - [1692618559.962884][31688:31690] CHIP:TOO: ServerList: 7 entries - [1692618559.962910][31688:31690] CHIP:TOO: [1]: 3 - [1692618559.962922][31688:31690] CHIP:TOO: [2]: 4 - [1692618559.962933][31688:31690] CHIP:TOO: [3]: 5 - [1692618559.962945][31688:31690] CHIP:TOO: [4]: 6 - [1692618559.962955][31688:31690] CHIP:TOO: [5]: 29 - [1692618559.962966][31688:31690] CHIP:TOO: [6]: 47 - [1692618559.962978][31688:31690] CHIP:TOO: [7]: 1030 + [1692618559.962829][31688:31690] [TOO] Endpoint: 2 Cluster: 0x0000_001D Attribute 0x0000_0001 DataVersion: 1103199808 + [1692618559.962884][31688:31690] [TOO] ServerList: 7 entries + [1692618559.962910][31688:31690] [TOO] [1]: 3 (Identify) + [1692618559.962922][31688:31690] [TOO] [2]: 4 (Groups) + [1692618559.962933][31688:31690] [TOO] [3]: 5 (Unknown) + [1692618559.962945][31688:31690] [TOO] [4]: 6 (OnOff) + [1692618559.962955][31688:31690] [TOO] [5]: 29 (Descriptor) + [1692618559.962966][31688:31690] [TOO] [6]: 47 (PowerSource) + [1692618559.962978][31688:31690] [TOO] [7]: 1030 (OccupancySensing) disabled: true - label: "Step 3: TH reads 'ClientList' attribute" @@ -244,17 +244,17 @@ tests: Verify client list entries on the TH (Chip-tool) and below is the sample log provided for the raspi platform, Here ClientList entries are 1. - [1676367470.160199][9805:9807] CHIP:DMG: } - [1676367470.160268][9805:9807] CHIP:TOO: Endpoint: 1 Cluster: 0x0000_001D Attribute 0x0000_0002 DataVersion: 3336430903 - [1676367470.160282][9805:9807] CHIP:TOO: ClientList: 1 entries - [1676367470.160289][9805:9807] CHIP:TOO: [1]: 6 + [1676367470.160199][9805:9807] [DMG] } + [1676367470.160268][9805:9807] [TOO] Endpoint: 1 Cluster: 0x0000_001D Attribute 0x0000_0002 DataVersion: 3336430903 + [1676367470.160282][9805:9807] [TOO] ClientList: 1 entries + [1676367470.160289][9805:9807] [TOO] [1]: 6 (OnOff) ./chip-tool descriptor read client-list 1 2 Verify client list entries on the TH (Chip-tool) and below is the sample log provided for the raspi platform, Here ClientList entries are 0. - [1660146160.390200][46818:46823] CHIP:TOO: Endpoint: 2 Cluster: 0x0000_001D Attribute 0x0000_0002 DataVersion: 1051414887 - [1660146160.390211][46818:46823] CHIP:TOO: ClientList: 0 entries + [1660146160.390200][46818:46823] [TOO] Endpoint: 2 Cluster: 0x0000_001D Attribute 0x0000_0002 DataVersion: 1051414887 + [1660146160.390211][46818:46823] [TOO] ClientList: 0 entries disabled: true - label: "Step 4: TH reads 'PartsList' attribute." diff --git a/src/app/tests/suites/certification/Test_TC_IDM_2_2.yaml b/src/app/tests/suites/certification/Test_TC_IDM_2_2.yaml index 6b4f2c7e7d..7c00f74535 100644 --- a/src/app/tests/suites/certification/Test_TC_IDM_2_2.yaml +++ b/src/app/tests/suites/certification/Test_TC_IDM_2_2.yaml @@ -81,33 +81,33 @@ tests: On the TH(chip-tool) verify the received report data message has only the attributes that the TH has privilege to. - [1655727546.354466][5286:5291] CHIP:DMG: - [1655727546.354512][5286:5291] CHIP:DMG: SuppressResponse = true, - [1655727546.354538][5286:5291] CHIP:DMG: InteractionModelRevision = 1 - [1655727546.354580][5286:5291] CHIP:DMG: } - [1655727546.355252][5286:5291] CHIP:TOO: Endpoint: 0 Cluster: 0x0000_0003 Attribute 0x0000_0000 DataVersion: 1545325355 - [1655727546.355324][5286:5291] CHIP:TOO: identify time: 0 - [1655727546.355386][5286:5291] CHIP:TOO: Endpoint: 0 Cluster: 0x0000_0003 Attribute 0x0000_0001 DataVersion: 1545325355 - [1655727546.355414][5286:5291] CHIP:TOO: identify type: 2 - [1655727546.355470][5286:5291] CHIP:TOO: Endpoint: 0 Cluster: 0x0000_0003 Attribute 0x0000_FFFC DataVersion: 1545325355 - [1655727546.355524][5286:5291] CHIP:TOO: FeatureMap: 0 - [1655727546.355606][5286:5291] CHIP:TOO: Endpoint: 0 Cluster: 0x0000_0003 Attribute 0x0000_FFFD DataVersion: 1545325355 - [1655727546.355635][5286:5291] CHIP:TOO: ClusterRevision: 4 - [1655727546.355788][5286:5291] CHIP:TOO: Endpoint: 0 Cluster: 0x0000_0003 Attribute 0x0000_FFF8 DataVersion: 1545325355 - [1655727546.355845][5286:5291] CHIP:TOO: GeneratedCommandList: 0 entries - [1655727546.356030][5286:5291] CHIP:TOO: Endpoint: 0 Cluster: 0x0000_0003 Attribute 0x0000_FFF9 DataVersion: 1545325355 - [1655727546.356087][5286:5291] CHIP:TOO: AcceptedCommandList: 2 entries - [1655727546.356117][5286:5291] CHIP:TOO: [1]: 0 - [1655727546.356143][5286:5291] CHIP:TOO: [2]: 64 - [1655727546.356552][5286:5291] CHIP:TOO: Endpoint: 0 Cluster: 0x0000_0003 Attribute 0x0000_FFFB DataVersion: 1545325355 - [1655727546.356590][5286:5291] CHIP:TOO: AttributeList: 7 entries - [1655727546.356617][5286:5291] CHIP:TOO: [1]: 0 - [1655727546.356642][5286:5291] CHIP:TOO: [2]: 1 - [1655727546.356667][5286:5291] CHIP:TOO: [3]: 65528 - [1655727546.356692][5286:5291] CHIP:TOO: [4]: 65529 - [1655727546.356716][5286:5291] CHIP:TOO: [5]: 65531 - [1655727546.356741][5286:5291] CHIP:TOO: [6]: 65532 - [1655727546.356766][5286:5291] CHIP:TOO: [7]: 65533 + [1723642164.392] [329152:329154] [DMG] + [1723642164.392] [329152:329154] [DMG] SuppressResponse = true, + [1723642164.392] [329152:329154] [DMG] InteractionModelRevision = 11 + [1723642164.392] [329152:329154] [DMG] } + [1723642164.392] [329152:329154] [TOO] Endpoint: 0 Cluster: 0x0000_0003 Attribute 0x0000_0000 DataVersion: 357555707 + [1723642164.392] [329152:329154] [TOO] IdentifyTime: 0 + [1723642164.392] [329152:329154] [TOO] Endpoint: 0 Cluster: 0x0000_0003 Attribute 0x0000_0001 DataVersion: 357555707 + [1723642164.392] [329152:329154] [TOO] IdentifyType: 2 + [1723642164.392] [329152:329154] [TOO] Endpoint: 0 Cluster: 0x0000_0003 Attribute 0x0000_FFFC DataVersion: 357555707 + [1723642164.392] [329152:329154] [TOO] FeatureMap: 0 + [1723642164.392] [329152:329154] [TOO] Endpoint: 0 Cluster: 0x0000_0003 Attribute 0x0000_FFFD DataVersion: 357555707 + [1723642164.392] [329152:329154] [TOO] ClusterRevision: 4 + [1723642164.393] [329152:329154] [TOO] Endpoint: 0 Cluster: 0x0000_0003 Attribute 0x0000_FFF8 DataVersion: 357555707 + [1723642164.393] [329152:329154] [TOO] GeneratedCommandList: 0 entries + [1723642164.393] [329152:329154] [TOO] Endpoint: 0 Cluster: 0x0000_0003 Attribute 0x0000_FFF9 DataVersion: 357555707 + [1723642164.393] [329152:329154] [TOO] AcceptedCommandList: 2 entries + [1723642164.393] [329152:329154] [TOO] [1]: 0 (Identify) + [1723642164.393] [329152:329154] [TOO] [2]: 64 (TriggerEffect) + [1723642164.393] [329152:329154] [TOO] Endpoint: 0 Cluster: 0x0000_0003 Attribute 0x0000_FFFB DataVersion: 357555707 + [1723642164.393] [329152:329154] [TOO] AttributeList: 7 entries + [1723642164.393] [329152:329154] [TOO] [1]: 0 (IdentifyTime) + [1723642164.393] [329152:329154] [TOO] [2]: 1 (IdentifyType) + [1723642164.393] [329152:329154] [TOO] [3]: 65528 (GeneratedCommandList) + [1723642164.393] [329152:329154] [TOO] [4]: 65529 (AcceptedCommandList) + [1723642164.393] [329152:329154] [TOO] [5]: 65531 (AttributeList) + [1723642164.393] [329152:329154] [TOO] [6]: 65532 (FeatureMap) + [1723642164.393] [329152:329154] [TOO] [7]: 65533 (ClusterRevision) disabled: true - label: @@ -272,7 +272,7 @@ tests: disabled: true - label: - "Step 7: TH sends the Read Request Message to the DUT to read all + "Step 7: TH sends the Read Requ`est Message to the DUT to read all attributes from a cluster at all Endpoints AttributePath = [[Cluster = Specific ClusterID]] On receipt of this message, DUT should send a report data action with the attribute value from all the Endpoints to @@ -284,52 +284,52 @@ tests: On the TH(chip-tool) verify the received report data message has all the right attribute values for above command - [1653629930.057852][8778:8783] CHIP:DMG: } - [1653629930.058739][8778:8783] CHIP:TOO: Endpoint: 0 Cluster: 0x0000_0003 Attribute 0x0000_0000 DataVersion: 2065044836 - [1653629930.058788][8778:8783] CHIP:TOO: identify time: 0 - [1653629930.058889][8778:8783] CHIP:TOO: Endpoint: 0 Cluster: 0x0000_0003 Attribute 0x0000_0001 DataVersion: 2065044836 - [1653629930.058919][8778:8783] CHIP:TOO: identify type: 2 - [1653629930.058980][8778:8783] CHIP:TOO: Endpoint: 0 Cluster: 0x0000_0003 Attribute 0x0000_FFFD DataVersion: 2065044836 - [1653629930.058998][8778:8783] CHIP:TOO: ClusterRevision: 4 - [1653629930.059191][8778:8783] CHIP:TOO: Endpoint: 0 Cluster: 0x0000_0003 Attribute 0x0000_FFF8 DataVersion: 2065044836 - [1653629930.059220][8778:8783] CHIP:TOO: GeneratedCommandList: 1 entries - [1653629930.059239][8778:8783] CHIP:TOO: [1]: 0 - [1653629930.059478][8778:8783] CHIP:TOO: Endpoint: 0 Cluster: 0x0000_0003 Attribute 0x0000_FFF9 DataVersion: 2065044836 - [1653629930.059503][8778:8783] CHIP:TOO: AcceptedCommandList: 3 entries - [1653629930.059519][8778:8783] CHIP:TOO: [1]: 0 - [1653629930.059532][8778:8783] CHIP:TOO: [2]: 1 - [1653629930.059546][8778:8783] CHIP:TOO: [3]: 64 - [1653629930.059945][8778:8783] CHIP:TOO: Endpoint: 0 Cluster: 0x0000_0003 Attribute 0x0000_FFFB DataVersion: 2065044836 - [1653629930.059974][8778:8783] CHIP:TOO: AttributeList: 6 entries - [1653629930.059989][8778:8783] CHIP:TOO: [1]: 0 - [1653629930.060002][8778:8783] CHIP:TOO: [2]: 1 - [1653629930.060015][8778:8783] CHIP:TOO: [3]: 65528 - [1653629930.060032][8778:8783] CHIP:TOO: [4]: 65529 - [1653629930.060048][8778:8783] CHIP:TOO: [5]: 65531 - [1653629930.060064][8778:8783] CHIP:TOO: [6]: 65533 - [1653629930.060077][8778:8783] CHIP:TOO: Endpoint: 1 Cluster: 0x0000_0003 Attribute 0x0000_0000 DataVersion: 3620435651 - [1653629930.060095][8778:8783] CHIP:TOO: identify time: 0 - [1653629930.060151][8778:8783] CHIP:TOO: Endpoint: 1 Cluster: 0x0000_0003 Attribute 0x0000_0001 DataVersion: 3620435651 - [1653629930.060167][8778:8783] CHIP:TOO: identify type: 2 - [1653629930.060224][8778:8783] CHIP:TOO: Endpoint: 1 Cluster: 0x0000_0003 Attribute 0x0000_FFFD DataVersion: 3620435651 - [1653629930.060240][8778:8783] CHIP:TOO: ClusterRevision: 4 - [1653629930.060411][8778:8783] CHIP:TOO: Endpoint: 1 Cluster: 0x0000_0003 Attribute 0x0000_FFF8 DataVersion: 3620435651 - [1653629930.060433][8778:8783] CHIP:TOO: GeneratedCommandList: 1 entries - [1653629930.060448][8778:8783] CHIP:TOO: [1]: 0 - [1653629930.060671][8778:8783] CHIP:TOO: Endpoint: 1 Cluster: 0x0000_0003 Attribute 0x0000_FFF9 DataVersion: 3620435651 - [1653629930.060695][8778:8783] CHIP:TOO: AcceptedCommandList: 3 entries - [1653629930.060710][8778:8783] CHIP:TOO: [1]: 0 - [1653629930.060722][8778:8783] CHIP:TOO: [2]: 1 - [1653629930.060735][8778:8783] CHIP:TOO: [3]: 64 - [1653629930.061086][8778:8783] CHIP:TOO: Endpoint: 1 Cluster: 0x0000_0003 Attribute 0x0000_FFFB DataVersion: 3620435651 - [1653629930.061114][8778:8783] CHIP:TOO: AttributeList: 6 entries - [1653629930.061129][8778:8783] CHIP:TOO: [1]: 0 - [1653629930.061141][8778:8783] CHIP:TOO: [2]: 1 - [1653629930.061154][8778:8783] CHIP:TOO: [3]: 65528 - [1653629930.061167][8778:8783] CHIP:TOO: [4]: 65529 - [1653629930.061184][8778:8783] CHIP:TOO: [5]: 65531 - [1653629930.061201][8778:8783] CHIP:TOO: [6]: 65533 - [1653629930.061435][8778:8783] CHIP:EM: Sending Standalone Ack for MessageCounter:5968688 on exchange 11683i + [1653629930.057] [8778:8783] [DMG] } + [1653629930.058] [8778:8783] [TOO] Endpoint: 0 Cluster: 0x0000_0003 Attribute 0x0000_0000 DataVersion: 2065044836 + [1653629930.058] [8778:8783] [TOO] identify time: 0 + [1653629930.058] [8778:8783] [TOO] Endpoint: 0 Cluster: 0x0000_0003 Attribute 0x0000_0001 DataVersion: 2065044836 + [1653629930.058] [8778:8783] [TOO] identify type: 2 + [1653629930.058] [8778:8783] [TOO] Endpoint: 0 Cluster: 0x0000_0003 Attribute 0x0000_FFFD DataVersion: 2065044836 + [1653629930.058] [8778:8783] [TOO] ClusterRevision: 4 + [1653629930.059] [8778:8783] [TOO] Endpoint: 0 Cluster: 0x0000_0003 Attribute 0x0000_FFF8 DataVersion: 2065044836 + [1653629930.059] [8778:8783] [TOO] GeneratedCommandList: 1 entries + [1653629930.059] [8778:8783] [TOO] [1]: 0 (Identify) + [1653629930.059] [8778:8783] [TOO] Endpoint: 0 Cluster: 0x0000_0003 Attribute 0x0000_FFF9 DataVersion: 2065044836 + [1653629930.059] [8778:8783] [TOO] AcceptedCommandList: 3 entries + [1653629930.059] [8778:8783] [TOO] [1]: 0 (Identify) + [1653629930.059] [8778:8783] [TOO] [2]: 1 (Unknown) + [1653629930.059] [8778:8783] [TOO] [3]: 64 (TriggerEffect) + [1653629930.059] [8778:8783] [TOO] Endpoint: 0 Cluster: 0x0000_0003 Attribute 0x0000_FFFB DataVersion: 2065044836 + [1653629930.059] [8778:8783] [TOO] AttributeList: 6 entries + [1653629930.059] [8778:8783] [TOO] [1]: 0 (IdentifyTime) + [1653629930.060] [8778:8783] [TOO] [2]: 1 (IdentifyType) + [1653629930.060] [8778:8783] [TOO] [3]: 65528 (GeneratedCommandList) + [1653629930.060] [8778:8783] [TOO] [4]: 65529 (AcceptedCommandList) + [1653629930.060] [8778:8783] [TOO] [5]: 65531 (AttributeList) + [1653629930.060] [8778:8783] [TOO] [6]: 65533 (ClusterRevision) + [1653629930.060] [8778:8783] [TOO] Endpoint: 1 Cluster: 0x0000_0003 Attribute 0x0000_0000 DataVersion: 3620435651 + [1653629930.060] [8778:8783] [TOO] identify time: 0 + [1653629930.060] [8778:8783] [TOO] Endpoint: 1 Cluster: 0x0000_0003 Attribute 0x0000_0001 DataVersion: 3620435651 + [1653629930.060] [8778:8783] [TOO] identify type: 2 + [1653629930.060] [8778:8783] [TOO] Endpoint: 1 Cluster: 0x0000_0003 Attribute 0x0000_FFFD DataVersion: 3620435651 + [1653629930.060] [8778:8783] [TOO] ClusterRevision: 4 + [1653629930.060] [8778:8783] [TOO] Endpoint: 1 Cluster: 0x0000_0003 Attribute 0x0000_FFF8 DataVersion: 3620435651 + [1653629930.060] [8778:8783] [TOO] GeneratedCommandList: 1 entries + [1653629930.060] [8778:8783] [TOO] [1]: 0 (Identify) + [1653629930.060] [8778:8783] [TOO] Endpoint: 1 Cluster: 0x0000_0003 Attribute 0x0000_FFF9 DataVersion: 3620435651 + [1653629930.060] [8778:8783] [TOO] AcceptedCommandList: 3 entries + [1653629930.060] [8778:8783] [TOO] [1]: 0 (Identify) + [1653629930.060] [8778:8783] [TOO] [2]: 1 (Unknown) + [1653629930.060] [8778:8783] [TOO] [3]: 64 (TriggerEffect) + [1653629930.061] [8778:8783] [TOO] Endpoint: 1 Cluster: 0x0000_0003 Attribute 0x0000_FFFB DataVersion: 3620435651 + [1653629930.061] [8778:8783] [TOO] AttributeList: 6 entries + [1653629930.061] [8778:8783] [TOO] [1]: 0 (IdentifyTime) + [1653629930.061] [8778:8783] [TOO] [2]: 1 (IdentifyType) + [1653629930.061] [8778:8783] [TOO] [3]: 65528 (GeneratedCommandList) + [1653629930.061] [8778:8783] [TOO] [4]: 65529 (AcceptedCommandList) + [1653629930.061] [8778:8783] [TOO] [5]: 65531 (AttributeList) + [1653629930.061] [8778:8783] [TOO] [6]: 65533 (ClusterRevision) + [1653629930.061] [8778:8783] [EM] Sending Standalone Ack for MessageCounter:5968688 on exchange 11683i disabled: true - label: @@ -825,30 +825,29 @@ tests: Verify on TH(chip-tool), DUT is responds right attribute value for below command - [1653633965.092996][9835:9840] CHIP:TOO: Endpoint: 1 Cluster: 0x0000_0003 Attribute 0x0000_0000 DataVersion: 3620435654 - [1653633965.093041][9835:9840] CHIP:TOO: identify time: 0 - [1653633965.093120][9835:9840] CHIP:TOO: Endpoint: 1 Cluster: 0x0000_0003 Attribute 0x0000_0001 DataVersion: 3620435654 - [1653633965.093140][9835:9840] CHIP:TOO: identify type: 2 - [1653633965.093202][9835:9840] CHIP:TOO: Endpoint: 1 Cluster: 0x0000_0003 Attribute 0x0000_FFFD DataVersion: 3620435654 - [1653633965.093221][9835:9840] CHIP:TOO: ClusterRevision: 4 - [1653633965.093411][9835:9840] CHIP:TOO: Endpoint: 1 Cluster: 0x0000_0003 Attribute 0x0000_FFF8 DataVersion: 3620435654 - [1653633965.093451][9835:9840] CHIP:TOO: GeneratedCommandList: 1 entries - [1653633965.093474][9835:9840] CHIP:TOO: [1]: 0 - [1653633965.093721][9835:9840] CHIP:TOO: Endpoint: 1 Cluster: 0x0000_0003 Attribute 0x0000_FFF9 DataVersion: 3620435654 - [1653633965.093748][9835:9840] CHIP:TOO: AcceptedCommandList: 3 entries - [1653633965.093767][9835:9840] CHIP:TOO: [1]: 0 - [1653633965.093784][9835:9840] CHIP:TOO: [2]: 1 - [1653633965.093800][9835:9840] CHIP:TOO: [3]: 64 - [1653633965.094169][9835:9840] CHIP:TOO: Endpoint: 1 Cluster: 0x0000_0003 Attribute 0x0000_FFFB DataVersion: 3620435654 - [1653633965.094200][9835:9840] CHIP:TOO: AttributeList: 6 entries - [1653633965.094218][9835:9840] CHIP:TOO: [1]: 0 - [1653633965.094235][9835:9840] CHIP:TOO: [2]: 1 - [1653633965.094252][9835:9840] CHIP:TOO: [3]: 65528 - [1653633965.094269][9835:9840] CHIP:TOO: [4]: 65529 - [1653633965.094286][9835:9840] CHIP:TOO: [5]: 65531 - [1653633965.094302][9835:9840] CHIP:TOO: [6]: 65533 - [1653633965.094449][9835:9840] CHIP:EM: Sending Standalone Ack for MessageCounter:14221655 on exchange 17356i - + [1653633965.092996][9835:9840] [TOO] Endpoint: 1 Cluster: 0x0000_0003 Attribute 0x0000_0000 DataVersion: 3620435654 + [1653633965.093041][9835:9840] [TOO] identify time: 0 + [1653633965.093120][9835:9840] [TOO] Endpoint: 1 Cluster: 0x0000_0003 Attribute 0x0000_0001 DataVersion: 3620435654 + [1653633965.093140][9835:9840] [TOO] identify type: 2 + [1653633965.093202][9835:9840] [TOO] Endpoint: 1 Cluster: 0x0000_0003 Attribute 0x0000_FFFD DataVersion: 3620435654 + [1653633965.093221][9835:9840] [TOO] ClusterRevision: 4 + [1653633965.093411][9835:9840] [TOO] Endpoint: 1 Cluster: 0x0000_0003 Attribute 0x0000_FFF8 DataVersion: 3620435654 + [1653633965.093451][9835:9840] [TOO] GeneratedCommandList: 1 entries + [1653633965.093474][9835:9840] [TOO] [1]: 0 (Identify) + [1653633965.093721][9835:9840] [TOO] Endpoint: 1 Cluster: 0x0000_0003 Attribute 0x0000_FFF9 DataVersion: 3620435654 + [1653633965.093748][9835:9840] [TOO] AcceptedCommandList: 3 entries + [1653633965.093767][9835:9840] [TOO] [1]: 0 (Identify) + [1653633965.093784][9835:9840] [TOO] [2]: 1 (Unknown) + [1653633965.093800][9835:9840] [TOO] [3]: 64 (TriggerEffect) + [1653633965.094169][9835:9840] [TOO] Endpoint: 1 Cluster: 0x0000_0003 Attribute 0x0000_FFFB DataVersion: 3620435654 + [1653633965.094200][9835:9840] [TOO] AttributeList: 6 entries + [1653633965.094218][9835:9840] [TOO] [1]: 0 (IdentifyTime) + [1653633965.094235][9835:9840] [TOO] [2]: 1 (IdentifyType) + [1653633965.094252][9835:9840] [TOO] [3]: 65528 (GeneratedCommandList) + [1653633965.094269][9835:9840] [TOO] [4]: 65529 (AcceptedCommandList) + [1653633965.094286][9835:9840] [TOO] [5]: 65531 (AttributeList) + [1653633965.094302][9835:9840] [TOO] [6]: 65533 (ClusterRevision) + [1653633965.094449][9835:9840] [EM] Sending Standalone Ack for MessageCounter:14221655 on exchange 17356i ./chip-tool any write-by-id 0x03 0x00 2 1 1 @@ -884,29 +883,29 @@ tests: ./chip-tool any read-by-id 0x03 0xFFFFFFFF 1 1 --data-version 0xd7cb76c6 - [1653634117.935268][9878:9883] CHIP:TOO: Endpoint: 1 Cluster: 0x0000_0003 Attribute 0x0000_0000 DataVersion: 3620435657 - [1653634117.935294][9878:9883] CHIP:TOO: identify time: 0 - [1653634117.935322][9878:9883] CHIP:TOO: Endpoint: 1 Cluster: 0x0000_0003 Attribute 0x0000_0001 DataVersion: 3620435657 - [1653634117.935331][9878:9883] CHIP:TOO: identify type: 2 - [1653634117.935357][9878:9883] CHIP:TOO: Endpoint: 1 Cluster: 0x0000_0003 Attribute 0x0000_FFFD DataVersion: 3620435657 - [1653634117.935366][9878:9883] CHIP:TOO: ClusterRevision: 4 - [1653634117.935452][9878:9883] CHIP:TOO: Endpoint: 1 Cluster: 0x0000_0003 Attribute 0x0000_FFF8 DataVersion: 3620435657 - [1653634117.935470][9878:9883] CHIP:TOO: GeneratedCommandList: 1 entries - [1653634117.935480][9878:9883] CHIP:TOO: [1]: 0 - [1653634117.935589][9878:9883] CHIP:TOO: Endpoint: 1 Cluster: 0x0000_0003 Attribute 0x0000_FFF9 DataVersion: 3620435657 - [1653634117.935601][9878:9883] CHIP:TOO: AcceptedCommandList: 3 entries - [1653634117.935609][9878:9883] CHIP:TOO: [1]: 0 - [1653634117.935616][9878:9883] CHIP:TOO: [2]: 1 - [1653634117.935623][9878:9883] CHIP:TOO: [3]: 64 - [1653634117.935788][9878:9883] CHIP:TOO: Endpoint: 1 Cluster: 0x0000_0003 Attribute 0x0000_FFFB DataVersion: 3620435657 - [1653634117.935802][9878:9883] CHIP:TOO: AttributeList: 6 entries - [1653634117.935809][9878:9883] CHIP:TOO: [1]: 0 - [1653634117.935817][9878:9883] CHIP:TOO: [2]: 1 - [1653634117.935824][9878:9883] CHIP:TOO: [3]: 65528 - [1653634117.935831][9878:9883] CHIP:TOO: [4]: 65529 - [1653634117.935838][9878:9883] CHIP:TOO: [5]: 65531 - [1653634117.935845][9878:9883] CHIP:TOO: [6]: 65533 - [1653634117.935910][9878:9883] CHIP:EM: Sending Standalone Ack for MessageCounter:531776 on exchange 45674i + [1653634117.935268][9878:9883] [TOO] Endpoint: 1 Cluster: 0x0000_0003 Attribute 0x0000_0000 DataVersion: 3620435657 + [1653634117.935294][9878:9883] [TOO] identify time: 0 + [1653634117.935322][9878:9883] [TOO] Endpoint: 1 Cluster: 0x0000_0003 Attribute 0x0000_0001 DataVersion: 3620435657 + [1653634117.935331][9878:9883] [TOO] identify type: 2 + [1653634117.935357][9878:9883] [TOO] Endpoint: 1 Cluster: 0x0000_0003 Attribute 0x0000_FFFD DataVersion: 3620435657 + [1653634117.935366][9878:9883] [TOO] ClusterRevision: 4 + [1653634117.935452][9878:9883] [TOO] Endpoint: 1 Cluster: 0x0000_0003 Attribute 0x0000_FFF8 DataVersion: 3620435657 + [1653634117.935470][9878:9883] [TOO] GeneratedCommandList: 1 entries + [1653634117.935480][9878:9883] [TOO] [1]: 0 (Identify) + [1653634117.935589][9878:9883] [TOO] Endpoint: 1 Cluster: 0x0000_0003 Attribute 0x0000_FFF9 DataVersion: 3620435657 + [1653634117.935601][9878:9883] [TOO] AcceptedCommandList: 3 entries + [1653634117.935609][9878:9883] [TOO] [1]: 0 (Identify) + [1653634117.935616][9878:9883] [TOO] [2]: 1 (Unknown) + [1653634117.935623][9878:9883] [TOO] [3]: 64 (TriggerEffect) + [1653634117.935788][9878:9883] [TOO] Endpoint: 1 Cluster: 0x0000_0003 Attribute 0x0000_FFFB DataVersion: 3620435657 + [1653634117.935802][9878:9883] [TOO] AttributeList: 6 entries + [1653634117.935809][9878:9883] [TOO] [1]: 0 (IdentifyTime) + [1653634117.935817][9878:9883] [TOO] [2]: 1 (IdentifyType) + [1653634117.935824][9878:9883] [TOO] [3]: 65528 (GeneratedCommandList) + [1653634117.935831][9878:9883] [TOO] [4]: 65529 (AcceptedCommandList) + [1653634117.935838][9878:9883] [TOO] [5]: 65531 (AttributeList) + [1653634117.935845][9878:9883] [TOO] [6]: 65533 (ClusterRevision) + [1653634117.935910][9878:9883] [EM] Sending Standalone Ack for MessageCounter:531776 on exchange 45674i disabled: true - label: @@ -1000,55 +999,55 @@ tests: ./chip-tool any read-by-id 0x03 0xFFFFFFFF 1 1 - [1653634446.678378][9962:9967] CHIP:TOO: Endpoint: 1 Cluster: 0x0000_0003 Attribute 0x0000_0000 DataVersion: 3620435660 - [1653634446.678404][9962:9967] CHIP:TOO: identify time: 0 - [1653634446.678437][9962:9967] CHIP:TOO: Endpoint: 1 Cluster: 0x0000_0003 Attribute 0x0000_0001 DataVersion: 3620435660 - [1653634446.678447][9962:9967] CHIP:TOO: identify type: 2 - [1653634446.678474][9962:9967] CHIP:TOO: Endpoint: 1 Cluster: 0x0000_0003 Attribute 0x0000_FFFD DataVersion: 3620435660 - [1653634446.678483][9962:9967] CHIP:TOO: ClusterRevision: 4 - [1653634446.678570][9962:9967] CHIP:TOO: Endpoint: 1 Cluster: 0x0000_0003 Attribute 0x0000_FFF8 DataVersion: 3620435660 - [1653634446.678584][9962:9967] CHIP:TOO: GeneratedCommandList: 1 entries - [1653634446.678594][9962:9967] CHIP:TOO: [1]: 0 - [1653634446.678767][9962:9967] CHIP:TOO: Endpoint: 1 Cluster: 0x0000_0003 Attribute 0x0000_FFF9 DataVersion: 3620435660 - [1653634446.678780][9962:9967] CHIP:TOO: AcceptedCommandList: 3 entries - [1653634446.678789][9962:9967] CHIP:TOO: [1]: 0 - [1653634446.678796][9962:9967] CHIP:TOO: [2]: 1 - [1653634446.678805][9962:9967] CHIP:TOO: [3]: 64 - [1653634446.678998][9962:9967] CHIP:TOO: Endpoint: 1 Cluster: 0x0000_0003 Attribute 0x0000_FFFB DataVersion: 3620435660 - [1653634446.679017][9962:9967] CHIP:TOO: AttributeList: 6 entries - [1653634446.679024][9962:9967] CHIP:TOO: [1]: 0 - [1653634446.679030][9962:9967] CHIP:TOO: [2]: 1 - [1653634446.679036][9962:9967] CHIP:TOO: [3]: 65528 - [1653634446.679042][9962:9967] CHIP:TOO: [4]: 65529 - [1653634446.679048][9962:9967] CHIP:TOO: [5]: 65531 - [1653634446.679055][9962:9967] CHIP:TOO: [6]: 65533 - [1653634446.679129][9962:9967] CHIP:EM: Sending Standalone Ack for MessageCounter:15830359 on exchange 10739i + [1653634446.678378] [9962:9967] [TOO] Endpoint: 1 Cluster: 0x0000_0003 Attribute 0x0000_0000 DataVersion: 3620435660 + [1653634446.678404] [9962:9967] [TOO] identify time: 0 + [1653634446.678437] [9962:9967] [TOO] Endpoint: 1 Cluster: 0x0000_0003 Attribute 0x0000_0001 DataVersion: 3620435660 + [1653634446.678447] [9962:9967] [TOO] identify type: 2 + [1653634446.678474] [9962:9967] [TOO] Endpoint: 1 Cluster: 0x0000_0003 Attribute 0x0000_FFFD DataVersion: 3620435660 + [1653634446.678483] [9962:9967] [TOO] ClusterRevision: 4 + [1653634446.678570] [9962:9967] [TOO] Endpoint: 1 Cluster: 0x0000_0003 Attribute 0x0000_FFF8 DataVersion: 3620435660 + [1653634446.678584] [9962:9967] [TOO] GeneratedCommandList: 1 entries + [1653634446.678594] [9962:9967] [TOO] [1]: 0 (Identify) + [1653634446.678767] [9962:9967] [TOO] Endpoint: 1 Cluster: 0x0000_0003 Attribute 0x0000_FFF9 DataVersion: 3620435660 + [1653634446.678780] [9962:9967] [TOO] AcceptedCommandList: 3 entries + [1653634446.678789] [9962:9967] [TOO] [1]: 0 (Identify) + [1653634446.678796] [9962:9967] [TOO] [2]: 1 (Unknown) + [1653634446.678805] [9962:9967] [TOO] [3]: 64 (TriggerEffect) + [1653634446.678998] [9962:9967] [TOO] Endpoint: 1 Cluster: 0x0000_0003 Attribute 0x0000_FFFB DataVersion: 3620435660 + [1653634446.679017] [9962:9967] [TOO] AttributeList: 6 entries + [1653634446.679024] [9962:9967] [TOO] [1]: 0 (IdentifyTime) + [1653634446.679030] [9962:9967] [TOO] [2]: 1 (IdentifyType) + [1653634446.679036] [9962:9967] [TOO] [3]: 65528 (GeneratedCommandList) + [1653634446.679042] [9962:9967] [TOO] [4]: 65529 (AcceptedCommandList) + [1653634446.679048] [9962:9967] [TOO] [5]: 65531 (AttributeList) + [1653634446.679055] [9962:9967] [TOO] [6]: 65533 (ClusterRevision) + [1653634446.679129] [9962:9967] [EM] Sending Standalone Ack for MessageCounter:15830359 on exchange 10739i ./chip-tool levelcontrol read-by-id 0xFFFFFFFF 1 1 --data-version 0xd7cb76cc (Here given data version received for identify cluster) - [1653634568.902390][9990:9995] CHIP:TOO: Endpoint: 1 Cluster: 0x0000_0008 Attribute 0x0000_FFFB DataVersion: 199562416 - [1653634568.902417][9990:9995] CHIP:TOO: AttributeList: 19 entries - [1653634568.902428][9990:9995] CHIP:TOO: [1]: 0 - [1653634568.902436][9990:9995] CHIP:TOO: [2]: 1 - [1653634568.902444][9990:9995] CHIP:TOO: [3]: 2 - [1653634568.902451][9990:9995] CHIP:TOO: [4]: 3 - [1653634568.902458][9990:9995] CHIP:TOO: [5]: 4 - [1653634568.902466][9990:9995] CHIP:TOO: [6]: 5 - [1653634568.902475][9990:9995] CHIP:TOO: [7]: 6 - [1653634568.902483][9990:9995] CHIP:TOO: [8]: 15 - [1653634568.902490][9990:9995] CHIP:TOO: [9]: 16 - [1653634568.902498][9990:9995] CHIP:TOO: [10]: 17 - [1653634568.902506][9990:9995] CHIP:TOO: [11]: 18 - [1653634568.902513][9990:9995] CHIP:TOO: [12]: 19 - [1653634568.902520][9990:9995] CHIP:TOO: [13]: 20 - [1653634568.902528][9990:9995] CHIP:TOO: [14]: 16384 - [1653634568.902535][9990:9995] CHIP:TOO: [15]: 65528 - [1653634568.902542][9990:9995] CHIP:TOO: [16]: 65529 - [1653634568.902550][9990:9995] CHIP:TOO: [17]: 65531 - [1653634568.902557][9990:9995] CHIP:TOO: [18]: 65532 - [1653634568.902565][9990:9995] CHIP:TOO: [19]: 65533 - [1653634568.902621][9990:9995] CHIP:EM: Sending Standalone Ack for MessageCounter:3712616 on exchange 9501 + [1653634568.902390] [9990:9995] [TOO] Endpoint: 1 Cluster: 0x0000_0008 Attribute 0x0000_FFFB DataVersion: 199562416 + [1653634568.902417] [9990:9995] [TOO] AttributeList: 19 entries + [1653634568.902428] [9990:9995] [TOO] [1]: 0 (CurrentLevel) + [1653634568.902436] [9990:9995] [TOO] [2]: 1 (RemainingTime) + [1653634568.902444] [9990:9995] [TOO] [3]: 2 (MinLevel) + [1653634568.902451] [9990:9995] [TOO] [4]: 3 (MaxLevel) + [1653634568.902458] [9990:9995] [TOO] [5]: 4 (CurrentFrequency) + [1653634568.902466] [9990:9995] [TOO] [6]: 5 (MinFrequency) + [1653634568.902475] [9990:9995] [TOO] [7]: 6 (MaxFrequency) + [1653634568.902483] [9990:9995] [TOO] [8]: 15 (Options) + [1653634568.902490] [9990:9995] [TOO] [9]: 16 (OnOffTransitionTime) + [1653634568.902498] [9990:9995] [TOO] [10]: 17 (OnLevel) + [1653634568.902506] [9990:9995] [TOO] [11]: 18 (OnTransitionTime) + [1653634568.902513] [9990:9995] [TOO] [12]: 19 (OffTransitionTime) + [1653634568.902520] [9990:9995] [TOO] [13]: 20 (DefaultMoveRate) + [1653634568.902528] [9990:9995] [TOO] [14]: 16384 (StartUpCurrentLevel) + [1653634568.902535] [9990:9995] [TOO] [15]: 65528 (GeneratedCommandList) + [1653634568.902542] [9990:9995] [TOO] [16]: 65529 (AcceptedCommandList) + [1653634568.902550] [9990:9995] [TOO] [17]: 65531 (AttributeList) + [1653634568.902557] [9990:9995] [TOO] [18]: 65532 (FeatureMap) + [1653634568.902565] [9990:9995] [TOO] [19]: 65533 (ClusterRevision) + [1653634568.902621] [9990:9995] [EM] Sending Standalone Ack for MessageCounter:3712616 on exchange 9501 disabled: true - label: @@ -1166,53 +1165,52 @@ tests: Verify that there are no errors sent back for attributes the TH has no access to. - [1659422360.478947][2049:2054] CHIP:DMG: } - [1659422360.479556][2049:2054] CHIP:TOO: Endpoint: 0 Cluster: 0x0000_001F Attribute 0x0000_0000 DataVersion: 3949809681 - [1659422360.479619][2049:2054] CHIP:TOO: ACL: 1 entries - [1659422360.479679][2049:2054] CHIP:TOO: [1]: { - [1659422360.479706][2049:2054] CHIP:TOO: Privilege: 5 - [1659422360.479729][2049:2054] CHIP:TOO: AuthMode: 2 - [1659422360.479768][2049:2054] CHIP:TOO: Subjects: 2 entries - [1659422360.479819][2049:2054] CHIP:TOO: [1]: 1 - [1659422360.479847][2049:2054] CHIP:TOO: [2]: 112233 - [1659422360.479876][2049:2054] CHIP:TOO: Targets: 1 entries - [1659422360.479925][2049:2054] CHIP:TOO: [1]: { - [1659422360.479969][2049:2054] CHIP:TOO: Cluster: 31 - [1659422360.479993][2049:2054] CHIP:TOO: Endpoint: 0 - [1659422360.480016][2049:2054] CHIP:TOO: DeviceType: null - [1659422360.480038][2049:2054] CHIP:TOO: } - [1659422360.480062][2049:2054] CHIP:TOO: FabricIndex: 1 - [1659422360.480085][2049:2054] CHIP:TOO: } - [1659422360.480165][2049:2054] CHIP:TOO: Endpoint: 0 Cluster: 0x0000_001F Attribute 0x0000_0001 DataVersion: 3949809681 - [1659422360.480197][2049:2054] CHIP:TOO: Extension: 0 entries - [1659422360.480225][2049:2054] CHIP:TOO: Endpoint: 0 Cluster: 0x0000_001F Attribute 0x0000_0002 DataVersion: 3949809681 - [1659422360.480251][2049:2054] CHIP:TOO: SubjectsPerAccessControlEntry: 4 - [1659422360.480311][2049:2054] CHIP:TOO: Endpoint: 0 Cluster: 0x0000_001F Attribute 0x0000_0003 DataVersion: 3949809681 - [1659422360.480337][2049:2054] CHIP:TOO: TargetsPerAccessControlEntry: 3 - [1659422360.480395][2049:2054] CHIP:TOO: Endpoint: 0 Cluster: 0x0000_001F Attribute 0x0000_0004 DataVersion: 3949809681 - [1659422360.480421][2049:2054] CHIP:TOO: AccessControlEntriesPerFabric: 3 - [1659422360.480479][2049:2054] CHIP:TOO: Endpoint: 0 Cluster: 0x0000_001F Attribute 0x0000_FFFC DataVersion: 3949809681 - [1659422360.480505][2049:2054] CHIP:TOO: FeatureMap: 0 - [1659422360.480563][2049:2054] CHIP:TOO: Endpoint: 0 Cluster: 0x0000_001F Attribute 0x0000_FFFD DataVersion: 3949809681 - [1659422360.480588][2049:2054] CHIP:TOO: ClusterRevision: 1 - [1659422360.480690][2049:2054] CHIP:TOO: Endpoint: 0 Cluster: 0x0000_001F Attribute 0x0000_FFF8 DataVersion: 3949809681 - [1659422360.480721][2049:2054] CHIP:TOO: GeneratedCommandList: 0 entries - [1659422360.480789][2049:2054] CHIP:TOO: Endpoint: 0 Cluster: 0x0000_001F Attribute 0x0000_FFF9 DataVersion: 3949809681 - [1659422360.480818][2049:2054] CHIP:TOO: AcceptedCommandList: 0 entries - [1659422360.481269][2049:2054] CHIP:TOO: Endpoint: 0 Cluster: 0x0000_001F Attribute 0x0000_FFFB DataVersion: 3949809681 - [1659422360.481307][2049:2054] CHIP:TOO: AttributeList: 10 entries - [1659422360.481334][2049:2054] CHIP:TOO: [1]: 0 - [1659422360.481359][2049:2054] CHIP:TOO: [2]: 1 - [1659422360.481383][2049:2054] CHIP:TOO: [3]: 2 - [1659422360.481408][2049:2054] CHIP:TOO: [4]: 3 - [1659422360.481432][2049:2054] CHIP:TOO: [5]: 4 - [1659422360.481457][2049:2054] CHIP:TOO: [6]: 65528 - [1659422360.481482][2049:2054] CHIP:TOO: [7]: 65529 - [1659422360.481506][2049:2054] CHIP:TOO: [8]: 65531 - [1659422360.481531][2049:2054] CHIP:TOO: [9]: 65532 - [1659422360.481556][2049:2054] CHIP:TOO: [10]: 65533 - [1659422360.481706][2049:2054] CHIP:EM: Sending Standalone Ack for MessageCounter:183166533 on exchange 17693i - + [1659422360.478947][2049:2054] [DMG] } + [1659422360.479556][2049:2054] [TOO] Endpoint: 0 Cluster: 0x0000_001F Attribute 0x0000_0000 DataVersion: 3949809681 + [1659422360.479619][2049:2054] [TOO] ACL: 1 entries + [1659422360.479679][2049:2054] [TOO] [1]: { + [1659422360.479706][2049:2054] [TOO] Privilege: 5 + [1659422360.479729][2049:2054] [TOO] AuthMode: 2 + [1659422360.479768][2049:2054] [TOO] Subjects: 2 entries + [1659422360.479819][2049:2054] [TOO] [1]: 1 + [1659422360.479847][2049:2054] [TOO] [2]: 112233 + [1659422360.479876][2049:2054] [TOO] Targets: 1 entries + [1659422360.479925][2049:2054] [TOO] [1]: { + [1659422360.479969][2049:2054] [TOO] Cluster: 31 + [1659422360.479993][2049:2054] [TOO] Endpoint: 0 + [1659422360.480016][2049:2054] [TOO] DeviceType: null + [1659422360.480038][2049:2054] [TOO] } + [1659422360.480062][2049:2054] [TOO] FabricIndex: 1 + [1659422360.480085][2049:2054] [TOO] } + [1659422360.480165][2049:2054] [TOO] Endpoint: 0 Cluster: 0x0000_001F Attribute 0x0000_0001 DataVersion: 3949809681 + [1659422360.480197][2049:2054] [TOO] Extension: 0 entries + [1659422360.480225][2049:2054] [TOO] Endpoint: 0 Cluster: 0x0000_001F Attribute 0x0000_0002 DataVersion: 3949809681 + [1659422360.480251][2049:2054] [TOO] SubjectsPerAccessControlEntry: 4 + [1659422360.480311][2049:2054] [TOO] Endpoint: 0 Cluster: 0x0000_001F Attribute 0x0000_0003 DataVersion: 3949809681 + [1659422360.480337][2049:2054] [TOO] TargetsPerAccessControlEntry: 3 + [1659422360.480395][2049:2054] [TOO] Endpoint: 0 Cluster: 0x0000_001F Attribute 0x0000_0004 DataVersion: 3949809681 + [1659422360.480421][2049:2054] [TOO] AccessControlEntriesPerFabric: 3 + [1659422360.480479][2049:2054] [TOO] Endpoint: 0 Cluster: 0x0000_001F Attribute 0x0000_FFFC DataVersion: 3949809681 + [1659422360.480505][2049:2054] [TOO] FeatureMap: 0 + [1659422360.480563][2049:2054] [TOO] Endpoint: 0 Cluster: 0x0000_001F Attribute 0x0000_FFFD DataVersion: 3949809681 + [1659422360.480588][2049:2054] [TOO] ClusterRevision: 1 + [1659422360.480690][2049:2054] [TOO] Endpoint: 0 Cluster: 0x0000_001F Attribute 0x0000_FFF8 DataVersion: 3949809681 + [1659422360.480721][2049:2054] [TOO] GeneratedCommandList: 0 entries + [1659422360.480789][2049:2054] [TOO] Endpoint: 0 Cluster: 0x0000_001F Attribute 0x0000_FFF9 DataVersion: 3949809681 + [1659422360.480818][2049:2054] [TOO] AcceptedCommandList: 0 entries + [1659422360.481269][2049:2054] [TOO] Endpoint: 0 Cluster: 0x0000_001F Attribute 0x0000_FFFB DataVersion: 3949809681 + [1659422360.481307][2049:2054] [TOO] AttributeList: 10 entries + [1659422360.481334][2049:2054] [TOO] [1]: 0 (NOCs) + [1659422360.481359][2049:2054] [TOO] [2]: 1 (Fabrics) + [1659422360.481383][2049:2054] [TOO] [3]: 2 (SupportedFabrics) + [1659422360.481408][2049:2054] [TOO] [4]: 3 (CommissionedFabrics) + [1659422360.481432][2049:2054] [TOO] [5]: 4 (TrustedRootCertificates) + [1659422360.481457][2049:2054] [TOO] [6]: 65528 (GeneratedCommandList) + [1659422360.481482][2049:2054] [TOO] [7]: 65529 (AcceptedCommandList) + [1659422360.481506][2049:2054] [TOO] [8]: 65531 (AttributeList) + [1659422360.481531][2049:2054] [TOO] [9]: 65532 (FeatureMap) + [1659422360.481556][2049:2054] [TOO] [10]: 65533 (ClusterRevision) + [1659422360.481706][2049:2054] [EM] Sending Standalone Ack for MessageCounter:183166533 on exchange 17693i With the above command, we are overwriting the default privilege that chip-tool has as an admin. After this test step you need to send below mentioned command to Grant access to all clusters again. diff --git a/src/app/tests/suites/certification/Test_TC_WAKEONLAN_4_1.yaml b/src/app/tests/suites/certification/Test_TC_WAKEONLAN_4_1.yaml index eb36c1a418..fc3f667468 100644 --- a/src/app/tests/suites/certification/Test_TC_WAKEONLAN_4_1.yaml +++ b/src/app/tests/suites/certification/Test_TC_WAKEONLAN_4_1.yaml @@ -55,10 +55,10 @@ tests: ./chip-tv-casting-app lowpower read accepted-command-list 1 1 On TH Verify that the DUT is no longer in a low-power state by sending above command - [1654248854.491911][3652:3657] CHIP:TOO: Endpoint: 1 Cluster: 0x0000_0508 Attribute 0x0000_FFF9 DataVersion: 2125568804 - [1654248854.491994][3652:3657] CHIP:TOO: AcceptedCommandList: 1 entries - [1654248854.492040][3652:3657] CHIP:TOO: [1]: 0 - [1654248854.492157][3652:3657] CHIP:EM: Sending Standalone Ack for MessageCounter:15063522 on exchange 51389i + [1654248854.491911][3652:3657] [TOO] Endpoint: 1 Cluster: 0x0000_0508 Attribute 0x0000_FFF9 DataVersion: 2125568804 + [1654248854.491994][3652:3657] [TOO] AcceptedCommandList: 1 entries + [1654248854.492040][3652:3657] [TOO] [1]: 0 (Sleep) + [1654248854.492157][3652:3657] [EM] Sending Standalone Ack for MessageCounter:15063522 on exchange 51389i cluster: "LogCommands" command: "UserPrompt" PICS: PICS_USER_PROMPT 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 12382e3cb4..3d40f3897e 100644 --- a/zzz_generated/chip-tool/zap-generated/cluster/logging/DataModelLogger.cpp +++ b/zzz_generated/chip-tool/zap-generated/cluster/logging/DataModelLogger.cpp @@ -8952,12 +8952,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case Identify::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, Identify::Id); } case Identify::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, Identify::Id); } case Identify::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -8967,7 +8967,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case Identify::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, Identify::Id); } case Identify::Attributes::FeatureMap::Id: { uint32_t value; @@ -8993,12 +8993,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case Groups::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, Groups::Id); } case Groups::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, Groups::Id); } case Groups::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -9008,7 +9008,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case Groups::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, Groups::Id); } case Groups::Attributes::FeatureMap::Id: { uint32_t value; @@ -9054,12 +9054,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case OnOff::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, OnOff::Id); } case OnOff::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, OnOff::Id); } case OnOff::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -9069,7 +9069,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case OnOff::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, OnOff::Id); } case OnOff::Attributes::FeatureMap::Id: { uint32_t value; @@ -9100,12 +9100,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case OnOffSwitchConfiguration::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, OnOffSwitchConfiguration::Id); } case OnOffSwitchConfiguration::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, OnOffSwitchConfiguration::Id); } case OnOffSwitchConfiguration::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -9115,7 +9115,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case OnOffSwitchConfiguration::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, OnOffSwitchConfiguration::Id); } case OnOffSwitchConfiguration::Attributes::FeatureMap::Id: { uint32_t value; @@ -9206,12 +9206,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case LevelControl::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, LevelControl::Id); } case LevelControl::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, LevelControl::Id); } case LevelControl::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -9221,7 +9221,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case LevelControl::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, LevelControl::Id); } case LevelControl::Attributes::FeatureMap::Id: { uint32_t value; @@ -9287,12 +9287,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case BinaryInputBasic::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, BinaryInputBasic::Id); } case BinaryInputBasic::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, BinaryInputBasic::Id); } case BinaryInputBasic::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -9302,7 +9302,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case BinaryInputBasic::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, BinaryInputBasic::Id); } case BinaryInputBasic::Attributes::FeatureMap::Id: { uint32_t value; @@ -9323,12 +9323,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case PulseWidthModulation::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, PulseWidthModulation::Id); } case PulseWidthModulation::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, PulseWidthModulation::Id); } case PulseWidthModulation::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -9338,7 +9338,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case PulseWidthModulation::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, PulseWidthModulation::Id); } case PulseWidthModulation::Attributes::FeatureMap::Id: { uint32_t value; @@ -9364,12 +9364,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case Descriptor::Attributes::ServerList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("ServerList", 1, value); + return DataModelLogger::LogClusterId("ServerList", 1, value); } case Descriptor::Attributes::ClientList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("ClientList", 1, value); + return DataModelLogger::LogClusterId("ClientList", 1, value); } case Descriptor::Attributes::PartsList::Id: { chip::app::DataModel::DecodableList value; @@ -9384,12 +9384,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case Descriptor::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, Descriptor::Id); } case Descriptor::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, Descriptor::Id); } case Descriptor::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -9399,7 +9399,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case Descriptor::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, Descriptor::Id); } case Descriptor::Attributes::FeatureMap::Id: { uint32_t value; @@ -9425,12 +9425,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case Binding::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, Binding::Id); } case Binding::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, Binding::Id); } case Binding::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -9440,7 +9440,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case Binding::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, Binding::Id); } case Binding::Attributes::FeatureMap::Id: { uint32_t value; @@ -9504,12 +9504,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case AccessControl::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, AccessControl::Id); } case AccessControl::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, AccessControl::Id); } case AccessControl::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -9519,7 +9519,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case AccessControl::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, AccessControl::Id); } case AccessControl::Attributes::FeatureMap::Id: { uint32_t value; @@ -9555,12 +9555,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case Actions::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, Actions::Id); } case Actions::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, Actions::Id); } case Actions::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -9570,7 +9570,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case Actions::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, Actions::Id); } case Actions::Attributes::FeatureMap::Id: { uint32_t value; @@ -9706,12 +9706,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case BasicInformation::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, BasicInformation::Id); } case BasicInformation::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, BasicInformation::Id); } case BasicInformation::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -9721,7 +9721,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case BasicInformation::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, BasicInformation::Id); } case BasicInformation::Attributes::FeatureMap::Id: { uint32_t value; @@ -9742,12 +9742,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case OtaSoftwareUpdateProvider::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, OtaSoftwareUpdateProvider::Id); } case OtaSoftwareUpdateProvider::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, OtaSoftwareUpdateProvider::Id); } case OtaSoftwareUpdateProvider::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -9757,7 +9757,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case OtaSoftwareUpdateProvider::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, OtaSoftwareUpdateProvider::Id); } case OtaSoftwareUpdateProvider::Attributes::FeatureMap::Id: { uint32_t value; @@ -9800,12 +9800,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case OtaSoftwareUpdateRequestor::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, OtaSoftwareUpdateRequestor::Id); } case OtaSoftwareUpdateRequestor::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, OtaSoftwareUpdateRequestor::Id); } case OtaSoftwareUpdateRequestor::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -9815,7 +9815,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case OtaSoftwareUpdateRequestor::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, OtaSoftwareUpdateRequestor::Id); } case OtaSoftwareUpdateRequestor::Attributes::FeatureMap::Id: { uint32_t value; @@ -9846,12 +9846,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case LocalizationConfiguration::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, LocalizationConfiguration::Id); } case LocalizationConfiguration::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, LocalizationConfiguration::Id); } case LocalizationConfiguration::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -9861,7 +9861,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case LocalizationConfiguration::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, LocalizationConfiguration::Id); } case LocalizationConfiguration::Attributes::FeatureMap::Id: { uint32_t value; @@ -9897,12 +9897,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case TimeFormatLocalization::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, TimeFormatLocalization::Id); } case TimeFormatLocalization::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, TimeFormatLocalization::Id); } case TimeFormatLocalization::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -9912,7 +9912,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case TimeFormatLocalization::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, TimeFormatLocalization::Id); } case TimeFormatLocalization::Attributes::FeatureMap::Id: { uint32_t value; @@ -9938,12 +9938,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case UnitLocalization::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, UnitLocalization::Id); } case UnitLocalization::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, UnitLocalization::Id); } case UnitLocalization::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -9953,7 +9953,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case UnitLocalization::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, UnitLocalization::Id); } case UnitLocalization::Attributes::FeatureMap::Id: { uint32_t value; @@ -9979,12 +9979,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case PowerSourceConfiguration::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, PowerSourceConfiguration::Id); } case PowerSourceConfiguration::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, PowerSourceConfiguration::Id); } case PowerSourceConfiguration::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -9994,7 +9994,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case PowerSourceConfiguration::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, PowerSourceConfiguration::Id); } case PowerSourceConfiguration::Attributes::FeatureMap::Id: { uint32_t value; @@ -10175,12 +10175,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case PowerSource::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, PowerSource::Id); } case PowerSource::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, PowerSource::Id); } case PowerSource::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -10190,7 +10190,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case PowerSource::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, PowerSource::Id); } case PowerSource::Attributes::FeatureMap::Id: { uint32_t value; @@ -10256,12 +10256,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case GeneralCommissioning::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, GeneralCommissioning::Id); } case GeneralCommissioning::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, GeneralCommissioning::Id); } case GeneralCommissioning::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -10271,7 +10271,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case GeneralCommissioning::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, GeneralCommissioning::Id); } case GeneralCommissioning::Attributes::FeatureMap::Id: { uint32_t value; @@ -10349,12 +10349,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case NetworkCommissioning::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, NetworkCommissioning::Id); } case NetworkCommissioning::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, NetworkCommissioning::Id); } case NetworkCommissioning::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -10364,7 +10364,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case NetworkCommissioning::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, NetworkCommissioning::Id); } case NetworkCommissioning::Attributes::FeatureMap::Id: { uint32_t value; @@ -10385,12 +10385,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case DiagnosticLogs::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, DiagnosticLogs::Id); } case DiagnosticLogs::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, DiagnosticLogs::Id); } case DiagnosticLogs::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -10400,7 +10400,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case DiagnosticLogs::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, DiagnosticLogs::Id); } case DiagnosticLogs::Attributes::FeatureMap::Id: { uint32_t value; @@ -10467,12 +10467,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case GeneralDiagnostics::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, GeneralDiagnostics::Id); } case GeneralDiagnostics::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, GeneralDiagnostics::Id); } case GeneralDiagnostics::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -10482,7 +10482,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case GeneralDiagnostics::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, GeneralDiagnostics::Id); } case GeneralDiagnostics::Attributes::FeatureMap::Id: { uint32_t value; @@ -10525,12 +10525,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case SoftwareDiagnostics::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, SoftwareDiagnostics::Id); } case SoftwareDiagnostics::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, SoftwareDiagnostics::Id); } case SoftwareDiagnostics::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -10540,7 +10540,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case SoftwareDiagnostics::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, SoftwareDiagnostics::Id); } case SoftwareDiagnostics::Attributes::FeatureMap::Id: { uint32_t value; @@ -10883,12 +10883,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case ThreadNetworkDiagnostics::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, ThreadNetworkDiagnostics::Id); } case ThreadNetworkDiagnostics::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, ThreadNetworkDiagnostics::Id); } case ThreadNetworkDiagnostics::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -10898,7 +10898,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case ThreadNetworkDiagnostics::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, ThreadNetworkDiagnostics::Id); } case ThreadNetworkDiagnostics::Attributes::FeatureMap::Id: { uint32_t value; @@ -10984,12 +10984,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case WiFiNetworkDiagnostics::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, WiFiNetworkDiagnostics::Id); } case WiFiNetworkDiagnostics::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, WiFiNetworkDiagnostics::Id); } case WiFiNetworkDiagnostics::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -10999,7 +10999,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case WiFiNetworkDiagnostics::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, WiFiNetworkDiagnostics::Id); } case WiFiNetworkDiagnostics::Attributes::FeatureMap::Id: { uint32_t value; @@ -11065,12 +11065,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case EthernetNetworkDiagnostics::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, EthernetNetworkDiagnostics::Id); } case EthernetNetworkDiagnostics::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, EthernetNetworkDiagnostics::Id); } case EthernetNetworkDiagnostics::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -11080,7 +11080,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case EthernetNetworkDiagnostics::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, EthernetNetworkDiagnostics::Id); } case EthernetNetworkDiagnostics::Attributes::FeatureMap::Id: { uint32_t value; @@ -11170,12 +11170,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case TimeSynchronization::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, TimeSynchronization::Id); } case TimeSynchronization::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, TimeSynchronization::Id); } case TimeSynchronization::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -11185,7 +11185,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case TimeSynchronization::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, TimeSynchronization::Id); } case TimeSynchronization::Attributes::FeatureMap::Id: { uint32_t value; @@ -11291,12 +11291,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case BridgedDeviceBasicInformation::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, BridgedDeviceBasicInformation::Id); } case BridgedDeviceBasicInformation::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, BridgedDeviceBasicInformation::Id); } case BridgedDeviceBasicInformation::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -11306,7 +11306,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case BridgedDeviceBasicInformation::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, BridgedDeviceBasicInformation::Id); } case BridgedDeviceBasicInformation::Attributes::FeatureMap::Id: { uint32_t value; @@ -11342,12 +11342,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case Switch::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, Switch::Id); } case Switch::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, Switch::Id); } case Switch::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -11357,7 +11357,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case Switch::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, Switch::Id); } case Switch::Attributes::FeatureMap::Id: { uint32_t value; @@ -11393,12 +11393,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case AdministratorCommissioning::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, AdministratorCommissioning::Id); } case AdministratorCommissioning::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, AdministratorCommissioning::Id); } case AdministratorCommissioning::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -11408,7 +11408,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case AdministratorCommissioning::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, AdministratorCommissioning::Id); } case AdministratorCommissioning::Attributes::FeatureMap::Id: { uint32_t value; @@ -11462,12 +11462,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case OperationalCredentials::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, OperationalCredentials::Id); } case OperationalCredentials::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, OperationalCredentials::Id); } case OperationalCredentials::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -11477,7 +11477,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case OperationalCredentials::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, OperationalCredentials::Id); } case OperationalCredentials::Attributes::FeatureMap::Id: { uint32_t value; @@ -11520,12 +11520,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case GroupKeyManagement::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, GroupKeyManagement::Id); } case GroupKeyManagement::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, GroupKeyManagement::Id); } case GroupKeyManagement::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -11535,7 +11535,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case GroupKeyManagement::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, GroupKeyManagement::Id); } case GroupKeyManagement::Attributes::FeatureMap::Id: { uint32_t value; @@ -11561,12 +11561,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case FixedLabel::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, FixedLabel::Id); } case FixedLabel::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, FixedLabel::Id); } case FixedLabel::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -11576,7 +11576,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case FixedLabel::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, FixedLabel::Id); } case FixedLabel::Attributes::FeatureMap::Id: { uint32_t value; @@ -11602,12 +11602,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case UserLabel::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, UserLabel::Id); } case UserLabel::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, UserLabel::Id); } case UserLabel::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -11617,7 +11617,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case UserLabel::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, UserLabel::Id); } case UserLabel::Attributes::FeatureMap::Id: { uint32_t value; @@ -11638,12 +11638,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case ProxyConfiguration::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, ProxyConfiguration::Id); } case ProxyConfiguration::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, ProxyConfiguration::Id); } case ProxyConfiguration::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -11653,7 +11653,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case ProxyConfiguration::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, ProxyConfiguration::Id); } case ProxyConfiguration::Attributes::FeatureMap::Id: { uint32_t value; @@ -11674,12 +11674,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case ProxyDiscovery::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, ProxyDiscovery::Id); } case ProxyDiscovery::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, ProxyDiscovery::Id); } case ProxyDiscovery::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -11689,7 +11689,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case ProxyDiscovery::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, ProxyDiscovery::Id); } case ProxyDiscovery::Attributes::FeatureMap::Id: { uint32_t value; @@ -11710,12 +11710,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case ProxyValid::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, ProxyValid::Id); } case ProxyValid::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, ProxyValid::Id); } case ProxyValid::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -11725,7 +11725,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case ProxyValid::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, ProxyValid::Id); } case ProxyValid::Attributes::FeatureMap::Id: { uint32_t value; @@ -11751,12 +11751,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case BooleanState::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, BooleanState::Id); } case BooleanState::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, BooleanState::Id); } case BooleanState::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -11766,7 +11766,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case BooleanState::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, BooleanState::Id); } case BooleanState::Attributes::FeatureMap::Id: { uint32_t value; @@ -11839,12 +11839,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case IcdManagement::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, IcdManagement::Id); } case IcdManagement::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, IcdManagement::Id); } case IcdManagement::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -11854,7 +11854,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case IcdManagement::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, IcdManagement::Id); } case IcdManagement::Attributes::FeatureMap::Id: { uint32_t value; @@ -11890,12 +11890,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case Timer::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, Timer::Id); } case Timer::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, Timer::Id); } case Timer::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -11905,7 +11905,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case Timer::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, Timer::Id); } case Timer::Attributes::FeatureMap::Id: { uint32_t value; @@ -11958,12 +11958,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case OvenCavityOperationalState::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, OvenCavityOperationalState::Id); } case OvenCavityOperationalState::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, OvenCavityOperationalState::Id); } case OvenCavityOperationalState::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -11973,7 +11973,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case OvenCavityOperationalState::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, OvenCavityOperationalState::Id); } case OvenCavityOperationalState::Attributes::FeatureMap::Id: { uint32_t value; @@ -12014,12 +12014,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case OvenMode::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, OvenMode::Id); } case OvenMode::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, OvenMode::Id); } case OvenMode::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -12029,7 +12029,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case OvenMode::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, OvenMode::Id); } case OvenMode::Attributes::FeatureMap::Id: { uint32_t value; @@ -12060,12 +12060,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case LaundryDryerControls::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, LaundryDryerControls::Id); } case LaundryDryerControls::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, LaundryDryerControls::Id); } case LaundryDryerControls::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -12075,7 +12075,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case LaundryDryerControls::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, LaundryDryerControls::Id); } case LaundryDryerControls::Attributes::FeatureMap::Id: { uint32_t value; @@ -12126,12 +12126,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case ModeSelect::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, ModeSelect::Id); } case ModeSelect::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, ModeSelect::Id); } case ModeSelect::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -12141,7 +12141,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case ModeSelect::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, ModeSelect::Id); } case ModeSelect::Attributes::FeatureMap::Id: { uint32_t value; @@ -12183,12 +12183,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case LaundryWasherMode::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, LaundryWasherMode::Id); } case LaundryWasherMode::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, LaundryWasherMode::Id); } case LaundryWasherMode::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -12198,7 +12198,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case LaundryWasherMode::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, LaundryWasherMode::Id); } case LaundryWasherMode::Attributes::FeatureMap::Id: { uint32_t value; @@ -12241,12 +12241,14 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case RefrigeratorAndTemperatureControlledCabinetMode::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, + RefrigeratorAndTemperatureControlledCabinetMode::Id); } case RefrigeratorAndTemperatureControlledCabinetMode::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, + RefrigeratorAndTemperatureControlledCabinetMode::Id); } case RefrigeratorAndTemperatureControlledCabinetMode::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -12256,7 +12258,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case RefrigeratorAndTemperatureControlledCabinetMode::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, RefrigeratorAndTemperatureControlledCabinetMode::Id); } case RefrigeratorAndTemperatureControlledCabinetMode::Attributes::FeatureMap::Id: { uint32_t value; @@ -12297,12 +12299,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case LaundryWasherControls::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, LaundryWasherControls::Id); } case LaundryWasherControls::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, LaundryWasherControls::Id); } case LaundryWasherControls::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -12312,7 +12314,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case LaundryWasherControls::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, LaundryWasherControls::Id); } case LaundryWasherControls::Attributes::FeatureMap::Id: { uint32_t value; @@ -12343,12 +12345,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case RvcRunMode::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, RvcRunMode::Id); } case RvcRunMode::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, RvcRunMode::Id); } case RvcRunMode::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -12358,7 +12360,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case RvcRunMode::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, RvcRunMode::Id); } case RvcRunMode::Attributes::FeatureMap::Id: { uint32_t value; @@ -12389,12 +12391,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case RvcCleanMode::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, RvcCleanMode::Id); } case RvcCleanMode::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, RvcCleanMode::Id); } case RvcCleanMode::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -12404,7 +12406,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case RvcCleanMode::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, RvcCleanMode::Id); } case RvcCleanMode::Attributes::FeatureMap::Id: { uint32_t value; @@ -12455,12 +12457,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case TemperatureControl::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, TemperatureControl::Id); } case TemperatureControl::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, TemperatureControl::Id); } case TemperatureControl::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -12470,7 +12472,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case TemperatureControl::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, TemperatureControl::Id); } case TemperatureControl::Attributes::FeatureMap::Id: { uint32_t value; @@ -12506,12 +12508,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case RefrigeratorAlarm::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, RefrigeratorAlarm::Id); } case RefrigeratorAlarm::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, RefrigeratorAlarm::Id); } case RefrigeratorAlarm::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -12521,7 +12523,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case RefrigeratorAlarm::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, RefrigeratorAlarm::Id); } case RefrigeratorAlarm::Attributes::FeatureMap::Id: { uint32_t value; @@ -12563,12 +12565,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case DishwasherMode::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, DishwasherMode::Id); } case DishwasherMode::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, DishwasherMode::Id); } case DishwasherMode::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -12578,7 +12580,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case DishwasherMode::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, DishwasherMode::Id); } case DishwasherMode::Attributes::FeatureMap::Id: { uint32_t value; @@ -12604,12 +12606,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case AirQuality::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, AirQuality::Id); } case AirQuality::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, AirQuality::Id); } case AirQuality::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -12619,7 +12621,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case AirQuality::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, AirQuality::Id); } case AirQuality::Attributes::FeatureMap::Id: { uint32_t value; @@ -12705,12 +12707,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case SmokeCoAlarm::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, SmokeCoAlarm::Id); } case SmokeCoAlarm::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, SmokeCoAlarm::Id); } case SmokeCoAlarm::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -12720,7 +12722,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case SmokeCoAlarm::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, SmokeCoAlarm::Id); } case SmokeCoAlarm::Attributes::FeatureMap::Id: { uint32_t value; @@ -12761,12 +12763,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case DishwasherAlarm::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, DishwasherAlarm::Id); } case DishwasherAlarm::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, DishwasherAlarm::Id); } case DishwasherAlarm::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -12776,7 +12778,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case DishwasherAlarm::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, DishwasherAlarm::Id); } case DishwasherAlarm::Attributes::FeatureMap::Id: { uint32_t value; @@ -12808,12 +12810,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case MicrowaveOvenMode::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, MicrowaveOvenMode::Id); } case MicrowaveOvenMode::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, MicrowaveOvenMode::Id); } case MicrowaveOvenMode::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -12823,7 +12825,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case MicrowaveOvenMode::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, MicrowaveOvenMode::Id); } case MicrowaveOvenMode::Attributes::FeatureMap::Id: { uint32_t value; @@ -12889,12 +12891,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case MicrowaveOvenControl::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, MicrowaveOvenControl::Id); } case MicrowaveOvenControl::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, MicrowaveOvenControl::Id); } case MicrowaveOvenControl::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -12904,7 +12906,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case MicrowaveOvenControl::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, MicrowaveOvenControl::Id); } case MicrowaveOvenControl::Attributes::FeatureMap::Id: { uint32_t value; @@ -12957,12 +12959,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case OperationalState::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, OperationalState::Id); } case OperationalState::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, OperationalState::Id); } case OperationalState::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -12972,7 +12974,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case OperationalState::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, OperationalState::Id); } case OperationalState::Attributes::FeatureMap::Id: { uint32_t value; @@ -13025,12 +13027,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case RvcOperationalState::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, RvcOperationalState::Id); } case RvcOperationalState::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, RvcOperationalState::Id); } case RvcOperationalState::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -13040,7 +13042,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case RvcOperationalState::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, RvcOperationalState::Id); } case RvcOperationalState::Attributes::FeatureMap::Id: { uint32_t value; @@ -13077,12 +13079,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case ScenesManagement::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, ScenesManagement::Id); } case ScenesManagement::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, ScenesManagement::Id); } case ScenesManagement::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -13092,7 +13094,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case ScenesManagement::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, ScenesManagement::Id); } case ScenesManagement::Attributes::FeatureMap::Id: { uint32_t value; @@ -13145,12 +13147,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case HepaFilterMonitoring::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, HepaFilterMonitoring::Id); } case HepaFilterMonitoring::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, HepaFilterMonitoring::Id); } case HepaFilterMonitoring::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -13160,7 +13162,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case HepaFilterMonitoring::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, HepaFilterMonitoring::Id); } case HepaFilterMonitoring::Attributes::FeatureMap::Id: { uint32_t value; @@ -13213,12 +13215,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case ActivatedCarbonFilterMonitoring::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, ActivatedCarbonFilterMonitoring::Id); } case ActivatedCarbonFilterMonitoring::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, ActivatedCarbonFilterMonitoring::Id); } case ActivatedCarbonFilterMonitoring::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -13228,7 +13230,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case ActivatedCarbonFilterMonitoring::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, ActivatedCarbonFilterMonitoring::Id); } case ActivatedCarbonFilterMonitoring::Attributes::FeatureMap::Id: { uint32_t value; @@ -13289,12 +13291,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case BooleanStateConfiguration::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, BooleanStateConfiguration::Id); } case BooleanStateConfiguration::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, BooleanStateConfiguration::Id); } case BooleanStateConfiguration::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -13304,7 +13306,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case BooleanStateConfiguration::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, BooleanStateConfiguration::Id); } case BooleanStateConfiguration::Attributes::FeatureMap::Id: { uint32_t value; @@ -13380,12 +13382,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case ValveConfigurationAndControl::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, ValveConfigurationAndControl::Id); } case ValveConfigurationAndControl::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, ValveConfigurationAndControl::Id); } case ValveConfigurationAndControl::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -13395,7 +13397,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case ValveConfigurationAndControl::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, ValveConfigurationAndControl::Id); } case ValveConfigurationAndControl::Attributes::FeatureMap::Id: { uint32_t value; @@ -13519,12 +13521,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case ElectricalPowerMeasurement::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, ElectricalPowerMeasurement::Id); } case ElectricalPowerMeasurement::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, ElectricalPowerMeasurement::Id); } case ElectricalPowerMeasurement::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -13534,7 +13536,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case ElectricalPowerMeasurement::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, ElectricalPowerMeasurement::Id); } case ElectricalPowerMeasurement::Attributes::FeatureMap::Id: { uint32_t value; @@ -13595,12 +13597,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case ElectricalEnergyMeasurement::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, ElectricalEnergyMeasurement::Id); } case ElectricalEnergyMeasurement::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, ElectricalEnergyMeasurement::Id); } case ElectricalEnergyMeasurement::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -13610,7 +13612,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case ElectricalEnergyMeasurement::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, ElectricalEnergyMeasurement::Id); } case ElectricalEnergyMeasurement::Attributes::FeatureMap::Id: { uint32_t value; @@ -13661,12 +13663,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case WaterHeaterManagement::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, WaterHeaterManagement::Id); } case WaterHeaterManagement::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, WaterHeaterManagement::Id); } case WaterHeaterManagement::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -13676,7 +13678,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case WaterHeaterManagement::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, WaterHeaterManagement::Id); } case WaterHeaterManagement::Attributes::FeatureMap::Id: { uint32_t value; @@ -13743,12 +13745,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case DemandResponseLoadControl::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, DemandResponseLoadControl::Id); } case DemandResponseLoadControl::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, DemandResponseLoadControl::Id); } case DemandResponseLoadControl::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -13758,7 +13760,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case DemandResponseLoadControl::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, DemandResponseLoadControl::Id); } case DemandResponseLoadControl::Attributes::FeatureMap::Id: { uint32_t value; @@ -13789,12 +13791,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case Messages::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, Messages::Id); } case Messages::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, Messages::Id); } case Messages::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -13804,7 +13806,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case Messages::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, Messages::Id); } case Messages::Attributes::FeatureMap::Id: { uint32_t value; @@ -13868,12 +13870,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case DeviceEnergyManagement::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, DeviceEnergyManagement::Id); } case DeviceEnergyManagement::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, DeviceEnergyManagement::Id); } case DeviceEnergyManagement::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -13883,7 +13885,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case DeviceEnergyManagement::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, DeviceEnergyManagement::Id); } case DeviceEnergyManagement::Attributes::FeatureMap::Id: { uint32_t value; @@ -14019,12 +14021,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case EnergyEvse::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, EnergyEvse::Id); } case EnergyEvse::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, EnergyEvse::Id); } case EnergyEvse::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -14034,7 +14036,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case EnergyEvse::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, EnergyEvse::Id); } case EnergyEvse::Attributes::FeatureMap::Id: { uint32_t value; @@ -14080,12 +14082,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case EnergyPreference::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, EnergyPreference::Id); } case EnergyPreference::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, EnergyPreference::Id); } case EnergyPreference::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -14095,7 +14097,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case EnergyPreference::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, EnergyPreference::Id); } case EnergyPreference::Attributes::FeatureMap::Id: { uint32_t value; @@ -14126,12 +14128,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case PowerTopology::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, PowerTopology::Id); } case PowerTopology::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, PowerTopology::Id); } case PowerTopology::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -14141,7 +14143,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case PowerTopology::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, PowerTopology::Id); } case PowerTopology::Attributes::FeatureMap::Id: { uint32_t value; @@ -14183,12 +14185,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case EnergyEvseMode::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, EnergyEvseMode::Id); } case EnergyEvseMode::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, EnergyEvseMode::Id); } case EnergyEvseMode::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -14198,7 +14200,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case EnergyEvseMode::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, EnergyEvseMode::Id); } case EnergyEvseMode::Attributes::FeatureMap::Id: { uint32_t value; @@ -14240,12 +14242,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case WaterHeaterMode::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, WaterHeaterMode::Id); } case WaterHeaterMode::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, WaterHeaterMode::Id); } case WaterHeaterMode::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -14255,7 +14257,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case WaterHeaterMode::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, WaterHeaterMode::Id); } case WaterHeaterMode::Attributes::FeatureMap::Id: { uint32_t value; @@ -14298,12 +14300,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case DeviceEnergyManagementMode::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, DeviceEnergyManagementMode::Id); } case DeviceEnergyManagementMode::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, DeviceEnergyManagementMode::Id); } case DeviceEnergyManagementMode::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -14313,7 +14315,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case DeviceEnergyManagementMode::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, DeviceEnergyManagementMode::Id); } case DeviceEnergyManagementMode::Attributes::FeatureMap::Id: { uint32_t value; @@ -14559,12 +14561,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case DoorLock::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, DoorLock::Id); } case DoorLock::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, DoorLock::Id); } case DoorLock::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -14574,7 +14576,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case DoorLock::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, DoorLock::Id); } case DoorLock::Attributes::FeatureMap::Id: { uint32_t value; @@ -14705,12 +14707,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case WindowCovering::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, WindowCovering::Id); } case WindowCovering::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, WindowCovering::Id); } case WindowCovering::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -14720,7 +14722,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case WindowCovering::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, WindowCovering::Id); } case WindowCovering::Attributes::FeatureMap::Id: { uint32_t value; @@ -14791,12 +14793,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case BarrierControl::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, BarrierControl::Id); } case BarrierControl::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, BarrierControl::Id); } case BarrierControl::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -14806,7 +14808,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case BarrierControl::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, BarrierControl::Id); } case BarrierControl::Attributes::FeatureMap::Id: { uint32_t value; @@ -14857,12 +14859,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case ServiceArea::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, ServiceArea::Id); } case ServiceArea::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, ServiceArea::Id); } case ServiceArea::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -14872,7 +14874,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case ServiceArea::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, ServiceArea::Id); } case ServiceArea::Attributes::FeatureMap::Id: { uint32_t value; @@ -15008,12 +15010,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case PumpConfigurationAndControl::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, PumpConfigurationAndControl::Id); } case PumpConfigurationAndControl::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, PumpConfigurationAndControl::Id); } case PumpConfigurationAndControl::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -15023,7 +15025,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case PumpConfigurationAndControl::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, PumpConfigurationAndControl::Id); } case PumpConfigurationAndControl::Attributes::FeatureMap::Id: { uint32_t value; @@ -15344,12 +15346,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case Thermostat::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, Thermostat::Id); } case Thermostat::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, Thermostat::Id); } case Thermostat::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -15359,7 +15361,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case Thermostat::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, Thermostat::Id); } case Thermostat::Attributes::FeatureMap::Id: { uint32_t value; @@ -15440,12 +15442,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case FanControl::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, FanControl::Id); } case FanControl::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, FanControl::Id); } case FanControl::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -15455,7 +15457,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case FanControl::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, FanControl::Id); } case FanControl::Attributes::FeatureMap::Id: { uint32_t value; @@ -15491,12 +15493,13 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case ThermostatUserInterfaceConfiguration::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, + ThermostatUserInterfaceConfiguration::Id); } case ThermostatUserInterfaceConfiguration::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, ThermostatUserInterfaceConfiguration::Id); } case ThermostatUserInterfaceConfiguration::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -15506,7 +15509,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case ThermostatUserInterfaceConfiguration::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, ThermostatUserInterfaceConfiguration::Id); } case ThermostatUserInterfaceConfiguration::Attributes::FeatureMap::Id: { uint32_t value; @@ -15787,12 +15790,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case ColorControl::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, ColorControl::Id); } case ColorControl::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, ColorControl::Id); } case ColorControl::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -15802,7 +15805,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case ColorControl::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, ColorControl::Id); } case ColorControl::Attributes::FeatureMap::Id: { uint32_t value; @@ -15893,12 +15896,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case BallastConfiguration::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, BallastConfiguration::Id); } case BallastConfiguration::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, BallastConfiguration::Id); } case BallastConfiguration::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -15908,7 +15911,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case BallastConfiguration::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, BallastConfiguration::Id); } case BallastConfiguration::Attributes::FeatureMap::Id: { uint32_t value; @@ -15954,12 +15957,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case IlluminanceMeasurement::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, IlluminanceMeasurement::Id); } case IlluminanceMeasurement::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, IlluminanceMeasurement::Id); } case IlluminanceMeasurement::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -15969,7 +15972,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case IlluminanceMeasurement::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, IlluminanceMeasurement::Id); } case IlluminanceMeasurement::Attributes::FeatureMap::Id: { uint32_t value; @@ -16010,12 +16013,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case TemperatureMeasurement::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, TemperatureMeasurement::Id); } case TemperatureMeasurement::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, TemperatureMeasurement::Id); } case TemperatureMeasurement::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -16025,7 +16028,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case TemperatureMeasurement::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, TemperatureMeasurement::Id); } case TemperatureMeasurement::Attributes::FeatureMap::Id: { uint32_t value; @@ -16091,12 +16094,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case PressureMeasurement::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, PressureMeasurement::Id); } case PressureMeasurement::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, PressureMeasurement::Id); } case PressureMeasurement::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -16106,7 +16109,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case PressureMeasurement::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, PressureMeasurement::Id); } case PressureMeasurement::Attributes::FeatureMap::Id: { uint32_t value; @@ -16147,12 +16150,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case FlowMeasurement::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, FlowMeasurement::Id); } case FlowMeasurement::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, FlowMeasurement::Id); } case FlowMeasurement::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -16162,7 +16165,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case FlowMeasurement::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, FlowMeasurement::Id); } case FlowMeasurement::Attributes::FeatureMap::Id: { uint32_t value; @@ -16203,12 +16206,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case RelativeHumidityMeasurement::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, RelativeHumidityMeasurement::Id); } case RelativeHumidityMeasurement::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, RelativeHumidityMeasurement::Id); } case RelativeHumidityMeasurement::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -16218,7 +16221,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case RelativeHumidityMeasurement::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, RelativeHumidityMeasurement::Id); } case RelativeHumidityMeasurement::Attributes::FeatureMap::Id: { uint32_t value; @@ -16309,12 +16312,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case OccupancySensing::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, OccupancySensing::Id); } case OccupancySensing::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, OccupancySensing::Id); } case OccupancySensing::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -16324,7 +16327,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case OccupancySensing::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, OccupancySensing::Id); } case OccupancySensing::Attributes::FeatureMap::Id: { uint32_t value; @@ -16400,12 +16403,14 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case CarbonMonoxideConcentrationMeasurement::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, + CarbonMonoxideConcentrationMeasurement::Id); } case CarbonMonoxideConcentrationMeasurement::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, + CarbonMonoxideConcentrationMeasurement::Id); } case CarbonMonoxideConcentrationMeasurement::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -16415,7 +16420,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case CarbonMonoxideConcentrationMeasurement::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, CarbonMonoxideConcentrationMeasurement::Id); } case CarbonMonoxideConcentrationMeasurement::Attributes::FeatureMap::Id: { uint32_t value; @@ -16491,12 +16496,14 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case CarbonDioxideConcentrationMeasurement::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, + CarbonDioxideConcentrationMeasurement::Id); } case CarbonDioxideConcentrationMeasurement::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, + CarbonDioxideConcentrationMeasurement::Id); } case CarbonDioxideConcentrationMeasurement::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -16506,7 +16513,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case CarbonDioxideConcentrationMeasurement::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, CarbonDioxideConcentrationMeasurement::Id); } case CarbonDioxideConcentrationMeasurement::Attributes::FeatureMap::Id: { uint32_t value; @@ -16582,12 +16589,14 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case NitrogenDioxideConcentrationMeasurement::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, + NitrogenDioxideConcentrationMeasurement::Id); } case NitrogenDioxideConcentrationMeasurement::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, + NitrogenDioxideConcentrationMeasurement::Id); } case NitrogenDioxideConcentrationMeasurement::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -16597,7 +16606,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case NitrogenDioxideConcentrationMeasurement::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, NitrogenDioxideConcentrationMeasurement::Id); } case NitrogenDioxideConcentrationMeasurement::Attributes::FeatureMap::Id: { uint32_t value; @@ -16673,12 +16682,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case OzoneConcentrationMeasurement::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, OzoneConcentrationMeasurement::Id); } case OzoneConcentrationMeasurement::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, OzoneConcentrationMeasurement::Id); } case OzoneConcentrationMeasurement::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -16688,7 +16697,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case OzoneConcentrationMeasurement::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, OzoneConcentrationMeasurement::Id); } case OzoneConcentrationMeasurement::Attributes::FeatureMap::Id: { uint32_t value; @@ -16764,12 +16773,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case Pm25ConcentrationMeasurement::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, Pm25ConcentrationMeasurement::Id); } case Pm25ConcentrationMeasurement::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, Pm25ConcentrationMeasurement::Id); } case Pm25ConcentrationMeasurement::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -16779,7 +16788,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case Pm25ConcentrationMeasurement::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, Pm25ConcentrationMeasurement::Id); } case Pm25ConcentrationMeasurement::Attributes::FeatureMap::Id: { uint32_t value; @@ -16855,12 +16864,13 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case FormaldehydeConcentrationMeasurement::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, + FormaldehydeConcentrationMeasurement::Id); } case FormaldehydeConcentrationMeasurement::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, FormaldehydeConcentrationMeasurement::Id); } case FormaldehydeConcentrationMeasurement::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -16870,7 +16880,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case FormaldehydeConcentrationMeasurement::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, FormaldehydeConcentrationMeasurement::Id); } case FormaldehydeConcentrationMeasurement::Attributes::FeatureMap::Id: { uint32_t value; @@ -16946,12 +16956,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case Pm1ConcentrationMeasurement::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, Pm1ConcentrationMeasurement::Id); } case Pm1ConcentrationMeasurement::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, Pm1ConcentrationMeasurement::Id); } case Pm1ConcentrationMeasurement::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -16961,7 +16971,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case Pm1ConcentrationMeasurement::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, Pm1ConcentrationMeasurement::Id); } case Pm1ConcentrationMeasurement::Attributes::FeatureMap::Id: { uint32_t value; @@ -17037,12 +17047,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case Pm10ConcentrationMeasurement::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, Pm10ConcentrationMeasurement::Id); } case Pm10ConcentrationMeasurement::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, Pm10ConcentrationMeasurement::Id); } case Pm10ConcentrationMeasurement::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -17052,7 +17062,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case Pm10ConcentrationMeasurement::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, Pm10ConcentrationMeasurement::Id); } case Pm10ConcentrationMeasurement::Attributes::FeatureMap::Id: { uint32_t value; @@ -17128,12 +17138,14 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case TotalVolatileOrganicCompoundsConcentrationMeasurement::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, + TotalVolatileOrganicCompoundsConcentrationMeasurement::Id); } case TotalVolatileOrganicCompoundsConcentrationMeasurement::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, + TotalVolatileOrganicCompoundsConcentrationMeasurement::Id); } case TotalVolatileOrganicCompoundsConcentrationMeasurement::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -17143,7 +17155,8 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case TotalVolatileOrganicCompoundsConcentrationMeasurement::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, + TotalVolatileOrganicCompoundsConcentrationMeasurement::Id); } case TotalVolatileOrganicCompoundsConcentrationMeasurement::Attributes::FeatureMap::Id: { uint32_t value; @@ -17219,12 +17232,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case RadonConcentrationMeasurement::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, RadonConcentrationMeasurement::Id); } case RadonConcentrationMeasurement::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, RadonConcentrationMeasurement::Id); } case RadonConcentrationMeasurement::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -17234,7 +17247,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case RadonConcentrationMeasurement::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, RadonConcentrationMeasurement::Id); } case RadonConcentrationMeasurement::Attributes::FeatureMap::Id: { uint32_t value; @@ -17265,12 +17278,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case WiFiNetworkManagement::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, WiFiNetworkManagement::Id); } case WiFiNetworkManagement::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, WiFiNetworkManagement::Id); } case WiFiNetworkManagement::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -17280,7 +17293,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case WiFiNetworkManagement::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, WiFiNetworkManagement::Id); } case WiFiNetworkManagement::Attributes::FeatureMap::Id: { uint32_t value; @@ -17331,12 +17344,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case ThreadBorderRouterManagement::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, ThreadBorderRouterManagement::Id); } case ThreadBorderRouterManagement::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, ThreadBorderRouterManagement::Id); } case ThreadBorderRouterManagement::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -17346,7 +17359,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case ThreadBorderRouterManagement::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, ThreadBorderRouterManagement::Id); } case ThreadBorderRouterManagement::Attributes::FeatureMap::Id: { uint32_t value; @@ -17384,12 +17397,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case ThreadNetworkDirectory::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, ThreadNetworkDirectory::Id); } case ThreadNetworkDirectory::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, ThreadNetworkDirectory::Id); } case ThreadNetworkDirectory::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -17399,7 +17412,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case ThreadNetworkDirectory::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, ThreadNetworkDirectory::Id); } case ThreadNetworkDirectory::Attributes::FeatureMap::Id: { uint32_t value; @@ -17430,12 +17443,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case WakeOnLan::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, WakeOnLan::Id); } case WakeOnLan::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, WakeOnLan::Id); } case WakeOnLan::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -17445,7 +17458,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case WakeOnLan::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, WakeOnLan::Id); } case WakeOnLan::Attributes::FeatureMap::Id: { uint32_t value; @@ -17481,12 +17494,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case Channel::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, Channel::Id); } case Channel::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, Channel::Id); } case Channel::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -17496,7 +17509,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case Channel::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, Channel::Id); } case Channel::Attributes::FeatureMap::Id: { uint32_t value; @@ -17528,12 +17541,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case TargetNavigator::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, TargetNavigator::Id); } case TargetNavigator::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, TargetNavigator::Id); } case TargetNavigator::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -17543,7 +17556,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case TargetNavigator::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, TargetNavigator::Id); } case TargetNavigator::Attributes::FeatureMap::Id: { uint32_t value; @@ -17624,12 +17637,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case MediaPlayback::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, MediaPlayback::Id); } case MediaPlayback::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, MediaPlayback::Id); } case MediaPlayback::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -17639,7 +17652,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case MediaPlayback::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, MediaPlayback::Id); } case MediaPlayback::Attributes::FeatureMap::Id: { uint32_t value; @@ -17670,12 +17683,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case MediaInput::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, MediaInput::Id); } case MediaInput::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, MediaInput::Id); } case MediaInput::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -17685,7 +17698,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case MediaInput::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, MediaInput::Id); } case MediaInput::Attributes::FeatureMap::Id: { uint32_t value; @@ -17706,12 +17719,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case LowPower::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, LowPower::Id); } case LowPower::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, LowPower::Id); } case LowPower::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -17721,7 +17734,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case LowPower::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, LowPower::Id); } case LowPower::Attributes::FeatureMap::Id: { uint32_t value; @@ -17742,12 +17755,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case KeypadInput::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, KeypadInput::Id); } case KeypadInput::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, KeypadInput::Id); } case KeypadInput::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -17757,7 +17770,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case KeypadInput::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, KeypadInput::Id); } case KeypadInput::Attributes::FeatureMap::Id: { uint32_t value; @@ -17788,12 +17801,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case ContentLauncher::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, ContentLauncher::Id); } case ContentLauncher::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, ContentLauncher::Id); } case ContentLauncher::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -17803,7 +17816,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case ContentLauncher::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, ContentLauncher::Id); } case ContentLauncher::Attributes::FeatureMap::Id: { uint32_t value; @@ -17834,12 +17847,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case AudioOutput::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, AudioOutput::Id); } case AudioOutput::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, AudioOutput::Id); } case AudioOutput::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -17849,7 +17862,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case AudioOutput::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, AudioOutput::Id); } case AudioOutput::Attributes::FeatureMap::Id: { uint32_t value; @@ -17881,12 +17894,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case ApplicationLauncher::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, ApplicationLauncher::Id); } case ApplicationLauncher::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, ApplicationLauncher::Id); } case ApplicationLauncher::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -17896,7 +17909,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case ApplicationLauncher::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, ApplicationLauncher::Id); } case ApplicationLauncher::Attributes::FeatureMap::Id: { uint32_t value; @@ -17957,12 +17970,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case ApplicationBasic::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, ApplicationBasic::Id); } case ApplicationBasic::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, ApplicationBasic::Id); } case ApplicationBasic::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -17972,7 +17985,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case ApplicationBasic::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, ApplicationBasic::Id); } case ApplicationBasic::Attributes::FeatureMap::Id: { uint32_t value; @@ -17993,12 +18006,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case AccountLogin::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, AccountLogin::Id); } case AccountLogin::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, AccountLogin::Id); } case AccountLogin::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -18008,7 +18021,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case AccountLogin::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, AccountLogin::Id); } case AccountLogin::Attributes::FeatureMap::Id: { uint32_t value; @@ -18071,12 +18084,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case ContentControl::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, ContentControl::Id); } case ContentControl::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, ContentControl::Id); } case ContentControl::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -18086,7 +18099,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case ContentControl::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, ContentControl::Id); } case ContentControl::Attributes::FeatureMap::Id: { uint32_t value; @@ -18107,12 +18120,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case ContentAppObserver::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, ContentAppObserver::Id); } case ContentAppObserver::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, ContentAppObserver::Id); } case ContentAppObserver::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -18122,7 +18135,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case ContentAppObserver::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, ContentAppObserver::Id); } case ContentAppObserver::Attributes::FeatureMap::Id: { uint32_t value; @@ -18162,12 +18175,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case EcosystemInformation::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, EcosystemInformation::Id); } case EcosystemInformation::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, EcosystemInformation::Id); } case EcosystemInformation::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -18177,7 +18190,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case EcosystemInformation::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, EcosystemInformation::Id); } case EcosystemInformation::Attributes::FeatureMap::Id: { uint32_t value; @@ -18203,12 +18216,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case CommissionerControl::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, CommissionerControl::Id); } case CommissionerControl::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, CommissionerControl::Id); } case CommissionerControl::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -18218,7 +18231,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case CommissionerControl::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, CommissionerControl::Id); } case CommissionerControl::Attributes::FeatureMap::Id: { uint32_t value; @@ -18879,12 +18892,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case ElectricalMeasurement::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, ElectricalMeasurement::Id); } case ElectricalMeasurement::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, ElectricalMeasurement::Id); } case ElectricalMeasurement::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -18894,7 +18907,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case ElectricalMeasurement::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, ElectricalMeasurement::Id); } case ElectricalMeasurement::Attributes::FeatureMap::Id: { uint32_t value; @@ -19348,12 +19361,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case UnitTesting::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, UnitTesting::Id); } case UnitTesting::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, UnitTesting::Id); } case UnitTesting::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -19363,7 +19376,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case UnitTesting::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, UnitTesting::Id); } case UnitTesting::Attributes::FeatureMap::Id: { uint32_t value; @@ -19389,12 +19402,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case FaultInjection::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, FaultInjection::Id); } case FaultInjection::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, FaultInjection::Id); } case FaultInjection::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -19404,7 +19417,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case FaultInjection::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, FaultInjection::Id); } case FaultInjection::Attributes::FeatureMap::Id: { uint32_t value; @@ -19430,12 +19443,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case SampleMei::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + return DataModelLogger::LogGeneratedCommandId("GeneratedCommandList", 1, value, SampleMei::Id); } case SampleMei::Attributes::AcceptedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + return DataModelLogger::LogAcceptedCommandId("AcceptedCommandList", 1, value, SampleMei::Id); } case SampleMei::Attributes::EventList::Id: { chip::app::DataModel::DecodableList value; @@ -19445,7 +19458,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP case SampleMei::Attributes::AttributeList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AttributeList", 1, value); + return DataModelLogger::LogAttributeId("AttributeList", 1, value, SampleMei::Id); } case SampleMei::Attributes::FeatureMap::Id: { uint32_t 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 new file mode 100644 index 0000000000..c97ff2590f --- /dev/null +++ b/zzz_generated/chip-tool/zap-generated/cluster/logging/EntryToText.cpp @@ -0,0 +1,6700 @@ +/* + * + * 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. + */ + +// THIS FILE IS GENERATED BY ZAP + +#include +#include +#include + +char const * ClusterIdToText(chip::ClusterId id) +{ + switch (id) + { + case chip::app::Clusters::Identify::Id: + return "Identify"; + case chip::app::Clusters::Groups::Id: + return "Groups"; + case chip::app::Clusters::OnOff::Id: + return "OnOff"; + case chip::app::Clusters::OnOffSwitchConfiguration::Id: + return "OnOffSwitchConfiguration"; + case chip::app::Clusters::LevelControl::Id: + return "LevelControl"; + case chip::app::Clusters::BinaryInputBasic::Id: + return "BinaryInputBasic"; + case chip::app::Clusters::PulseWidthModulation::Id: + return "PulseWidthModulation"; + case chip::app::Clusters::Descriptor::Id: + return "Descriptor"; + case chip::app::Clusters::Binding::Id: + return "Binding"; + case chip::app::Clusters::AccessControl::Id: + return "AccessControl"; + case chip::app::Clusters::Actions::Id: + return "Actions"; + case chip::app::Clusters::BasicInformation::Id: + return "BasicInformation"; + case chip::app::Clusters::OtaSoftwareUpdateProvider::Id: + return "OtaSoftwareUpdateProvider"; + case chip::app::Clusters::OtaSoftwareUpdateRequestor::Id: + return "OtaSoftwareUpdateRequestor"; + case chip::app::Clusters::LocalizationConfiguration::Id: + return "LocalizationConfiguration"; + case chip::app::Clusters::TimeFormatLocalization::Id: + return "TimeFormatLocalization"; + case chip::app::Clusters::UnitLocalization::Id: + return "UnitLocalization"; + case chip::app::Clusters::PowerSourceConfiguration::Id: + return "PowerSourceConfiguration"; + case chip::app::Clusters::PowerSource::Id: + return "PowerSource"; + case chip::app::Clusters::GeneralCommissioning::Id: + return "GeneralCommissioning"; + case chip::app::Clusters::NetworkCommissioning::Id: + return "NetworkCommissioning"; + case chip::app::Clusters::DiagnosticLogs::Id: + return "DiagnosticLogs"; + case chip::app::Clusters::GeneralDiagnostics::Id: + return "GeneralDiagnostics"; + case chip::app::Clusters::SoftwareDiagnostics::Id: + return "SoftwareDiagnostics"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Id: + return "ThreadNetworkDiagnostics"; + case chip::app::Clusters::WiFiNetworkDiagnostics::Id: + return "WiFiNetworkDiagnostics"; + case chip::app::Clusters::EthernetNetworkDiagnostics::Id: + return "EthernetNetworkDiagnostics"; + case chip::app::Clusters::TimeSynchronization::Id: + return "TimeSynchronization"; + case chip::app::Clusters::BridgedDeviceBasicInformation::Id: + return "BridgedDeviceBasicInformation"; + case chip::app::Clusters::Switch::Id: + return "Switch"; + case chip::app::Clusters::AdministratorCommissioning::Id: + return "AdministratorCommissioning"; + case chip::app::Clusters::OperationalCredentials::Id: + return "OperationalCredentials"; + case chip::app::Clusters::GroupKeyManagement::Id: + return "GroupKeyManagement"; + case chip::app::Clusters::FixedLabel::Id: + return "FixedLabel"; + case chip::app::Clusters::UserLabel::Id: + return "UserLabel"; + case chip::app::Clusters::ProxyConfiguration::Id: + return "ProxyConfiguration"; + case chip::app::Clusters::ProxyDiscovery::Id: + return "ProxyDiscovery"; + case chip::app::Clusters::ProxyValid::Id: + return "ProxyValid"; + case chip::app::Clusters::BooleanState::Id: + return "BooleanState"; + case chip::app::Clusters::IcdManagement::Id: + return "IcdManagement"; + case chip::app::Clusters::Timer::Id: + return "Timer"; + case chip::app::Clusters::OvenCavityOperationalState::Id: + return "OvenCavityOperationalState"; + case chip::app::Clusters::OvenMode::Id: + return "OvenMode"; + case chip::app::Clusters::LaundryDryerControls::Id: + return "LaundryDryerControls"; + case chip::app::Clusters::ModeSelect::Id: + return "ModeSelect"; + case chip::app::Clusters::LaundryWasherMode::Id: + return "LaundryWasherMode"; + case chip::app::Clusters::RefrigeratorAndTemperatureControlledCabinetMode::Id: + return "RefrigeratorAndTemperatureControlledCabinetMode"; + case chip::app::Clusters::LaundryWasherControls::Id: + return "LaundryWasherControls"; + case chip::app::Clusters::RvcRunMode::Id: + return "RvcRunMode"; + case chip::app::Clusters::RvcCleanMode::Id: + return "RvcCleanMode"; + case chip::app::Clusters::TemperatureControl::Id: + return "TemperatureControl"; + case chip::app::Clusters::RefrigeratorAlarm::Id: + return "RefrigeratorAlarm"; + case chip::app::Clusters::DishwasherMode::Id: + return "DishwasherMode"; + case chip::app::Clusters::AirQuality::Id: + return "AirQuality"; + case chip::app::Clusters::SmokeCoAlarm::Id: + return "SmokeCoAlarm"; + case chip::app::Clusters::DishwasherAlarm::Id: + return "DishwasherAlarm"; + case chip::app::Clusters::MicrowaveOvenMode::Id: + return "MicrowaveOvenMode"; + case chip::app::Clusters::MicrowaveOvenControl::Id: + return "MicrowaveOvenControl"; + case chip::app::Clusters::OperationalState::Id: + return "OperationalState"; + case chip::app::Clusters::RvcOperationalState::Id: + return "RvcOperationalState"; + case chip::app::Clusters::ScenesManagement::Id: + return "ScenesManagement"; + case chip::app::Clusters::HepaFilterMonitoring::Id: + return "HepaFilterMonitoring"; + case chip::app::Clusters::ActivatedCarbonFilterMonitoring::Id: + return "ActivatedCarbonFilterMonitoring"; + case chip::app::Clusters::BooleanStateConfiguration::Id: + return "BooleanStateConfiguration"; + case chip::app::Clusters::ValveConfigurationAndControl::Id: + return "ValveConfigurationAndControl"; + case chip::app::Clusters::ElectricalPowerMeasurement::Id: + return "ElectricalPowerMeasurement"; + case chip::app::Clusters::ElectricalEnergyMeasurement::Id: + return "ElectricalEnergyMeasurement"; + case chip::app::Clusters::WaterHeaterManagement::Id: + return "WaterHeaterManagement"; + case chip::app::Clusters::DemandResponseLoadControl::Id: + return "DemandResponseLoadControl"; + case chip::app::Clusters::Messages::Id: + return "Messages"; + case chip::app::Clusters::DeviceEnergyManagement::Id: + return "DeviceEnergyManagement"; + case chip::app::Clusters::EnergyEvse::Id: + return "EnergyEvse"; + case chip::app::Clusters::EnergyPreference::Id: + return "EnergyPreference"; + case chip::app::Clusters::PowerTopology::Id: + return "PowerTopology"; + case chip::app::Clusters::EnergyEvseMode::Id: + return "EnergyEvseMode"; + case chip::app::Clusters::WaterHeaterMode::Id: + return "WaterHeaterMode"; + case chip::app::Clusters::DeviceEnergyManagementMode::Id: + return "DeviceEnergyManagementMode"; + case chip::app::Clusters::DoorLock::Id: + return "DoorLock"; + case chip::app::Clusters::WindowCovering::Id: + return "WindowCovering"; + case chip::app::Clusters::BarrierControl::Id: + return "BarrierControl"; + case chip::app::Clusters::ServiceArea::Id: + return "ServiceArea"; + case chip::app::Clusters::PumpConfigurationAndControl::Id: + return "PumpConfigurationAndControl"; + case chip::app::Clusters::Thermostat::Id: + return "Thermostat"; + case chip::app::Clusters::FanControl::Id: + return "FanControl"; + case chip::app::Clusters::ThermostatUserInterfaceConfiguration::Id: + return "ThermostatUserInterfaceConfiguration"; + case chip::app::Clusters::ColorControl::Id: + return "ColorControl"; + case chip::app::Clusters::BallastConfiguration::Id: + return "BallastConfiguration"; + case chip::app::Clusters::IlluminanceMeasurement::Id: + return "IlluminanceMeasurement"; + case chip::app::Clusters::TemperatureMeasurement::Id: + return "TemperatureMeasurement"; + case chip::app::Clusters::PressureMeasurement::Id: + return "PressureMeasurement"; + case chip::app::Clusters::FlowMeasurement::Id: + return "FlowMeasurement"; + case chip::app::Clusters::RelativeHumidityMeasurement::Id: + return "RelativeHumidityMeasurement"; + case chip::app::Clusters::OccupancySensing::Id: + return "OccupancySensing"; + case chip::app::Clusters::CarbonMonoxideConcentrationMeasurement::Id: + return "CarbonMonoxideConcentrationMeasurement"; + case chip::app::Clusters::CarbonDioxideConcentrationMeasurement::Id: + return "CarbonDioxideConcentrationMeasurement"; + case chip::app::Clusters::NitrogenDioxideConcentrationMeasurement::Id: + return "NitrogenDioxideConcentrationMeasurement"; + case chip::app::Clusters::OzoneConcentrationMeasurement::Id: + return "OzoneConcentrationMeasurement"; + case chip::app::Clusters::Pm25ConcentrationMeasurement::Id: + return "Pm25ConcentrationMeasurement"; + case chip::app::Clusters::FormaldehydeConcentrationMeasurement::Id: + return "FormaldehydeConcentrationMeasurement"; + case chip::app::Clusters::Pm1ConcentrationMeasurement::Id: + return "Pm1ConcentrationMeasurement"; + case chip::app::Clusters::Pm10ConcentrationMeasurement::Id: + return "Pm10ConcentrationMeasurement"; + case chip::app::Clusters::TotalVolatileOrganicCompoundsConcentrationMeasurement::Id: + return "TotalVolatileOrganicCompoundsConcentrationMeasurement"; + case chip::app::Clusters::RadonConcentrationMeasurement::Id: + return "RadonConcentrationMeasurement"; + case chip::app::Clusters::WiFiNetworkManagement::Id: + return "WiFiNetworkManagement"; + case chip::app::Clusters::ThreadBorderRouterManagement::Id: + return "ThreadBorderRouterManagement"; + case chip::app::Clusters::ThreadNetworkDirectory::Id: + return "ThreadNetworkDirectory"; + case chip::app::Clusters::WakeOnLan::Id: + return "WakeOnLan"; + case chip::app::Clusters::Channel::Id: + return "Channel"; + case chip::app::Clusters::TargetNavigator::Id: + return "TargetNavigator"; + case chip::app::Clusters::MediaPlayback::Id: + return "MediaPlayback"; + case chip::app::Clusters::MediaInput::Id: + return "MediaInput"; + case chip::app::Clusters::LowPower::Id: + return "LowPower"; + case chip::app::Clusters::KeypadInput::Id: + return "KeypadInput"; + case chip::app::Clusters::ContentLauncher::Id: + return "ContentLauncher"; + case chip::app::Clusters::AudioOutput::Id: + return "AudioOutput"; + case chip::app::Clusters::ApplicationLauncher::Id: + return "ApplicationLauncher"; + case chip::app::Clusters::ApplicationBasic::Id: + return "ApplicationBasic"; + case chip::app::Clusters::AccountLogin::Id: + return "AccountLogin"; + case chip::app::Clusters::ContentControl::Id: + return "ContentControl"; + case chip::app::Clusters::ContentAppObserver::Id: + return "ContentAppObserver"; + case chip::app::Clusters::EcosystemInformation::Id: + return "EcosystemInformation"; + case chip::app::Clusters::CommissionerControl::Id: + return "CommissionerControl"; + case chip::app::Clusters::ElectricalMeasurement::Id: + return "ElectricalMeasurement"; + case chip::app::Clusters::UnitTesting::Id: + return "UnitTesting"; + case chip::app::Clusters::FaultInjection::Id: + return "FaultInjection"; + case chip::app::Clusters::SampleMei::Id: + return "SampleMei"; + default: + return "Unknown"; + } +} + +char const * AttributeIdToText(chip::ClusterId cluster, chip::AttributeId id) +{ + switch (cluster) + { + case chip::app::Clusters::Identify::Id: { + switch (id) + { + case chip::app::Clusters::Identify::Attributes::IdentifyTime::Id: + return "IdentifyTime"; + case chip::app::Clusters::Identify::Attributes::IdentifyType::Id: + return "IdentifyType"; + case chip::app::Clusters::Identify::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::Identify::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::Identify::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::Identify::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::Identify::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::Identify::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::Groups::Id: { + switch (id) + { + case chip::app::Clusters::Groups::Attributes::NameSupport::Id: + return "NameSupport"; + case chip::app::Clusters::Groups::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::Groups::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::Groups::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::Groups::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::Groups::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::Groups::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::OnOff::Id: { + switch (id) + { + case chip::app::Clusters::OnOff::Attributes::OnOff::Id: + return "OnOff"; + case chip::app::Clusters::OnOff::Attributes::GlobalSceneControl::Id: + return "GlobalSceneControl"; + case chip::app::Clusters::OnOff::Attributes::OnTime::Id: + return "OnTime"; + case chip::app::Clusters::OnOff::Attributes::OffWaitTime::Id: + return "OffWaitTime"; + case chip::app::Clusters::OnOff::Attributes::StartUpOnOff::Id: + return "StartUpOnOff"; + case chip::app::Clusters::OnOff::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::OnOff::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::OnOff::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::OnOff::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::OnOff::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::OnOff::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::OnOffSwitchConfiguration::Id: { + switch (id) + { + case chip::app::Clusters::OnOffSwitchConfiguration::Attributes::SwitchType::Id: + return "SwitchType"; + case chip::app::Clusters::OnOffSwitchConfiguration::Attributes::SwitchActions::Id: + return "SwitchActions"; + case chip::app::Clusters::OnOffSwitchConfiguration::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::OnOffSwitchConfiguration::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::OnOffSwitchConfiguration::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::OnOffSwitchConfiguration::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::OnOffSwitchConfiguration::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::OnOffSwitchConfiguration::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::LevelControl::Id: { + switch (id) + { + case chip::app::Clusters::LevelControl::Attributes::CurrentLevel::Id: + return "CurrentLevel"; + case chip::app::Clusters::LevelControl::Attributes::RemainingTime::Id: + return "RemainingTime"; + case chip::app::Clusters::LevelControl::Attributes::MinLevel::Id: + return "MinLevel"; + case chip::app::Clusters::LevelControl::Attributes::MaxLevel::Id: + return "MaxLevel"; + case chip::app::Clusters::LevelControl::Attributes::CurrentFrequency::Id: + return "CurrentFrequency"; + case chip::app::Clusters::LevelControl::Attributes::MinFrequency::Id: + return "MinFrequency"; + case chip::app::Clusters::LevelControl::Attributes::MaxFrequency::Id: + return "MaxFrequency"; + case chip::app::Clusters::LevelControl::Attributes::Options::Id: + return "Options"; + case chip::app::Clusters::LevelControl::Attributes::OnOffTransitionTime::Id: + return "OnOffTransitionTime"; + case chip::app::Clusters::LevelControl::Attributes::OnLevel::Id: + return "OnLevel"; + case chip::app::Clusters::LevelControl::Attributes::OnTransitionTime::Id: + return "OnTransitionTime"; + case chip::app::Clusters::LevelControl::Attributes::OffTransitionTime::Id: + return "OffTransitionTime"; + case chip::app::Clusters::LevelControl::Attributes::DefaultMoveRate::Id: + return "DefaultMoveRate"; + case chip::app::Clusters::LevelControl::Attributes::StartUpCurrentLevel::Id: + return "StartUpCurrentLevel"; + case chip::app::Clusters::LevelControl::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::LevelControl::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::LevelControl::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::LevelControl::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::LevelControl::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::LevelControl::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::BinaryInputBasic::Id: { + switch (id) + { + case chip::app::Clusters::BinaryInputBasic::Attributes::ActiveText::Id: + return "ActiveText"; + case chip::app::Clusters::BinaryInputBasic::Attributes::Description::Id: + return "Description"; + case chip::app::Clusters::BinaryInputBasic::Attributes::InactiveText::Id: + return "InactiveText"; + case chip::app::Clusters::BinaryInputBasic::Attributes::OutOfService::Id: + return "OutOfService"; + case chip::app::Clusters::BinaryInputBasic::Attributes::Polarity::Id: + return "Polarity"; + case chip::app::Clusters::BinaryInputBasic::Attributes::PresentValue::Id: + return "PresentValue"; + case chip::app::Clusters::BinaryInputBasic::Attributes::Reliability::Id: + return "Reliability"; + case chip::app::Clusters::BinaryInputBasic::Attributes::StatusFlags::Id: + return "StatusFlags"; + case chip::app::Clusters::BinaryInputBasic::Attributes::ApplicationType::Id: + return "ApplicationType"; + case chip::app::Clusters::BinaryInputBasic::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::BinaryInputBasic::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::BinaryInputBasic::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::BinaryInputBasic::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::BinaryInputBasic::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::BinaryInputBasic::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::PulseWidthModulation::Id: { + switch (id) + { + case chip::app::Clusters::PulseWidthModulation::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::PulseWidthModulation::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::PulseWidthModulation::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::PulseWidthModulation::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::PulseWidthModulation::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::PulseWidthModulation::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::Descriptor::Id: { + switch (id) + { + case chip::app::Clusters::Descriptor::Attributes::DeviceTypeList::Id: + return "DeviceTypeList"; + case chip::app::Clusters::Descriptor::Attributes::ServerList::Id: + return "ServerList"; + case chip::app::Clusters::Descriptor::Attributes::ClientList::Id: + return "ClientList"; + case chip::app::Clusters::Descriptor::Attributes::PartsList::Id: + return "PartsList"; + case chip::app::Clusters::Descriptor::Attributes::TagList::Id: + return "TagList"; + case chip::app::Clusters::Descriptor::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::Descriptor::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::Descriptor::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::Descriptor::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::Descriptor::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::Descriptor::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::Binding::Id: { + switch (id) + { + case chip::app::Clusters::Binding::Attributes::Binding::Id: + return "Binding"; + case chip::app::Clusters::Binding::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::Binding::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::Binding::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::Binding::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::Binding::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::Binding::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::AccessControl::Id: { + switch (id) + { + case chip::app::Clusters::AccessControl::Attributes::Acl::Id: + return "Acl"; + case chip::app::Clusters::AccessControl::Attributes::Extension::Id: + return "Extension"; + case chip::app::Clusters::AccessControl::Attributes::SubjectsPerAccessControlEntry::Id: + return "SubjectsPerAccessControlEntry"; + case chip::app::Clusters::AccessControl::Attributes::TargetsPerAccessControlEntry::Id: + return "TargetsPerAccessControlEntry"; + case chip::app::Clusters::AccessControl::Attributes::AccessControlEntriesPerFabric::Id: + return "AccessControlEntriesPerFabric"; + case chip::app::Clusters::AccessControl::Attributes::CommissioningARL::Id: + return "CommissioningARL"; + case chip::app::Clusters::AccessControl::Attributes::Arl::Id: + return "Arl"; + case chip::app::Clusters::AccessControl::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::AccessControl::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::AccessControl::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::AccessControl::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::AccessControl::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::AccessControl::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::Actions::Id: { + switch (id) + { + case chip::app::Clusters::Actions::Attributes::ActionList::Id: + return "ActionList"; + case chip::app::Clusters::Actions::Attributes::EndpointLists::Id: + return "EndpointLists"; + case chip::app::Clusters::Actions::Attributes::SetupURL::Id: + return "SetupURL"; + case chip::app::Clusters::Actions::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::Actions::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::Actions::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::Actions::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::Actions::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::Actions::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::BasicInformation::Id: { + switch (id) + { + case chip::app::Clusters::BasicInformation::Attributes::DataModelRevision::Id: + return "DataModelRevision"; + case chip::app::Clusters::BasicInformation::Attributes::VendorName::Id: + return "VendorName"; + case chip::app::Clusters::BasicInformation::Attributes::VendorID::Id: + return "VendorID"; + case chip::app::Clusters::BasicInformation::Attributes::ProductName::Id: + return "ProductName"; + case chip::app::Clusters::BasicInformation::Attributes::ProductID::Id: + return "ProductID"; + case chip::app::Clusters::BasicInformation::Attributes::NodeLabel::Id: + return "NodeLabel"; + case chip::app::Clusters::BasicInformation::Attributes::Location::Id: + return "Location"; + case chip::app::Clusters::BasicInformation::Attributes::HardwareVersion::Id: + return "HardwareVersion"; + case chip::app::Clusters::BasicInformation::Attributes::HardwareVersionString::Id: + return "HardwareVersionString"; + case chip::app::Clusters::BasicInformation::Attributes::SoftwareVersion::Id: + return "SoftwareVersion"; + case chip::app::Clusters::BasicInformation::Attributes::SoftwareVersionString::Id: + return "SoftwareVersionString"; + case chip::app::Clusters::BasicInformation::Attributes::ManufacturingDate::Id: + return "ManufacturingDate"; + case chip::app::Clusters::BasicInformation::Attributes::PartNumber::Id: + return "PartNumber"; + case chip::app::Clusters::BasicInformation::Attributes::ProductURL::Id: + return "ProductURL"; + case chip::app::Clusters::BasicInformation::Attributes::ProductLabel::Id: + return "ProductLabel"; + case chip::app::Clusters::BasicInformation::Attributes::SerialNumber::Id: + return "SerialNumber"; + case chip::app::Clusters::BasicInformation::Attributes::LocalConfigDisabled::Id: + return "LocalConfigDisabled"; + case chip::app::Clusters::BasicInformation::Attributes::Reachable::Id: + return "Reachable"; + case chip::app::Clusters::BasicInformation::Attributes::UniqueID::Id: + return "UniqueID"; + case chip::app::Clusters::BasicInformation::Attributes::CapabilityMinima::Id: + return "CapabilityMinima"; + case chip::app::Clusters::BasicInformation::Attributes::ProductAppearance::Id: + return "ProductAppearance"; + case chip::app::Clusters::BasicInformation::Attributes::SpecificationVersion::Id: + return "SpecificationVersion"; + case chip::app::Clusters::BasicInformation::Attributes::MaxPathsPerInvoke::Id: + return "MaxPathsPerInvoke"; + case chip::app::Clusters::BasicInformation::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::BasicInformation::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::BasicInformation::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::BasicInformation::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::BasicInformation::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::BasicInformation::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::OtaSoftwareUpdateProvider::Id: { + switch (id) + { + case chip::app::Clusters::OtaSoftwareUpdateProvider::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::OtaSoftwareUpdateProvider::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::OtaSoftwareUpdateProvider::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::OtaSoftwareUpdateProvider::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::OtaSoftwareUpdateProvider::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::OtaSoftwareUpdateProvider::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::OtaSoftwareUpdateRequestor::Id: { + switch (id) + { + case chip::app::Clusters::OtaSoftwareUpdateRequestor::Attributes::DefaultOTAProviders::Id: + return "DefaultOTAProviders"; + case chip::app::Clusters::OtaSoftwareUpdateRequestor::Attributes::UpdatePossible::Id: + return "UpdatePossible"; + case chip::app::Clusters::OtaSoftwareUpdateRequestor::Attributes::UpdateState::Id: + return "UpdateState"; + case chip::app::Clusters::OtaSoftwareUpdateRequestor::Attributes::UpdateStateProgress::Id: + return "UpdateStateProgress"; + case chip::app::Clusters::OtaSoftwareUpdateRequestor::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::OtaSoftwareUpdateRequestor::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::OtaSoftwareUpdateRequestor::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::OtaSoftwareUpdateRequestor::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::OtaSoftwareUpdateRequestor::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::OtaSoftwareUpdateRequestor::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::LocalizationConfiguration::Id: { + switch (id) + { + case chip::app::Clusters::LocalizationConfiguration::Attributes::ActiveLocale::Id: + return "ActiveLocale"; + case chip::app::Clusters::LocalizationConfiguration::Attributes::SupportedLocales::Id: + return "SupportedLocales"; + case chip::app::Clusters::LocalizationConfiguration::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::LocalizationConfiguration::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::LocalizationConfiguration::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::LocalizationConfiguration::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::LocalizationConfiguration::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::LocalizationConfiguration::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::TimeFormatLocalization::Id: { + switch (id) + { + case chip::app::Clusters::TimeFormatLocalization::Attributes::HourFormat::Id: + return "HourFormat"; + case chip::app::Clusters::TimeFormatLocalization::Attributes::ActiveCalendarType::Id: + return "ActiveCalendarType"; + case chip::app::Clusters::TimeFormatLocalization::Attributes::SupportedCalendarTypes::Id: + return "SupportedCalendarTypes"; + case chip::app::Clusters::TimeFormatLocalization::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::TimeFormatLocalization::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::TimeFormatLocalization::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::TimeFormatLocalization::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::TimeFormatLocalization::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::TimeFormatLocalization::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::UnitLocalization::Id: { + switch (id) + { + case chip::app::Clusters::UnitLocalization::Attributes::TemperatureUnit::Id: + return "TemperatureUnit"; + case chip::app::Clusters::UnitLocalization::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::UnitLocalization::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::UnitLocalization::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::UnitLocalization::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::UnitLocalization::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::UnitLocalization::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::PowerSourceConfiguration::Id: { + switch (id) + { + case chip::app::Clusters::PowerSourceConfiguration::Attributes::Sources::Id: + return "Sources"; + case chip::app::Clusters::PowerSourceConfiguration::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::PowerSourceConfiguration::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::PowerSourceConfiguration::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::PowerSourceConfiguration::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::PowerSourceConfiguration::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::PowerSourceConfiguration::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::PowerSource::Id: { + switch (id) + { + case chip::app::Clusters::PowerSource::Attributes::Status::Id: + return "Status"; + case chip::app::Clusters::PowerSource::Attributes::Order::Id: + return "Order"; + case chip::app::Clusters::PowerSource::Attributes::Description::Id: + return "Description"; + case chip::app::Clusters::PowerSource::Attributes::WiredAssessedInputVoltage::Id: + return "WiredAssessedInputVoltage"; + case chip::app::Clusters::PowerSource::Attributes::WiredAssessedInputFrequency::Id: + return "WiredAssessedInputFrequency"; + case chip::app::Clusters::PowerSource::Attributes::WiredCurrentType::Id: + return "WiredCurrentType"; + case chip::app::Clusters::PowerSource::Attributes::WiredAssessedCurrent::Id: + return "WiredAssessedCurrent"; + case chip::app::Clusters::PowerSource::Attributes::WiredNominalVoltage::Id: + return "WiredNominalVoltage"; + case chip::app::Clusters::PowerSource::Attributes::WiredMaximumCurrent::Id: + return "WiredMaximumCurrent"; + case chip::app::Clusters::PowerSource::Attributes::WiredPresent::Id: + return "WiredPresent"; + case chip::app::Clusters::PowerSource::Attributes::ActiveWiredFaults::Id: + return "ActiveWiredFaults"; + case chip::app::Clusters::PowerSource::Attributes::BatVoltage::Id: + return "BatVoltage"; + case chip::app::Clusters::PowerSource::Attributes::BatPercentRemaining::Id: + return "BatPercentRemaining"; + case chip::app::Clusters::PowerSource::Attributes::BatTimeRemaining::Id: + return "BatTimeRemaining"; + case chip::app::Clusters::PowerSource::Attributes::BatChargeLevel::Id: + return "BatChargeLevel"; + case chip::app::Clusters::PowerSource::Attributes::BatReplacementNeeded::Id: + return "BatReplacementNeeded"; + case chip::app::Clusters::PowerSource::Attributes::BatReplaceability::Id: + return "BatReplaceability"; + case chip::app::Clusters::PowerSource::Attributes::BatPresent::Id: + return "BatPresent"; + case chip::app::Clusters::PowerSource::Attributes::ActiveBatFaults::Id: + return "ActiveBatFaults"; + case chip::app::Clusters::PowerSource::Attributes::BatReplacementDescription::Id: + return "BatReplacementDescription"; + case chip::app::Clusters::PowerSource::Attributes::BatCommonDesignation::Id: + return "BatCommonDesignation"; + case chip::app::Clusters::PowerSource::Attributes::BatANSIDesignation::Id: + return "BatANSIDesignation"; + case chip::app::Clusters::PowerSource::Attributes::BatIECDesignation::Id: + return "BatIECDesignation"; + case chip::app::Clusters::PowerSource::Attributes::BatApprovedChemistry::Id: + return "BatApprovedChemistry"; + case chip::app::Clusters::PowerSource::Attributes::BatCapacity::Id: + return "BatCapacity"; + case chip::app::Clusters::PowerSource::Attributes::BatQuantity::Id: + return "BatQuantity"; + case chip::app::Clusters::PowerSource::Attributes::BatChargeState::Id: + return "BatChargeState"; + case chip::app::Clusters::PowerSource::Attributes::BatTimeToFullCharge::Id: + return "BatTimeToFullCharge"; + case chip::app::Clusters::PowerSource::Attributes::BatFunctionalWhileCharging::Id: + return "BatFunctionalWhileCharging"; + case chip::app::Clusters::PowerSource::Attributes::BatChargingCurrent::Id: + return "BatChargingCurrent"; + case chip::app::Clusters::PowerSource::Attributes::ActiveBatChargeFaults::Id: + return "ActiveBatChargeFaults"; + case chip::app::Clusters::PowerSource::Attributes::EndpointList::Id: + return "EndpointList"; + case chip::app::Clusters::PowerSource::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::PowerSource::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::PowerSource::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::PowerSource::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::PowerSource::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::PowerSource::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::GeneralCommissioning::Id: { + switch (id) + { + case chip::app::Clusters::GeneralCommissioning::Attributes::Breadcrumb::Id: + return "Breadcrumb"; + case chip::app::Clusters::GeneralCommissioning::Attributes::BasicCommissioningInfo::Id: + return "BasicCommissioningInfo"; + case chip::app::Clusters::GeneralCommissioning::Attributes::RegulatoryConfig::Id: + return "RegulatoryConfig"; + case chip::app::Clusters::GeneralCommissioning::Attributes::LocationCapability::Id: + return "LocationCapability"; + case chip::app::Clusters::GeneralCommissioning::Attributes::SupportsConcurrentConnection::Id: + return "SupportsConcurrentConnection"; + case chip::app::Clusters::GeneralCommissioning::Attributes::TCAcceptedVersion::Id: + return "TCAcceptedVersion"; + case chip::app::Clusters::GeneralCommissioning::Attributes::TCMinRequiredVersion::Id: + return "TCMinRequiredVersion"; + case chip::app::Clusters::GeneralCommissioning::Attributes::TCAcknowledgements::Id: + return "TCAcknowledgements"; + case chip::app::Clusters::GeneralCommissioning::Attributes::TCAcknowledgementsRequired::Id: + return "TCAcknowledgementsRequired"; + case chip::app::Clusters::GeneralCommissioning::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::GeneralCommissioning::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::GeneralCommissioning::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::GeneralCommissioning::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::GeneralCommissioning::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::GeneralCommissioning::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::NetworkCommissioning::Id: { + switch (id) + { + case chip::app::Clusters::NetworkCommissioning::Attributes::MaxNetworks::Id: + return "MaxNetworks"; + case chip::app::Clusters::NetworkCommissioning::Attributes::Networks::Id: + return "Networks"; + case chip::app::Clusters::NetworkCommissioning::Attributes::ScanMaxTimeSeconds::Id: + return "ScanMaxTimeSeconds"; + case chip::app::Clusters::NetworkCommissioning::Attributes::ConnectMaxTimeSeconds::Id: + return "ConnectMaxTimeSeconds"; + case chip::app::Clusters::NetworkCommissioning::Attributes::InterfaceEnabled::Id: + return "InterfaceEnabled"; + case chip::app::Clusters::NetworkCommissioning::Attributes::LastNetworkingStatus::Id: + return "LastNetworkingStatus"; + case chip::app::Clusters::NetworkCommissioning::Attributes::LastNetworkID::Id: + return "LastNetworkID"; + case chip::app::Clusters::NetworkCommissioning::Attributes::LastConnectErrorValue::Id: + return "LastConnectErrorValue"; + case chip::app::Clusters::NetworkCommissioning::Attributes::SupportedWiFiBands::Id: + return "SupportedWiFiBands"; + case chip::app::Clusters::NetworkCommissioning::Attributes::SupportedThreadFeatures::Id: + return "SupportedThreadFeatures"; + case chip::app::Clusters::NetworkCommissioning::Attributes::ThreadVersion::Id: + return "ThreadVersion"; + case chip::app::Clusters::NetworkCommissioning::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::NetworkCommissioning::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::NetworkCommissioning::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::NetworkCommissioning::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::NetworkCommissioning::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::NetworkCommissioning::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::DiagnosticLogs::Id: { + switch (id) + { + case chip::app::Clusters::DiagnosticLogs::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::DiagnosticLogs::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::DiagnosticLogs::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::DiagnosticLogs::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::DiagnosticLogs::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::DiagnosticLogs::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::GeneralDiagnostics::Id: { + switch (id) + { + case chip::app::Clusters::GeneralDiagnostics::Attributes::NetworkInterfaces::Id: + return "NetworkInterfaces"; + case chip::app::Clusters::GeneralDiagnostics::Attributes::RebootCount::Id: + return "RebootCount"; + case chip::app::Clusters::GeneralDiagnostics::Attributes::UpTime::Id: + return "UpTime"; + case chip::app::Clusters::GeneralDiagnostics::Attributes::TotalOperationalHours::Id: + return "TotalOperationalHours"; + case chip::app::Clusters::GeneralDiagnostics::Attributes::BootReason::Id: + return "BootReason"; + case chip::app::Clusters::GeneralDiagnostics::Attributes::ActiveHardwareFaults::Id: + return "ActiveHardwareFaults"; + case chip::app::Clusters::GeneralDiagnostics::Attributes::ActiveRadioFaults::Id: + return "ActiveRadioFaults"; + case chip::app::Clusters::GeneralDiagnostics::Attributes::ActiveNetworkFaults::Id: + return "ActiveNetworkFaults"; + case chip::app::Clusters::GeneralDiagnostics::Attributes::TestEventTriggersEnabled::Id: + return "TestEventTriggersEnabled"; + case chip::app::Clusters::GeneralDiagnostics::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::GeneralDiagnostics::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::GeneralDiagnostics::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::GeneralDiagnostics::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::GeneralDiagnostics::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::GeneralDiagnostics::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::SoftwareDiagnostics::Id: { + switch (id) + { + case chip::app::Clusters::SoftwareDiagnostics::Attributes::ThreadMetrics::Id: + return "ThreadMetrics"; + case chip::app::Clusters::SoftwareDiagnostics::Attributes::CurrentHeapFree::Id: + return "CurrentHeapFree"; + case chip::app::Clusters::SoftwareDiagnostics::Attributes::CurrentHeapUsed::Id: + return "CurrentHeapUsed"; + case chip::app::Clusters::SoftwareDiagnostics::Attributes::CurrentHeapHighWatermark::Id: + return "CurrentHeapHighWatermark"; + case chip::app::Clusters::SoftwareDiagnostics::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::SoftwareDiagnostics::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::SoftwareDiagnostics::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::SoftwareDiagnostics::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::SoftwareDiagnostics::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::SoftwareDiagnostics::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::ThreadNetworkDiagnostics::Id: { + switch (id) + { + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::Channel::Id: + return "Channel"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::RoutingRole::Id: + return "RoutingRole"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::NetworkName::Id: + return "NetworkName"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::PanId::Id: + return "PanId"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::ExtendedPanId::Id: + return "ExtendedPanId"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::MeshLocalPrefix::Id: + return "MeshLocalPrefix"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::OverrunCount::Id: + return "OverrunCount"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::NeighborTable::Id: + return "NeighborTable"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::RouteTable::Id: + return "RouteTable"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::PartitionId::Id: + return "PartitionId"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::Weighting::Id: + return "Weighting"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::DataVersion::Id: + return "DataVersion"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::StableDataVersion::Id: + return "StableDataVersion"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::LeaderRouterId::Id: + return "LeaderRouterId"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::DetachedRoleCount::Id: + return "DetachedRoleCount"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::ChildRoleCount::Id: + return "ChildRoleCount"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::RouterRoleCount::Id: + return "RouterRoleCount"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::LeaderRoleCount::Id: + return "LeaderRoleCount"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::AttachAttemptCount::Id: + return "AttachAttemptCount"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::PartitionIdChangeCount::Id: + return "PartitionIdChangeCount"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::BetterPartitionAttachAttemptCount::Id: + return "BetterPartitionAttachAttemptCount"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::ParentChangeCount::Id: + return "ParentChangeCount"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::TxTotalCount::Id: + return "TxTotalCount"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::TxUnicastCount::Id: + return "TxUnicastCount"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::TxBroadcastCount::Id: + return "TxBroadcastCount"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::TxAckRequestedCount::Id: + return "TxAckRequestedCount"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::TxAckedCount::Id: + return "TxAckedCount"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::TxNoAckRequestedCount::Id: + return "TxNoAckRequestedCount"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::TxDataCount::Id: + return "TxDataCount"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::TxDataPollCount::Id: + return "TxDataPollCount"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::TxBeaconCount::Id: + return "TxBeaconCount"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::TxBeaconRequestCount::Id: + return "TxBeaconRequestCount"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::TxOtherCount::Id: + return "TxOtherCount"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::TxRetryCount::Id: + return "TxRetryCount"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::TxDirectMaxRetryExpiryCount::Id: + return "TxDirectMaxRetryExpiryCount"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::TxIndirectMaxRetryExpiryCount::Id: + return "TxIndirectMaxRetryExpiryCount"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::TxErrCcaCount::Id: + return "TxErrCcaCount"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::TxErrAbortCount::Id: + return "TxErrAbortCount"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::TxErrBusyChannelCount::Id: + return "TxErrBusyChannelCount"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::RxTotalCount::Id: + return "RxTotalCount"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::RxUnicastCount::Id: + return "RxUnicastCount"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::RxBroadcastCount::Id: + return "RxBroadcastCount"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::RxDataCount::Id: + return "RxDataCount"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::RxDataPollCount::Id: + return "RxDataPollCount"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::RxBeaconCount::Id: + return "RxBeaconCount"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::RxBeaconRequestCount::Id: + return "RxBeaconRequestCount"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::RxOtherCount::Id: + return "RxOtherCount"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::RxAddressFilteredCount::Id: + return "RxAddressFilteredCount"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::RxDestAddrFilteredCount::Id: + return "RxDestAddrFilteredCount"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::RxDuplicatedCount::Id: + return "RxDuplicatedCount"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::RxErrNoFrameCount::Id: + return "RxErrNoFrameCount"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::RxErrUnknownNeighborCount::Id: + return "RxErrUnknownNeighborCount"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::RxErrInvalidSrcAddrCount::Id: + return "RxErrInvalidSrcAddrCount"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::RxErrSecCount::Id: + return "RxErrSecCount"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::RxErrFcsCount::Id: + return "RxErrFcsCount"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::RxErrOtherCount::Id: + return "RxErrOtherCount"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::ActiveTimestamp::Id: + return "ActiveTimestamp"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::PendingTimestamp::Id: + return "PendingTimestamp"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::Delay::Id: + return "Delay"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::SecurityPolicy::Id: + return "SecurityPolicy"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::ChannelPage0Mask::Id: + return "ChannelPage0Mask"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::OperationalDatasetComponents::Id: + return "OperationalDatasetComponents"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::ActiveNetworkFaultsList::Id: + return "ActiveNetworkFaultsList"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::ThreadNetworkDiagnostics::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::WiFiNetworkDiagnostics::Id: { + switch (id) + { + case chip::app::Clusters::WiFiNetworkDiagnostics::Attributes::Bssid::Id: + return "Bssid"; + case chip::app::Clusters::WiFiNetworkDiagnostics::Attributes::SecurityType::Id: + return "SecurityType"; + case chip::app::Clusters::WiFiNetworkDiagnostics::Attributes::WiFiVersion::Id: + return "WiFiVersion"; + case chip::app::Clusters::WiFiNetworkDiagnostics::Attributes::ChannelNumber::Id: + return "ChannelNumber"; + case chip::app::Clusters::WiFiNetworkDiagnostics::Attributes::Rssi::Id: + return "Rssi"; + case chip::app::Clusters::WiFiNetworkDiagnostics::Attributes::BeaconLostCount::Id: + return "BeaconLostCount"; + case chip::app::Clusters::WiFiNetworkDiagnostics::Attributes::BeaconRxCount::Id: + return "BeaconRxCount"; + case chip::app::Clusters::WiFiNetworkDiagnostics::Attributes::PacketMulticastRxCount::Id: + return "PacketMulticastRxCount"; + case chip::app::Clusters::WiFiNetworkDiagnostics::Attributes::PacketMulticastTxCount::Id: + return "PacketMulticastTxCount"; + case chip::app::Clusters::WiFiNetworkDiagnostics::Attributes::PacketUnicastRxCount::Id: + return "PacketUnicastRxCount"; + case chip::app::Clusters::WiFiNetworkDiagnostics::Attributes::PacketUnicastTxCount::Id: + return "PacketUnicastTxCount"; + case chip::app::Clusters::WiFiNetworkDiagnostics::Attributes::CurrentMaxRate::Id: + return "CurrentMaxRate"; + case chip::app::Clusters::WiFiNetworkDiagnostics::Attributes::OverrunCount::Id: + return "OverrunCount"; + case chip::app::Clusters::WiFiNetworkDiagnostics::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::WiFiNetworkDiagnostics::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::WiFiNetworkDiagnostics::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::WiFiNetworkDiagnostics::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::WiFiNetworkDiagnostics::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::WiFiNetworkDiagnostics::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::EthernetNetworkDiagnostics::Id: { + switch (id) + { + case chip::app::Clusters::EthernetNetworkDiagnostics::Attributes::PHYRate::Id: + return "PHYRate"; + case chip::app::Clusters::EthernetNetworkDiagnostics::Attributes::FullDuplex::Id: + return "FullDuplex"; + case chip::app::Clusters::EthernetNetworkDiagnostics::Attributes::PacketRxCount::Id: + return "PacketRxCount"; + case chip::app::Clusters::EthernetNetworkDiagnostics::Attributes::PacketTxCount::Id: + return "PacketTxCount"; + case chip::app::Clusters::EthernetNetworkDiagnostics::Attributes::TxErrCount::Id: + return "TxErrCount"; + case chip::app::Clusters::EthernetNetworkDiagnostics::Attributes::CollisionCount::Id: + return "CollisionCount"; + case chip::app::Clusters::EthernetNetworkDiagnostics::Attributes::OverrunCount::Id: + return "OverrunCount"; + case chip::app::Clusters::EthernetNetworkDiagnostics::Attributes::CarrierDetect::Id: + return "CarrierDetect"; + case chip::app::Clusters::EthernetNetworkDiagnostics::Attributes::TimeSinceReset::Id: + return "TimeSinceReset"; + case chip::app::Clusters::EthernetNetworkDiagnostics::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::EthernetNetworkDiagnostics::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::EthernetNetworkDiagnostics::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::EthernetNetworkDiagnostics::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::EthernetNetworkDiagnostics::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::EthernetNetworkDiagnostics::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::TimeSynchronization::Id: { + switch (id) + { + case chip::app::Clusters::TimeSynchronization::Attributes::UTCTime::Id: + return "UTCTime"; + case chip::app::Clusters::TimeSynchronization::Attributes::Granularity::Id: + return "Granularity"; + case chip::app::Clusters::TimeSynchronization::Attributes::TimeSource::Id: + return "TimeSource"; + case chip::app::Clusters::TimeSynchronization::Attributes::TrustedTimeSource::Id: + return "TrustedTimeSource"; + case chip::app::Clusters::TimeSynchronization::Attributes::DefaultNTP::Id: + return "DefaultNTP"; + case chip::app::Clusters::TimeSynchronization::Attributes::TimeZone::Id: + return "TimeZone"; + case chip::app::Clusters::TimeSynchronization::Attributes::DSTOffset::Id: + return "DSTOffset"; + case chip::app::Clusters::TimeSynchronization::Attributes::LocalTime::Id: + return "LocalTime"; + case chip::app::Clusters::TimeSynchronization::Attributes::TimeZoneDatabase::Id: + return "TimeZoneDatabase"; + case chip::app::Clusters::TimeSynchronization::Attributes::NTPServerAvailable::Id: + return "NTPServerAvailable"; + case chip::app::Clusters::TimeSynchronization::Attributes::TimeZoneListMaxSize::Id: + return "TimeZoneListMaxSize"; + case chip::app::Clusters::TimeSynchronization::Attributes::DSTOffsetListMaxSize::Id: + return "DSTOffsetListMaxSize"; + case chip::app::Clusters::TimeSynchronization::Attributes::SupportsDNSResolve::Id: + return "SupportsDNSResolve"; + case chip::app::Clusters::TimeSynchronization::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::TimeSynchronization::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::TimeSynchronization::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::TimeSynchronization::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::TimeSynchronization::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::TimeSynchronization::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::BridgedDeviceBasicInformation::Id: { + switch (id) + { + case chip::app::Clusters::BridgedDeviceBasicInformation::Attributes::VendorName::Id: + return "VendorName"; + case chip::app::Clusters::BridgedDeviceBasicInformation::Attributes::VendorID::Id: + return "VendorID"; + case chip::app::Clusters::BridgedDeviceBasicInformation::Attributes::ProductName::Id: + return "ProductName"; + case chip::app::Clusters::BridgedDeviceBasicInformation::Attributes::ProductID::Id: + return "ProductID"; + case chip::app::Clusters::BridgedDeviceBasicInformation::Attributes::NodeLabel::Id: + return "NodeLabel"; + case chip::app::Clusters::BridgedDeviceBasicInformation::Attributes::HardwareVersion::Id: + return "HardwareVersion"; + case chip::app::Clusters::BridgedDeviceBasicInformation::Attributes::HardwareVersionString::Id: + return "HardwareVersionString"; + case chip::app::Clusters::BridgedDeviceBasicInformation::Attributes::SoftwareVersion::Id: + return "SoftwareVersion"; + case chip::app::Clusters::BridgedDeviceBasicInformation::Attributes::SoftwareVersionString::Id: + return "SoftwareVersionString"; + case chip::app::Clusters::BridgedDeviceBasicInformation::Attributes::ManufacturingDate::Id: + return "ManufacturingDate"; + case chip::app::Clusters::BridgedDeviceBasicInformation::Attributes::PartNumber::Id: + return "PartNumber"; + case chip::app::Clusters::BridgedDeviceBasicInformation::Attributes::ProductURL::Id: + return "ProductURL"; + case chip::app::Clusters::BridgedDeviceBasicInformation::Attributes::ProductLabel::Id: + return "ProductLabel"; + case chip::app::Clusters::BridgedDeviceBasicInformation::Attributes::SerialNumber::Id: + return "SerialNumber"; + case chip::app::Clusters::BridgedDeviceBasicInformation::Attributes::Reachable::Id: + return "Reachable"; + case chip::app::Clusters::BridgedDeviceBasicInformation::Attributes::UniqueID::Id: + return "UniqueID"; + case chip::app::Clusters::BridgedDeviceBasicInformation::Attributes::ProductAppearance::Id: + return "ProductAppearance"; + case chip::app::Clusters::BridgedDeviceBasicInformation::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::BridgedDeviceBasicInformation::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::BridgedDeviceBasicInformation::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::BridgedDeviceBasicInformation::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::BridgedDeviceBasicInformation::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::BridgedDeviceBasicInformation::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::Switch::Id: { + switch (id) + { + case chip::app::Clusters::Switch::Attributes::NumberOfPositions::Id: + return "NumberOfPositions"; + case chip::app::Clusters::Switch::Attributes::CurrentPosition::Id: + return "CurrentPosition"; + case chip::app::Clusters::Switch::Attributes::MultiPressMax::Id: + return "MultiPressMax"; + case chip::app::Clusters::Switch::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::Switch::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::Switch::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::Switch::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::Switch::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::Switch::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::AdministratorCommissioning::Id: { + switch (id) + { + case chip::app::Clusters::AdministratorCommissioning::Attributes::WindowStatus::Id: + return "WindowStatus"; + case chip::app::Clusters::AdministratorCommissioning::Attributes::AdminFabricIndex::Id: + return "AdminFabricIndex"; + case chip::app::Clusters::AdministratorCommissioning::Attributes::AdminVendorId::Id: + return "AdminVendorId"; + case chip::app::Clusters::AdministratorCommissioning::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::AdministratorCommissioning::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::AdministratorCommissioning::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::AdministratorCommissioning::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::AdministratorCommissioning::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::AdministratorCommissioning::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::OperationalCredentials::Id: { + switch (id) + { + case chip::app::Clusters::OperationalCredentials::Attributes::NOCs::Id: + return "NOCs"; + case chip::app::Clusters::OperationalCredentials::Attributes::Fabrics::Id: + return "Fabrics"; + case chip::app::Clusters::OperationalCredentials::Attributes::SupportedFabrics::Id: + return "SupportedFabrics"; + case chip::app::Clusters::OperationalCredentials::Attributes::CommissionedFabrics::Id: + return "CommissionedFabrics"; + case chip::app::Clusters::OperationalCredentials::Attributes::TrustedRootCertificates::Id: + return "TrustedRootCertificates"; + case chip::app::Clusters::OperationalCredentials::Attributes::CurrentFabricIndex::Id: + return "CurrentFabricIndex"; + case chip::app::Clusters::OperationalCredentials::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::OperationalCredentials::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::OperationalCredentials::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::OperationalCredentials::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::OperationalCredentials::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::OperationalCredentials::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::GroupKeyManagement::Id: { + switch (id) + { + case chip::app::Clusters::GroupKeyManagement::Attributes::GroupKeyMap::Id: + return "GroupKeyMap"; + case chip::app::Clusters::GroupKeyManagement::Attributes::GroupTable::Id: + return "GroupTable"; + case chip::app::Clusters::GroupKeyManagement::Attributes::MaxGroupsPerFabric::Id: + return "MaxGroupsPerFabric"; + case chip::app::Clusters::GroupKeyManagement::Attributes::MaxGroupKeysPerFabric::Id: + return "MaxGroupKeysPerFabric"; + case chip::app::Clusters::GroupKeyManagement::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::GroupKeyManagement::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::GroupKeyManagement::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::GroupKeyManagement::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::GroupKeyManagement::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::GroupKeyManagement::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::FixedLabel::Id: { + switch (id) + { + case chip::app::Clusters::FixedLabel::Attributes::LabelList::Id: + return "LabelList"; + case chip::app::Clusters::FixedLabel::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::FixedLabel::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::FixedLabel::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::FixedLabel::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::FixedLabel::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::FixedLabel::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::UserLabel::Id: { + switch (id) + { + case chip::app::Clusters::UserLabel::Attributes::LabelList::Id: + return "LabelList"; + case chip::app::Clusters::UserLabel::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::UserLabel::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::UserLabel::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::UserLabel::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::UserLabel::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::UserLabel::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::ProxyConfiguration::Id: { + switch (id) + { + case chip::app::Clusters::ProxyConfiguration::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::ProxyConfiguration::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::ProxyConfiguration::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::ProxyConfiguration::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::ProxyConfiguration::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::ProxyConfiguration::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::ProxyDiscovery::Id: { + switch (id) + { + case chip::app::Clusters::ProxyDiscovery::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::ProxyDiscovery::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::ProxyDiscovery::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::ProxyDiscovery::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::ProxyDiscovery::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::ProxyDiscovery::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::ProxyValid::Id: { + switch (id) + { + case chip::app::Clusters::ProxyValid::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::ProxyValid::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::ProxyValid::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::ProxyValid::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::ProxyValid::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::ProxyValid::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::BooleanState::Id: { + switch (id) + { + case chip::app::Clusters::BooleanState::Attributes::StateValue::Id: + return "StateValue"; + case chip::app::Clusters::BooleanState::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::BooleanState::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::BooleanState::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::BooleanState::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::BooleanState::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::BooleanState::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::IcdManagement::Id: { + switch (id) + { + case chip::app::Clusters::IcdManagement::Attributes::IdleModeDuration::Id: + return "IdleModeDuration"; + case chip::app::Clusters::IcdManagement::Attributes::ActiveModeDuration::Id: + return "ActiveModeDuration"; + case chip::app::Clusters::IcdManagement::Attributes::ActiveModeThreshold::Id: + return "ActiveModeThreshold"; + case chip::app::Clusters::IcdManagement::Attributes::RegisteredClients::Id: + return "RegisteredClients"; + case chip::app::Clusters::IcdManagement::Attributes::ICDCounter::Id: + return "ICDCounter"; + case chip::app::Clusters::IcdManagement::Attributes::ClientsSupportedPerFabric::Id: + return "ClientsSupportedPerFabric"; + case chip::app::Clusters::IcdManagement::Attributes::UserActiveModeTriggerHint::Id: + return "UserActiveModeTriggerHint"; + case chip::app::Clusters::IcdManagement::Attributes::UserActiveModeTriggerInstruction::Id: + return "UserActiveModeTriggerInstruction"; + case chip::app::Clusters::IcdManagement::Attributes::OperatingMode::Id: + return "OperatingMode"; + case chip::app::Clusters::IcdManagement::Attributes::MaximumCheckInBackOff::Id: + return "MaximumCheckInBackOff"; + case chip::app::Clusters::IcdManagement::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::IcdManagement::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::IcdManagement::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::IcdManagement::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::IcdManagement::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::IcdManagement::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::Timer::Id: { + switch (id) + { + case chip::app::Clusters::Timer::Attributes::SetTime::Id: + return "SetTime"; + case chip::app::Clusters::Timer::Attributes::TimeRemaining::Id: + return "TimeRemaining"; + case chip::app::Clusters::Timer::Attributes::TimerState::Id: + return "TimerState"; + case chip::app::Clusters::Timer::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::Timer::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::Timer::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::Timer::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::Timer::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::Timer::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::OvenCavityOperationalState::Id: { + switch (id) + { + case chip::app::Clusters::OvenCavityOperationalState::Attributes::PhaseList::Id: + return "PhaseList"; + case chip::app::Clusters::OvenCavityOperationalState::Attributes::CurrentPhase::Id: + return "CurrentPhase"; + case chip::app::Clusters::OvenCavityOperationalState::Attributes::CountdownTime::Id: + return "CountdownTime"; + case chip::app::Clusters::OvenCavityOperationalState::Attributes::OperationalStateList::Id: + return "OperationalStateList"; + case chip::app::Clusters::OvenCavityOperationalState::Attributes::OperationalState::Id: + return "OperationalState"; + case chip::app::Clusters::OvenCavityOperationalState::Attributes::OperationalError::Id: + return "OperationalError"; + case chip::app::Clusters::OvenCavityOperationalState::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::OvenCavityOperationalState::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::OvenCavityOperationalState::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::OvenCavityOperationalState::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::OvenCavityOperationalState::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::OvenCavityOperationalState::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::OvenMode::Id: { + switch (id) + { + case chip::app::Clusters::OvenMode::Attributes::SupportedModes::Id: + return "SupportedModes"; + case chip::app::Clusters::OvenMode::Attributes::CurrentMode::Id: + return "CurrentMode"; + case chip::app::Clusters::OvenMode::Attributes::StartUpMode::Id: + return "StartUpMode"; + case chip::app::Clusters::OvenMode::Attributes::OnMode::Id: + return "OnMode"; + case chip::app::Clusters::OvenMode::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::OvenMode::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::OvenMode::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::OvenMode::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::OvenMode::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::OvenMode::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::LaundryDryerControls::Id: { + switch (id) + { + case chip::app::Clusters::LaundryDryerControls::Attributes::SupportedDrynessLevels::Id: + return "SupportedDrynessLevels"; + case chip::app::Clusters::LaundryDryerControls::Attributes::SelectedDrynessLevel::Id: + return "SelectedDrynessLevel"; + case chip::app::Clusters::LaundryDryerControls::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::LaundryDryerControls::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::LaundryDryerControls::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::LaundryDryerControls::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::LaundryDryerControls::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::LaundryDryerControls::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::ModeSelect::Id: { + switch (id) + { + case chip::app::Clusters::ModeSelect::Attributes::Description::Id: + return "Description"; + case chip::app::Clusters::ModeSelect::Attributes::StandardNamespace::Id: + return "StandardNamespace"; + case chip::app::Clusters::ModeSelect::Attributes::SupportedModes::Id: + return "SupportedModes"; + case chip::app::Clusters::ModeSelect::Attributes::CurrentMode::Id: + return "CurrentMode"; + case chip::app::Clusters::ModeSelect::Attributes::StartUpMode::Id: + return "StartUpMode"; + case chip::app::Clusters::ModeSelect::Attributes::OnMode::Id: + return "OnMode"; + case chip::app::Clusters::ModeSelect::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::ModeSelect::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::ModeSelect::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::ModeSelect::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::ModeSelect::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::ModeSelect::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::LaundryWasherMode::Id: { + switch (id) + { + case chip::app::Clusters::LaundryWasherMode::Attributes::SupportedModes::Id: + return "SupportedModes"; + case chip::app::Clusters::LaundryWasherMode::Attributes::CurrentMode::Id: + return "CurrentMode"; + case chip::app::Clusters::LaundryWasherMode::Attributes::StartUpMode::Id: + return "StartUpMode"; + case chip::app::Clusters::LaundryWasherMode::Attributes::OnMode::Id: + return "OnMode"; + case chip::app::Clusters::LaundryWasherMode::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::LaundryWasherMode::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::LaundryWasherMode::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::LaundryWasherMode::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::LaundryWasherMode::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::LaundryWasherMode::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::RefrigeratorAndTemperatureControlledCabinetMode::Id: { + switch (id) + { + case chip::app::Clusters::RefrigeratorAndTemperatureControlledCabinetMode::Attributes::SupportedModes::Id: + return "SupportedModes"; + case chip::app::Clusters::RefrigeratorAndTemperatureControlledCabinetMode::Attributes::CurrentMode::Id: + return "CurrentMode"; + case chip::app::Clusters::RefrigeratorAndTemperatureControlledCabinetMode::Attributes::StartUpMode::Id: + return "StartUpMode"; + case chip::app::Clusters::RefrigeratorAndTemperatureControlledCabinetMode::Attributes::OnMode::Id: + return "OnMode"; + case chip::app::Clusters::RefrigeratorAndTemperatureControlledCabinetMode::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::RefrigeratorAndTemperatureControlledCabinetMode::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::RefrigeratorAndTemperatureControlledCabinetMode::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::RefrigeratorAndTemperatureControlledCabinetMode::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::RefrigeratorAndTemperatureControlledCabinetMode::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::RefrigeratorAndTemperatureControlledCabinetMode::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::LaundryWasherControls::Id: { + switch (id) + { + case chip::app::Clusters::LaundryWasherControls::Attributes::SpinSpeeds::Id: + return "SpinSpeeds"; + case chip::app::Clusters::LaundryWasherControls::Attributes::SpinSpeedCurrent::Id: + return "SpinSpeedCurrent"; + case chip::app::Clusters::LaundryWasherControls::Attributes::NumberOfRinses::Id: + return "NumberOfRinses"; + case chip::app::Clusters::LaundryWasherControls::Attributes::SupportedRinses::Id: + return "SupportedRinses"; + case chip::app::Clusters::LaundryWasherControls::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::LaundryWasherControls::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::LaundryWasherControls::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::LaundryWasherControls::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::LaundryWasherControls::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::LaundryWasherControls::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::RvcRunMode::Id: { + switch (id) + { + case chip::app::Clusters::RvcRunMode::Attributes::SupportedModes::Id: + return "SupportedModes"; + case chip::app::Clusters::RvcRunMode::Attributes::CurrentMode::Id: + return "CurrentMode"; + case chip::app::Clusters::RvcRunMode::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::RvcRunMode::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::RvcRunMode::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::RvcRunMode::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::RvcRunMode::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::RvcRunMode::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::RvcCleanMode::Id: { + switch (id) + { + case chip::app::Clusters::RvcCleanMode::Attributes::SupportedModes::Id: + return "SupportedModes"; + case chip::app::Clusters::RvcCleanMode::Attributes::CurrentMode::Id: + return "CurrentMode"; + case chip::app::Clusters::RvcCleanMode::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::RvcCleanMode::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::RvcCleanMode::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::RvcCleanMode::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::RvcCleanMode::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::RvcCleanMode::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::TemperatureControl::Id: { + switch (id) + { + case chip::app::Clusters::TemperatureControl::Attributes::TemperatureSetpoint::Id: + return "TemperatureSetpoint"; + case chip::app::Clusters::TemperatureControl::Attributes::MinTemperature::Id: + return "MinTemperature"; + case chip::app::Clusters::TemperatureControl::Attributes::MaxTemperature::Id: + return "MaxTemperature"; + case chip::app::Clusters::TemperatureControl::Attributes::Step::Id: + return "Step"; + case chip::app::Clusters::TemperatureControl::Attributes::SelectedTemperatureLevel::Id: + return "SelectedTemperatureLevel"; + case chip::app::Clusters::TemperatureControl::Attributes::SupportedTemperatureLevels::Id: + return "SupportedTemperatureLevels"; + case chip::app::Clusters::TemperatureControl::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::TemperatureControl::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::TemperatureControl::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::TemperatureControl::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::TemperatureControl::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::TemperatureControl::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::RefrigeratorAlarm::Id: { + switch (id) + { + case chip::app::Clusters::RefrigeratorAlarm::Attributes::Mask::Id: + return "Mask"; + case chip::app::Clusters::RefrigeratorAlarm::Attributes::State::Id: + return "State"; + case chip::app::Clusters::RefrigeratorAlarm::Attributes::Supported::Id: + return "Supported"; + case chip::app::Clusters::RefrigeratorAlarm::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::RefrigeratorAlarm::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::RefrigeratorAlarm::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::RefrigeratorAlarm::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::RefrigeratorAlarm::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::RefrigeratorAlarm::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::DishwasherMode::Id: { + switch (id) + { + case chip::app::Clusters::DishwasherMode::Attributes::SupportedModes::Id: + return "SupportedModes"; + case chip::app::Clusters::DishwasherMode::Attributes::CurrentMode::Id: + return "CurrentMode"; + case chip::app::Clusters::DishwasherMode::Attributes::StartUpMode::Id: + return "StartUpMode"; + case chip::app::Clusters::DishwasherMode::Attributes::OnMode::Id: + return "OnMode"; + case chip::app::Clusters::DishwasherMode::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::DishwasherMode::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::DishwasherMode::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::DishwasherMode::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::DishwasherMode::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::DishwasherMode::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::AirQuality::Id: { + switch (id) + { + case chip::app::Clusters::AirQuality::Attributes::AirQuality::Id: + return "AirQuality"; + case chip::app::Clusters::AirQuality::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::AirQuality::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::AirQuality::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::AirQuality::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::AirQuality::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::AirQuality::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::SmokeCoAlarm::Id: { + switch (id) + { + case chip::app::Clusters::SmokeCoAlarm::Attributes::ExpressedState::Id: + return "ExpressedState"; + case chip::app::Clusters::SmokeCoAlarm::Attributes::SmokeState::Id: + return "SmokeState"; + case chip::app::Clusters::SmokeCoAlarm::Attributes::COState::Id: + return "COState"; + case chip::app::Clusters::SmokeCoAlarm::Attributes::BatteryAlert::Id: + return "BatteryAlert"; + case chip::app::Clusters::SmokeCoAlarm::Attributes::DeviceMuted::Id: + return "DeviceMuted"; + case chip::app::Clusters::SmokeCoAlarm::Attributes::TestInProgress::Id: + return "TestInProgress"; + case chip::app::Clusters::SmokeCoAlarm::Attributes::HardwareFaultAlert::Id: + return "HardwareFaultAlert"; + case chip::app::Clusters::SmokeCoAlarm::Attributes::EndOfServiceAlert::Id: + return "EndOfServiceAlert"; + case chip::app::Clusters::SmokeCoAlarm::Attributes::InterconnectSmokeAlarm::Id: + return "InterconnectSmokeAlarm"; + case chip::app::Clusters::SmokeCoAlarm::Attributes::InterconnectCOAlarm::Id: + return "InterconnectCOAlarm"; + case chip::app::Clusters::SmokeCoAlarm::Attributes::ContaminationState::Id: + return "ContaminationState"; + case chip::app::Clusters::SmokeCoAlarm::Attributes::SmokeSensitivityLevel::Id: + return "SmokeSensitivityLevel"; + case chip::app::Clusters::SmokeCoAlarm::Attributes::ExpiryDate::Id: + return "ExpiryDate"; + case chip::app::Clusters::SmokeCoAlarm::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::SmokeCoAlarm::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::SmokeCoAlarm::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::SmokeCoAlarm::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::SmokeCoAlarm::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::SmokeCoAlarm::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::DishwasherAlarm::Id: { + switch (id) + { + case chip::app::Clusters::DishwasherAlarm::Attributes::Mask::Id: + return "Mask"; + case chip::app::Clusters::DishwasherAlarm::Attributes::Latch::Id: + return "Latch"; + case chip::app::Clusters::DishwasherAlarm::Attributes::State::Id: + return "State"; + case chip::app::Clusters::DishwasherAlarm::Attributes::Supported::Id: + return "Supported"; + case chip::app::Clusters::DishwasherAlarm::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::DishwasherAlarm::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::DishwasherAlarm::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::DishwasherAlarm::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::DishwasherAlarm::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::DishwasherAlarm::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::MicrowaveOvenMode::Id: { + switch (id) + { + case chip::app::Clusters::MicrowaveOvenMode::Attributes::SupportedModes::Id: + return "SupportedModes"; + case chip::app::Clusters::MicrowaveOvenMode::Attributes::CurrentMode::Id: + return "CurrentMode"; + case chip::app::Clusters::MicrowaveOvenMode::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::MicrowaveOvenMode::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::MicrowaveOvenMode::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::MicrowaveOvenMode::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::MicrowaveOvenMode::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::MicrowaveOvenMode::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::MicrowaveOvenControl::Id: { + switch (id) + { + case chip::app::Clusters::MicrowaveOvenControl::Attributes::CookTime::Id: + return "CookTime"; + case chip::app::Clusters::MicrowaveOvenControl::Attributes::MaxCookTime::Id: + return "MaxCookTime"; + case chip::app::Clusters::MicrowaveOvenControl::Attributes::PowerSetting::Id: + return "PowerSetting"; + case chip::app::Clusters::MicrowaveOvenControl::Attributes::MinPower::Id: + return "MinPower"; + case chip::app::Clusters::MicrowaveOvenControl::Attributes::MaxPower::Id: + return "MaxPower"; + case chip::app::Clusters::MicrowaveOvenControl::Attributes::PowerStep::Id: + return "PowerStep"; + case chip::app::Clusters::MicrowaveOvenControl::Attributes::SupportedWatts::Id: + return "SupportedWatts"; + case chip::app::Clusters::MicrowaveOvenControl::Attributes::SelectedWattIndex::Id: + return "SelectedWattIndex"; + case chip::app::Clusters::MicrowaveOvenControl::Attributes::WattRating::Id: + return "WattRating"; + case chip::app::Clusters::MicrowaveOvenControl::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::MicrowaveOvenControl::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::MicrowaveOvenControl::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::MicrowaveOvenControl::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::MicrowaveOvenControl::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::MicrowaveOvenControl::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::OperationalState::Id: { + switch (id) + { + case chip::app::Clusters::OperationalState::Attributes::PhaseList::Id: + return "PhaseList"; + case chip::app::Clusters::OperationalState::Attributes::CurrentPhase::Id: + return "CurrentPhase"; + case chip::app::Clusters::OperationalState::Attributes::CountdownTime::Id: + return "CountdownTime"; + case chip::app::Clusters::OperationalState::Attributes::OperationalStateList::Id: + return "OperationalStateList"; + case chip::app::Clusters::OperationalState::Attributes::OperationalState::Id: + return "OperationalState"; + case chip::app::Clusters::OperationalState::Attributes::OperationalError::Id: + return "OperationalError"; + case chip::app::Clusters::OperationalState::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::OperationalState::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::OperationalState::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::OperationalState::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::OperationalState::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::OperationalState::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::RvcOperationalState::Id: { + switch (id) + { + case chip::app::Clusters::RvcOperationalState::Attributes::PhaseList::Id: + return "PhaseList"; + case chip::app::Clusters::RvcOperationalState::Attributes::CurrentPhase::Id: + return "CurrentPhase"; + case chip::app::Clusters::RvcOperationalState::Attributes::CountdownTime::Id: + return "CountdownTime"; + case chip::app::Clusters::RvcOperationalState::Attributes::OperationalStateList::Id: + return "OperationalStateList"; + case chip::app::Clusters::RvcOperationalState::Attributes::OperationalState::Id: + return "OperationalState"; + case chip::app::Clusters::RvcOperationalState::Attributes::OperationalError::Id: + return "OperationalError"; + case chip::app::Clusters::RvcOperationalState::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::RvcOperationalState::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::RvcOperationalState::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::RvcOperationalState::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::RvcOperationalState::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::RvcOperationalState::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::ScenesManagement::Id: { + switch (id) + { + case chip::app::Clusters::ScenesManagement::Attributes::LastConfiguredBy::Id: + return "LastConfiguredBy"; + case chip::app::Clusters::ScenesManagement::Attributes::SceneTableSize::Id: + return "SceneTableSize"; + case chip::app::Clusters::ScenesManagement::Attributes::FabricSceneInfo::Id: + return "FabricSceneInfo"; + case chip::app::Clusters::ScenesManagement::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::ScenesManagement::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::ScenesManagement::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::ScenesManagement::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::ScenesManagement::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::ScenesManagement::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::HepaFilterMonitoring::Id: { + switch (id) + { + case chip::app::Clusters::HepaFilterMonitoring::Attributes::Condition::Id: + return "Condition"; + case chip::app::Clusters::HepaFilterMonitoring::Attributes::DegradationDirection::Id: + return "DegradationDirection"; + case chip::app::Clusters::HepaFilterMonitoring::Attributes::ChangeIndication::Id: + return "ChangeIndication"; + case chip::app::Clusters::HepaFilterMonitoring::Attributes::InPlaceIndicator::Id: + return "InPlaceIndicator"; + case chip::app::Clusters::HepaFilterMonitoring::Attributes::LastChangedTime::Id: + return "LastChangedTime"; + case chip::app::Clusters::HepaFilterMonitoring::Attributes::ReplacementProductList::Id: + return "ReplacementProductList"; + case chip::app::Clusters::HepaFilterMonitoring::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::HepaFilterMonitoring::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::HepaFilterMonitoring::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::HepaFilterMonitoring::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::HepaFilterMonitoring::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::HepaFilterMonitoring::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::ActivatedCarbonFilterMonitoring::Id: { + switch (id) + { + case chip::app::Clusters::ActivatedCarbonFilterMonitoring::Attributes::Condition::Id: + return "Condition"; + case chip::app::Clusters::ActivatedCarbonFilterMonitoring::Attributes::DegradationDirection::Id: + return "DegradationDirection"; + case chip::app::Clusters::ActivatedCarbonFilterMonitoring::Attributes::ChangeIndication::Id: + return "ChangeIndication"; + case chip::app::Clusters::ActivatedCarbonFilterMonitoring::Attributes::InPlaceIndicator::Id: + return "InPlaceIndicator"; + case chip::app::Clusters::ActivatedCarbonFilterMonitoring::Attributes::LastChangedTime::Id: + return "LastChangedTime"; + case chip::app::Clusters::ActivatedCarbonFilterMonitoring::Attributes::ReplacementProductList::Id: + return "ReplacementProductList"; + case chip::app::Clusters::ActivatedCarbonFilterMonitoring::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::ActivatedCarbonFilterMonitoring::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::ActivatedCarbonFilterMonitoring::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::ActivatedCarbonFilterMonitoring::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::ActivatedCarbonFilterMonitoring::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::ActivatedCarbonFilterMonitoring::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::BooleanStateConfiguration::Id: { + switch (id) + { + case chip::app::Clusters::BooleanStateConfiguration::Attributes::CurrentSensitivityLevel::Id: + return "CurrentSensitivityLevel"; + case chip::app::Clusters::BooleanStateConfiguration::Attributes::SupportedSensitivityLevels::Id: + return "SupportedSensitivityLevels"; + case chip::app::Clusters::BooleanStateConfiguration::Attributes::DefaultSensitivityLevel::Id: + return "DefaultSensitivityLevel"; + case chip::app::Clusters::BooleanStateConfiguration::Attributes::AlarmsActive::Id: + return "AlarmsActive"; + case chip::app::Clusters::BooleanStateConfiguration::Attributes::AlarmsSuppressed::Id: + return "AlarmsSuppressed"; + case chip::app::Clusters::BooleanStateConfiguration::Attributes::AlarmsEnabled::Id: + return "AlarmsEnabled"; + case chip::app::Clusters::BooleanStateConfiguration::Attributes::AlarmsSupported::Id: + return "AlarmsSupported"; + case chip::app::Clusters::BooleanStateConfiguration::Attributes::SensorFault::Id: + return "SensorFault"; + case chip::app::Clusters::BooleanStateConfiguration::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::BooleanStateConfiguration::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::BooleanStateConfiguration::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::BooleanStateConfiguration::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::BooleanStateConfiguration::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::BooleanStateConfiguration::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::ValveConfigurationAndControl::Id: { + switch (id) + { + case chip::app::Clusters::ValveConfigurationAndControl::Attributes::OpenDuration::Id: + return "OpenDuration"; + case chip::app::Clusters::ValveConfigurationAndControl::Attributes::DefaultOpenDuration::Id: + return "DefaultOpenDuration"; + case chip::app::Clusters::ValveConfigurationAndControl::Attributes::AutoCloseTime::Id: + return "AutoCloseTime"; + case chip::app::Clusters::ValveConfigurationAndControl::Attributes::RemainingDuration::Id: + return "RemainingDuration"; + case chip::app::Clusters::ValveConfigurationAndControl::Attributes::CurrentState::Id: + return "CurrentState"; + case chip::app::Clusters::ValveConfigurationAndControl::Attributes::TargetState::Id: + return "TargetState"; + case chip::app::Clusters::ValveConfigurationAndControl::Attributes::CurrentLevel::Id: + return "CurrentLevel"; + case chip::app::Clusters::ValveConfigurationAndControl::Attributes::TargetLevel::Id: + return "TargetLevel"; + case chip::app::Clusters::ValveConfigurationAndControl::Attributes::DefaultOpenLevel::Id: + return "DefaultOpenLevel"; + case chip::app::Clusters::ValveConfigurationAndControl::Attributes::ValveFault::Id: + return "ValveFault"; + case chip::app::Clusters::ValveConfigurationAndControl::Attributes::LevelStep::Id: + return "LevelStep"; + case chip::app::Clusters::ValveConfigurationAndControl::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::ValveConfigurationAndControl::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::ValveConfigurationAndControl::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::ValveConfigurationAndControl::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::ValveConfigurationAndControl::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::ValveConfigurationAndControl::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::ElectricalPowerMeasurement::Id: { + switch (id) + { + case chip::app::Clusters::ElectricalPowerMeasurement::Attributes::PowerMode::Id: + return "PowerMode"; + case chip::app::Clusters::ElectricalPowerMeasurement::Attributes::NumberOfMeasurementTypes::Id: + return "NumberOfMeasurementTypes"; + case chip::app::Clusters::ElectricalPowerMeasurement::Attributes::Accuracy::Id: + return "Accuracy"; + case chip::app::Clusters::ElectricalPowerMeasurement::Attributes::Ranges::Id: + return "Ranges"; + case chip::app::Clusters::ElectricalPowerMeasurement::Attributes::Voltage::Id: + return "Voltage"; + case chip::app::Clusters::ElectricalPowerMeasurement::Attributes::ActiveCurrent::Id: + return "ActiveCurrent"; + case chip::app::Clusters::ElectricalPowerMeasurement::Attributes::ReactiveCurrent::Id: + return "ReactiveCurrent"; + case chip::app::Clusters::ElectricalPowerMeasurement::Attributes::ApparentCurrent::Id: + return "ApparentCurrent"; + case chip::app::Clusters::ElectricalPowerMeasurement::Attributes::ActivePower::Id: + return "ActivePower"; + case chip::app::Clusters::ElectricalPowerMeasurement::Attributes::ReactivePower::Id: + return "ReactivePower"; + case chip::app::Clusters::ElectricalPowerMeasurement::Attributes::ApparentPower::Id: + return "ApparentPower"; + case chip::app::Clusters::ElectricalPowerMeasurement::Attributes::RMSVoltage::Id: + return "RMSVoltage"; + case chip::app::Clusters::ElectricalPowerMeasurement::Attributes::RMSCurrent::Id: + return "RMSCurrent"; + case chip::app::Clusters::ElectricalPowerMeasurement::Attributes::RMSPower::Id: + return "RMSPower"; + case chip::app::Clusters::ElectricalPowerMeasurement::Attributes::Frequency::Id: + return "Frequency"; + case chip::app::Clusters::ElectricalPowerMeasurement::Attributes::HarmonicCurrents::Id: + return "HarmonicCurrents"; + case chip::app::Clusters::ElectricalPowerMeasurement::Attributes::HarmonicPhases::Id: + return "HarmonicPhases"; + case chip::app::Clusters::ElectricalPowerMeasurement::Attributes::PowerFactor::Id: + return "PowerFactor"; + case chip::app::Clusters::ElectricalPowerMeasurement::Attributes::NeutralCurrent::Id: + return "NeutralCurrent"; + case chip::app::Clusters::ElectricalPowerMeasurement::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::ElectricalPowerMeasurement::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::ElectricalPowerMeasurement::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::ElectricalPowerMeasurement::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::ElectricalPowerMeasurement::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::ElectricalPowerMeasurement::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::ElectricalEnergyMeasurement::Id: { + switch (id) + { + case chip::app::Clusters::ElectricalEnergyMeasurement::Attributes::Accuracy::Id: + return "Accuracy"; + case chip::app::Clusters::ElectricalEnergyMeasurement::Attributes::CumulativeEnergyImported::Id: + return "CumulativeEnergyImported"; + case chip::app::Clusters::ElectricalEnergyMeasurement::Attributes::CumulativeEnergyExported::Id: + return "CumulativeEnergyExported"; + case chip::app::Clusters::ElectricalEnergyMeasurement::Attributes::PeriodicEnergyImported::Id: + return "PeriodicEnergyImported"; + case chip::app::Clusters::ElectricalEnergyMeasurement::Attributes::PeriodicEnergyExported::Id: + return "PeriodicEnergyExported"; + case chip::app::Clusters::ElectricalEnergyMeasurement::Attributes::CumulativeEnergyReset::Id: + return "CumulativeEnergyReset"; + case chip::app::Clusters::ElectricalEnergyMeasurement::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::ElectricalEnergyMeasurement::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::ElectricalEnergyMeasurement::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::ElectricalEnergyMeasurement::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::ElectricalEnergyMeasurement::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::ElectricalEnergyMeasurement::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::WaterHeaterManagement::Id: { + switch (id) + { + case chip::app::Clusters::WaterHeaterManagement::Attributes::HeaterTypes::Id: + return "HeaterTypes"; + case chip::app::Clusters::WaterHeaterManagement::Attributes::HeatDemand::Id: + return "HeatDemand"; + case chip::app::Clusters::WaterHeaterManagement::Attributes::TankVolume::Id: + return "TankVolume"; + case chip::app::Clusters::WaterHeaterManagement::Attributes::EstimatedHeatRequired::Id: + return "EstimatedHeatRequired"; + case chip::app::Clusters::WaterHeaterManagement::Attributes::TankPercentage::Id: + return "TankPercentage"; + case chip::app::Clusters::WaterHeaterManagement::Attributes::BoostState::Id: + return "BoostState"; + case chip::app::Clusters::WaterHeaterManagement::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::WaterHeaterManagement::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::WaterHeaterManagement::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::WaterHeaterManagement::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::WaterHeaterManagement::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::WaterHeaterManagement::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::DemandResponseLoadControl::Id: { + switch (id) + { + case chip::app::Clusters::DemandResponseLoadControl::Attributes::LoadControlPrograms::Id: + return "LoadControlPrograms"; + case chip::app::Clusters::DemandResponseLoadControl::Attributes::NumberOfLoadControlPrograms::Id: + return "NumberOfLoadControlPrograms"; + case chip::app::Clusters::DemandResponseLoadControl::Attributes::Events::Id: + return "Events"; + case chip::app::Clusters::DemandResponseLoadControl::Attributes::ActiveEvents::Id: + return "ActiveEvents"; + case chip::app::Clusters::DemandResponseLoadControl::Attributes::NumberOfEventsPerProgram::Id: + return "NumberOfEventsPerProgram"; + case chip::app::Clusters::DemandResponseLoadControl::Attributes::NumberOfTransitions::Id: + return "NumberOfTransitions"; + case chip::app::Clusters::DemandResponseLoadControl::Attributes::DefaultRandomStart::Id: + return "DefaultRandomStart"; + case chip::app::Clusters::DemandResponseLoadControl::Attributes::DefaultRandomDuration::Id: + return "DefaultRandomDuration"; + case chip::app::Clusters::DemandResponseLoadControl::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::DemandResponseLoadControl::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::DemandResponseLoadControl::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::DemandResponseLoadControl::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::DemandResponseLoadControl::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::DemandResponseLoadControl::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::Messages::Id: { + switch (id) + { + case chip::app::Clusters::Messages::Attributes::Messages::Id: + return "Messages"; + case chip::app::Clusters::Messages::Attributes::ActiveMessageIDs::Id: + return "ActiveMessageIDs"; + case chip::app::Clusters::Messages::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::Messages::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::Messages::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::Messages::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::Messages::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::Messages::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::DeviceEnergyManagement::Id: { + switch (id) + { + case chip::app::Clusters::DeviceEnergyManagement::Attributes::ESAType::Id: + return "ESAType"; + case chip::app::Clusters::DeviceEnergyManagement::Attributes::ESACanGenerate::Id: + return "ESACanGenerate"; + case chip::app::Clusters::DeviceEnergyManagement::Attributes::ESAState::Id: + return "ESAState"; + case chip::app::Clusters::DeviceEnergyManagement::Attributes::AbsMinPower::Id: + return "AbsMinPower"; + case chip::app::Clusters::DeviceEnergyManagement::Attributes::AbsMaxPower::Id: + return "AbsMaxPower"; + case chip::app::Clusters::DeviceEnergyManagement::Attributes::PowerAdjustmentCapability::Id: + return "PowerAdjustmentCapability"; + case chip::app::Clusters::DeviceEnergyManagement::Attributes::Forecast::Id: + return "Forecast"; + case chip::app::Clusters::DeviceEnergyManagement::Attributes::OptOutState::Id: + return "OptOutState"; + case chip::app::Clusters::DeviceEnergyManagement::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::DeviceEnergyManagement::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::DeviceEnergyManagement::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::DeviceEnergyManagement::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::DeviceEnergyManagement::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::DeviceEnergyManagement::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::EnergyEvse::Id: { + switch (id) + { + case chip::app::Clusters::EnergyEvse::Attributes::State::Id: + return "State"; + case chip::app::Clusters::EnergyEvse::Attributes::SupplyState::Id: + return "SupplyState"; + case chip::app::Clusters::EnergyEvse::Attributes::FaultState::Id: + return "FaultState"; + case chip::app::Clusters::EnergyEvse::Attributes::ChargingEnabledUntil::Id: + return "ChargingEnabledUntil"; + case chip::app::Clusters::EnergyEvse::Attributes::DischargingEnabledUntil::Id: + return "DischargingEnabledUntil"; + case chip::app::Clusters::EnergyEvse::Attributes::CircuitCapacity::Id: + return "CircuitCapacity"; + case chip::app::Clusters::EnergyEvse::Attributes::MinimumChargeCurrent::Id: + return "MinimumChargeCurrent"; + case chip::app::Clusters::EnergyEvse::Attributes::MaximumChargeCurrent::Id: + return "MaximumChargeCurrent"; + case chip::app::Clusters::EnergyEvse::Attributes::MaximumDischargeCurrent::Id: + return "MaximumDischargeCurrent"; + case chip::app::Clusters::EnergyEvse::Attributes::UserMaximumChargeCurrent::Id: + return "UserMaximumChargeCurrent"; + case chip::app::Clusters::EnergyEvse::Attributes::RandomizationDelayWindow::Id: + return "RandomizationDelayWindow"; + case chip::app::Clusters::EnergyEvse::Attributes::NextChargeStartTime::Id: + return "NextChargeStartTime"; + case chip::app::Clusters::EnergyEvse::Attributes::NextChargeTargetTime::Id: + return "NextChargeTargetTime"; + case chip::app::Clusters::EnergyEvse::Attributes::NextChargeRequiredEnergy::Id: + return "NextChargeRequiredEnergy"; + case chip::app::Clusters::EnergyEvse::Attributes::NextChargeTargetSoC::Id: + return "NextChargeTargetSoC"; + case chip::app::Clusters::EnergyEvse::Attributes::ApproximateEVEfficiency::Id: + return "ApproximateEVEfficiency"; + case chip::app::Clusters::EnergyEvse::Attributes::StateOfCharge::Id: + return "StateOfCharge"; + case chip::app::Clusters::EnergyEvse::Attributes::BatteryCapacity::Id: + return "BatteryCapacity"; + case chip::app::Clusters::EnergyEvse::Attributes::VehicleID::Id: + return "VehicleID"; + case chip::app::Clusters::EnergyEvse::Attributes::SessionID::Id: + return "SessionID"; + case chip::app::Clusters::EnergyEvse::Attributes::SessionDuration::Id: + return "SessionDuration"; + case chip::app::Clusters::EnergyEvse::Attributes::SessionEnergyCharged::Id: + return "SessionEnergyCharged"; + case chip::app::Clusters::EnergyEvse::Attributes::SessionEnergyDischarged::Id: + return "SessionEnergyDischarged"; + case chip::app::Clusters::EnergyEvse::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::EnergyEvse::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::EnergyEvse::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::EnergyEvse::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::EnergyEvse::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::EnergyEvse::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::EnergyPreference::Id: { + switch (id) + { + case chip::app::Clusters::EnergyPreference::Attributes::EnergyBalances::Id: + return "EnergyBalances"; + case chip::app::Clusters::EnergyPreference::Attributes::CurrentEnergyBalance::Id: + return "CurrentEnergyBalance"; + case chip::app::Clusters::EnergyPreference::Attributes::EnergyPriorities::Id: + return "EnergyPriorities"; + case chip::app::Clusters::EnergyPreference::Attributes::LowPowerModeSensitivities::Id: + return "LowPowerModeSensitivities"; + case chip::app::Clusters::EnergyPreference::Attributes::CurrentLowPowerModeSensitivity::Id: + return "CurrentLowPowerModeSensitivity"; + case chip::app::Clusters::EnergyPreference::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::EnergyPreference::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::EnergyPreference::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::EnergyPreference::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::EnergyPreference::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::EnergyPreference::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::PowerTopology::Id: { + switch (id) + { + case chip::app::Clusters::PowerTopology::Attributes::AvailableEndpoints::Id: + return "AvailableEndpoints"; + case chip::app::Clusters::PowerTopology::Attributes::ActiveEndpoints::Id: + return "ActiveEndpoints"; + case chip::app::Clusters::PowerTopology::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::PowerTopology::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::PowerTopology::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::PowerTopology::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::PowerTopology::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::PowerTopology::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::EnergyEvseMode::Id: { + switch (id) + { + case chip::app::Clusters::EnergyEvseMode::Attributes::SupportedModes::Id: + return "SupportedModes"; + case chip::app::Clusters::EnergyEvseMode::Attributes::CurrentMode::Id: + return "CurrentMode"; + case chip::app::Clusters::EnergyEvseMode::Attributes::StartUpMode::Id: + return "StartUpMode"; + case chip::app::Clusters::EnergyEvseMode::Attributes::OnMode::Id: + return "OnMode"; + case chip::app::Clusters::EnergyEvseMode::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::EnergyEvseMode::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::EnergyEvseMode::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::EnergyEvseMode::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::EnergyEvseMode::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::EnergyEvseMode::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::WaterHeaterMode::Id: { + switch (id) + { + case chip::app::Clusters::WaterHeaterMode::Attributes::SupportedModes::Id: + return "SupportedModes"; + case chip::app::Clusters::WaterHeaterMode::Attributes::CurrentMode::Id: + return "CurrentMode"; + case chip::app::Clusters::WaterHeaterMode::Attributes::StartUpMode::Id: + return "StartUpMode"; + case chip::app::Clusters::WaterHeaterMode::Attributes::OnMode::Id: + return "OnMode"; + case chip::app::Clusters::WaterHeaterMode::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::WaterHeaterMode::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::WaterHeaterMode::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::WaterHeaterMode::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::WaterHeaterMode::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::WaterHeaterMode::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::DeviceEnergyManagementMode::Id: { + switch (id) + { + case chip::app::Clusters::DeviceEnergyManagementMode::Attributes::SupportedModes::Id: + return "SupportedModes"; + case chip::app::Clusters::DeviceEnergyManagementMode::Attributes::CurrentMode::Id: + return "CurrentMode"; + case chip::app::Clusters::DeviceEnergyManagementMode::Attributes::StartUpMode::Id: + return "StartUpMode"; + case chip::app::Clusters::DeviceEnergyManagementMode::Attributes::OnMode::Id: + return "OnMode"; + case chip::app::Clusters::DeviceEnergyManagementMode::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::DeviceEnergyManagementMode::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::DeviceEnergyManagementMode::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::DeviceEnergyManagementMode::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::DeviceEnergyManagementMode::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::DeviceEnergyManagementMode::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::DoorLock::Id: { + switch (id) + { + case chip::app::Clusters::DoorLock::Attributes::LockState::Id: + return "LockState"; + case chip::app::Clusters::DoorLock::Attributes::LockType::Id: + return "LockType"; + case chip::app::Clusters::DoorLock::Attributes::ActuatorEnabled::Id: + return "ActuatorEnabled"; + case chip::app::Clusters::DoorLock::Attributes::DoorState::Id: + return "DoorState"; + case chip::app::Clusters::DoorLock::Attributes::DoorOpenEvents::Id: + return "DoorOpenEvents"; + case chip::app::Clusters::DoorLock::Attributes::DoorClosedEvents::Id: + return "DoorClosedEvents"; + case chip::app::Clusters::DoorLock::Attributes::OpenPeriod::Id: + return "OpenPeriod"; + case chip::app::Clusters::DoorLock::Attributes::NumberOfTotalUsersSupported::Id: + return "NumberOfTotalUsersSupported"; + case chip::app::Clusters::DoorLock::Attributes::NumberOfPINUsersSupported::Id: + return "NumberOfPINUsersSupported"; + case chip::app::Clusters::DoorLock::Attributes::NumberOfRFIDUsersSupported::Id: + return "NumberOfRFIDUsersSupported"; + case chip::app::Clusters::DoorLock::Attributes::NumberOfWeekDaySchedulesSupportedPerUser::Id: + return "NumberOfWeekDaySchedulesSupportedPerUser"; + case chip::app::Clusters::DoorLock::Attributes::NumberOfYearDaySchedulesSupportedPerUser::Id: + return "NumberOfYearDaySchedulesSupportedPerUser"; + case chip::app::Clusters::DoorLock::Attributes::NumberOfHolidaySchedulesSupported::Id: + return "NumberOfHolidaySchedulesSupported"; + case chip::app::Clusters::DoorLock::Attributes::MaxPINCodeLength::Id: + return "MaxPINCodeLength"; + case chip::app::Clusters::DoorLock::Attributes::MinPINCodeLength::Id: + return "MinPINCodeLength"; + case chip::app::Clusters::DoorLock::Attributes::MaxRFIDCodeLength::Id: + return "MaxRFIDCodeLength"; + case chip::app::Clusters::DoorLock::Attributes::MinRFIDCodeLength::Id: + return "MinRFIDCodeLength"; + case chip::app::Clusters::DoorLock::Attributes::CredentialRulesSupport::Id: + return "CredentialRulesSupport"; + case chip::app::Clusters::DoorLock::Attributes::NumberOfCredentialsSupportedPerUser::Id: + return "NumberOfCredentialsSupportedPerUser"; + case chip::app::Clusters::DoorLock::Attributes::Language::Id: + return "Language"; + case chip::app::Clusters::DoorLock::Attributes::LEDSettings::Id: + return "LEDSettings"; + case chip::app::Clusters::DoorLock::Attributes::AutoRelockTime::Id: + return "AutoRelockTime"; + case chip::app::Clusters::DoorLock::Attributes::SoundVolume::Id: + return "SoundVolume"; + case chip::app::Clusters::DoorLock::Attributes::OperatingMode::Id: + return "OperatingMode"; + case chip::app::Clusters::DoorLock::Attributes::SupportedOperatingModes::Id: + return "SupportedOperatingModes"; + case chip::app::Clusters::DoorLock::Attributes::DefaultConfigurationRegister::Id: + return "DefaultConfigurationRegister"; + case chip::app::Clusters::DoorLock::Attributes::EnableLocalProgramming::Id: + return "EnableLocalProgramming"; + case chip::app::Clusters::DoorLock::Attributes::EnableOneTouchLocking::Id: + return "EnableOneTouchLocking"; + case chip::app::Clusters::DoorLock::Attributes::EnableInsideStatusLED::Id: + return "EnableInsideStatusLED"; + case chip::app::Clusters::DoorLock::Attributes::EnablePrivacyModeButton::Id: + return "EnablePrivacyModeButton"; + case chip::app::Clusters::DoorLock::Attributes::LocalProgrammingFeatures::Id: + return "LocalProgrammingFeatures"; + case chip::app::Clusters::DoorLock::Attributes::WrongCodeEntryLimit::Id: + return "WrongCodeEntryLimit"; + case chip::app::Clusters::DoorLock::Attributes::UserCodeTemporaryDisableTime::Id: + return "UserCodeTemporaryDisableTime"; + case chip::app::Clusters::DoorLock::Attributes::SendPINOverTheAir::Id: + return "SendPINOverTheAir"; + case chip::app::Clusters::DoorLock::Attributes::RequirePINforRemoteOperation::Id: + return "RequirePINforRemoteOperation"; + case chip::app::Clusters::DoorLock::Attributes::ExpiringUserTimeout::Id: + return "ExpiringUserTimeout"; + case chip::app::Clusters::DoorLock::Attributes::AliroReaderVerificationKey::Id: + return "AliroReaderVerificationKey"; + case chip::app::Clusters::DoorLock::Attributes::AliroReaderGroupIdentifier::Id: + return "AliroReaderGroupIdentifier"; + case chip::app::Clusters::DoorLock::Attributes::AliroReaderGroupSubIdentifier::Id: + return "AliroReaderGroupSubIdentifier"; + case chip::app::Clusters::DoorLock::Attributes::AliroExpeditedTransactionSupportedProtocolVersions::Id: + return "AliroExpeditedTransactionSupportedProtocolVersions"; + case chip::app::Clusters::DoorLock::Attributes::AliroGroupResolvingKey::Id: + return "AliroGroupResolvingKey"; + case chip::app::Clusters::DoorLock::Attributes::AliroSupportedBLEUWBProtocolVersions::Id: + return "AliroSupportedBLEUWBProtocolVersions"; + case chip::app::Clusters::DoorLock::Attributes::AliroBLEAdvertisingVersion::Id: + return "AliroBLEAdvertisingVersion"; + case chip::app::Clusters::DoorLock::Attributes::NumberOfAliroCredentialIssuerKeysSupported::Id: + return "NumberOfAliroCredentialIssuerKeysSupported"; + case chip::app::Clusters::DoorLock::Attributes::NumberOfAliroEndpointKeysSupported::Id: + return "NumberOfAliroEndpointKeysSupported"; + case chip::app::Clusters::DoorLock::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::DoorLock::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::DoorLock::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::DoorLock::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::DoorLock::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::DoorLock::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::WindowCovering::Id: { + switch (id) + { + case chip::app::Clusters::WindowCovering::Attributes::Type::Id: + return "Type"; + case chip::app::Clusters::WindowCovering::Attributes::PhysicalClosedLimitLift::Id: + return "PhysicalClosedLimitLift"; + case chip::app::Clusters::WindowCovering::Attributes::PhysicalClosedLimitTilt::Id: + return "PhysicalClosedLimitTilt"; + case chip::app::Clusters::WindowCovering::Attributes::CurrentPositionLift::Id: + return "CurrentPositionLift"; + case chip::app::Clusters::WindowCovering::Attributes::CurrentPositionTilt::Id: + return "CurrentPositionTilt"; + case chip::app::Clusters::WindowCovering::Attributes::NumberOfActuationsLift::Id: + return "NumberOfActuationsLift"; + case chip::app::Clusters::WindowCovering::Attributes::NumberOfActuationsTilt::Id: + return "NumberOfActuationsTilt"; + case chip::app::Clusters::WindowCovering::Attributes::ConfigStatus::Id: + return "ConfigStatus"; + case chip::app::Clusters::WindowCovering::Attributes::CurrentPositionLiftPercentage::Id: + return "CurrentPositionLiftPercentage"; + case chip::app::Clusters::WindowCovering::Attributes::CurrentPositionTiltPercentage::Id: + return "CurrentPositionTiltPercentage"; + case chip::app::Clusters::WindowCovering::Attributes::OperationalStatus::Id: + return "OperationalStatus"; + case chip::app::Clusters::WindowCovering::Attributes::TargetPositionLiftPercent100ths::Id: + return "TargetPositionLiftPercent100ths"; + case chip::app::Clusters::WindowCovering::Attributes::TargetPositionTiltPercent100ths::Id: + return "TargetPositionTiltPercent100ths"; + case chip::app::Clusters::WindowCovering::Attributes::EndProductType::Id: + return "EndProductType"; + case chip::app::Clusters::WindowCovering::Attributes::CurrentPositionLiftPercent100ths::Id: + return "CurrentPositionLiftPercent100ths"; + case chip::app::Clusters::WindowCovering::Attributes::CurrentPositionTiltPercent100ths::Id: + return "CurrentPositionTiltPercent100ths"; + case chip::app::Clusters::WindowCovering::Attributes::InstalledOpenLimitLift::Id: + return "InstalledOpenLimitLift"; + case chip::app::Clusters::WindowCovering::Attributes::InstalledClosedLimitLift::Id: + return "InstalledClosedLimitLift"; + case chip::app::Clusters::WindowCovering::Attributes::InstalledOpenLimitTilt::Id: + return "InstalledOpenLimitTilt"; + case chip::app::Clusters::WindowCovering::Attributes::InstalledClosedLimitTilt::Id: + return "InstalledClosedLimitTilt"; + case chip::app::Clusters::WindowCovering::Attributes::Mode::Id: + return "Mode"; + case chip::app::Clusters::WindowCovering::Attributes::SafetyStatus::Id: + return "SafetyStatus"; + case chip::app::Clusters::WindowCovering::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::WindowCovering::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::WindowCovering::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::WindowCovering::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::WindowCovering::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::WindowCovering::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::BarrierControl::Id: { + switch (id) + { + case chip::app::Clusters::BarrierControl::Attributes::BarrierMovingState::Id: + return "BarrierMovingState"; + case chip::app::Clusters::BarrierControl::Attributes::BarrierSafetyStatus::Id: + return "BarrierSafetyStatus"; + case chip::app::Clusters::BarrierControl::Attributes::BarrierCapabilities::Id: + return "BarrierCapabilities"; + case chip::app::Clusters::BarrierControl::Attributes::BarrierOpenEvents::Id: + return "BarrierOpenEvents"; + case chip::app::Clusters::BarrierControl::Attributes::BarrierCloseEvents::Id: + return "BarrierCloseEvents"; + case chip::app::Clusters::BarrierControl::Attributes::BarrierCommandOpenEvents::Id: + return "BarrierCommandOpenEvents"; + case chip::app::Clusters::BarrierControl::Attributes::BarrierCommandCloseEvents::Id: + return "BarrierCommandCloseEvents"; + case chip::app::Clusters::BarrierControl::Attributes::BarrierOpenPeriod::Id: + return "BarrierOpenPeriod"; + case chip::app::Clusters::BarrierControl::Attributes::BarrierClosePeriod::Id: + return "BarrierClosePeriod"; + case chip::app::Clusters::BarrierControl::Attributes::BarrierPosition::Id: + return "BarrierPosition"; + case chip::app::Clusters::BarrierControl::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::BarrierControl::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::BarrierControl::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::BarrierControl::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::BarrierControl::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::BarrierControl::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::ServiceArea::Id: { + switch (id) + { + case chip::app::Clusters::ServiceArea::Attributes::SupportedAreas::Id: + return "SupportedAreas"; + case chip::app::Clusters::ServiceArea::Attributes::SupportedMaps::Id: + return "SupportedMaps"; + case chip::app::Clusters::ServiceArea::Attributes::SelectedAreas::Id: + return "SelectedAreas"; + case chip::app::Clusters::ServiceArea::Attributes::CurrentArea::Id: + return "CurrentArea"; + case chip::app::Clusters::ServiceArea::Attributes::EstimatedEndTime::Id: + return "EstimatedEndTime"; + case chip::app::Clusters::ServiceArea::Attributes::Progress::Id: + return "Progress"; + case chip::app::Clusters::ServiceArea::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::ServiceArea::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::ServiceArea::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::ServiceArea::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::ServiceArea::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::ServiceArea::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::PumpConfigurationAndControl::Id: { + switch (id) + { + case chip::app::Clusters::PumpConfigurationAndControl::Attributes::MaxPressure::Id: + return "MaxPressure"; + case chip::app::Clusters::PumpConfigurationAndControl::Attributes::MaxSpeed::Id: + return "MaxSpeed"; + case chip::app::Clusters::PumpConfigurationAndControl::Attributes::MaxFlow::Id: + return "MaxFlow"; + case chip::app::Clusters::PumpConfigurationAndControl::Attributes::MinConstPressure::Id: + return "MinConstPressure"; + case chip::app::Clusters::PumpConfigurationAndControl::Attributes::MaxConstPressure::Id: + return "MaxConstPressure"; + case chip::app::Clusters::PumpConfigurationAndControl::Attributes::MinCompPressure::Id: + return "MinCompPressure"; + case chip::app::Clusters::PumpConfigurationAndControl::Attributes::MaxCompPressure::Id: + return "MaxCompPressure"; + case chip::app::Clusters::PumpConfigurationAndControl::Attributes::MinConstSpeed::Id: + return "MinConstSpeed"; + case chip::app::Clusters::PumpConfigurationAndControl::Attributes::MaxConstSpeed::Id: + return "MaxConstSpeed"; + case chip::app::Clusters::PumpConfigurationAndControl::Attributes::MinConstFlow::Id: + return "MinConstFlow"; + case chip::app::Clusters::PumpConfigurationAndControl::Attributes::MaxConstFlow::Id: + return "MaxConstFlow"; + case chip::app::Clusters::PumpConfigurationAndControl::Attributes::MinConstTemp::Id: + return "MinConstTemp"; + case chip::app::Clusters::PumpConfigurationAndControl::Attributes::MaxConstTemp::Id: + return "MaxConstTemp"; + case chip::app::Clusters::PumpConfigurationAndControl::Attributes::PumpStatus::Id: + return "PumpStatus"; + case chip::app::Clusters::PumpConfigurationAndControl::Attributes::EffectiveOperationMode::Id: + return "EffectiveOperationMode"; + case chip::app::Clusters::PumpConfigurationAndControl::Attributes::EffectiveControlMode::Id: + return "EffectiveControlMode"; + case chip::app::Clusters::PumpConfigurationAndControl::Attributes::Capacity::Id: + return "Capacity"; + case chip::app::Clusters::PumpConfigurationAndControl::Attributes::Speed::Id: + return "Speed"; + case chip::app::Clusters::PumpConfigurationAndControl::Attributes::LifetimeRunningHours::Id: + return "LifetimeRunningHours"; + case chip::app::Clusters::PumpConfigurationAndControl::Attributes::Power::Id: + return "Power"; + case chip::app::Clusters::PumpConfigurationAndControl::Attributes::LifetimeEnergyConsumed::Id: + return "LifetimeEnergyConsumed"; + case chip::app::Clusters::PumpConfigurationAndControl::Attributes::OperationMode::Id: + return "OperationMode"; + case chip::app::Clusters::PumpConfigurationAndControl::Attributes::ControlMode::Id: + return "ControlMode"; + case chip::app::Clusters::PumpConfigurationAndControl::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::PumpConfigurationAndControl::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::PumpConfigurationAndControl::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::PumpConfigurationAndControl::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::PumpConfigurationAndControl::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::PumpConfigurationAndControl::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::Thermostat::Id: { + switch (id) + { + case chip::app::Clusters::Thermostat::Attributes::LocalTemperature::Id: + return "LocalTemperature"; + case chip::app::Clusters::Thermostat::Attributes::OutdoorTemperature::Id: + return "OutdoorTemperature"; + case chip::app::Clusters::Thermostat::Attributes::Occupancy::Id: + return "Occupancy"; + case chip::app::Clusters::Thermostat::Attributes::AbsMinHeatSetpointLimit::Id: + return "AbsMinHeatSetpointLimit"; + case chip::app::Clusters::Thermostat::Attributes::AbsMaxHeatSetpointLimit::Id: + return "AbsMaxHeatSetpointLimit"; + case chip::app::Clusters::Thermostat::Attributes::AbsMinCoolSetpointLimit::Id: + return "AbsMinCoolSetpointLimit"; + case chip::app::Clusters::Thermostat::Attributes::AbsMaxCoolSetpointLimit::Id: + return "AbsMaxCoolSetpointLimit"; + case chip::app::Clusters::Thermostat::Attributes::PICoolingDemand::Id: + return "PICoolingDemand"; + case chip::app::Clusters::Thermostat::Attributes::PIHeatingDemand::Id: + return "PIHeatingDemand"; + case chip::app::Clusters::Thermostat::Attributes::HVACSystemTypeConfiguration::Id: + return "HVACSystemTypeConfiguration"; + case chip::app::Clusters::Thermostat::Attributes::LocalTemperatureCalibration::Id: + return "LocalTemperatureCalibration"; + case chip::app::Clusters::Thermostat::Attributes::OccupiedCoolingSetpoint::Id: + return "OccupiedCoolingSetpoint"; + case chip::app::Clusters::Thermostat::Attributes::OccupiedHeatingSetpoint::Id: + return "OccupiedHeatingSetpoint"; + case chip::app::Clusters::Thermostat::Attributes::UnoccupiedCoolingSetpoint::Id: + return "UnoccupiedCoolingSetpoint"; + case chip::app::Clusters::Thermostat::Attributes::UnoccupiedHeatingSetpoint::Id: + return "UnoccupiedHeatingSetpoint"; + case chip::app::Clusters::Thermostat::Attributes::MinHeatSetpointLimit::Id: + return "MinHeatSetpointLimit"; + case chip::app::Clusters::Thermostat::Attributes::MaxHeatSetpointLimit::Id: + return "MaxHeatSetpointLimit"; + case chip::app::Clusters::Thermostat::Attributes::MinCoolSetpointLimit::Id: + return "MinCoolSetpointLimit"; + case chip::app::Clusters::Thermostat::Attributes::MaxCoolSetpointLimit::Id: + return "MaxCoolSetpointLimit"; + case chip::app::Clusters::Thermostat::Attributes::MinSetpointDeadBand::Id: + return "MinSetpointDeadBand"; + case chip::app::Clusters::Thermostat::Attributes::RemoteSensing::Id: + return "RemoteSensing"; + case chip::app::Clusters::Thermostat::Attributes::ControlSequenceOfOperation::Id: + return "ControlSequenceOfOperation"; + case chip::app::Clusters::Thermostat::Attributes::SystemMode::Id: + return "SystemMode"; + case chip::app::Clusters::Thermostat::Attributes::ThermostatRunningMode::Id: + return "ThermostatRunningMode"; + case chip::app::Clusters::Thermostat::Attributes::StartOfWeek::Id: + return "StartOfWeek"; + case chip::app::Clusters::Thermostat::Attributes::NumberOfWeeklyTransitions::Id: + return "NumberOfWeeklyTransitions"; + case chip::app::Clusters::Thermostat::Attributes::NumberOfDailyTransitions::Id: + return "NumberOfDailyTransitions"; + case chip::app::Clusters::Thermostat::Attributes::TemperatureSetpointHold::Id: + return "TemperatureSetpointHold"; + case chip::app::Clusters::Thermostat::Attributes::TemperatureSetpointHoldDuration::Id: + return "TemperatureSetpointHoldDuration"; + case chip::app::Clusters::Thermostat::Attributes::ThermostatProgrammingOperationMode::Id: + return "ThermostatProgrammingOperationMode"; + case chip::app::Clusters::Thermostat::Attributes::ThermostatRunningState::Id: + return "ThermostatRunningState"; + case chip::app::Clusters::Thermostat::Attributes::SetpointChangeSource::Id: + return "SetpointChangeSource"; + case chip::app::Clusters::Thermostat::Attributes::SetpointChangeAmount::Id: + return "SetpointChangeAmount"; + case chip::app::Clusters::Thermostat::Attributes::SetpointChangeSourceTimestamp::Id: + return "SetpointChangeSourceTimestamp"; + case chip::app::Clusters::Thermostat::Attributes::OccupiedSetback::Id: + return "OccupiedSetback"; + case chip::app::Clusters::Thermostat::Attributes::OccupiedSetbackMin::Id: + return "OccupiedSetbackMin"; + case chip::app::Clusters::Thermostat::Attributes::OccupiedSetbackMax::Id: + return "OccupiedSetbackMax"; + case chip::app::Clusters::Thermostat::Attributes::UnoccupiedSetback::Id: + return "UnoccupiedSetback"; + case chip::app::Clusters::Thermostat::Attributes::UnoccupiedSetbackMin::Id: + return "UnoccupiedSetbackMin"; + case chip::app::Clusters::Thermostat::Attributes::UnoccupiedSetbackMax::Id: + return "UnoccupiedSetbackMax"; + case chip::app::Clusters::Thermostat::Attributes::EmergencyHeatDelta::Id: + return "EmergencyHeatDelta"; + case chip::app::Clusters::Thermostat::Attributes::ACType::Id: + return "ACType"; + case chip::app::Clusters::Thermostat::Attributes::ACCapacity::Id: + return "ACCapacity"; + case chip::app::Clusters::Thermostat::Attributes::ACRefrigerantType::Id: + return "ACRefrigerantType"; + case chip::app::Clusters::Thermostat::Attributes::ACCompressorType::Id: + return "ACCompressorType"; + case chip::app::Clusters::Thermostat::Attributes::ACErrorCode::Id: + return "ACErrorCode"; + case chip::app::Clusters::Thermostat::Attributes::ACLouverPosition::Id: + return "ACLouverPosition"; + case chip::app::Clusters::Thermostat::Attributes::ACCoilTemperature::Id: + return "ACCoilTemperature"; + case chip::app::Clusters::Thermostat::Attributes::ACCapacityformat::Id: + return "ACCapacityformat"; + case chip::app::Clusters::Thermostat::Attributes::PresetTypes::Id: + return "PresetTypes"; + case chip::app::Clusters::Thermostat::Attributes::ScheduleTypes::Id: + return "ScheduleTypes"; + case chip::app::Clusters::Thermostat::Attributes::NumberOfPresets::Id: + return "NumberOfPresets"; + case chip::app::Clusters::Thermostat::Attributes::NumberOfSchedules::Id: + return "NumberOfSchedules"; + case chip::app::Clusters::Thermostat::Attributes::NumberOfScheduleTransitions::Id: + return "NumberOfScheduleTransitions"; + case chip::app::Clusters::Thermostat::Attributes::NumberOfScheduleTransitionPerDay::Id: + return "NumberOfScheduleTransitionPerDay"; + case chip::app::Clusters::Thermostat::Attributes::ActivePresetHandle::Id: + return "ActivePresetHandle"; + case chip::app::Clusters::Thermostat::Attributes::ActiveScheduleHandle::Id: + return "ActiveScheduleHandle"; + case chip::app::Clusters::Thermostat::Attributes::Presets::Id: + return "Presets"; + case chip::app::Clusters::Thermostat::Attributes::Schedules::Id: + return "Schedules"; + case chip::app::Clusters::Thermostat::Attributes::SetpointHoldExpiryTimestamp::Id: + return "SetpointHoldExpiryTimestamp"; + case chip::app::Clusters::Thermostat::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::Thermostat::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::Thermostat::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::Thermostat::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::Thermostat::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::Thermostat::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::FanControl::Id: { + switch (id) + { + case chip::app::Clusters::FanControl::Attributes::FanMode::Id: + return "FanMode"; + case chip::app::Clusters::FanControl::Attributes::FanModeSequence::Id: + return "FanModeSequence"; + case chip::app::Clusters::FanControl::Attributes::PercentSetting::Id: + return "PercentSetting"; + case chip::app::Clusters::FanControl::Attributes::PercentCurrent::Id: + return "PercentCurrent"; + case chip::app::Clusters::FanControl::Attributes::SpeedMax::Id: + return "SpeedMax"; + case chip::app::Clusters::FanControl::Attributes::SpeedSetting::Id: + return "SpeedSetting"; + case chip::app::Clusters::FanControl::Attributes::SpeedCurrent::Id: + return "SpeedCurrent"; + case chip::app::Clusters::FanControl::Attributes::RockSupport::Id: + return "RockSupport"; + case chip::app::Clusters::FanControl::Attributes::RockSetting::Id: + return "RockSetting"; + case chip::app::Clusters::FanControl::Attributes::WindSupport::Id: + return "WindSupport"; + case chip::app::Clusters::FanControl::Attributes::WindSetting::Id: + return "WindSetting"; + case chip::app::Clusters::FanControl::Attributes::AirflowDirection::Id: + return "AirflowDirection"; + case chip::app::Clusters::FanControl::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::FanControl::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::FanControl::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::FanControl::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::FanControl::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::FanControl::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::ThermostatUserInterfaceConfiguration::Id: { + switch (id) + { + case chip::app::Clusters::ThermostatUserInterfaceConfiguration::Attributes::TemperatureDisplayMode::Id: + return "TemperatureDisplayMode"; + case chip::app::Clusters::ThermostatUserInterfaceConfiguration::Attributes::KeypadLockout::Id: + return "KeypadLockout"; + case chip::app::Clusters::ThermostatUserInterfaceConfiguration::Attributes::ScheduleProgrammingVisibility::Id: + return "ScheduleProgrammingVisibility"; + case chip::app::Clusters::ThermostatUserInterfaceConfiguration::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::ThermostatUserInterfaceConfiguration::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::ThermostatUserInterfaceConfiguration::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::ThermostatUserInterfaceConfiguration::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::ThermostatUserInterfaceConfiguration::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::ThermostatUserInterfaceConfiguration::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::ColorControl::Id: { + switch (id) + { + case chip::app::Clusters::ColorControl::Attributes::CurrentHue::Id: + return "CurrentHue"; + case chip::app::Clusters::ColorControl::Attributes::CurrentSaturation::Id: + return "CurrentSaturation"; + case chip::app::Clusters::ColorControl::Attributes::RemainingTime::Id: + return "RemainingTime"; + case chip::app::Clusters::ColorControl::Attributes::CurrentX::Id: + return "CurrentX"; + case chip::app::Clusters::ColorControl::Attributes::CurrentY::Id: + return "CurrentY"; + case chip::app::Clusters::ColorControl::Attributes::DriftCompensation::Id: + return "DriftCompensation"; + case chip::app::Clusters::ColorControl::Attributes::CompensationText::Id: + return "CompensationText"; + case chip::app::Clusters::ColorControl::Attributes::ColorTemperatureMireds::Id: + return "ColorTemperatureMireds"; + case chip::app::Clusters::ColorControl::Attributes::ColorMode::Id: + return "ColorMode"; + case chip::app::Clusters::ColorControl::Attributes::Options::Id: + return "Options"; + case chip::app::Clusters::ColorControl::Attributes::NumberOfPrimaries::Id: + return "NumberOfPrimaries"; + case chip::app::Clusters::ColorControl::Attributes::Primary1X::Id: + return "Primary1X"; + case chip::app::Clusters::ColorControl::Attributes::Primary1Y::Id: + return "Primary1Y"; + case chip::app::Clusters::ColorControl::Attributes::Primary1Intensity::Id: + return "Primary1Intensity"; + case chip::app::Clusters::ColorControl::Attributes::Primary2X::Id: + return "Primary2X"; + case chip::app::Clusters::ColorControl::Attributes::Primary2Y::Id: + return "Primary2Y"; + case chip::app::Clusters::ColorControl::Attributes::Primary2Intensity::Id: + return "Primary2Intensity"; + case chip::app::Clusters::ColorControl::Attributes::Primary3X::Id: + return "Primary3X"; + case chip::app::Clusters::ColorControl::Attributes::Primary3Y::Id: + return "Primary3Y"; + case chip::app::Clusters::ColorControl::Attributes::Primary3Intensity::Id: + return "Primary3Intensity"; + case chip::app::Clusters::ColorControl::Attributes::Primary4X::Id: + return "Primary4X"; + case chip::app::Clusters::ColorControl::Attributes::Primary4Y::Id: + return "Primary4Y"; + case chip::app::Clusters::ColorControl::Attributes::Primary4Intensity::Id: + return "Primary4Intensity"; + case chip::app::Clusters::ColorControl::Attributes::Primary5X::Id: + return "Primary5X"; + case chip::app::Clusters::ColorControl::Attributes::Primary5Y::Id: + return "Primary5Y"; + case chip::app::Clusters::ColorControl::Attributes::Primary5Intensity::Id: + return "Primary5Intensity"; + case chip::app::Clusters::ColorControl::Attributes::Primary6X::Id: + return "Primary6X"; + case chip::app::Clusters::ColorControl::Attributes::Primary6Y::Id: + return "Primary6Y"; + case chip::app::Clusters::ColorControl::Attributes::Primary6Intensity::Id: + return "Primary6Intensity"; + case chip::app::Clusters::ColorControl::Attributes::WhitePointX::Id: + return "WhitePointX"; + case chip::app::Clusters::ColorControl::Attributes::WhitePointY::Id: + return "WhitePointY"; + case chip::app::Clusters::ColorControl::Attributes::ColorPointRX::Id: + return "ColorPointRX"; + case chip::app::Clusters::ColorControl::Attributes::ColorPointRY::Id: + return "ColorPointRY"; + case chip::app::Clusters::ColorControl::Attributes::ColorPointRIntensity::Id: + return "ColorPointRIntensity"; + case chip::app::Clusters::ColorControl::Attributes::ColorPointGX::Id: + return "ColorPointGX"; + case chip::app::Clusters::ColorControl::Attributes::ColorPointGY::Id: + return "ColorPointGY"; + case chip::app::Clusters::ColorControl::Attributes::ColorPointGIntensity::Id: + return "ColorPointGIntensity"; + case chip::app::Clusters::ColorControl::Attributes::ColorPointBX::Id: + return "ColorPointBX"; + case chip::app::Clusters::ColorControl::Attributes::ColorPointBY::Id: + return "ColorPointBY"; + case chip::app::Clusters::ColorControl::Attributes::ColorPointBIntensity::Id: + return "ColorPointBIntensity"; + case chip::app::Clusters::ColorControl::Attributes::EnhancedCurrentHue::Id: + return "EnhancedCurrentHue"; + case chip::app::Clusters::ColorControl::Attributes::EnhancedColorMode::Id: + return "EnhancedColorMode"; + case chip::app::Clusters::ColorControl::Attributes::ColorLoopActive::Id: + return "ColorLoopActive"; + case chip::app::Clusters::ColorControl::Attributes::ColorLoopDirection::Id: + return "ColorLoopDirection"; + case chip::app::Clusters::ColorControl::Attributes::ColorLoopTime::Id: + return "ColorLoopTime"; + case chip::app::Clusters::ColorControl::Attributes::ColorLoopStartEnhancedHue::Id: + return "ColorLoopStartEnhancedHue"; + case chip::app::Clusters::ColorControl::Attributes::ColorLoopStoredEnhancedHue::Id: + return "ColorLoopStoredEnhancedHue"; + case chip::app::Clusters::ColorControl::Attributes::ColorCapabilities::Id: + return "ColorCapabilities"; + case chip::app::Clusters::ColorControl::Attributes::ColorTempPhysicalMinMireds::Id: + return "ColorTempPhysicalMinMireds"; + case chip::app::Clusters::ColorControl::Attributes::ColorTempPhysicalMaxMireds::Id: + return "ColorTempPhysicalMaxMireds"; + case chip::app::Clusters::ColorControl::Attributes::CoupleColorTempToLevelMinMireds::Id: + return "CoupleColorTempToLevelMinMireds"; + case chip::app::Clusters::ColorControl::Attributes::StartUpColorTemperatureMireds::Id: + return "StartUpColorTemperatureMireds"; + case chip::app::Clusters::ColorControl::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::ColorControl::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::ColorControl::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::ColorControl::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::ColorControl::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::ColorControl::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::BallastConfiguration::Id: { + switch (id) + { + case chip::app::Clusters::BallastConfiguration::Attributes::PhysicalMinLevel::Id: + return "PhysicalMinLevel"; + case chip::app::Clusters::BallastConfiguration::Attributes::PhysicalMaxLevel::Id: + return "PhysicalMaxLevel"; + case chip::app::Clusters::BallastConfiguration::Attributes::BallastStatus::Id: + return "BallastStatus"; + case chip::app::Clusters::BallastConfiguration::Attributes::MinLevel::Id: + return "MinLevel"; + case chip::app::Clusters::BallastConfiguration::Attributes::MaxLevel::Id: + return "MaxLevel"; + case chip::app::Clusters::BallastConfiguration::Attributes::IntrinsicBallastFactor::Id: + return "IntrinsicBallastFactor"; + case chip::app::Clusters::BallastConfiguration::Attributes::BallastFactorAdjustment::Id: + return "BallastFactorAdjustment"; + case chip::app::Clusters::BallastConfiguration::Attributes::LampQuantity::Id: + return "LampQuantity"; + case chip::app::Clusters::BallastConfiguration::Attributes::LampType::Id: + return "LampType"; + case chip::app::Clusters::BallastConfiguration::Attributes::LampManufacturer::Id: + return "LampManufacturer"; + case chip::app::Clusters::BallastConfiguration::Attributes::LampRatedHours::Id: + return "LampRatedHours"; + case chip::app::Clusters::BallastConfiguration::Attributes::LampBurnHours::Id: + return "LampBurnHours"; + case chip::app::Clusters::BallastConfiguration::Attributes::LampAlarmMode::Id: + return "LampAlarmMode"; + case chip::app::Clusters::BallastConfiguration::Attributes::LampBurnHoursTripPoint::Id: + return "LampBurnHoursTripPoint"; + case chip::app::Clusters::BallastConfiguration::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::BallastConfiguration::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::BallastConfiguration::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::BallastConfiguration::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::BallastConfiguration::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::BallastConfiguration::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::IlluminanceMeasurement::Id: { + switch (id) + { + case chip::app::Clusters::IlluminanceMeasurement::Attributes::MeasuredValue::Id: + return "MeasuredValue"; + case chip::app::Clusters::IlluminanceMeasurement::Attributes::MinMeasuredValue::Id: + return "MinMeasuredValue"; + case chip::app::Clusters::IlluminanceMeasurement::Attributes::MaxMeasuredValue::Id: + return "MaxMeasuredValue"; + case chip::app::Clusters::IlluminanceMeasurement::Attributes::Tolerance::Id: + return "Tolerance"; + case chip::app::Clusters::IlluminanceMeasurement::Attributes::LightSensorType::Id: + return "LightSensorType"; + case chip::app::Clusters::IlluminanceMeasurement::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::IlluminanceMeasurement::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::IlluminanceMeasurement::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::IlluminanceMeasurement::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::IlluminanceMeasurement::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::IlluminanceMeasurement::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::TemperatureMeasurement::Id: { + switch (id) + { + case chip::app::Clusters::TemperatureMeasurement::Attributes::MeasuredValue::Id: + return "MeasuredValue"; + case chip::app::Clusters::TemperatureMeasurement::Attributes::MinMeasuredValue::Id: + return "MinMeasuredValue"; + case chip::app::Clusters::TemperatureMeasurement::Attributes::MaxMeasuredValue::Id: + return "MaxMeasuredValue"; + case chip::app::Clusters::TemperatureMeasurement::Attributes::Tolerance::Id: + return "Tolerance"; + case chip::app::Clusters::TemperatureMeasurement::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::TemperatureMeasurement::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::TemperatureMeasurement::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::TemperatureMeasurement::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::TemperatureMeasurement::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::TemperatureMeasurement::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::PressureMeasurement::Id: { + switch (id) + { + case chip::app::Clusters::PressureMeasurement::Attributes::MeasuredValue::Id: + return "MeasuredValue"; + case chip::app::Clusters::PressureMeasurement::Attributes::MinMeasuredValue::Id: + return "MinMeasuredValue"; + case chip::app::Clusters::PressureMeasurement::Attributes::MaxMeasuredValue::Id: + return "MaxMeasuredValue"; + case chip::app::Clusters::PressureMeasurement::Attributes::Tolerance::Id: + return "Tolerance"; + case chip::app::Clusters::PressureMeasurement::Attributes::ScaledValue::Id: + return "ScaledValue"; + case chip::app::Clusters::PressureMeasurement::Attributes::MinScaledValue::Id: + return "MinScaledValue"; + case chip::app::Clusters::PressureMeasurement::Attributes::MaxScaledValue::Id: + return "MaxScaledValue"; + case chip::app::Clusters::PressureMeasurement::Attributes::ScaledTolerance::Id: + return "ScaledTolerance"; + case chip::app::Clusters::PressureMeasurement::Attributes::Scale::Id: + return "Scale"; + case chip::app::Clusters::PressureMeasurement::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::PressureMeasurement::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::PressureMeasurement::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::PressureMeasurement::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::PressureMeasurement::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::PressureMeasurement::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::FlowMeasurement::Id: { + switch (id) + { + case chip::app::Clusters::FlowMeasurement::Attributes::MeasuredValue::Id: + return "MeasuredValue"; + case chip::app::Clusters::FlowMeasurement::Attributes::MinMeasuredValue::Id: + return "MinMeasuredValue"; + case chip::app::Clusters::FlowMeasurement::Attributes::MaxMeasuredValue::Id: + return "MaxMeasuredValue"; + case chip::app::Clusters::FlowMeasurement::Attributes::Tolerance::Id: + return "Tolerance"; + case chip::app::Clusters::FlowMeasurement::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::FlowMeasurement::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::FlowMeasurement::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::FlowMeasurement::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::FlowMeasurement::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::FlowMeasurement::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::RelativeHumidityMeasurement::Id: { + switch (id) + { + case chip::app::Clusters::RelativeHumidityMeasurement::Attributes::MeasuredValue::Id: + return "MeasuredValue"; + case chip::app::Clusters::RelativeHumidityMeasurement::Attributes::MinMeasuredValue::Id: + return "MinMeasuredValue"; + case chip::app::Clusters::RelativeHumidityMeasurement::Attributes::MaxMeasuredValue::Id: + return "MaxMeasuredValue"; + case chip::app::Clusters::RelativeHumidityMeasurement::Attributes::Tolerance::Id: + return "Tolerance"; + case chip::app::Clusters::RelativeHumidityMeasurement::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::RelativeHumidityMeasurement::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::RelativeHumidityMeasurement::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::RelativeHumidityMeasurement::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::RelativeHumidityMeasurement::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::RelativeHumidityMeasurement::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::OccupancySensing::Id: { + switch (id) + { + case chip::app::Clusters::OccupancySensing::Attributes::Occupancy::Id: + return "Occupancy"; + case chip::app::Clusters::OccupancySensing::Attributes::OccupancySensorType::Id: + return "OccupancySensorType"; + case chip::app::Clusters::OccupancySensing::Attributes::OccupancySensorTypeBitmap::Id: + return "OccupancySensorTypeBitmap"; + case chip::app::Clusters::OccupancySensing::Attributes::HoldTime::Id: + return "HoldTime"; + case chip::app::Clusters::OccupancySensing::Attributes::HoldTimeLimits::Id: + return "HoldTimeLimits"; + case chip::app::Clusters::OccupancySensing::Attributes::PIROccupiedToUnoccupiedDelay::Id: + return "PIROccupiedToUnoccupiedDelay"; + case chip::app::Clusters::OccupancySensing::Attributes::PIRUnoccupiedToOccupiedDelay::Id: + return "PIRUnoccupiedToOccupiedDelay"; + case chip::app::Clusters::OccupancySensing::Attributes::PIRUnoccupiedToOccupiedThreshold::Id: + return "PIRUnoccupiedToOccupiedThreshold"; + case chip::app::Clusters::OccupancySensing::Attributes::UltrasonicOccupiedToUnoccupiedDelay::Id: + return "UltrasonicOccupiedToUnoccupiedDelay"; + case chip::app::Clusters::OccupancySensing::Attributes::UltrasonicUnoccupiedToOccupiedDelay::Id: + return "UltrasonicUnoccupiedToOccupiedDelay"; + case chip::app::Clusters::OccupancySensing::Attributes::UltrasonicUnoccupiedToOccupiedThreshold::Id: + return "UltrasonicUnoccupiedToOccupiedThreshold"; + case chip::app::Clusters::OccupancySensing::Attributes::PhysicalContactOccupiedToUnoccupiedDelay::Id: + return "PhysicalContactOccupiedToUnoccupiedDelay"; + case chip::app::Clusters::OccupancySensing::Attributes::PhysicalContactUnoccupiedToOccupiedDelay::Id: + return "PhysicalContactUnoccupiedToOccupiedDelay"; + case chip::app::Clusters::OccupancySensing::Attributes::PhysicalContactUnoccupiedToOccupiedThreshold::Id: + return "PhysicalContactUnoccupiedToOccupiedThreshold"; + case chip::app::Clusters::OccupancySensing::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::OccupancySensing::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::OccupancySensing::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::OccupancySensing::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::OccupancySensing::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::OccupancySensing::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::CarbonMonoxideConcentrationMeasurement::Id: { + switch (id) + { + case chip::app::Clusters::CarbonMonoxideConcentrationMeasurement::Attributes::MeasuredValue::Id: + return "MeasuredValue"; + case chip::app::Clusters::CarbonMonoxideConcentrationMeasurement::Attributes::MinMeasuredValue::Id: + return "MinMeasuredValue"; + case chip::app::Clusters::CarbonMonoxideConcentrationMeasurement::Attributes::MaxMeasuredValue::Id: + return "MaxMeasuredValue"; + case chip::app::Clusters::CarbonMonoxideConcentrationMeasurement::Attributes::PeakMeasuredValue::Id: + return "PeakMeasuredValue"; + case chip::app::Clusters::CarbonMonoxideConcentrationMeasurement::Attributes::PeakMeasuredValueWindow::Id: + return "PeakMeasuredValueWindow"; + case chip::app::Clusters::CarbonMonoxideConcentrationMeasurement::Attributes::AverageMeasuredValue::Id: + return "AverageMeasuredValue"; + case chip::app::Clusters::CarbonMonoxideConcentrationMeasurement::Attributes::AverageMeasuredValueWindow::Id: + return "AverageMeasuredValueWindow"; + case chip::app::Clusters::CarbonMonoxideConcentrationMeasurement::Attributes::Uncertainty::Id: + return "Uncertainty"; + case chip::app::Clusters::CarbonMonoxideConcentrationMeasurement::Attributes::MeasurementUnit::Id: + return "MeasurementUnit"; + case chip::app::Clusters::CarbonMonoxideConcentrationMeasurement::Attributes::MeasurementMedium::Id: + return "MeasurementMedium"; + case chip::app::Clusters::CarbonMonoxideConcentrationMeasurement::Attributes::LevelValue::Id: + return "LevelValue"; + case chip::app::Clusters::CarbonMonoxideConcentrationMeasurement::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::CarbonMonoxideConcentrationMeasurement::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::CarbonMonoxideConcentrationMeasurement::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::CarbonMonoxideConcentrationMeasurement::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::CarbonMonoxideConcentrationMeasurement::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::CarbonMonoxideConcentrationMeasurement::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::CarbonDioxideConcentrationMeasurement::Id: { + switch (id) + { + case chip::app::Clusters::CarbonDioxideConcentrationMeasurement::Attributes::MeasuredValue::Id: + return "MeasuredValue"; + case chip::app::Clusters::CarbonDioxideConcentrationMeasurement::Attributes::MinMeasuredValue::Id: + return "MinMeasuredValue"; + case chip::app::Clusters::CarbonDioxideConcentrationMeasurement::Attributes::MaxMeasuredValue::Id: + return "MaxMeasuredValue"; + case chip::app::Clusters::CarbonDioxideConcentrationMeasurement::Attributes::PeakMeasuredValue::Id: + return "PeakMeasuredValue"; + case chip::app::Clusters::CarbonDioxideConcentrationMeasurement::Attributes::PeakMeasuredValueWindow::Id: + return "PeakMeasuredValueWindow"; + case chip::app::Clusters::CarbonDioxideConcentrationMeasurement::Attributes::AverageMeasuredValue::Id: + return "AverageMeasuredValue"; + case chip::app::Clusters::CarbonDioxideConcentrationMeasurement::Attributes::AverageMeasuredValueWindow::Id: + return "AverageMeasuredValueWindow"; + case chip::app::Clusters::CarbonDioxideConcentrationMeasurement::Attributes::Uncertainty::Id: + return "Uncertainty"; + case chip::app::Clusters::CarbonDioxideConcentrationMeasurement::Attributes::MeasurementUnit::Id: + return "MeasurementUnit"; + case chip::app::Clusters::CarbonDioxideConcentrationMeasurement::Attributes::MeasurementMedium::Id: + return "MeasurementMedium"; + case chip::app::Clusters::CarbonDioxideConcentrationMeasurement::Attributes::LevelValue::Id: + return "LevelValue"; + case chip::app::Clusters::CarbonDioxideConcentrationMeasurement::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::CarbonDioxideConcentrationMeasurement::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::CarbonDioxideConcentrationMeasurement::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::CarbonDioxideConcentrationMeasurement::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::CarbonDioxideConcentrationMeasurement::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::CarbonDioxideConcentrationMeasurement::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::NitrogenDioxideConcentrationMeasurement::Id: { + switch (id) + { + case chip::app::Clusters::NitrogenDioxideConcentrationMeasurement::Attributes::MeasuredValue::Id: + return "MeasuredValue"; + case chip::app::Clusters::NitrogenDioxideConcentrationMeasurement::Attributes::MinMeasuredValue::Id: + return "MinMeasuredValue"; + case chip::app::Clusters::NitrogenDioxideConcentrationMeasurement::Attributes::MaxMeasuredValue::Id: + return "MaxMeasuredValue"; + case chip::app::Clusters::NitrogenDioxideConcentrationMeasurement::Attributes::PeakMeasuredValue::Id: + return "PeakMeasuredValue"; + case chip::app::Clusters::NitrogenDioxideConcentrationMeasurement::Attributes::PeakMeasuredValueWindow::Id: + return "PeakMeasuredValueWindow"; + case chip::app::Clusters::NitrogenDioxideConcentrationMeasurement::Attributes::AverageMeasuredValue::Id: + return "AverageMeasuredValue"; + case chip::app::Clusters::NitrogenDioxideConcentrationMeasurement::Attributes::AverageMeasuredValueWindow::Id: + return "AverageMeasuredValueWindow"; + case chip::app::Clusters::NitrogenDioxideConcentrationMeasurement::Attributes::Uncertainty::Id: + return "Uncertainty"; + case chip::app::Clusters::NitrogenDioxideConcentrationMeasurement::Attributes::MeasurementUnit::Id: + return "MeasurementUnit"; + case chip::app::Clusters::NitrogenDioxideConcentrationMeasurement::Attributes::MeasurementMedium::Id: + return "MeasurementMedium"; + case chip::app::Clusters::NitrogenDioxideConcentrationMeasurement::Attributes::LevelValue::Id: + return "LevelValue"; + case chip::app::Clusters::NitrogenDioxideConcentrationMeasurement::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::NitrogenDioxideConcentrationMeasurement::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::NitrogenDioxideConcentrationMeasurement::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::NitrogenDioxideConcentrationMeasurement::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::NitrogenDioxideConcentrationMeasurement::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::NitrogenDioxideConcentrationMeasurement::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::OzoneConcentrationMeasurement::Id: { + switch (id) + { + case chip::app::Clusters::OzoneConcentrationMeasurement::Attributes::MeasuredValue::Id: + return "MeasuredValue"; + case chip::app::Clusters::OzoneConcentrationMeasurement::Attributes::MinMeasuredValue::Id: + return "MinMeasuredValue"; + case chip::app::Clusters::OzoneConcentrationMeasurement::Attributes::MaxMeasuredValue::Id: + return "MaxMeasuredValue"; + case chip::app::Clusters::OzoneConcentrationMeasurement::Attributes::PeakMeasuredValue::Id: + return "PeakMeasuredValue"; + case chip::app::Clusters::OzoneConcentrationMeasurement::Attributes::PeakMeasuredValueWindow::Id: + return "PeakMeasuredValueWindow"; + case chip::app::Clusters::OzoneConcentrationMeasurement::Attributes::AverageMeasuredValue::Id: + return "AverageMeasuredValue"; + case chip::app::Clusters::OzoneConcentrationMeasurement::Attributes::AverageMeasuredValueWindow::Id: + return "AverageMeasuredValueWindow"; + case chip::app::Clusters::OzoneConcentrationMeasurement::Attributes::Uncertainty::Id: + return "Uncertainty"; + case chip::app::Clusters::OzoneConcentrationMeasurement::Attributes::MeasurementUnit::Id: + return "MeasurementUnit"; + case chip::app::Clusters::OzoneConcentrationMeasurement::Attributes::MeasurementMedium::Id: + return "MeasurementMedium"; + case chip::app::Clusters::OzoneConcentrationMeasurement::Attributes::LevelValue::Id: + return "LevelValue"; + case chip::app::Clusters::OzoneConcentrationMeasurement::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::OzoneConcentrationMeasurement::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::OzoneConcentrationMeasurement::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::OzoneConcentrationMeasurement::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::OzoneConcentrationMeasurement::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::OzoneConcentrationMeasurement::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::Pm25ConcentrationMeasurement::Id: { + switch (id) + { + case chip::app::Clusters::Pm25ConcentrationMeasurement::Attributes::MeasuredValue::Id: + return "MeasuredValue"; + case chip::app::Clusters::Pm25ConcentrationMeasurement::Attributes::MinMeasuredValue::Id: + return "MinMeasuredValue"; + case chip::app::Clusters::Pm25ConcentrationMeasurement::Attributes::MaxMeasuredValue::Id: + return "MaxMeasuredValue"; + case chip::app::Clusters::Pm25ConcentrationMeasurement::Attributes::PeakMeasuredValue::Id: + return "PeakMeasuredValue"; + case chip::app::Clusters::Pm25ConcentrationMeasurement::Attributes::PeakMeasuredValueWindow::Id: + return "PeakMeasuredValueWindow"; + case chip::app::Clusters::Pm25ConcentrationMeasurement::Attributes::AverageMeasuredValue::Id: + return "AverageMeasuredValue"; + case chip::app::Clusters::Pm25ConcentrationMeasurement::Attributes::AverageMeasuredValueWindow::Id: + return "AverageMeasuredValueWindow"; + case chip::app::Clusters::Pm25ConcentrationMeasurement::Attributes::Uncertainty::Id: + return "Uncertainty"; + case chip::app::Clusters::Pm25ConcentrationMeasurement::Attributes::MeasurementUnit::Id: + return "MeasurementUnit"; + case chip::app::Clusters::Pm25ConcentrationMeasurement::Attributes::MeasurementMedium::Id: + return "MeasurementMedium"; + case chip::app::Clusters::Pm25ConcentrationMeasurement::Attributes::LevelValue::Id: + return "LevelValue"; + case chip::app::Clusters::Pm25ConcentrationMeasurement::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::Pm25ConcentrationMeasurement::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::Pm25ConcentrationMeasurement::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::Pm25ConcentrationMeasurement::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::Pm25ConcentrationMeasurement::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::Pm25ConcentrationMeasurement::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::FormaldehydeConcentrationMeasurement::Id: { + switch (id) + { + case chip::app::Clusters::FormaldehydeConcentrationMeasurement::Attributes::MeasuredValue::Id: + return "MeasuredValue"; + case chip::app::Clusters::FormaldehydeConcentrationMeasurement::Attributes::MinMeasuredValue::Id: + return "MinMeasuredValue"; + case chip::app::Clusters::FormaldehydeConcentrationMeasurement::Attributes::MaxMeasuredValue::Id: + return "MaxMeasuredValue"; + case chip::app::Clusters::FormaldehydeConcentrationMeasurement::Attributes::PeakMeasuredValue::Id: + return "PeakMeasuredValue"; + case chip::app::Clusters::FormaldehydeConcentrationMeasurement::Attributes::PeakMeasuredValueWindow::Id: + return "PeakMeasuredValueWindow"; + case chip::app::Clusters::FormaldehydeConcentrationMeasurement::Attributes::AverageMeasuredValue::Id: + return "AverageMeasuredValue"; + case chip::app::Clusters::FormaldehydeConcentrationMeasurement::Attributes::AverageMeasuredValueWindow::Id: + return "AverageMeasuredValueWindow"; + case chip::app::Clusters::FormaldehydeConcentrationMeasurement::Attributes::Uncertainty::Id: + return "Uncertainty"; + case chip::app::Clusters::FormaldehydeConcentrationMeasurement::Attributes::MeasurementUnit::Id: + return "MeasurementUnit"; + case chip::app::Clusters::FormaldehydeConcentrationMeasurement::Attributes::MeasurementMedium::Id: + return "MeasurementMedium"; + case chip::app::Clusters::FormaldehydeConcentrationMeasurement::Attributes::LevelValue::Id: + return "LevelValue"; + case chip::app::Clusters::FormaldehydeConcentrationMeasurement::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::FormaldehydeConcentrationMeasurement::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::FormaldehydeConcentrationMeasurement::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::FormaldehydeConcentrationMeasurement::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::FormaldehydeConcentrationMeasurement::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::FormaldehydeConcentrationMeasurement::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::Pm1ConcentrationMeasurement::Id: { + switch (id) + { + case chip::app::Clusters::Pm1ConcentrationMeasurement::Attributes::MeasuredValue::Id: + return "MeasuredValue"; + case chip::app::Clusters::Pm1ConcentrationMeasurement::Attributes::MinMeasuredValue::Id: + return "MinMeasuredValue"; + case chip::app::Clusters::Pm1ConcentrationMeasurement::Attributes::MaxMeasuredValue::Id: + return "MaxMeasuredValue"; + case chip::app::Clusters::Pm1ConcentrationMeasurement::Attributes::PeakMeasuredValue::Id: + return "PeakMeasuredValue"; + case chip::app::Clusters::Pm1ConcentrationMeasurement::Attributes::PeakMeasuredValueWindow::Id: + return "PeakMeasuredValueWindow"; + case chip::app::Clusters::Pm1ConcentrationMeasurement::Attributes::AverageMeasuredValue::Id: + return "AverageMeasuredValue"; + case chip::app::Clusters::Pm1ConcentrationMeasurement::Attributes::AverageMeasuredValueWindow::Id: + return "AverageMeasuredValueWindow"; + case chip::app::Clusters::Pm1ConcentrationMeasurement::Attributes::Uncertainty::Id: + return "Uncertainty"; + case chip::app::Clusters::Pm1ConcentrationMeasurement::Attributes::MeasurementUnit::Id: + return "MeasurementUnit"; + case chip::app::Clusters::Pm1ConcentrationMeasurement::Attributes::MeasurementMedium::Id: + return "MeasurementMedium"; + case chip::app::Clusters::Pm1ConcentrationMeasurement::Attributes::LevelValue::Id: + return "LevelValue"; + case chip::app::Clusters::Pm1ConcentrationMeasurement::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::Pm1ConcentrationMeasurement::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::Pm1ConcentrationMeasurement::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::Pm1ConcentrationMeasurement::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::Pm1ConcentrationMeasurement::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::Pm1ConcentrationMeasurement::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::Pm10ConcentrationMeasurement::Id: { + switch (id) + { + case chip::app::Clusters::Pm10ConcentrationMeasurement::Attributes::MeasuredValue::Id: + return "MeasuredValue"; + case chip::app::Clusters::Pm10ConcentrationMeasurement::Attributes::MinMeasuredValue::Id: + return "MinMeasuredValue"; + case chip::app::Clusters::Pm10ConcentrationMeasurement::Attributes::MaxMeasuredValue::Id: + return "MaxMeasuredValue"; + case chip::app::Clusters::Pm10ConcentrationMeasurement::Attributes::PeakMeasuredValue::Id: + return "PeakMeasuredValue"; + case chip::app::Clusters::Pm10ConcentrationMeasurement::Attributes::PeakMeasuredValueWindow::Id: + return "PeakMeasuredValueWindow"; + case chip::app::Clusters::Pm10ConcentrationMeasurement::Attributes::AverageMeasuredValue::Id: + return "AverageMeasuredValue"; + case chip::app::Clusters::Pm10ConcentrationMeasurement::Attributes::AverageMeasuredValueWindow::Id: + return "AverageMeasuredValueWindow"; + case chip::app::Clusters::Pm10ConcentrationMeasurement::Attributes::Uncertainty::Id: + return "Uncertainty"; + case chip::app::Clusters::Pm10ConcentrationMeasurement::Attributes::MeasurementUnit::Id: + return "MeasurementUnit"; + case chip::app::Clusters::Pm10ConcentrationMeasurement::Attributes::MeasurementMedium::Id: + return "MeasurementMedium"; + case chip::app::Clusters::Pm10ConcentrationMeasurement::Attributes::LevelValue::Id: + return "LevelValue"; + case chip::app::Clusters::Pm10ConcentrationMeasurement::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::Pm10ConcentrationMeasurement::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::Pm10ConcentrationMeasurement::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::Pm10ConcentrationMeasurement::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::Pm10ConcentrationMeasurement::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::Pm10ConcentrationMeasurement::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::TotalVolatileOrganicCompoundsConcentrationMeasurement::Id: { + switch (id) + { + case chip::app::Clusters::TotalVolatileOrganicCompoundsConcentrationMeasurement::Attributes::MeasuredValue::Id: + return "MeasuredValue"; + case chip::app::Clusters::TotalVolatileOrganicCompoundsConcentrationMeasurement::Attributes::MinMeasuredValue::Id: + return "MinMeasuredValue"; + case chip::app::Clusters::TotalVolatileOrganicCompoundsConcentrationMeasurement::Attributes::MaxMeasuredValue::Id: + return "MaxMeasuredValue"; + case chip::app::Clusters::TotalVolatileOrganicCompoundsConcentrationMeasurement::Attributes::PeakMeasuredValue::Id: + return "PeakMeasuredValue"; + case chip::app::Clusters::TotalVolatileOrganicCompoundsConcentrationMeasurement::Attributes::PeakMeasuredValueWindow::Id: + return "PeakMeasuredValueWindow"; + case chip::app::Clusters::TotalVolatileOrganicCompoundsConcentrationMeasurement::Attributes::AverageMeasuredValue::Id: + return "AverageMeasuredValue"; + case chip::app::Clusters::TotalVolatileOrganicCompoundsConcentrationMeasurement::Attributes::AverageMeasuredValueWindow::Id: + return "AverageMeasuredValueWindow"; + case chip::app::Clusters::TotalVolatileOrganicCompoundsConcentrationMeasurement::Attributes::Uncertainty::Id: + return "Uncertainty"; + case chip::app::Clusters::TotalVolatileOrganicCompoundsConcentrationMeasurement::Attributes::MeasurementUnit::Id: + return "MeasurementUnit"; + case chip::app::Clusters::TotalVolatileOrganicCompoundsConcentrationMeasurement::Attributes::MeasurementMedium::Id: + return "MeasurementMedium"; + case chip::app::Clusters::TotalVolatileOrganicCompoundsConcentrationMeasurement::Attributes::LevelValue::Id: + return "LevelValue"; + case chip::app::Clusters::TotalVolatileOrganicCompoundsConcentrationMeasurement::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::TotalVolatileOrganicCompoundsConcentrationMeasurement::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::TotalVolatileOrganicCompoundsConcentrationMeasurement::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::TotalVolatileOrganicCompoundsConcentrationMeasurement::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::TotalVolatileOrganicCompoundsConcentrationMeasurement::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::TotalVolatileOrganicCompoundsConcentrationMeasurement::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::RadonConcentrationMeasurement::Id: { + switch (id) + { + case chip::app::Clusters::RadonConcentrationMeasurement::Attributes::MeasuredValue::Id: + return "MeasuredValue"; + case chip::app::Clusters::RadonConcentrationMeasurement::Attributes::MinMeasuredValue::Id: + return "MinMeasuredValue"; + case chip::app::Clusters::RadonConcentrationMeasurement::Attributes::MaxMeasuredValue::Id: + return "MaxMeasuredValue"; + case chip::app::Clusters::RadonConcentrationMeasurement::Attributes::PeakMeasuredValue::Id: + return "PeakMeasuredValue"; + case chip::app::Clusters::RadonConcentrationMeasurement::Attributes::PeakMeasuredValueWindow::Id: + return "PeakMeasuredValueWindow"; + case chip::app::Clusters::RadonConcentrationMeasurement::Attributes::AverageMeasuredValue::Id: + return "AverageMeasuredValue"; + case chip::app::Clusters::RadonConcentrationMeasurement::Attributes::AverageMeasuredValueWindow::Id: + return "AverageMeasuredValueWindow"; + case chip::app::Clusters::RadonConcentrationMeasurement::Attributes::Uncertainty::Id: + return "Uncertainty"; + case chip::app::Clusters::RadonConcentrationMeasurement::Attributes::MeasurementUnit::Id: + return "MeasurementUnit"; + case chip::app::Clusters::RadonConcentrationMeasurement::Attributes::MeasurementMedium::Id: + return "MeasurementMedium"; + case chip::app::Clusters::RadonConcentrationMeasurement::Attributes::LevelValue::Id: + return "LevelValue"; + case chip::app::Clusters::RadonConcentrationMeasurement::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::RadonConcentrationMeasurement::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::RadonConcentrationMeasurement::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::RadonConcentrationMeasurement::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::RadonConcentrationMeasurement::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::RadonConcentrationMeasurement::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::WiFiNetworkManagement::Id: { + switch (id) + { + case chip::app::Clusters::WiFiNetworkManagement::Attributes::Ssid::Id: + return "Ssid"; + case chip::app::Clusters::WiFiNetworkManagement::Attributes::PassphraseSurrogate::Id: + return "PassphraseSurrogate"; + case chip::app::Clusters::WiFiNetworkManagement::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::WiFiNetworkManagement::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::WiFiNetworkManagement::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::WiFiNetworkManagement::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::WiFiNetworkManagement::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::WiFiNetworkManagement::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::ThreadBorderRouterManagement::Id: { + switch (id) + { + case chip::app::Clusters::ThreadBorderRouterManagement::Attributes::BorderRouterName::Id: + return "BorderRouterName"; + case chip::app::Clusters::ThreadBorderRouterManagement::Attributes::BorderAgentID::Id: + return "BorderAgentID"; + case chip::app::Clusters::ThreadBorderRouterManagement::Attributes::ThreadVersion::Id: + return "ThreadVersion"; + case chip::app::Clusters::ThreadBorderRouterManagement::Attributes::InterfaceEnabled::Id: + return "InterfaceEnabled"; + case chip::app::Clusters::ThreadBorderRouterManagement::Attributes::ActiveDatasetTimestamp::Id: + return "ActiveDatasetTimestamp"; + case chip::app::Clusters::ThreadBorderRouterManagement::Attributes::PendingDatasetTimestamp::Id: + return "PendingDatasetTimestamp"; + case chip::app::Clusters::ThreadBorderRouterManagement::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::ThreadBorderRouterManagement::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::ThreadBorderRouterManagement::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::ThreadBorderRouterManagement::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::ThreadBorderRouterManagement::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::ThreadBorderRouterManagement::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::ThreadNetworkDirectory::Id: { + switch (id) + { + case chip::app::Clusters::ThreadNetworkDirectory::Attributes::PreferredExtendedPanID::Id: + return "PreferredExtendedPanID"; + case chip::app::Clusters::ThreadNetworkDirectory::Attributes::ThreadNetworks::Id: + return "ThreadNetworks"; + case chip::app::Clusters::ThreadNetworkDirectory::Attributes::ThreadNetworkTableSize::Id: + return "ThreadNetworkTableSize"; + case chip::app::Clusters::ThreadNetworkDirectory::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::ThreadNetworkDirectory::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::ThreadNetworkDirectory::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::ThreadNetworkDirectory::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::ThreadNetworkDirectory::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::ThreadNetworkDirectory::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::WakeOnLan::Id: { + switch (id) + { + case chip::app::Clusters::WakeOnLan::Attributes::MACAddress::Id: + return "MACAddress"; + case chip::app::Clusters::WakeOnLan::Attributes::LinkLocalAddress::Id: + return "LinkLocalAddress"; + case chip::app::Clusters::WakeOnLan::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::WakeOnLan::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::WakeOnLan::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::WakeOnLan::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::WakeOnLan::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::WakeOnLan::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::Channel::Id: { + switch (id) + { + case chip::app::Clusters::Channel::Attributes::ChannelList::Id: + return "ChannelList"; + case chip::app::Clusters::Channel::Attributes::Lineup::Id: + return "Lineup"; + case chip::app::Clusters::Channel::Attributes::CurrentChannel::Id: + return "CurrentChannel"; + case chip::app::Clusters::Channel::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::Channel::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::Channel::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::Channel::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::Channel::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::Channel::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::TargetNavigator::Id: { + switch (id) + { + case chip::app::Clusters::TargetNavigator::Attributes::TargetList::Id: + return "TargetList"; + case chip::app::Clusters::TargetNavigator::Attributes::CurrentTarget::Id: + return "CurrentTarget"; + case chip::app::Clusters::TargetNavigator::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::TargetNavigator::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::TargetNavigator::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::TargetNavigator::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::TargetNavigator::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::TargetNavigator::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::MediaPlayback::Id: { + switch (id) + { + case chip::app::Clusters::MediaPlayback::Attributes::CurrentState::Id: + return "CurrentState"; + case chip::app::Clusters::MediaPlayback::Attributes::StartTime::Id: + return "StartTime"; + case chip::app::Clusters::MediaPlayback::Attributes::Duration::Id: + return "Duration"; + case chip::app::Clusters::MediaPlayback::Attributes::SampledPosition::Id: + return "SampledPosition"; + case chip::app::Clusters::MediaPlayback::Attributes::PlaybackSpeed::Id: + return "PlaybackSpeed"; + case chip::app::Clusters::MediaPlayback::Attributes::SeekRangeEnd::Id: + return "SeekRangeEnd"; + case chip::app::Clusters::MediaPlayback::Attributes::SeekRangeStart::Id: + return "SeekRangeStart"; + case chip::app::Clusters::MediaPlayback::Attributes::ActiveAudioTrack::Id: + return "ActiveAudioTrack"; + case chip::app::Clusters::MediaPlayback::Attributes::AvailableAudioTracks::Id: + return "AvailableAudioTracks"; + case chip::app::Clusters::MediaPlayback::Attributes::ActiveTextTrack::Id: + return "ActiveTextTrack"; + case chip::app::Clusters::MediaPlayback::Attributes::AvailableTextTracks::Id: + return "AvailableTextTracks"; + case chip::app::Clusters::MediaPlayback::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::MediaPlayback::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::MediaPlayback::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::MediaPlayback::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::MediaPlayback::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::MediaPlayback::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::MediaInput::Id: { + switch (id) + { + case chip::app::Clusters::MediaInput::Attributes::InputList::Id: + return "InputList"; + case chip::app::Clusters::MediaInput::Attributes::CurrentInput::Id: + return "CurrentInput"; + case chip::app::Clusters::MediaInput::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::MediaInput::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::MediaInput::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::MediaInput::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::MediaInput::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::MediaInput::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::LowPower::Id: { + switch (id) + { + case chip::app::Clusters::LowPower::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::LowPower::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::LowPower::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::LowPower::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::LowPower::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::LowPower::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::KeypadInput::Id: { + switch (id) + { + case chip::app::Clusters::KeypadInput::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::KeypadInput::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::KeypadInput::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::KeypadInput::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::KeypadInput::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::KeypadInput::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::ContentLauncher::Id: { + switch (id) + { + case chip::app::Clusters::ContentLauncher::Attributes::AcceptHeader::Id: + return "AcceptHeader"; + case chip::app::Clusters::ContentLauncher::Attributes::SupportedStreamingProtocols::Id: + return "SupportedStreamingProtocols"; + case chip::app::Clusters::ContentLauncher::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::ContentLauncher::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::ContentLauncher::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::ContentLauncher::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::ContentLauncher::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::ContentLauncher::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::AudioOutput::Id: { + switch (id) + { + case chip::app::Clusters::AudioOutput::Attributes::OutputList::Id: + return "OutputList"; + case chip::app::Clusters::AudioOutput::Attributes::CurrentOutput::Id: + return "CurrentOutput"; + case chip::app::Clusters::AudioOutput::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::AudioOutput::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::AudioOutput::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::AudioOutput::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::AudioOutput::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::AudioOutput::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::ApplicationLauncher::Id: { + switch (id) + { + case chip::app::Clusters::ApplicationLauncher::Attributes::CatalogList::Id: + return "CatalogList"; + case chip::app::Clusters::ApplicationLauncher::Attributes::CurrentApp::Id: + return "CurrentApp"; + case chip::app::Clusters::ApplicationLauncher::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::ApplicationLauncher::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::ApplicationLauncher::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::ApplicationLauncher::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::ApplicationLauncher::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::ApplicationLauncher::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::ApplicationBasic::Id: { + switch (id) + { + case chip::app::Clusters::ApplicationBasic::Attributes::VendorName::Id: + return "VendorName"; + case chip::app::Clusters::ApplicationBasic::Attributes::VendorID::Id: + return "VendorID"; + case chip::app::Clusters::ApplicationBasic::Attributes::ApplicationName::Id: + return "ApplicationName"; + case chip::app::Clusters::ApplicationBasic::Attributes::ProductID::Id: + return "ProductID"; + case chip::app::Clusters::ApplicationBasic::Attributes::Application::Id: + return "Application"; + case chip::app::Clusters::ApplicationBasic::Attributes::Status::Id: + return "Status"; + case chip::app::Clusters::ApplicationBasic::Attributes::ApplicationVersion::Id: + return "ApplicationVersion"; + case chip::app::Clusters::ApplicationBasic::Attributes::AllowedVendorList::Id: + return "AllowedVendorList"; + case chip::app::Clusters::ApplicationBasic::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::ApplicationBasic::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::ApplicationBasic::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::ApplicationBasic::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::ApplicationBasic::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::ApplicationBasic::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::AccountLogin::Id: { + switch (id) + { + case chip::app::Clusters::AccountLogin::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::AccountLogin::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::AccountLogin::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::AccountLogin::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::AccountLogin::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::AccountLogin::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::ContentControl::Id: { + switch (id) + { + case chip::app::Clusters::ContentControl::Attributes::Enabled::Id: + return "Enabled"; + case chip::app::Clusters::ContentControl::Attributes::OnDemandRatings::Id: + return "OnDemandRatings"; + case chip::app::Clusters::ContentControl::Attributes::OnDemandRatingThreshold::Id: + return "OnDemandRatingThreshold"; + case chip::app::Clusters::ContentControl::Attributes::ScheduledContentRatings::Id: + return "ScheduledContentRatings"; + case chip::app::Clusters::ContentControl::Attributes::ScheduledContentRatingThreshold::Id: + return "ScheduledContentRatingThreshold"; + case chip::app::Clusters::ContentControl::Attributes::ScreenDailyTime::Id: + return "ScreenDailyTime"; + case chip::app::Clusters::ContentControl::Attributes::RemainingScreenTime::Id: + return "RemainingScreenTime"; + case chip::app::Clusters::ContentControl::Attributes::BlockUnrated::Id: + return "BlockUnrated"; + case chip::app::Clusters::ContentControl::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::ContentControl::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::ContentControl::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::ContentControl::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::ContentControl::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::ContentControl::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::ContentAppObserver::Id: { + switch (id) + { + case chip::app::Clusters::ContentAppObserver::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::ContentAppObserver::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::ContentAppObserver::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::ContentAppObserver::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::ContentAppObserver::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::ContentAppObserver::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::EcosystemInformation::Id: { + switch (id) + { + case chip::app::Clusters::EcosystemInformation::Attributes::RemovedOn::Id: + return "RemovedOn"; + case chip::app::Clusters::EcosystemInformation::Attributes::DeviceDirectory::Id: + return "DeviceDirectory"; + case chip::app::Clusters::EcosystemInformation::Attributes::LocationDirectory::Id: + return "LocationDirectory"; + case chip::app::Clusters::EcosystemInformation::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::EcosystemInformation::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::EcosystemInformation::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::EcosystemInformation::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::EcosystemInformation::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::EcosystemInformation::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::CommissionerControl::Id: { + switch (id) + { + case chip::app::Clusters::CommissionerControl::Attributes::SupportedDeviceCategories::Id: + return "SupportedDeviceCategories"; + case chip::app::Clusters::CommissionerControl::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::CommissionerControl::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::CommissionerControl::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::CommissionerControl::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::CommissionerControl::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::CommissionerControl::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::ElectricalMeasurement::Id: { + switch (id) + { + case chip::app::Clusters::ElectricalMeasurement::Attributes::MeasurementType::Id: + return "MeasurementType"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::DcVoltage::Id: + return "DcVoltage"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::DcVoltageMin::Id: + return "DcVoltageMin"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::DcVoltageMax::Id: + return "DcVoltageMax"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::DcCurrent::Id: + return "DcCurrent"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::DcCurrentMin::Id: + return "DcCurrentMin"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::DcCurrentMax::Id: + return "DcCurrentMax"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::DcPower::Id: + return "DcPower"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::DcPowerMin::Id: + return "DcPowerMin"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::DcPowerMax::Id: + return "DcPowerMax"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::DcVoltageMultiplier::Id: + return "DcVoltageMultiplier"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::DcVoltageDivisor::Id: + return "DcVoltageDivisor"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::DcCurrentMultiplier::Id: + return "DcCurrentMultiplier"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::DcCurrentDivisor::Id: + return "DcCurrentDivisor"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::DcPowerMultiplier::Id: + return "DcPowerMultiplier"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::DcPowerDivisor::Id: + return "DcPowerDivisor"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::AcFrequency::Id: + return "AcFrequency"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::AcFrequencyMin::Id: + return "AcFrequencyMin"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::AcFrequencyMax::Id: + return "AcFrequencyMax"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::NeutralCurrent::Id: + return "NeutralCurrent"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::TotalActivePower::Id: + return "TotalActivePower"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::TotalReactivePower::Id: + return "TotalReactivePower"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::TotalApparentPower::Id: + return "TotalApparentPower"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::Measured1stHarmonicCurrent::Id: + return "Measured1stHarmonicCurrent"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::Measured3rdHarmonicCurrent::Id: + return "Measured3rdHarmonicCurrent"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::Measured5thHarmonicCurrent::Id: + return "Measured5thHarmonicCurrent"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::Measured7thHarmonicCurrent::Id: + return "Measured7thHarmonicCurrent"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::Measured9thHarmonicCurrent::Id: + return "Measured9thHarmonicCurrent"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::Measured11thHarmonicCurrent::Id: + return "Measured11thHarmonicCurrent"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::MeasuredPhase1stHarmonicCurrent::Id: + return "MeasuredPhase1stHarmonicCurrent"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::MeasuredPhase3rdHarmonicCurrent::Id: + return "MeasuredPhase3rdHarmonicCurrent"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::MeasuredPhase5thHarmonicCurrent::Id: + return "MeasuredPhase5thHarmonicCurrent"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::MeasuredPhase7thHarmonicCurrent::Id: + return "MeasuredPhase7thHarmonicCurrent"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::MeasuredPhase9thHarmonicCurrent::Id: + return "MeasuredPhase9thHarmonicCurrent"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::MeasuredPhase11thHarmonicCurrent::Id: + return "MeasuredPhase11thHarmonicCurrent"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::AcFrequencyMultiplier::Id: + return "AcFrequencyMultiplier"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::AcFrequencyDivisor::Id: + return "AcFrequencyDivisor"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::PowerMultiplier::Id: + return "PowerMultiplier"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::PowerDivisor::Id: + return "PowerDivisor"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::HarmonicCurrentMultiplier::Id: + return "HarmonicCurrentMultiplier"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::PhaseHarmonicCurrentMultiplier::Id: + return "PhaseHarmonicCurrentMultiplier"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::InstantaneousVoltage::Id: + return "InstantaneousVoltage"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::InstantaneousLineCurrent::Id: + return "InstantaneousLineCurrent"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::InstantaneousActiveCurrent::Id: + return "InstantaneousActiveCurrent"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::InstantaneousReactiveCurrent::Id: + return "InstantaneousReactiveCurrent"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::InstantaneousPower::Id: + return "InstantaneousPower"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::RmsVoltage::Id: + return "RmsVoltage"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::RmsVoltageMin::Id: + return "RmsVoltageMin"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::RmsVoltageMax::Id: + return "RmsVoltageMax"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::RmsCurrent::Id: + return "RmsCurrent"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::RmsCurrentMin::Id: + return "RmsCurrentMin"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::RmsCurrentMax::Id: + return "RmsCurrentMax"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::ActivePower::Id: + return "ActivePower"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::ActivePowerMin::Id: + return "ActivePowerMin"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::ActivePowerMax::Id: + return "ActivePowerMax"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::ReactivePower::Id: + return "ReactivePower"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::ApparentPower::Id: + return "ApparentPower"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::PowerFactor::Id: + return "PowerFactor"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::AverageRmsVoltageMeasurementPeriod::Id: + return "AverageRmsVoltageMeasurementPeriod"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::AverageRmsUnderVoltageCounter::Id: + return "AverageRmsUnderVoltageCounter"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::RmsExtremeOverVoltagePeriod::Id: + return "RmsExtremeOverVoltagePeriod"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::RmsExtremeUnderVoltagePeriod::Id: + return "RmsExtremeUnderVoltagePeriod"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::RmsVoltageSagPeriod::Id: + return "RmsVoltageSagPeriod"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::RmsVoltageSwellPeriod::Id: + return "RmsVoltageSwellPeriod"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::AcVoltageMultiplier::Id: + return "AcVoltageMultiplier"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::AcVoltageDivisor::Id: + return "AcVoltageDivisor"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::AcCurrentMultiplier::Id: + return "AcCurrentMultiplier"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::AcCurrentDivisor::Id: + return "AcCurrentDivisor"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::AcPowerMultiplier::Id: + return "AcPowerMultiplier"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::AcPowerDivisor::Id: + return "AcPowerDivisor"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::OverloadAlarmsMask::Id: + return "OverloadAlarmsMask"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::VoltageOverload::Id: + return "VoltageOverload"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::CurrentOverload::Id: + return "CurrentOverload"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::AcOverloadAlarmsMask::Id: + return "AcOverloadAlarmsMask"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::AcVoltageOverload::Id: + return "AcVoltageOverload"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::AcCurrentOverload::Id: + return "AcCurrentOverload"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::AcActivePowerOverload::Id: + return "AcActivePowerOverload"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::AcReactivePowerOverload::Id: + return "AcReactivePowerOverload"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::AverageRmsOverVoltage::Id: + return "AverageRmsOverVoltage"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::AverageRmsUnderVoltage::Id: + return "AverageRmsUnderVoltage"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::RmsExtremeOverVoltage::Id: + return "RmsExtremeOverVoltage"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::RmsExtremeUnderVoltage::Id: + return "RmsExtremeUnderVoltage"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::RmsVoltageSag::Id: + return "RmsVoltageSag"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::RmsVoltageSwell::Id: + return "RmsVoltageSwell"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::LineCurrentPhaseB::Id: + return "LineCurrentPhaseB"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::ActiveCurrentPhaseB::Id: + return "ActiveCurrentPhaseB"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::ReactiveCurrentPhaseB::Id: + return "ReactiveCurrentPhaseB"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::RmsVoltagePhaseB::Id: + return "RmsVoltagePhaseB"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::RmsVoltageMinPhaseB::Id: + return "RmsVoltageMinPhaseB"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::RmsVoltageMaxPhaseB::Id: + return "RmsVoltageMaxPhaseB"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::RmsCurrentPhaseB::Id: + return "RmsCurrentPhaseB"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::RmsCurrentMinPhaseB::Id: + return "RmsCurrentMinPhaseB"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::RmsCurrentMaxPhaseB::Id: + return "RmsCurrentMaxPhaseB"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::ActivePowerPhaseB::Id: + return "ActivePowerPhaseB"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::ActivePowerMinPhaseB::Id: + return "ActivePowerMinPhaseB"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::ActivePowerMaxPhaseB::Id: + return "ActivePowerMaxPhaseB"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::ReactivePowerPhaseB::Id: + return "ReactivePowerPhaseB"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::ApparentPowerPhaseB::Id: + return "ApparentPowerPhaseB"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::PowerFactorPhaseB::Id: + return "PowerFactorPhaseB"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::AverageRmsVoltageMeasurementPeriodPhaseB::Id: + return "AverageRmsVoltageMeasurementPeriodPhaseB"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::AverageRmsOverVoltageCounterPhaseB::Id: + return "AverageRmsOverVoltageCounterPhaseB"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::AverageRmsUnderVoltageCounterPhaseB::Id: + return "AverageRmsUnderVoltageCounterPhaseB"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::RmsExtremeOverVoltagePeriodPhaseB::Id: + return "RmsExtremeOverVoltagePeriodPhaseB"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::RmsExtremeUnderVoltagePeriodPhaseB::Id: + return "RmsExtremeUnderVoltagePeriodPhaseB"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::RmsVoltageSagPeriodPhaseB::Id: + return "RmsVoltageSagPeriodPhaseB"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::RmsVoltageSwellPeriodPhaseB::Id: + return "RmsVoltageSwellPeriodPhaseB"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::LineCurrentPhaseC::Id: + return "LineCurrentPhaseC"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::ActiveCurrentPhaseC::Id: + return "ActiveCurrentPhaseC"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::ReactiveCurrentPhaseC::Id: + return "ReactiveCurrentPhaseC"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::RmsVoltagePhaseC::Id: + return "RmsVoltagePhaseC"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::RmsVoltageMinPhaseC::Id: + return "RmsVoltageMinPhaseC"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::RmsVoltageMaxPhaseC::Id: + return "RmsVoltageMaxPhaseC"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::RmsCurrentPhaseC::Id: + return "RmsCurrentPhaseC"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::RmsCurrentMinPhaseC::Id: + return "RmsCurrentMinPhaseC"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::RmsCurrentMaxPhaseC::Id: + return "RmsCurrentMaxPhaseC"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::ActivePowerPhaseC::Id: + return "ActivePowerPhaseC"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::ActivePowerMinPhaseC::Id: + return "ActivePowerMinPhaseC"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::ActivePowerMaxPhaseC::Id: + return "ActivePowerMaxPhaseC"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::ReactivePowerPhaseC::Id: + return "ReactivePowerPhaseC"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::ApparentPowerPhaseC::Id: + return "ApparentPowerPhaseC"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::PowerFactorPhaseC::Id: + return "PowerFactorPhaseC"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::AverageRmsVoltageMeasurementPeriodPhaseC::Id: + return "AverageRmsVoltageMeasurementPeriodPhaseC"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::AverageRmsOverVoltageCounterPhaseC::Id: + return "AverageRmsOverVoltageCounterPhaseC"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::AverageRmsUnderVoltageCounterPhaseC::Id: + return "AverageRmsUnderVoltageCounterPhaseC"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::RmsExtremeOverVoltagePeriodPhaseC::Id: + return "RmsExtremeOverVoltagePeriodPhaseC"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::RmsExtremeUnderVoltagePeriodPhaseC::Id: + return "RmsExtremeUnderVoltagePeriodPhaseC"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::RmsVoltageSagPeriodPhaseC::Id: + return "RmsVoltageSagPeriodPhaseC"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::RmsVoltageSwellPeriodPhaseC::Id: + return "RmsVoltageSwellPeriodPhaseC"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::ElectricalMeasurement::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::UnitTesting::Id: { + switch (id) + { + case chip::app::Clusters::UnitTesting::Attributes::Boolean::Id: + return "Boolean"; + case chip::app::Clusters::UnitTesting::Attributes::Bitmap8::Id: + return "Bitmap8"; + case chip::app::Clusters::UnitTesting::Attributes::Bitmap16::Id: + return "Bitmap16"; + case chip::app::Clusters::UnitTesting::Attributes::Bitmap32::Id: + return "Bitmap32"; + case chip::app::Clusters::UnitTesting::Attributes::Bitmap64::Id: + return "Bitmap64"; + case chip::app::Clusters::UnitTesting::Attributes::Int8u::Id: + return "Int8u"; + case chip::app::Clusters::UnitTesting::Attributes::Int16u::Id: + return "Int16u"; + case chip::app::Clusters::UnitTesting::Attributes::Int24u::Id: + return "Int24u"; + case chip::app::Clusters::UnitTesting::Attributes::Int32u::Id: + return "Int32u"; + case chip::app::Clusters::UnitTesting::Attributes::Int40u::Id: + return "Int40u"; + case chip::app::Clusters::UnitTesting::Attributes::Int48u::Id: + return "Int48u"; + case chip::app::Clusters::UnitTesting::Attributes::Int56u::Id: + return "Int56u"; + case chip::app::Clusters::UnitTesting::Attributes::Int64u::Id: + return "Int64u"; + case chip::app::Clusters::UnitTesting::Attributes::Int8s::Id: + return "Int8s"; + case chip::app::Clusters::UnitTesting::Attributes::Int16s::Id: + return "Int16s"; + case chip::app::Clusters::UnitTesting::Attributes::Int24s::Id: + return "Int24s"; + case chip::app::Clusters::UnitTesting::Attributes::Int32s::Id: + return "Int32s"; + case chip::app::Clusters::UnitTesting::Attributes::Int40s::Id: + return "Int40s"; + case chip::app::Clusters::UnitTesting::Attributes::Int48s::Id: + return "Int48s"; + case chip::app::Clusters::UnitTesting::Attributes::Int56s::Id: + return "Int56s"; + case chip::app::Clusters::UnitTesting::Attributes::Int64s::Id: + return "Int64s"; + case chip::app::Clusters::UnitTesting::Attributes::Enum8::Id: + return "Enum8"; + case chip::app::Clusters::UnitTesting::Attributes::Enum16::Id: + return "Enum16"; + case chip::app::Clusters::UnitTesting::Attributes::FloatSingle::Id: + return "FloatSingle"; + case chip::app::Clusters::UnitTesting::Attributes::FloatDouble::Id: + return "FloatDouble"; + case chip::app::Clusters::UnitTesting::Attributes::OctetString::Id: + return "OctetString"; + case chip::app::Clusters::UnitTesting::Attributes::ListInt8u::Id: + return "ListInt8u"; + case chip::app::Clusters::UnitTesting::Attributes::ListOctetString::Id: + return "ListOctetString"; + case chip::app::Clusters::UnitTesting::Attributes::ListStructOctetString::Id: + return "ListStructOctetString"; + case chip::app::Clusters::UnitTesting::Attributes::LongOctetString::Id: + return "LongOctetString"; + case chip::app::Clusters::UnitTesting::Attributes::CharString::Id: + return "CharString"; + case chip::app::Clusters::UnitTesting::Attributes::LongCharString::Id: + return "LongCharString"; + case chip::app::Clusters::UnitTesting::Attributes::EpochUs::Id: + return "EpochUs"; + case chip::app::Clusters::UnitTesting::Attributes::EpochS::Id: + return "EpochS"; + case chip::app::Clusters::UnitTesting::Attributes::VendorId::Id: + return "VendorId"; + case chip::app::Clusters::UnitTesting::Attributes::ListNullablesAndOptionalsStruct::Id: + return "ListNullablesAndOptionalsStruct"; + case chip::app::Clusters::UnitTesting::Attributes::EnumAttr::Id: + return "EnumAttr"; + case chip::app::Clusters::UnitTesting::Attributes::StructAttr::Id: + return "StructAttr"; + case chip::app::Clusters::UnitTesting::Attributes::RangeRestrictedInt8u::Id: + return "RangeRestrictedInt8u"; + case chip::app::Clusters::UnitTesting::Attributes::RangeRestrictedInt8s::Id: + return "RangeRestrictedInt8s"; + case chip::app::Clusters::UnitTesting::Attributes::RangeRestrictedInt16u::Id: + return "RangeRestrictedInt16u"; + case chip::app::Clusters::UnitTesting::Attributes::RangeRestrictedInt16s::Id: + return "RangeRestrictedInt16s"; + case chip::app::Clusters::UnitTesting::Attributes::ListLongOctetString::Id: + return "ListLongOctetString"; + case chip::app::Clusters::UnitTesting::Attributes::ListFabricScoped::Id: + return "ListFabricScoped"; + case chip::app::Clusters::UnitTesting::Attributes::TimedWriteBoolean::Id: + return "TimedWriteBoolean"; + case chip::app::Clusters::UnitTesting::Attributes::GeneralErrorBoolean::Id: + return "GeneralErrorBoolean"; + case chip::app::Clusters::UnitTesting::Attributes::ClusterErrorBoolean::Id: + return "ClusterErrorBoolean"; + case chip::app::Clusters::UnitTesting::Attributes::GlobalEnum::Id: + return "GlobalEnum"; + case chip::app::Clusters::UnitTesting::Attributes::GlobalStruct::Id: + return "GlobalStruct"; + case chip::app::Clusters::UnitTesting::Attributes::Unsupported::Id: + return "Unsupported"; + case chip::app::Clusters::UnitTesting::Attributes::NullableBoolean::Id: + return "NullableBoolean"; + case chip::app::Clusters::UnitTesting::Attributes::NullableBitmap8::Id: + return "NullableBitmap8"; + case chip::app::Clusters::UnitTesting::Attributes::NullableBitmap16::Id: + return "NullableBitmap16"; + case chip::app::Clusters::UnitTesting::Attributes::NullableBitmap32::Id: + return "NullableBitmap32"; + case chip::app::Clusters::UnitTesting::Attributes::NullableBitmap64::Id: + return "NullableBitmap64"; + case chip::app::Clusters::UnitTesting::Attributes::NullableInt8u::Id: + return "NullableInt8u"; + case chip::app::Clusters::UnitTesting::Attributes::NullableInt16u::Id: + return "NullableInt16u"; + case chip::app::Clusters::UnitTesting::Attributes::NullableInt24u::Id: + return "NullableInt24u"; + case chip::app::Clusters::UnitTesting::Attributes::NullableInt32u::Id: + return "NullableInt32u"; + case chip::app::Clusters::UnitTesting::Attributes::NullableInt40u::Id: + return "NullableInt40u"; + case chip::app::Clusters::UnitTesting::Attributes::NullableInt48u::Id: + return "NullableInt48u"; + case chip::app::Clusters::UnitTesting::Attributes::NullableInt56u::Id: + return "NullableInt56u"; + case chip::app::Clusters::UnitTesting::Attributes::NullableInt64u::Id: + return "NullableInt64u"; + case chip::app::Clusters::UnitTesting::Attributes::NullableInt8s::Id: + return "NullableInt8s"; + case chip::app::Clusters::UnitTesting::Attributes::NullableInt16s::Id: + return "NullableInt16s"; + case chip::app::Clusters::UnitTesting::Attributes::NullableInt24s::Id: + return "NullableInt24s"; + case chip::app::Clusters::UnitTesting::Attributes::NullableInt32s::Id: + return "NullableInt32s"; + case chip::app::Clusters::UnitTesting::Attributes::NullableInt40s::Id: + return "NullableInt40s"; + case chip::app::Clusters::UnitTesting::Attributes::NullableInt48s::Id: + return "NullableInt48s"; + case chip::app::Clusters::UnitTesting::Attributes::NullableInt56s::Id: + return "NullableInt56s"; + case chip::app::Clusters::UnitTesting::Attributes::NullableInt64s::Id: + return "NullableInt64s"; + case chip::app::Clusters::UnitTesting::Attributes::NullableEnum8::Id: + return "NullableEnum8"; + case chip::app::Clusters::UnitTesting::Attributes::NullableEnum16::Id: + return "NullableEnum16"; + case chip::app::Clusters::UnitTesting::Attributes::NullableFloatSingle::Id: + return "NullableFloatSingle"; + case chip::app::Clusters::UnitTesting::Attributes::NullableFloatDouble::Id: + return "NullableFloatDouble"; + case chip::app::Clusters::UnitTesting::Attributes::NullableOctetString::Id: + return "NullableOctetString"; + case chip::app::Clusters::UnitTesting::Attributes::NullableCharString::Id: + return "NullableCharString"; + case chip::app::Clusters::UnitTesting::Attributes::NullableEnumAttr::Id: + return "NullableEnumAttr"; + case chip::app::Clusters::UnitTesting::Attributes::NullableStruct::Id: + return "NullableStruct"; + case chip::app::Clusters::UnitTesting::Attributes::NullableRangeRestrictedInt8u::Id: + return "NullableRangeRestrictedInt8u"; + case chip::app::Clusters::UnitTesting::Attributes::NullableRangeRestrictedInt8s::Id: + return "NullableRangeRestrictedInt8s"; + case chip::app::Clusters::UnitTesting::Attributes::NullableRangeRestrictedInt16u::Id: + return "NullableRangeRestrictedInt16u"; + case chip::app::Clusters::UnitTesting::Attributes::NullableRangeRestrictedInt16s::Id: + return "NullableRangeRestrictedInt16s"; + case chip::app::Clusters::UnitTesting::Attributes::WriteOnlyInt8u::Id: + return "WriteOnlyInt8u"; + case chip::app::Clusters::UnitTesting::Attributes::NullableGlobalEnum::Id: + return "NullableGlobalEnum"; + case chip::app::Clusters::UnitTesting::Attributes::NullableGlobalStruct::Id: + return "NullableGlobalStruct"; + case chip::app::Clusters::UnitTesting::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::UnitTesting::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::UnitTesting::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::UnitTesting::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::UnitTesting::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::UnitTesting::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + case chip::app::Clusters::UnitTesting::Attributes::MeiInt8u::Id: + return "MeiInt8u"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::FaultInjection::Id: { + switch (id) + { + case chip::app::Clusters::FaultInjection::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::FaultInjection::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::FaultInjection::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::FaultInjection::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::FaultInjection::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::FaultInjection::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::SampleMei::Id: { + switch (id) + { + case chip::app::Clusters::SampleMei::Attributes::FlipFlop::Id: + return "FlipFlop"; + case chip::app::Clusters::SampleMei::Attributes::GeneratedCommandList::Id: + return "GeneratedCommandList"; + case chip::app::Clusters::SampleMei::Attributes::AcceptedCommandList::Id: + return "AcceptedCommandList"; + case chip::app::Clusters::SampleMei::Attributes::EventList::Id: + return "EventList"; + case chip::app::Clusters::SampleMei::Attributes::AttributeList::Id: + return "AttributeList"; + case chip::app::Clusters::SampleMei::Attributes::FeatureMap::Id: + return "FeatureMap"; + case chip::app::Clusters::SampleMei::Attributes::ClusterRevision::Id: + return "ClusterRevision"; + default: + return "Unknown"; + } + } + default: + return "Unknown"; + } +} + +char const * AcceptedCommandIdToText(chip::ClusterId cluster, chip::CommandId id) +{ + switch (cluster) + { + case chip::app::Clusters::Identify::Id: { + switch (id) + { + case chip::app::Clusters::Identify::Commands::Identify::Id: + return "Identify"; + case chip::app::Clusters::Identify::Commands::TriggerEffect::Id: + return "TriggerEffect"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::Groups::Id: { + switch (id) + { + case chip::app::Clusters::Groups::Commands::AddGroup::Id: + return "AddGroup"; + case chip::app::Clusters::Groups::Commands::ViewGroup::Id: + return "ViewGroup"; + case chip::app::Clusters::Groups::Commands::GetGroupMembership::Id: + return "GetGroupMembership"; + case chip::app::Clusters::Groups::Commands::RemoveGroup::Id: + return "RemoveGroup"; + case chip::app::Clusters::Groups::Commands::RemoveAllGroups::Id: + return "RemoveAllGroups"; + case chip::app::Clusters::Groups::Commands::AddGroupIfIdentifying::Id: + return "AddGroupIfIdentifying"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::OnOff::Id: { + switch (id) + { + case chip::app::Clusters::OnOff::Commands::Off::Id: + return "Off"; + case chip::app::Clusters::OnOff::Commands::On::Id: + return "On"; + case chip::app::Clusters::OnOff::Commands::Toggle::Id: + return "Toggle"; + case chip::app::Clusters::OnOff::Commands::OffWithEffect::Id: + return "OffWithEffect"; + case chip::app::Clusters::OnOff::Commands::OnWithRecallGlobalScene::Id: + return "OnWithRecallGlobalScene"; + case chip::app::Clusters::OnOff::Commands::OnWithTimedOff::Id: + return "OnWithTimedOff"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::LevelControl::Id: { + switch (id) + { + case chip::app::Clusters::LevelControl::Commands::MoveToLevel::Id: + return "MoveToLevel"; + case chip::app::Clusters::LevelControl::Commands::Move::Id: + return "Move"; + case chip::app::Clusters::LevelControl::Commands::Step::Id: + return "Step"; + case chip::app::Clusters::LevelControl::Commands::Stop::Id: + return "Stop"; + case chip::app::Clusters::LevelControl::Commands::MoveToLevelWithOnOff::Id: + return "MoveToLevelWithOnOff"; + case chip::app::Clusters::LevelControl::Commands::MoveWithOnOff::Id: + return "MoveWithOnOff"; + case chip::app::Clusters::LevelControl::Commands::StepWithOnOff::Id: + return "StepWithOnOff"; + case chip::app::Clusters::LevelControl::Commands::StopWithOnOff::Id: + return "StopWithOnOff"; + case chip::app::Clusters::LevelControl::Commands::MoveToClosestFrequency::Id: + return "MoveToClosestFrequency"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::AccessControl::Id: { + switch (id) + { + case chip::app::Clusters::AccessControl::Commands::ReviewFabricRestrictions::Id: + return "ReviewFabricRestrictions"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::Actions::Id: { + switch (id) + { + case chip::app::Clusters::Actions::Commands::InstantAction::Id: + return "InstantAction"; + case chip::app::Clusters::Actions::Commands::InstantActionWithTransition::Id: + return "InstantActionWithTransition"; + case chip::app::Clusters::Actions::Commands::StartAction::Id: + return "StartAction"; + case chip::app::Clusters::Actions::Commands::StartActionWithDuration::Id: + return "StartActionWithDuration"; + case chip::app::Clusters::Actions::Commands::StopAction::Id: + return "StopAction"; + case chip::app::Clusters::Actions::Commands::PauseAction::Id: + return "PauseAction"; + case chip::app::Clusters::Actions::Commands::PauseActionWithDuration::Id: + return "PauseActionWithDuration"; + case chip::app::Clusters::Actions::Commands::ResumeAction::Id: + return "ResumeAction"; + case chip::app::Clusters::Actions::Commands::EnableAction::Id: + return "EnableAction"; + case chip::app::Clusters::Actions::Commands::EnableActionWithDuration::Id: + return "EnableActionWithDuration"; + case chip::app::Clusters::Actions::Commands::DisableAction::Id: + return "DisableAction"; + case chip::app::Clusters::Actions::Commands::DisableActionWithDuration::Id: + return "DisableActionWithDuration"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::BasicInformation::Id: { + switch (id) + { + case chip::app::Clusters::BasicInformation::Commands::MfgSpecificPing::Id: + return "MfgSpecificPing"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::OtaSoftwareUpdateProvider::Id: { + switch (id) + { + case chip::app::Clusters::OtaSoftwareUpdateProvider::Commands::QueryImage::Id: + return "QueryImage"; + case chip::app::Clusters::OtaSoftwareUpdateProvider::Commands::ApplyUpdateRequest::Id: + return "ApplyUpdateRequest"; + case chip::app::Clusters::OtaSoftwareUpdateProvider::Commands::NotifyUpdateApplied::Id: + return "NotifyUpdateApplied"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::OtaSoftwareUpdateRequestor::Id: { + switch (id) + { + case chip::app::Clusters::OtaSoftwareUpdateRequestor::Commands::AnnounceOTAProvider::Id: + return "AnnounceOTAProvider"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::GeneralCommissioning::Id: { + switch (id) + { + case chip::app::Clusters::GeneralCommissioning::Commands::ArmFailSafe::Id: + return "ArmFailSafe"; + case chip::app::Clusters::GeneralCommissioning::Commands::SetRegulatoryConfig::Id: + return "SetRegulatoryConfig"; + case chip::app::Clusters::GeneralCommissioning::Commands::CommissioningComplete::Id: + return "CommissioningComplete"; + case chip::app::Clusters::GeneralCommissioning::Commands::SetTCAcknowledgements::Id: + return "SetTCAcknowledgements"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::NetworkCommissioning::Id: { + switch (id) + { + case chip::app::Clusters::NetworkCommissioning::Commands::ScanNetworks::Id: + return "ScanNetworks"; + case chip::app::Clusters::NetworkCommissioning::Commands::AddOrUpdateWiFiNetwork::Id: + return "AddOrUpdateWiFiNetwork"; + case chip::app::Clusters::NetworkCommissioning::Commands::AddOrUpdateThreadNetwork::Id: + return "AddOrUpdateThreadNetwork"; + case chip::app::Clusters::NetworkCommissioning::Commands::RemoveNetwork::Id: + return "RemoveNetwork"; + case chip::app::Clusters::NetworkCommissioning::Commands::ConnectNetwork::Id: + return "ConnectNetwork"; + case chip::app::Clusters::NetworkCommissioning::Commands::ReorderNetwork::Id: + return "ReorderNetwork"; + case chip::app::Clusters::NetworkCommissioning::Commands::QueryIdentity::Id: + return "QueryIdentity"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::DiagnosticLogs::Id: { + switch (id) + { + case chip::app::Clusters::DiagnosticLogs::Commands::RetrieveLogsRequest::Id: + return "RetrieveLogsRequest"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::GeneralDiagnostics::Id: { + switch (id) + { + case chip::app::Clusters::GeneralDiagnostics::Commands::TestEventTrigger::Id: + return "TestEventTrigger"; + case chip::app::Clusters::GeneralDiagnostics::Commands::TimeSnapshot::Id: + return "TimeSnapshot"; + case chip::app::Clusters::GeneralDiagnostics::Commands::PayloadTestRequest::Id: + return "PayloadTestRequest"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::SoftwareDiagnostics::Id: { + switch (id) + { + case chip::app::Clusters::SoftwareDiagnostics::Commands::ResetWatermarks::Id: + return "ResetWatermarks"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::ThreadNetworkDiagnostics::Id: { + switch (id) + { + case chip::app::Clusters::ThreadNetworkDiagnostics::Commands::ResetCounts::Id: + return "ResetCounts"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::WiFiNetworkDiagnostics::Id: { + switch (id) + { + case chip::app::Clusters::WiFiNetworkDiagnostics::Commands::ResetCounts::Id: + return "ResetCounts"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::EthernetNetworkDiagnostics::Id: { + switch (id) + { + case chip::app::Clusters::EthernetNetworkDiagnostics::Commands::ResetCounts::Id: + return "ResetCounts"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::TimeSynchronization::Id: { + switch (id) + { + case chip::app::Clusters::TimeSynchronization::Commands::SetUTCTime::Id: + return "SetUTCTime"; + case chip::app::Clusters::TimeSynchronization::Commands::SetTrustedTimeSource::Id: + return "SetTrustedTimeSource"; + case chip::app::Clusters::TimeSynchronization::Commands::SetTimeZone::Id: + return "SetTimeZone"; + case chip::app::Clusters::TimeSynchronization::Commands::SetDSTOffset::Id: + return "SetDSTOffset"; + case chip::app::Clusters::TimeSynchronization::Commands::SetDefaultNTP::Id: + return "SetDefaultNTP"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::BridgedDeviceBasicInformation::Id: { + switch (id) + { + case chip::app::Clusters::BridgedDeviceBasicInformation::Commands::KeepActive::Id: + return "KeepActive"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::AdministratorCommissioning::Id: { + switch (id) + { + case chip::app::Clusters::AdministratorCommissioning::Commands::OpenCommissioningWindow::Id: + return "OpenCommissioningWindow"; + case chip::app::Clusters::AdministratorCommissioning::Commands::OpenBasicCommissioningWindow::Id: + return "OpenBasicCommissioningWindow"; + case chip::app::Clusters::AdministratorCommissioning::Commands::RevokeCommissioning::Id: + return "RevokeCommissioning"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::OperationalCredentials::Id: { + switch (id) + { + case chip::app::Clusters::OperationalCredentials::Commands::AttestationRequest::Id: + return "AttestationRequest"; + case chip::app::Clusters::OperationalCredentials::Commands::CertificateChainRequest::Id: + return "CertificateChainRequest"; + case chip::app::Clusters::OperationalCredentials::Commands::CSRRequest::Id: + return "CSRRequest"; + case chip::app::Clusters::OperationalCredentials::Commands::AddNOC::Id: + return "AddNOC"; + case chip::app::Clusters::OperationalCredentials::Commands::UpdateNOC::Id: + return "UpdateNOC"; + case chip::app::Clusters::OperationalCredentials::Commands::UpdateFabricLabel::Id: + return "UpdateFabricLabel"; + case chip::app::Clusters::OperationalCredentials::Commands::RemoveFabric::Id: + return "RemoveFabric"; + case chip::app::Clusters::OperationalCredentials::Commands::AddTrustedRootCertificate::Id: + return "AddTrustedRootCertificate"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::GroupKeyManagement::Id: { + switch (id) + { + case chip::app::Clusters::GroupKeyManagement::Commands::KeySetWrite::Id: + return "KeySetWrite"; + case chip::app::Clusters::GroupKeyManagement::Commands::KeySetRead::Id: + return "KeySetRead"; + case chip::app::Clusters::GroupKeyManagement::Commands::KeySetRemove::Id: + return "KeySetRemove"; + case chip::app::Clusters::GroupKeyManagement::Commands::KeySetReadAllIndices::Id: + return "KeySetReadAllIndices"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::IcdManagement::Id: { + switch (id) + { + case chip::app::Clusters::IcdManagement::Commands::RegisterClient::Id: + return "RegisterClient"; + case chip::app::Clusters::IcdManagement::Commands::UnregisterClient::Id: + return "UnregisterClient"; + case chip::app::Clusters::IcdManagement::Commands::StayActiveRequest::Id: + return "StayActiveRequest"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::Timer::Id: { + switch (id) + { + case chip::app::Clusters::Timer::Commands::SetTimer::Id: + return "SetTimer"; + case chip::app::Clusters::Timer::Commands::ResetTimer::Id: + return "ResetTimer"; + case chip::app::Clusters::Timer::Commands::AddTime::Id: + return "AddTime"; + case chip::app::Clusters::Timer::Commands::ReduceTime::Id: + return "ReduceTime"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::OvenCavityOperationalState::Id: { + switch (id) + { + case chip::app::Clusters::OvenCavityOperationalState::Commands::Pause::Id: + return "Pause"; + case chip::app::Clusters::OvenCavityOperationalState::Commands::Stop::Id: + return "Stop"; + case chip::app::Clusters::OvenCavityOperationalState::Commands::Start::Id: + return "Start"; + case chip::app::Clusters::OvenCavityOperationalState::Commands::Resume::Id: + return "Resume"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::OvenMode::Id: { + switch (id) + { + case chip::app::Clusters::OvenMode::Commands::ChangeToMode::Id: + return "ChangeToMode"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::ModeSelect::Id: { + switch (id) + { + case chip::app::Clusters::ModeSelect::Commands::ChangeToMode::Id: + return "ChangeToMode"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::LaundryWasherMode::Id: { + switch (id) + { + case chip::app::Clusters::LaundryWasherMode::Commands::ChangeToMode::Id: + return "ChangeToMode"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::RefrigeratorAndTemperatureControlledCabinetMode::Id: { + switch (id) + { + case chip::app::Clusters::RefrigeratorAndTemperatureControlledCabinetMode::Commands::ChangeToMode::Id: + return "ChangeToMode"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::RvcRunMode::Id: { + switch (id) + { + case chip::app::Clusters::RvcRunMode::Commands::ChangeToMode::Id: + return "ChangeToMode"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::RvcCleanMode::Id: { + switch (id) + { + case chip::app::Clusters::RvcCleanMode::Commands::ChangeToMode::Id: + return "ChangeToMode"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::TemperatureControl::Id: { + switch (id) + { + case chip::app::Clusters::TemperatureControl::Commands::SetTemperature::Id: + return "SetTemperature"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::DishwasherMode::Id: { + switch (id) + { + case chip::app::Clusters::DishwasherMode::Commands::ChangeToMode::Id: + return "ChangeToMode"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::SmokeCoAlarm::Id: { + switch (id) + { + case chip::app::Clusters::SmokeCoAlarm::Commands::SelfTestRequest::Id: + return "SelfTestRequest"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::DishwasherAlarm::Id: { + switch (id) + { + case chip::app::Clusters::DishwasherAlarm::Commands::Reset::Id: + return "Reset"; + case chip::app::Clusters::DishwasherAlarm::Commands::ModifyEnabledAlarms::Id: + return "ModifyEnabledAlarms"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::MicrowaveOvenControl::Id: { + switch (id) + { + case chip::app::Clusters::MicrowaveOvenControl::Commands::SetCookingParameters::Id: + return "SetCookingParameters"; + case chip::app::Clusters::MicrowaveOvenControl::Commands::AddMoreTime::Id: + return "AddMoreTime"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::OperationalState::Id: { + switch (id) + { + case chip::app::Clusters::OperationalState::Commands::Pause::Id: + return "Pause"; + case chip::app::Clusters::OperationalState::Commands::Stop::Id: + return "Stop"; + case chip::app::Clusters::OperationalState::Commands::Start::Id: + return "Start"; + case chip::app::Clusters::OperationalState::Commands::Resume::Id: + return "Resume"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::RvcOperationalState::Id: { + switch (id) + { + case chip::app::Clusters::RvcOperationalState::Commands::Pause::Id: + return "Pause"; + case chip::app::Clusters::RvcOperationalState::Commands::Resume::Id: + return "Resume"; + case chip::app::Clusters::RvcOperationalState::Commands::GoHome::Id: + return "GoHome"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::ScenesManagement::Id: { + switch (id) + { + case chip::app::Clusters::ScenesManagement::Commands::AddScene::Id: + return "AddScene"; + case chip::app::Clusters::ScenesManagement::Commands::ViewScene::Id: + return "ViewScene"; + case chip::app::Clusters::ScenesManagement::Commands::RemoveScene::Id: + return "RemoveScene"; + case chip::app::Clusters::ScenesManagement::Commands::RemoveAllScenes::Id: + return "RemoveAllScenes"; + case chip::app::Clusters::ScenesManagement::Commands::StoreScene::Id: + return "StoreScene"; + case chip::app::Clusters::ScenesManagement::Commands::RecallScene::Id: + return "RecallScene"; + case chip::app::Clusters::ScenesManagement::Commands::GetSceneMembership::Id: + return "GetSceneMembership"; + case chip::app::Clusters::ScenesManagement::Commands::CopyScene::Id: + return "CopyScene"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::HepaFilterMonitoring::Id: { + switch (id) + { + case chip::app::Clusters::HepaFilterMonitoring::Commands::ResetCondition::Id: + return "ResetCondition"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::ActivatedCarbonFilterMonitoring::Id: { + switch (id) + { + case chip::app::Clusters::ActivatedCarbonFilterMonitoring::Commands::ResetCondition::Id: + return "ResetCondition"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::BooleanStateConfiguration::Id: { + switch (id) + { + case chip::app::Clusters::BooleanStateConfiguration::Commands::SuppressAlarm::Id: + return "SuppressAlarm"; + case chip::app::Clusters::BooleanStateConfiguration::Commands::EnableDisableAlarm::Id: + return "EnableDisableAlarm"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::ValveConfigurationAndControl::Id: { + switch (id) + { + case chip::app::Clusters::ValveConfigurationAndControl::Commands::Open::Id: + return "Open"; + case chip::app::Clusters::ValveConfigurationAndControl::Commands::Close::Id: + return "Close"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::WaterHeaterManagement::Id: { + switch (id) + { + case chip::app::Clusters::WaterHeaterManagement::Commands::Boost::Id: + return "Boost"; + case chip::app::Clusters::WaterHeaterManagement::Commands::CancelBoost::Id: + return "CancelBoost"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::DemandResponseLoadControl::Id: { + switch (id) + { + case chip::app::Clusters::DemandResponseLoadControl::Commands::RegisterLoadControlProgramRequest::Id: + return "RegisterLoadControlProgramRequest"; + case chip::app::Clusters::DemandResponseLoadControl::Commands::UnregisterLoadControlProgramRequest::Id: + return "UnregisterLoadControlProgramRequest"; + case chip::app::Clusters::DemandResponseLoadControl::Commands::AddLoadControlEventRequest::Id: + return "AddLoadControlEventRequest"; + case chip::app::Clusters::DemandResponseLoadControl::Commands::RemoveLoadControlEventRequest::Id: + return "RemoveLoadControlEventRequest"; + case chip::app::Clusters::DemandResponseLoadControl::Commands::ClearLoadControlEventsRequest::Id: + return "ClearLoadControlEventsRequest"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::Messages::Id: { + switch (id) + { + case chip::app::Clusters::Messages::Commands::PresentMessagesRequest::Id: + return "PresentMessagesRequest"; + case chip::app::Clusters::Messages::Commands::CancelMessagesRequest::Id: + return "CancelMessagesRequest"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::DeviceEnergyManagement::Id: { + switch (id) + { + case chip::app::Clusters::DeviceEnergyManagement::Commands::PowerAdjustRequest::Id: + return "PowerAdjustRequest"; + case chip::app::Clusters::DeviceEnergyManagement::Commands::CancelPowerAdjustRequest::Id: + return "CancelPowerAdjustRequest"; + case chip::app::Clusters::DeviceEnergyManagement::Commands::StartTimeAdjustRequest::Id: + return "StartTimeAdjustRequest"; + case chip::app::Clusters::DeviceEnergyManagement::Commands::PauseRequest::Id: + return "PauseRequest"; + case chip::app::Clusters::DeviceEnergyManagement::Commands::ResumeRequest::Id: + return "ResumeRequest"; + case chip::app::Clusters::DeviceEnergyManagement::Commands::ModifyForecastRequest::Id: + return "ModifyForecastRequest"; + case chip::app::Clusters::DeviceEnergyManagement::Commands::RequestConstraintBasedForecast::Id: + return "RequestConstraintBasedForecast"; + case chip::app::Clusters::DeviceEnergyManagement::Commands::CancelRequest::Id: + return "CancelRequest"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::EnergyEvse::Id: { + switch (id) + { + case chip::app::Clusters::EnergyEvse::Commands::Disable::Id: + return "Disable"; + case chip::app::Clusters::EnergyEvse::Commands::EnableCharging::Id: + return "EnableCharging"; + case chip::app::Clusters::EnergyEvse::Commands::EnableDischarging::Id: + return "EnableDischarging"; + case chip::app::Clusters::EnergyEvse::Commands::StartDiagnostics::Id: + return "StartDiagnostics"; + case chip::app::Clusters::EnergyEvse::Commands::SetTargets::Id: + return "SetTargets"; + case chip::app::Clusters::EnergyEvse::Commands::GetTargets::Id: + return "GetTargets"; + case chip::app::Clusters::EnergyEvse::Commands::ClearTargets::Id: + return "ClearTargets"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::EnergyEvseMode::Id: { + switch (id) + { + case chip::app::Clusters::EnergyEvseMode::Commands::ChangeToMode::Id: + return "ChangeToMode"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::WaterHeaterMode::Id: { + switch (id) + { + case chip::app::Clusters::WaterHeaterMode::Commands::ChangeToMode::Id: + return "ChangeToMode"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::DeviceEnergyManagementMode::Id: { + switch (id) + { + case chip::app::Clusters::DeviceEnergyManagementMode::Commands::ChangeToMode::Id: + return "ChangeToMode"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::DoorLock::Id: { + switch (id) + { + case chip::app::Clusters::DoorLock::Commands::LockDoor::Id: + return "LockDoor"; + case chip::app::Clusters::DoorLock::Commands::UnlockDoor::Id: + return "UnlockDoor"; + case chip::app::Clusters::DoorLock::Commands::UnlockWithTimeout::Id: + return "UnlockWithTimeout"; + case chip::app::Clusters::DoorLock::Commands::SetWeekDaySchedule::Id: + return "SetWeekDaySchedule"; + case chip::app::Clusters::DoorLock::Commands::GetWeekDaySchedule::Id: + return "GetWeekDaySchedule"; + case chip::app::Clusters::DoorLock::Commands::ClearWeekDaySchedule::Id: + return "ClearWeekDaySchedule"; + case chip::app::Clusters::DoorLock::Commands::SetYearDaySchedule::Id: + return "SetYearDaySchedule"; + case chip::app::Clusters::DoorLock::Commands::GetYearDaySchedule::Id: + return "GetYearDaySchedule"; + case chip::app::Clusters::DoorLock::Commands::ClearYearDaySchedule::Id: + return "ClearYearDaySchedule"; + case chip::app::Clusters::DoorLock::Commands::SetHolidaySchedule::Id: + return "SetHolidaySchedule"; + case chip::app::Clusters::DoorLock::Commands::GetHolidaySchedule::Id: + return "GetHolidaySchedule"; + case chip::app::Clusters::DoorLock::Commands::ClearHolidaySchedule::Id: + return "ClearHolidaySchedule"; + case chip::app::Clusters::DoorLock::Commands::SetUser::Id: + return "SetUser"; + case chip::app::Clusters::DoorLock::Commands::GetUser::Id: + return "GetUser"; + case chip::app::Clusters::DoorLock::Commands::ClearUser::Id: + return "ClearUser"; + case chip::app::Clusters::DoorLock::Commands::SetCredential::Id: + return "SetCredential"; + case chip::app::Clusters::DoorLock::Commands::GetCredentialStatus::Id: + return "GetCredentialStatus"; + case chip::app::Clusters::DoorLock::Commands::ClearCredential::Id: + return "ClearCredential"; + case chip::app::Clusters::DoorLock::Commands::UnboltDoor::Id: + return "UnboltDoor"; + case chip::app::Clusters::DoorLock::Commands::SetAliroReaderConfig::Id: + return "SetAliroReaderConfig"; + case chip::app::Clusters::DoorLock::Commands::ClearAliroReaderConfig::Id: + return "ClearAliroReaderConfig"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::WindowCovering::Id: { + switch (id) + { + case chip::app::Clusters::WindowCovering::Commands::UpOrOpen::Id: + return "UpOrOpen"; + case chip::app::Clusters::WindowCovering::Commands::DownOrClose::Id: + return "DownOrClose"; + case chip::app::Clusters::WindowCovering::Commands::StopMotion::Id: + return "StopMotion"; + case chip::app::Clusters::WindowCovering::Commands::GoToLiftValue::Id: + return "GoToLiftValue"; + case chip::app::Clusters::WindowCovering::Commands::GoToLiftPercentage::Id: + return "GoToLiftPercentage"; + case chip::app::Clusters::WindowCovering::Commands::GoToTiltValue::Id: + return "GoToTiltValue"; + case chip::app::Clusters::WindowCovering::Commands::GoToTiltPercentage::Id: + return "GoToTiltPercentage"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::BarrierControl::Id: { + switch (id) + { + case chip::app::Clusters::BarrierControl::Commands::BarrierControlGoToPercent::Id: + return "BarrierControlGoToPercent"; + case chip::app::Clusters::BarrierControl::Commands::BarrierControlStop::Id: + return "BarrierControlStop"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::ServiceArea::Id: { + switch (id) + { + case chip::app::Clusters::ServiceArea::Commands::SelectAreas::Id: + return "SelectAreas"; + case chip::app::Clusters::ServiceArea::Commands::SkipArea::Id: + return "SkipArea"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::Thermostat::Id: { + switch (id) + { + case chip::app::Clusters::Thermostat::Commands::SetpointRaiseLower::Id: + return "SetpointRaiseLower"; + case chip::app::Clusters::Thermostat::Commands::SetWeeklySchedule::Id: + return "SetWeeklySchedule"; + case chip::app::Clusters::Thermostat::Commands::GetWeeklySchedule::Id: + return "GetWeeklySchedule"; + case chip::app::Clusters::Thermostat::Commands::ClearWeeklySchedule::Id: + return "ClearWeeklySchedule"; + case chip::app::Clusters::Thermostat::Commands::SetActiveScheduleRequest::Id: + return "SetActiveScheduleRequest"; + case chip::app::Clusters::Thermostat::Commands::SetActivePresetRequest::Id: + return "SetActivePresetRequest"; + case chip::app::Clusters::Thermostat::Commands::AtomicRequest::Id: + return "AtomicRequest"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::FanControl::Id: { + switch (id) + { + case chip::app::Clusters::FanControl::Commands::Step::Id: + return "Step"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::ColorControl::Id: { + switch (id) + { + case chip::app::Clusters::ColorControl::Commands::MoveToHue::Id: + return "MoveToHue"; + case chip::app::Clusters::ColorControl::Commands::MoveHue::Id: + return "MoveHue"; + case chip::app::Clusters::ColorControl::Commands::StepHue::Id: + return "StepHue"; + case chip::app::Clusters::ColorControl::Commands::MoveToSaturation::Id: + return "MoveToSaturation"; + case chip::app::Clusters::ColorControl::Commands::MoveSaturation::Id: + return "MoveSaturation"; + case chip::app::Clusters::ColorControl::Commands::StepSaturation::Id: + return "StepSaturation"; + case chip::app::Clusters::ColorControl::Commands::MoveToHueAndSaturation::Id: + return "MoveToHueAndSaturation"; + case chip::app::Clusters::ColorControl::Commands::MoveToColor::Id: + return "MoveToColor"; + case chip::app::Clusters::ColorControl::Commands::MoveColor::Id: + return "MoveColor"; + case chip::app::Clusters::ColorControl::Commands::StepColor::Id: + return "StepColor"; + case chip::app::Clusters::ColorControl::Commands::MoveToColorTemperature::Id: + return "MoveToColorTemperature"; + case chip::app::Clusters::ColorControl::Commands::EnhancedMoveToHue::Id: + return "EnhancedMoveToHue"; + case chip::app::Clusters::ColorControl::Commands::EnhancedMoveHue::Id: + return "EnhancedMoveHue"; + case chip::app::Clusters::ColorControl::Commands::EnhancedStepHue::Id: + return "EnhancedStepHue"; + case chip::app::Clusters::ColorControl::Commands::EnhancedMoveToHueAndSaturation::Id: + return "EnhancedMoveToHueAndSaturation"; + case chip::app::Clusters::ColorControl::Commands::ColorLoopSet::Id: + return "ColorLoopSet"; + case chip::app::Clusters::ColorControl::Commands::StopMoveStep::Id: + return "StopMoveStep"; + case chip::app::Clusters::ColorControl::Commands::MoveColorTemperature::Id: + return "MoveColorTemperature"; + case chip::app::Clusters::ColorControl::Commands::StepColorTemperature::Id: + return "StepColorTemperature"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::WiFiNetworkManagement::Id: { + switch (id) + { + case chip::app::Clusters::WiFiNetworkManagement::Commands::NetworkPassphraseRequest::Id: + return "NetworkPassphraseRequest"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::ThreadBorderRouterManagement::Id: { + switch (id) + { + case chip::app::Clusters::ThreadBorderRouterManagement::Commands::GetActiveDatasetRequest::Id: + return "GetActiveDatasetRequest"; + case chip::app::Clusters::ThreadBorderRouterManagement::Commands::GetPendingDatasetRequest::Id: + return "GetPendingDatasetRequest"; + case chip::app::Clusters::ThreadBorderRouterManagement::Commands::SetActiveDatasetRequest::Id: + return "SetActiveDatasetRequest"; + case chip::app::Clusters::ThreadBorderRouterManagement::Commands::SetPendingDatasetRequest::Id: + return "SetPendingDatasetRequest"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::ThreadNetworkDirectory::Id: { + switch (id) + { + case chip::app::Clusters::ThreadNetworkDirectory::Commands::AddNetwork::Id: + return "AddNetwork"; + case chip::app::Clusters::ThreadNetworkDirectory::Commands::RemoveNetwork::Id: + return "RemoveNetwork"; + case chip::app::Clusters::ThreadNetworkDirectory::Commands::GetOperationalDataset::Id: + return "GetOperationalDataset"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::Channel::Id: { + switch (id) + { + case chip::app::Clusters::Channel::Commands::ChangeChannel::Id: + return "ChangeChannel"; + case chip::app::Clusters::Channel::Commands::ChangeChannelByNumber::Id: + return "ChangeChannelByNumber"; + case chip::app::Clusters::Channel::Commands::SkipChannel::Id: + return "SkipChannel"; + case chip::app::Clusters::Channel::Commands::GetProgramGuide::Id: + return "GetProgramGuide"; + case chip::app::Clusters::Channel::Commands::RecordProgram::Id: + return "RecordProgram"; + case chip::app::Clusters::Channel::Commands::CancelRecordProgram::Id: + return "CancelRecordProgram"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::TargetNavigator::Id: { + switch (id) + { + case chip::app::Clusters::TargetNavigator::Commands::NavigateTarget::Id: + return "NavigateTarget"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::MediaPlayback::Id: { + switch (id) + { + case chip::app::Clusters::MediaPlayback::Commands::Play::Id: + return "Play"; + case chip::app::Clusters::MediaPlayback::Commands::Pause::Id: + return "Pause"; + case chip::app::Clusters::MediaPlayback::Commands::Stop::Id: + return "Stop"; + case chip::app::Clusters::MediaPlayback::Commands::StartOver::Id: + return "StartOver"; + case chip::app::Clusters::MediaPlayback::Commands::Previous::Id: + return "Previous"; + case chip::app::Clusters::MediaPlayback::Commands::Next::Id: + return "Next"; + case chip::app::Clusters::MediaPlayback::Commands::Rewind::Id: + return "Rewind"; + case chip::app::Clusters::MediaPlayback::Commands::FastForward::Id: + return "FastForward"; + case chip::app::Clusters::MediaPlayback::Commands::SkipForward::Id: + return "SkipForward"; + case chip::app::Clusters::MediaPlayback::Commands::SkipBackward::Id: + return "SkipBackward"; + case chip::app::Clusters::MediaPlayback::Commands::Seek::Id: + return "Seek"; + case chip::app::Clusters::MediaPlayback::Commands::ActivateAudioTrack::Id: + return "ActivateAudioTrack"; + case chip::app::Clusters::MediaPlayback::Commands::ActivateTextTrack::Id: + return "ActivateTextTrack"; + case chip::app::Clusters::MediaPlayback::Commands::DeactivateTextTrack::Id: + return "DeactivateTextTrack"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::MediaInput::Id: { + switch (id) + { + case chip::app::Clusters::MediaInput::Commands::SelectInput::Id: + return "SelectInput"; + case chip::app::Clusters::MediaInput::Commands::ShowInputStatus::Id: + return "ShowInputStatus"; + case chip::app::Clusters::MediaInput::Commands::HideInputStatus::Id: + return "HideInputStatus"; + case chip::app::Clusters::MediaInput::Commands::RenameInput::Id: + return "RenameInput"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::LowPower::Id: { + switch (id) + { + case chip::app::Clusters::LowPower::Commands::Sleep::Id: + return "Sleep"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::KeypadInput::Id: { + switch (id) + { + case chip::app::Clusters::KeypadInput::Commands::SendKey::Id: + return "SendKey"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::ContentLauncher::Id: { + switch (id) + { + case chip::app::Clusters::ContentLauncher::Commands::LaunchContent::Id: + return "LaunchContent"; + case chip::app::Clusters::ContentLauncher::Commands::LaunchURL::Id: + return "LaunchURL"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::AudioOutput::Id: { + switch (id) + { + case chip::app::Clusters::AudioOutput::Commands::SelectOutput::Id: + return "SelectOutput"; + case chip::app::Clusters::AudioOutput::Commands::RenameOutput::Id: + return "RenameOutput"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::ApplicationLauncher::Id: { + switch (id) + { + case chip::app::Clusters::ApplicationLauncher::Commands::LaunchApp::Id: + return "LaunchApp"; + case chip::app::Clusters::ApplicationLauncher::Commands::StopApp::Id: + return "StopApp"; + case chip::app::Clusters::ApplicationLauncher::Commands::HideApp::Id: + return "HideApp"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::AccountLogin::Id: { + switch (id) + { + case chip::app::Clusters::AccountLogin::Commands::GetSetupPIN::Id: + return "GetSetupPIN"; + case chip::app::Clusters::AccountLogin::Commands::Login::Id: + return "Login"; + case chip::app::Clusters::AccountLogin::Commands::Logout::Id: + return "Logout"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::ContentControl::Id: { + switch (id) + { + case chip::app::Clusters::ContentControl::Commands::UpdatePIN::Id: + return "UpdatePIN"; + case chip::app::Clusters::ContentControl::Commands::ResetPIN::Id: + return "ResetPIN"; + case chip::app::Clusters::ContentControl::Commands::Enable::Id: + return "Enable"; + case chip::app::Clusters::ContentControl::Commands::Disable::Id: + return "Disable"; + case chip::app::Clusters::ContentControl::Commands::AddBonusTime::Id: + return "AddBonusTime"; + case chip::app::Clusters::ContentControl::Commands::SetScreenDailyTime::Id: + return "SetScreenDailyTime"; + case chip::app::Clusters::ContentControl::Commands::BlockUnratedContent::Id: + return "BlockUnratedContent"; + case chip::app::Clusters::ContentControl::Commands::UnblockUnratedContent::Id: + return "UnblockUnratedContent"; + case chip::app::Clusters::ContentControl::Commands::SetOnDemandRatingThreshold::Id: + return "SetOnDemandRatingThreshold"; + case chip::app::Clusters::ContentControl::Commands::SetScheduledContentRatingThreshold::Id: + return "SetScheduledContentRatingThreshold"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::ContentAppObserver::Id: { + switch (id) + { + case chip::app::Clusters::ContentAppObserver::Commands::ContentAppMessage::Id: + return "ContentAppMessage"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::CommissionerControl::Id: { + switch (id) + { + case chip::app::Clusters::CommissionerControl::Commands::RequestCommissioningApproval::Id: + return "RequestCommissioningApproval"; + case chip::app::Clusters::CommissionerControl::Commands::CommissionNode::Id: + return "CommissionNode"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::ElectricalMeasurement::Id: { + switch (id) + { + case chip::app::Clusters::ElectricalMeasurement::Commands::GetProfileInfoCommand::Id: + return "GetProfileInfoCommand"; + case chip::app::Clusters::ElectricalMeasurement::Commands::GetMeasurementProfileCommand::Id: + return "GetMeasurementProfileCommand"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::UnitTesting::Id: { + switch (id) + { + case chip::app::Clusters::UnitTesting::Commands::Test::Id: + return "Test"; + case chip::app::Clusters::UnitTesting::Commands::TestNotHandled::Id: + return "TestNotHandled"; + case chip::app::Clusters::UnitTesting::Commands::TestSpecific::Id: + return "TestSpecific"; + case chip::app::Clusters::UnitTesting::Commands::TestUnknownCommand::Id: + return "TestUnknownCommand"; + case chip::app::Clusters::UnitTesting::Commands::TestAddArguments::Id: + return "TestAddArguments"; + case chip::app::Clusters::UnitTesting::Commands::TestSimpleArgumentRequest::Id: + return "TestSimpleArgumentRequest"; + case chip::app::Clusters::UnitTesting::Commands::TestStructArrayArgumentRequest::Id: + return "TestStructArrayArgumentRequest"; + case chip::app::Clusters::UnitTesting::Commands::TestStructArgumentRequest::Id: + return "TestStructArgumentRequest"; + case chip::app::Clusters::UnitTesting::Commands::TestNestedStructArgumentRequest::Id: + return "TestNestedStructArgumentRequest"; + case chip::app::Clusters::UnitTesting::Commands::TestListStructArgumentRequest::Id: + return "TestListStructArgumentRequest"; + case chip::app::Clusters::UnitTesting::Commands::TestListInt8UArgumentRequest::Id: + return "TestListInt8UArgumentRequest"; + case chip::app::Clusters::UnitTesting::Commands::TestNestedStructListArgumentRequest::Id: + return "TestNestedStructListArgumentRequest"; + case chip::app::Clusters::UnitTesting::Commands::TestListNestedStructListArgumentRequest::Id: + return "TestListNestedStructListArgumentRequest"; + case chip::app::Clusters::UnitTesting::Commands::TestListInt8UReverseRequest::Id: + return "TestListInt8UReverseRequest"; + case chip::app::Clusters::UnitTesting::Commands::TestEnumsRequest::Id: + return "TestEnumsRequest"; + case chip::app::Clusters::UnitTesting::Commands::TestNullableOptionalRequest::Id: + return "TestNullableOptionalRequest"; + case chip::app::Clusters::UnitTesting::Commands::TestComplexNullableOptionalRequest::Id: + return "TestComplexNullableOptionalRequest"; + case chip::app::Clusters::UnitTesting::Commands::SimpleStructEchoRequest::Id: + return "SimpleStructEchoRequest"; + case chip::app::Clusters::UnitTesting::Commands::TimedInvokeRequest::Id: + return "TimedInvokeRequest"; + case chip::app::Clusters::UnitTesting::Commands::TestSimpleOptionalArgumentRequest::Id: + return "TestSimpleOptionalArgumentRequest"; + case chip::app::Clusters::UnitTesting::Commands::TestEmitTestEventRequest::Id: + return "TestEmitTestEventRequest"; + case chip::app::Clusters::UnitTesting::Commands::TestEmitTestFabricScopedEventRequest::Id: + return "TestEmitTestFabricScopedEventRequest"; + case chip::app::Clusters::UnitTesting::Commands::TestBatchHelperRequest::Id: + return "TestBatchHelperRequest"; + case chip::app::Clusters::UnitTesting::Commands::TestSecondBatchHelperRequest::Id: + return "TestSecondBatchHelperRequest"; + case chip::app::Clusters::UnitTesting::Commands::StringEchoRequest::Id: + return "StringEchoRequest"; + case chip::app::Clusters::UnitTesting::Commands::GlobalEchoRequest::Id: + return "GlobalEchoRequest"; + case chip::app::Clusters::UnitTesting::Commands::TestDifferentVendorMeiRequest::Id: + return "TestDifferentVendorMeiRequest"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::FaultInjection::Id: { + switch (id) + { + case chip::app::Clusters::FaultInjection::Commands::FailAtFault::Id: + return "FailAtFault"; + case chip::app::Clusters::FaultInjection::Commands::FailRandomlyAtFault::Id: + return "FailRandomlyAtFault"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::SampleMei::Id: { + switch (id) + { + case chip::app::Clusters::SampleMei::Commands::Ping::Id: + return "Ping"; + case chip::app::Clusters::SampleMei::Commands::AddArguments::Id: + return "AddArguments"; + default: + return "Unknown"; + } + } + default: + return "Unknown"; + } +} + +char const * GeneratedCommandIdToText(chip::ClusterId cluster, chip::CommandId id) +{ + switch (cluster) + { + case chip::app::Clusters::Groups::Id: { + switch (id) + { + case chip::app::Clusters::Groups::Commands::AddGroupResponse::Id: + return "AddGroupResponse"; + case chip::app::Clusters::Groups::Commands::ViewGroupResponse::Id: + return "ViewGroupResponse"; + case chip::app::Clusters::Groups::Commands::GetGroupMembershipResponse::Id: + return "GetGroupMembershipResponse"; + case chip::app::Clusters::Groups::Commands::RemoveGroupResponse::Id: + return "RemoveGroupResponse"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::AccessControl::Id: { + switch (id) + { + case chip::app::Clusters::AccessControl::Commands::ReviewFabricRestrictionsResponse::Id: + return "ReviewFabricRestrictionsResponse"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::OtaSoftwareUpdateProvider::Id: { + switch (id) + { + case chip::app::Clusters::OtaSoftwareUpdateProvider::Commands::QueryImageResponse::Id: + return "QueryImageResponse"; + case chip::app::Clusters::OtaSoftwareUpdateProvider::Commands::ApplyUpdateResponse::Id: + return "ApplyUpdateResponse"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::GeneralCommissioning::Id: { + switch (id) + { + case chip::app::Clusters::GeneralCommissioning::Commands::ArmFailSafeResponse::Id: + return "ArmFailSafeResponse"; + case chip::app::Clusters::GeneralCommissioning::Commands::SetRegulatoryConfigResponse::Id: + return "SetRegulatoryConfigResponse"; + case chip::app::Clusters::GeneralCommissioning::Commands::CommissioningCompleteResponse::Id: + return "CommissioningCompleteResponse"; + case chip::app::Clusters::GeneralCommissioning::Commands::SetTCAcknowledgementsResponse::Id: + return "SetTCAcknowledgementsResponse"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::NetworkCommissioning::Id: { + switch (id) + { + case chip::app::Clusters::NetworkCommissioning::Commands::ScanNetworksResponse::Id: + return "ScanNetworksResponse"; + case chip::app::Clusters::NetworkCommissioning::Commands::NetworkConfigResponse::Id: + return "NetworkConfigResponse"; + case chip::app::Clusters::NetworkCommissioning::Commands::ConnectNetworkResponse::Id: + return "ConnectNetworkResponse"; + case chip::app::Clusters::NetworkCommissioning::Commands::QueryIdentityResponse::Id: + return "QueryIdentityResponse"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::DiagnosticLogs::Id: { + switch (id) + { + case chip::app::Clusters::DiagnosticLogs::Commands::RetrieveLogsResponse::Id: + return "RetrieveLogsResponse"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::GeneralDiagnostics::Id: { + switch (id) + { + case chip::app::Clusters::GeneralDiagnostics::Commands::TimeSnapshotResponse::Id: + return "TimeSnapshotResponse"; + case chip::app::Clusters::GeneralDiagnostics::Commands::PayloadTestResponse::Id: + return "PayloadTestResponse"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::TimeSynchronization::Id: { + switch (id) + { + case chip::app::Clusters::TimeSynchronization::Commands::SetTimeZoneResponse::Id: + return "SetTimeZoneResponse"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::OperationalCredentials::Id: { + switch (id) + { + case chip::app::Clusters::OperationalCredentials::Commands::AttestationResponse::Id: + return "AttestationResponse"; + case chip::app::Clusters::OperationalCredentials::Commands::CertificateChainResponse::Id: + return "CertificateChainResponse"; + case chip::app::Clusters::OperationalCredentials::Commands::CSRResponse::Id: + return "CSRResponse"; + case chip::app::Clusters::OperationalCredentials::Commands::NOCResponse::Id: + return "NOCResponse"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::GroupKeyManagement::Id: { + switch (id) + { + case chip::app::Clusters::GroupKeyManagement::Commands::KeySetReadResponse::Id: + return "KeySetReadResponse"; + case chip::app::Clusters::GroupKeyManagement::Commands::KeySetReadAllIndicesResponse::Id: + return "KeySetReadAllIndicesResponse"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::IcdManagement::Id: { + switch (id) + { + case chip::app::Clusters::IcdManagement::Commands::RegisterClientResponse::Id: + return "RegisterClientResponse"; + case chip::app::Clusters::IcdManagement::Commands::StayActiveResponse::Id: + return "StayActiveResponse"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::OvenCavityOperationalState::Id: { + switch (id) + { + case chip::app::Clusters::OvenCavityOperationalState::Commands::OperationalCommandResponse::Id: + return "OperationalCommandResponse"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::OvenMode::Id: { + switch (id) + { + case chip::app::Clusters::OvenMode::Commands::ChangeToModeResponse::Id: + return "ChangeToModeResponse"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::LaundryWasherMode::Id: { + switch (id) + { + case chip::app::Clusters::LaundryWasherMode::Commands::ChangeToModeResponse::Id: + return "ChangeToModeResponse"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::RefrigeratorAndTemperatureControlledCabinetMode::Id: { + switch (id) + { + case chip::app::Clusters::RefrigeratorAndTemperatureControlledCabinetMode::Commands::ChangeToModeResponse::Id: + return "ChangeToModeResponse"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::RvcRunMode::Id: { + switch (id) + { + case chip::app::Clusters::RvcRunMode::Commands::ChangeToModeResponse::Id: + return "ChangeToModeResponse"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::RvcCleanMode::Id: { + switch (id) + { + case chip::app::Clusters::RvcCleanMode::Commands::ChangeToModeResponse::Id: + return "ChangeToModeResponse"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::DishwasherMode::Id: { + switch (id) + { + case chip::app::Clusters::DishwasherMode::Commands::ChangeToModeResponse::Id: + return "ChangeToModeResponse"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::OperationalState::Id: { + switch (id) + { + case chip::app::Clusters::OperationalState::Commands::OperationalCommandResponse::Id: + return "OperationalCommandResponse"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::RvcOperationalState::Id: { + switch (id) + { + case chip::app::Clusters::RvcOperationalState::Commands::OperationalCommandResponse::Id: + return "OperationalCommandResponse"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::ScenesManagement::Id: { + switch (id) + { + case chip::app::Clusters::ScenesManagement::Commands::AddSceneResponse::Id: + return "AddSceneResponse"; + case chip::app::Clusters::ScenesManagement::Commands::ViewSceneResponse::Id: + return "ViewSceneResponse"; + case chip::app::Clusters::ScenesManagement::Commands::RemoveSceneResponse::Id: + return "RemoveSceneResponse"; + case chip::app::Clusters::ScenesManagement::Commands::RemoveAllScenesResponse::Id: + return "RemoveAllScenesResponse"; + case chip::app::Clusters::ScenesManagement::Commands::StoreSceneResponse::Id: + return "StoreSceneResponse"; + case chip::app::Clusters::ScenesManagement::Commands::GetSceneMembershipResponse::Id: + return "GetSceneMembershipResponse"; + case chip::app::Clusters::ScenesManagement::Commands::CopySceneResponse::Id: + return "CopySceneResponse"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::EnergyEvse::Id: { + switch (id) + { + case chip::app::Clusters::EnergyEvse::Commands::GetTargetsResponse::Id: + return "GetTargetsResponse"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::EnergyEvseMode::Id: { + switch (id) + { + case chip::app::Clusters::EnergyEvseMode::Commands::ChangeToModeResponse::Id: + return "ChangeToModeResponse"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::WaterHeaterMode::Id: { + switch (id) + { + case chip::app::Clusters::WaterHeaterMode::Commands::ChangeToModeResponse::Id: + return "ChangeToModeResponse"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::DeviceEnergyManagementMode::Id: { + switch (id) + { + case chip::app::Clusters::DeviceEnergyManagementMode::Commands::ChangeToModeResponse::Id: + return "ChangeToModeResponse"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::DoorLock::Id: { + switch (id) + { + case chip::app::Clusters::DoorLock::Commands::GetWeekDayScheduleResponse::Id: + return "GetWeekDayScheduleResponse"; + case chip::app::Clusters::DoorLock::Commands::GetYearDayScheduleResponse::Id: + return "GetYearDayScheduleResponse"; + case chip::app::Clusters::DoorLock::Commands::GetHolidayScheduleResponse::Id: + return "GetHolidayScheduleResponse"; + case chip::app::Clusters::DoorLock::Commands::GetUserResponse::Id: + return "GetUserResponse"; + case chip::app::Clusters::DoorLock::Commands::SetCredentialResponse::Id: + return "SetCredentialResponse"; + case chip::app::Clusters::DoorLock::Commands::GetCredentialStatusResponse::Id: + return "GetCredentialStatusResponse"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::ServiceArea::Id: { + switch (id) + { + case chip::app::Clusters::ServiceArea::Commands::SelectAreasResponse::Id: + return "SelectAreasResponse"; + case chip::app::Clusters::ServiceArea::Commands::SkipAreaResponse::Id: + return "SkipAreaResponse"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::Thermostat::Id: { + switch (id) + { + case chip::app::Clusters::Thermostat::Commands::GetWeeklyScheduleResponse::Id: + return "GetWeeklyScheduleResponse"; + case chip::app::Clusters::Thermostat::Commands::AtomicResponse::Id: + return "AtomicResponse"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::WiFiNetworkManagement::Id: { + switch (id) + { + case chip::app::Clusters::WiFiNetworkManagement::Commands::NetworkPassphraseResponse::Id: + return "NetworkPassphraseResponse"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::ThreadBorderRouterManagement::Id: { + switch (id) + { + case chip::app::Clusters::ThreadBorderRouterManagement::Commands::DatasetResponse::Id: + return "DatasetResponse"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::ThreadNetworkDirectory::Id: { + switch (id) + { + case chip::app::Clusters::ThreadNetworkDirectory::Commands::OperationalDatasetResponse::Id: + return "OperationalDatasetResponse"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::Channel::Id: { + switch (id) + { + case chip::app::Clusters::Channel::Commands::ChangeChannelResponse::Id: + return "ChangeChannelResponse"; + case chip::app::Clusters::Channel::Commands::ProgramGuideResponse::Id: + return "ProgramGuideResponse"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::TargetNavigator::Id: { + switch (id) + { + case chip::app::Clusters::TargetNavigator::Commands::NavigateTargetResponse::Id: + return "NavigateTargetResponse"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::MediaPlayback::Id: { + switch (id) + { + case chip::app::Clusters::MediaPlayback::Commands::PlaybackResponse::Id: + return "PlaybackResponse"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::KeypadInput::Id: { + switch (id) + { + case chip::app::Clusters::KeypadInput::Commands::SendKeyResponse::Id: + return "SendKeyResponse"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::ContentLauncher::Id: { + switch (id) + { + case chip::app::Clusters::ContentLauncher::Commands::LauncherResponse::Id: + return "LauncherResponse"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::ApplicationLauncher::Id: { + switch (id) + { + case chip::app::Clusters::ApplicationLauncher::Commands::LauncherResponse::Id: + return "LauncherResponse"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::AccountLogin::Id: { + switch (id) + { + case chip::app::Clusters::AccountLogin::Commands::GetSetupPINResponse::Id: + return "GetSetupPINResponse"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::ContentControl::Id: { + switch (id) + { + case chip::app::Clusters::ContentControl::Commands::ResetPINResponse::Id: + return "ResetPINResponse"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::ContentAppObserver::Id: { + switch (id) + { + case chip::app::Clusters::ContentAppObserver::Commands::ContentAppMessageResponse::Id: + return "ContentAppMessageResponse"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::CommissionerControl::Id: { + switch (id) + { + case chip::app::Clusters::CommissionerControl::Commands::ReverseOpenCommissioningWindow::Id: + return "ReverseOpenCommissioningWindow"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::ElectricalMeasurement::Id: { + switch (id) + { + case chip::app::Clusters::ElectricalMeasurement::Commands::GetProfileInfoResponseCommand::Id: + return "GetProfileInfoResponseCommand"; + case chip::app::Clusters::ElectricalMeasurement::Commands::GetMeasurementProfileResponseCommand::Id: + return "GetMeasurementProfileResponseCommand"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::UnitTesting::Id: { + switch (id) + { + case chip::app::Clusters::UnitTesting::Commands::TestSpecificResponse::Id: + return "TestSpecificResponse"; + case chip::app::Clusters::UnitTesting::Commands::TestAddArgumentsResponse::Id: + return "TestAddArgumentsResponse"; + case chip::app::Clusters::UnitTesting::Commands::TestSimpleArgumentResponse::Id: + return "TestSimpleArgumentResponse"; + case chip::app::Clusters::UnitTesting::Commands::TestStructArrayArgumentResponse::Id: + return "TestStructArrayArgumentResponse"; + case chip::app::Clusters::UnitTesting::Commands::TestListInt8UReverseResponse::Id: + return "TestListInt8UReverseResponse"; + case chip::app::Clusters::UnitTesting::Commands::TestEnumsResponse::Id: + return "TestEnumsResponse"; + case chip::app::Clusters::UnitTesting::Commands::TestNullableOptionalResponse::Id: + return "TestNullableOptionalResponse"; + case chip::app::Clusters::UnitTesting::Commands::TestComplexNullableOptionalResponse::Id: + return "TestComplexNullableOptionalResponse"; + case chip::app::Clusters::UnitTesting::Commands::BooleanResponse::Id: + return "BooleanResponse"; + case chip::app::Clusters::UnitTesting::Commands::SimpleStructResponse::Id: + return "SimpleStructResponse"; + case chip::app::Clusters::UnitTesting::Commands::TestEmitTestEventResponse::Id: + return "TestEmitTestEventResponse"; + case chip::app::Clusters::UnitTesting::Commands::TestEmitTestFabricScopedEventResponse::Id: + return "TestEmitTestFabricScopedEventResponse"; + case chip::app::Clusters::UnitTesting::Commands::TestBatchHelperResponse::Id: + return "TestBatchHelperResponse"; + case chip::app::Clusters::UnitTesting::Commands::StringEchoResponse::Id: + return "StringEchoResponse"; + case chip::app::Clusters::UnitTesting::Commands::GlobalEchoResponse::Id: + return "GlobalEchoResponse"; + case chip::app::Clusters::UnitTesting::Commands::TestDifferentVendorMeiResponse::Id: + return "TestDifferentVendorMeiResponse"; + default: + return "Unknown"; + } + } + case chip::app::Clusters::SampleMei::Id: { + switch (id) + { + case chip::app::Clusters::SampleMei::Commands::AddArgumentsResponse::Id: + return "AddArgumentsResponse"; + default: + return "Unknown"; + } + } + default: + return "Unknown"; + } +} diff --git a/zzz_generated/chip-tool/zap-generated/cluster/logging/EntryToText.h b/zzz_generated/chip-tool/zap-generated/cluster/logging/EntryToText.h new file mode 100644 index 0000000000..27fa6512fb --- /dev/null +++ b/zzz_generated/chip-tool/zap-generated/cluster/logging/EntryToText.h @@ -0,0 +1,30 @@ +/* + * + * 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. + */ + +// THIS FILE IS GENERATED BY ZAP + +#include +#include +#include + +char const * ClusterIdToText(chip::ClusterId id); + +char const * AttributeIdToText(chip::ClusterId cluster, chip::AttributeId id); + +char const * AcceptedCommandIdToText(chip::ClusterId cluster, chip::CommandId id); + +char const * GeneratedCommandIdToText(chip::ClusterId cluster, chip::CommandId id); From 07789d41bb849e18a970451c6bd6c7189cbc5362 Mon Sep 17 00:00:00 2001 From: William Date: Thu, 22 Aug 2024 09:56:19 +0100 Subject: [PATCH 138/165] Truncate map and area names (#35127) * Updated the setting of the area and map names so that if the name given is greater than the buffer size, it's truncated rater to set to empty. * Restyled by clang-format --------- Co-authored-by: Restyled.io --- .../service-area-cluster-objects.h | 23 +++++++++++-------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/src/app/clusters/service-area-server/service-area-cluster-objects.h b/src/app/clusters/service-area-server/service-area-cluster-objects.h index 66f2072070..69a392a874 100644 --- a/src/app/clusters/service-area-server/service-area-cluster-objects.h +++ b/src/app/clusters/service-area-server/service-area-cluster-objects.h @@ -109,12 +109,14 @@ struct AreaStructureWrapper : public chip::app::Clusters::ServiceArea::Structs:: const DataModel::Nullable & areaType) { areaDesc.locationInfo.SetNonNull(); - // Copy the name - auto areaNameSpan = MutableCharSpan(mAreaNameBuffer, kAreaNameMaxSize); - CopyCharSpanToMutableCharSpan(locationName, areaNameSpan); - areaDesc.locationInfo.Value().locationName = CharSpan(areaNameSpan.data(), areaNameSpan.size()); - areaDesc.locationInfo.Value().floorNumber = floorNumber; - areaDesc.locationInfo.Value().areaType = areaType; + + // Copy the name. If the name is larger than kAreaNameMaxSize, truncate it to fit. + auto sizeToCopy = std::min(kAreaNameMaxSize, locationName.size()); + memcpy(mAreaNameBuffer, locationName.data(), sizeToCopy); + areaDesc.locationInfo.Value().locationName = CharSpan(mAreaNameBuffer, sizeToCopy); + + areaDesc.locationInfo.Value().floorNumber = floorNumber; + areaDesc.locationInfo.Value().areaType = areaType; return *this; } @@ -320,10 +322,11 @@ struct MapStructureWrapper : public chip::app::Clusters::ServiceArea::Structs::M */ void Set(uint32_t aMapId, const CharSpan & aMapName) { - mapID = aMapId; - auto mapNameSpan = MutableCharSpan(mMapNameBuffer, kMapNameMaxSize); - CopyCharSpanToMutableCharSpan(aMapName, mapNameSpan); - name = CharSpan(mapNameSpan.data(), mapNameSpan.size()); + mapID = aMapId; + // Copy the name. If the name is larger than kMapNameMaxSize, truncate it to fit. + auto sizeToCopy = std::min(kMapNameMaxSize, aMapName.size()); + memcpy(mMapNameBuffer, aMapName.data(), sizeToCopy); + name = CharSpan(mMapNameBuffer, sizeToCopy); } /** From 607a6da04159723dd251262b960c5389bbd6318a Mon Sep 17 00:00:00 2001 From: Sean <97990350+s-mcclain@users.noreply.github.com> Date: Thu, 22 Aug 2024 09:56:36 -0500 Subject: [PATCH 139/165] Add new CHIP_CONFIG_ADDRESS_RESOLVE_MIN_LOOKUP_TIME_MS and (#35102) CHIP_CONFIG_ADDRESS_RESOLVE_MAX_LOOKUP_TIME_MS macros to CHIPConfig. Use new lookup time min/max macros inside AddressResolve for default kMinLookupTimeMsDefault and kMaxLookupTimeMsDefault to allow for applications to override the time required to wait for an address lookup before timing out. --- src/lib/address_resolve/AddressResolve.h | 10 ++++++++-- src/lib/core/CHIPConfig.h | 22 ++++++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/src/lib/address_resolve/AddressResolve.h b/src/lib/address_resolve/AddressResolve.h index 0d6f8ab719..1e45ffed5d 100644 --- a/src/lib/address_resolve/AddressResolve.h +++ b/src/lib/address_resolve/AddressResolve.h @@ -143,8 +143,14 @@ class NodeLookupRequest } private: - static constexpr uint32_t kMinLookupTimeMsDefault = 200; - static constexpr uint32_t kMaxLookupTimeMsDefault = 45000; + static_assert((CHIP_CONFIG_ADDRESS_RESOLVE_MIN_LOOKUP_TIME_MS) <= (CHIP_CONFIG_ADDRESS_RESOLVE_MAX_LOOKUP_TIME_MS), + "AddressResolveMinLookupTime must be equal or less than AddressResolveMaxLookupTime"); + static_assert((CHIP_CONFIG_ADDRESS_RESOLVE_MIN_LOOKUP_TIME_MS) >= 0, + "AddressResolveMinLookupTime must be equal or greater than 0"); + static_assert((CHIP_CONFIG_ADDRESS_RESOLVE_MAX_LOOKUP_TIME_MS) < UINT32_MAX, + "AddressResolveMaxLookupTime must be less than UINT32_MAX"); + static constexpr uint32_t kMinLookupTimeMsDefault = CHIP_CONFIG_ADDRESS_RESOLVE_MIN_LOOKUP_TIME_MS; + static constexpr uint32_t kMaxLookupTimeMsDefault = CHIP_CONFIG_ADDRESS_RESOLVE_MAX_LOOKUP_TIME_MS; PeerId mPeerId; System::Clock::Milliseconds32 mMinLookupTimeMs{ kMinLookupTimeMsDefault }; diff --git a/src/lib/core/CHIPConfig.h b/src/lib/core/CHIPConfig.h index e9c317dfc7..7600b4eaa4 100644 --- a/src/lib/core/CHIPConfig.h +++ b/src/lib/core/CHIPConfig.h @@ -1370,6 +1370,28 @@ extern const char CHIP_NON_PRODUCTION_MARKER[]; #define CHIP_CONFIG_MDNS_RESOLVE_LOOKUP_RESULTS 1 #endif // CHIP_CONFIG_MDNS_RESOLVE_LOOKUP_RESULTS +/** + * @def CHIP_CONFIG_ADDRESS_RESOLVE_MIN_LOOKUP_TIME_MS + * + * @brief Default minimum lookup time to wait during address resolve for + * additional DNSSD queries even if a reply has already been received, or + * to allow for additional heuristics regarding node choice to succeed, in + * milliseconds + */ +#ifndef CHIP_CONFIG_ADDRESS_RESOLVE_MIN_LOOKUP_TIME_MS +#define CHIP_CONFIG_ADDRESS_RESOLVE_MIN_LOOKUP_TIME_MS 200 +#endif // CHIP_CONFIG_ADDRESS_RESOLVE_MIN_LOOKUP_TIME_MS + +/** + * @def CHIP_CONFIG_ADDRESS_RESOLVE_MAX_LOOKUP_TIME_MS + * + * @brief Default maximum lookup time to wait during address resolve before + * a TIMEOUT error, in milliseconds + */ +#ifndef CHIP_CONFIG_ADDRESS_RESOLVE_MAX_LOOKUP_TIME_MS +#define CHIP_CONFIG_ADDRESS_RESOLVE_MAX_LOOKUP_TIME_MS 45000 +#endif // CHIP_CONFIG_ADDRESS_RESOLVE_MAX_LOOKUP_TIME_MS + /* * @def CHIP_CONFIG_NETWORK_COMMISSIONING_DEBUG_TEXT_BUFFER_SIZE * From 58896ab304b7b7e1b7e0ae279c1a4ba271952d5e Mon Sep 17 00:00:00 2001 From: Arkadiusz Bokowy Date: Thu, 22 Aug 2024 16:58:21 +0200 Subject: [PATCH 140/165] Fix CHIP REPL tests runner after changes in e407d40 (#34453) * Fix CHIP REPL tests runner after changes in e407d40 The click framework does not have a support for async functions. The async needs to be synchronized before applying click wrappers. * Accept 0x, 0b or 0o prefix for int values * Fix for non-string numbers * Exclude Test_TC_BRBINFO_2_1 from chip-repl engine * Log what happened in case of pseudo cluster creation failure * Fix typo * Fix typo when accessing TestGlobalStruct * Fix new line --- scripts/tests/chiptest/__init__.py | 1 + .../tests/chiptest/yamltest_with_chip_repl_tester.py | 11 ++++++++++- src/controller/python/chip/yaml/format_converter.py | 7 ++++--- src/controller/python/chip/yaml/runner.py | 3 ++- 4 files changed, 17 insertions(+), 5 deletions(-) diff --git a/scripts/tests/chiptest/__init__.py b/scripts/tests/chiptest/__init__.py index aef22e030e..03ac663427 100644 --- a/scripts/tests/chiptest/__init__.py +++ b/scripts/tests/chiptest/__init__.py @@ -234,6 +234,7 @@ def _GetChipReplUnsupportedTests() -> Set[str]: "TestEventsById.yaml", # chip-repl does not support AnyCommands (06/06/2023) "TestReadNoneSubscribeNone.yaml", # chip-repl does not support AnyCommands (07/27/2023) "Test_TC_IDM_1_2.yaml", # chip-repl does not support AnyCommands (19/07/2023) + "Test_TC_BRBINFO_2_1.yaml", # chip-repl does not support AnyCommands (24/07/2024) "TestIcdManagementCluster.yaml", # TODO(#30430): add ICD registration support in chip-repl "Test_TC_ICDM_3_4.yaml", # chip-repl does not support ICD registration # chip-repl and chip-tool disagree on what the YAML here should look like: https://github.com/project-chip/connectedhomeip/issues/29110 diff --git a/scripts/tests/chiptest/yamltest_with_chip_repl_tester.py b/scripts/tests/chiptest/yamltest_with_chip_repl_tester.py index 1b301c5728..70f9215f54 100644 --- a/scripts/tests/chiptest/yamltest_with_chip_repl_tester.py +++ b/scripts/tests/chiptest/yamltest_with_chip_repl_tester.py @@ -16,6 +16,7 @@ import asyncio import atexit +import functools import logging import os import tempfile @@ -84,6 +85,13 @@ async def execute_test(yaml, runner): raise Exception(f'Test step failed {test_step.label}') +def asyncio_executor(f): + @functools.wraps(f) + def wrapper(*args, **kwargs): + return asyncio.run(f(*args, **kwargs)) + return wrapper + + @click.command() @click.option( '--setup-code', @@ -101,6 +109,7 @@ async def execute_test(yaml, runner): '--pics-file', default=None, help='Optional PICS file') +@asyncio_executor async def main(setup_code, yaml_path, node_id, pics_file): # Setting up python environment for running YAML CI tests using python parser. with tempfile.NamedTemporaryFile() as chip_stack_storage: @@ -153,4 +162,4 @@ def _StackShutDown(): if __name__ == '__main__': - asyncio.run(main()) + main() diff --git a/src/controller/python/chip/yaml/format_converter.py b/src/controller/python/chip/yaml/format_converter.py index eefe61f172..1be051155b 100644 --- a/src/controller/python/chip/yaml/format_converter.py +++ b/src/controller/python/chip/yaml/format_converter.py @@ -198,10 +198,11 @@ def convert_to_data_model_type(field_value, field_type): return field_value # YAML conversion treats all numbers as ints. Convert to a uint type if the schema # type indicates so. - elif (field_type == uint): + elif (type(field_value) is str and field_type == uint): # Longer number are stored as strings. Need to make this conversion first. - value = int(field_value) - return field_type(value) + # The value can be represented in binary, octal, decimal or hexadecimal + # format. + return field_type(int(field_value, 0)) # YAML treats enums as ints. Convert to the typed enum class. elif (issubclass(field_type, MatterIntEnum)): return field_type.extend_enum_if_value_doesnt_exist(field_value) diff --git a/src/controller/python/chip/yaml/runner.py b/src/controller/python/chip/yaml/runner.py index 00e0de2154..8a19109439 100644 --- a/src/controller/python/chip/yaml/runner.py +++ b/src/controller/python/chip/yaml/runner.py @@ -832,7 +832,8 @@ def _commissioner_command_action_factory(self, test_step): def _default_pseudo_cluster(self, test_step): try: return DefaultPseudoCluster(test_step) - except ActionCreationError: + except ActionCreationError as e: + logger.warn(f"Failed create default pseudo cluster: {e}") return None def encode(self, request) -> Optional[BaseAction]: From 7ad2fc9b2db389f10f963a1b1d546df43375edac Mon Sep 17 00:00:00 2001 From: Junior Martinez <67972863+jmartinez-silabs@users.noreply.github.com> Date: Thu, 22 Aug 2024 13:00:41 -0400 Subject: [PATCH 141/165] use CHIP_DEVICE_CONFIG_FAILSAFE_EXPIRY_LENGTH_SEC define to arme the failsafe (#35137) --- src/app/server/CommissioningWindowManager.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/app/server/CommissioningWindowManager.cpp b/src/app/server/CommissioningWindowManager.cpp index 47bc3e8ff9..01bff4bf07 100644 --- a/src/app/server/CommissioningWindowManager.cpp +++ b/src/app/server/CommissioningWindowManager.cpp @@ -221,7 +221,8 @@ void CommissioningWindowManager::OnSessionEstablished(const SessionHandle & sess } else { - err = failSafeContext.ArmFailSafe(kUndefinedFabricIndex, System::Clock::Seconds16(60)); + err = failSafeContext.ArmFailSafe(kUndefinedFabricIndex, + System::Clock::Seconds16(CHIP_DEVICE_CONFIG_FAILSAFE_EXPIRY_LENGTH_SEC)); if (err != CHIP_NO_ERROR) { ChipLogError(AppServer, "Error arming failsafe on PASE session establishment completion"); From ae5d75c69f6cec4fb62b991e57b895b6f4812291 Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Thu, 22 Aug 2024 13:13:04 -0400 Subject: [PATCH 142/165] Remove unnecessary invokeCommand overrides from MTRDevice_Concrete. (#35151) The one part that is not shared with the XPC implementation is _invokeCommandWithEndpointID:.... Everything else is just generic argument massaging and forwarding that can keep living in the base MTRDevice. --- .../Framework/CHIP/MTRDevice_Concrete.mm | 126 ------------------ 1 file changed, 126 deletions(-) diff --git a/src/darwin/Framework/CHIP/MTRDevice_Concrete.mm b/src/darwin/Framework/CHIP/MTRDevice_Concrete.mm index 120d29aff1..12614ea409 100644 --- a/src/darwin/Framework/CHIP/MTRDevice_Concrete.mm +++ b/src/darwin/Framework/CHIP/MTRDevice_Concrete.mm @@ -2835,59 +2835,6 @@ - (void)writeAttributeWithEndpointID:(NSNumber *)endpointID [_asyncWorkQueue enqueueWorkItem:workItem descriptionWithFormat:@"write %@ 0x%llx 0x%llx", endpointID, clusterID.unsignedLongLongValue, attributeID.unsignedLongLongValue]; } -- (void)invokeCommandWithEndpointID:(NSNumber *)endpointID - clusterID:(NSNumber *)clusterID - commandID:(NSNumber *)commandID - commandFields:(NSDictionary * _Nullable)commandFields - expectedValues:(NSArray *> * _Nullable)expectedValues - expectedValueInterval:(NSNumber * _Nullable)expectedValueInterval - queue:(dispatch_queue_t)queue - completion:(MTRDeviceResponseHandler)completion -{ - if (commandFields == nil) { - commandFields = @{ - MTRTypeKey : MTRStructureValueType, - MTRValueKey : @[], - }; - } - - [self invokeCommandWithEndpointID:endpointID - clusterID:clusterID - commandID:commandID - commandFields:commandFields - expectedValues:expectedValues - expectedValueInterval:expectedValueInterval - timedInvokeTimeout:nil - queue:queue - completion:completion]; -} - -- (void)invokeCommandWithEndpointID:(NSNumber *)endpointID - clusterID:(NSNumber *)clusterID - commandID:(NSNumber *)commandID - commandFields:(id)commandFields - expectedValues:(NSArray *> * _Nullable)expectedValues - expectedValueInterval:(NSNumber * _Nullable)expectedValueInterval - timedInvokeTimeout:(NSNumber * _Nullable)timeout - queue:(dispatch_queue_t)queue - completion:(MTRDeviceResponseHandler)completion -{ - // We don't have a way to communicate a non-default invoke timeout - // here for now. - // TODO: https://github.com/project-chip/connectedhomeip/issues/24563 - - [self _invokeCommandWithEndpointID:endpointID - clusterID:clusterID - commandID:commandID - commandFields:commandFields - expectedValues:expectedValues - expectedValueInterval:expectedValueInterval - timedInvokeTimeout:timeout - serverSideProcessingTimeout:nil - queue:queue - completion:completion]; -} - - (void)_invokeCommandWithEndpointID:(NSNumber *)endpointID clusterID:(NSNumber *)clusterID commandID:(NSNumber *)commandID @@ -2985,58 +2932,6 @@ - (void)_invokeCommandWithEndpointID:(NSNumber *)endpointID [_asyncWorkQueue enqueueWorkItem:workItem descriptionWithFormat:@"invoke %@ 0x%llx 0x%llx", endpointID, clusterID.unsignedLongLongValue, commandID.unsignedLongLongValue]; } -- (void)_invokeKnownCommandWithEndpointID:(NSNumber *)endpointID - clusterID:(NSNumber *)clusterID - commandID:(NSNumber *)commandID - commandPayload:(id)commandPayload - expectedValues:(NSArray *> * _Nullable)expectedValues - expectedValueInterval:(NSNumber * _Nullable)expectedValueInterval - timedInvokeTimeout:(NSNumber * _Nullable)timeout - serverSideProcessingTimeout:(NSNumber * _Nullable)serverSideProcessingTimeout - responseClass:(Class _Nullable)responseClass - queue:(dispatch_queue_t)queue - completion:(void (^)(id _Nullable response, NSError * _Nullable error))completion -{ - if (![commandPayload respondsToSelector:@selector(_encodeAsDataValue:)]) { - dispatch_async(queue, ^{ - completion(nil, [MTRError errorForCHIPErrorCode:CHIP_ERROR_INVALID_ARGUMENT]); - }); - return; - } - - NSError * encodingError; - auto * commandFields = [commandPayload _encodeAsDataValue:&encodingError]; - if (commandFields == nil) { - dispatch_async(queue, ^{ - completion(nil, encodingError); - }); - return; - } - - auto responseHandler = ^(NSArray *> * _Nullable values, NSError * _Nullable error) { - id _Nullable response = nil; - if (error == nil) { - if (values.count != 1) { - error = [NSError errorWithDomain:MTRErrorDomain code:MTRErrorCodeSchemaMismatch userInfo:nil]; - } else if (responseClass != nil) { - response = [[responseClass alloc] initWithResponseValue:values[0] error:&error]; - } - } - completion(response, error); - }; - - [self _invokeCommandWithEndpointID:endpointID - clusterID:clusterID - commandID:commandID - commandFields:commandFields - expectedValues:expectedValues - expectedValueInterval:expectedValueInterval - timedInvokeTimeout:timeout - serverSideProcessingTimeout:serverSideProcessingTimeout - queue:queue - completion:responseHandler]; -} - - (void)openCommissioningWindowWithSetupPasscode:(NSNumber *)setupPasscode discriminator:(NSNumber *)discriminator duration:(NSNumber *)duration @@ -4072,27 +3967,6 @@ + (MTRDevice *)deviceWithNodeID:(uint64_t)nodeID deviceController:(MTRDeviceCont return [self deviceWithNodeID:@(nodeID) controller:deviceController]; } -- (void)invokeCommandWithEndpointID:(NSNumber *)endpointID - clusterID:(NSNumber *)clusterID - commandID:(NSNumber *)commandID - commandFields:(id)commandFields - expectedValues:(NSArray *> * _Nullable)expectedValues - expectedValueInterval:(NSNumber * _Nullable)expectedValueInterval - timedInvokeTimeout:(NSNumber * _Nullable)timeout - clientQueue:(dispatch_queue_t)queue - completion:(MTRDeviceResponseHandler)completion -{ - [self invokeCommandWithEndpointID:endpointID - clusterID:clusterID - commandID:commandID - commandFields:commandFields - expectedValues:expectedValues - expectedValueInterval:expectedValueInterval - timedInvokeTimeout:timeout - queue:queue - completion:completion]; -} - @end #pragma mark - SubscriptionCallback From 26956012d4d6d6a14796a2894ffe4af0a3c88ff9 Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Thu, 22 Aug 2024 13:16:50 -0400 Subject: [PATCH 143/165] Remove readAttributeWithEndpointID implementation from MTRDevice. (#35150) This is implemented (differently) by the different subclasses. Once this implementation is removed, the following become unreachable and can be removed: * _attributeValueDictionaryForAttributePath * _subscriptionAbleToReport * _readThroughSkipped At that point _subscriptionsAllowed becomes unreachable and can be removed. --- src/darwin/Framework/CHIP/MTRDevice.mm | 229 +------------------------ 1 file changed, 7 insertions(+), 222 deletions(-) diff --git a/src/darwin/Framework/CHIP/MTRDevice.mm b/src/darwin/Framework/CHIP/MTRDevice.mm index d4027f7725..3f2acce5f5 100644 --- a/src/darwin/Framework/CHIP/MTRDevice.mm +++ b/src/darwin/Framework/CHIP/MTRDevice.mm @@ -649,21 +649,7 @@ - (void)_setDSTOffsets:(NSArray return outputArray; } -#pragma mark Subscription and delegate handling - -// subscription intervals are in seconds -#define MTR_DEVICE_SUBSCRIPTION_MAX_INTERVAL_MIN (10 * 60) // 10 minutes (for now) -#define MTR_DEVICE_SUBSCRIPTION_MAX_INTERVAL_MAX (60 * 60) // 60 minutes - -- (BOOL)_subscriptionsAllowed -{ - os_unfair_lock_assert_owner(&self->_lock); - - // TODO: XPC: This function and all its callsites should go away from this class. - - // We should not allow a subscription for device controllers over XPC. - return ![_deviceController isKindOfClass:MTRDeviceControllerOverXPC.class]; -} +#pragma mark Delegate handling - (void)setDelegate:(id)delegate queue:(dispatch_queue_t)queue { @@ -757,41 +743,6 @@ - (void)nodeMayBeAdvertisingOperational MTR_LOG("%@ saw new operational advertisement", self); } -// Return YES if we are in a state where, apart from communication issues with -// the device, we will be able to get reports via our subscription. -- (BOOL)_subscriptionAbleToReport -{ - std::lock_guard lock(_lock); - if (![self _delegateExists]) { - // No delegate definitely means no subscription. - return NO; - } - - // For unit testing only, matching logic in setDelegate -#ifdef DEBUG - __block BOOL useTestDelegateOverride = NO; - __block BOOL testDelegateShouldSetUpSubscriptionForDevice = NO; - [self _callFirstDelegateSynchronouslyWithBlock:^(id testDelegate) { - if ([testDelegate respondsToSelector:@selector(unitTestShouldSetUpSubscriptionForDevice:)]) { - useTestDelegateOverride = YES; - testDelegateShouldSetUpSubscriptionForDevice = [testDelegate unitTestShouldSetUpSubscriptionForDevice:self]; - } - }]; - if (useTestDelegateOverride && !testDelegateShouldSetUpSubscriptionForDevice) { - return NO; - } - -#endif - - // Subscriptions are not able to report if they are not allowed. - return [self _subscriptionsAllowed]; -} - -// Notification that read-through was skipped for an attribute read. -- (void)_readThroughSkipped -{ -} - - (BOOL)_delegateExists { os_unfair_lock_assert_owner(&self->_lock); @@ -1880,147 +1831,12 @@ static BOOL AttributeHasChangesOmittedQuality(MTRAttributePath * attributePath) attributeID:(NSNumber *)attributeID params:(MTRReadParams * _Nullable)params { - MTRAttributePath * attributePath = [MTRAttributePath attributePathWithEndpointID:endpointID - clusterID:clusterID - attributeID:attributeID]; - - BOOL attributeIsSpecified = MTRAttributeIsSpecified(clusterID.unsignedIntValue, attributeID.unsignedIntValue); - BOOL hasChangesOmittedQuality; - if (attributeIsSpecified) { - hasChangesOmittedQuality = AttributeHasChangesOmittedQuality(attributePath); - } else { - if (params == nil) { - hasChangesOmittedQuality = NO; - } else { - hasChangesOmittedQuality = !params.assumeUnknownAttributesReportable; - } - } - - // Return current known / expected value right away - NSDictionary * attributeValueToReturn = [self _attributeValueDictionaryForAttributePath:attributePath]; - - // Send read request to device if any of the following are true: - // 1. Subscription not in a state we can expect reports - // 2. The attribute has the Changes Omitted quality, so we won't get reports for it. - // 3. The attribute is not in the spec, and the read params asks to assume - // an unknown attribute has the Changes Omitted quality. - if (![self _subscriptionAbleToReport] || hasChangesOmittedQuality) { - // Read requests container will be a mutable array of items, each being an array containing: - // [attribute request path, params] - // Batching handler should only coalesce when params are equal. - - // For this single read API there's only 1 array item. Use NSNull to stand in for nil params for easy comparison. - MTRAttributeRequestPath * readRequestPath = [MTRAttributeRequestPath requestPathWithEndpointID:endpointID - clusterID:clusterID - attributeID:attributeID]; - NSArray * readRequestData = @[ readRequestPath, params ?: [NSNull null] ]; - - // But first, check if a duplicate read request is already queued and return - if ([_asyncWorkQueue hasDuplicateForTypeID:MTRDeviceWorkItemDuplicateReadTypeID workItemData:readRequestData]) { - return attributeValueToReturn; - } - - NSMutableArray * readRequests = [NSMutableArray arrayWithObject:readRequestData]; - - // Create work item, set ready handler to perform task, then enqueue the work - MTRAsyncWorkItem * workItem = [[MTRAsyncWorkItem alloc] initWithQueue:self.queue]; - uint64_t workItemID = workItem.uniqueID; // capture only the ID, not the work item - NSNumber * nodeID = [self nodeID]; - - [workItem setBatchingID:MTRDeviceWorkItemBatchingReadID data:readRequests handler:^(id opaqueDataCurrent, id opaqueDataNext) { - mtr_hide(self); // don't capture self accidentally - NSMutableArray * readRequestsCurrent = opaqueDataCurrent; - NSMutableArray * readRequestsNext = opaqueDataNext; - - MTRBatchingOutcome outcome = MTRNotBatched; - while (readRequestsNext.count) { - // Can only read up to 9 paths at a time, per spec - if (readRequestsCurrent.count >= 9) { - MTR_LOG("Batching read attribute work item [%llu]: cannot add more work, item is full [0x%016llX:%@:0x%llx:0x%llx]", workItemID, nodeID.unsignedLongLongValue, endpointID, clusterID.unsignedLongLongValue, attributeID.unsignedLongLongValue); - return outcome; - } - - // if params don't match then they cannot be merged - if (![readRequestsNext[0][MTRDeviceReadRequestFieldParamsIndex] - isEqual:readRequestsCurrent[0][MTRDeviceReadRequestFieldParamsIndex]]) { - MTR_LOG("Batching read attribute work item [%llu]: cannot add more work, parameter mismatch [0x%016llX:%@:0x%llx:0x%llx]", workItemID, nodeID.unsignedLongLongValue, endpointID, clusterID.unsignedLongLongValue, attributeID.unsignedLongLongValue); - return outcome; - } - - // merge the next item's first request into the current item's list - auto readItem = readRequestsNext.firstObject; - [readRequestsNext removeObjectAtIndex:0]; - [readRequestsCurrent addObject:readItem]; - MTR_LOG("Batching read attribute work item [%llu]: added %@ (now %lu requests total) [0x%016llX:%@:0x%llx:0x%llx]", - workItemID, readItem, static_cast(readRequestsCurrent.count), nodeID.unsignedLongLongValue, endpointID, clusterID.unsignedLongLongValue, attributeID.unsignedLongLongValue); - outcome = MTRBatchedPartially; - } - NSCAssert(readRequestsNext.count == 0, @"should have batched everything or returned early"); - return MTRBatchedFully; - }]; - [workItem setDuplicateTypeID:MTRDeviceWorkItemDuplicateReadTypeID handler:^(id opaqueItemData, BOOL * isDuplicate, BOOL * stop) { - mtr_hide(self); // don't capture self accidentally - for (NSArray * readItem in readRequests) { - if ([readItem isEqual:opaqueItemData]) { - MTR_LOG("Read attribute work item [%llu] report duplicate %@ [0x%016llX:%@:0x%llx:0x%llx]", workItemID, readItem, nodeID.unsignedLongLongValue, endpointID, clusterID.unsignedLongLongValue, attributeID.unsignedLongLongValue); - *isDuplicate = YES; - *stop = YES; - return; - } - } - *stop = NO; - }]; - [workItem setReadyHandler:^(MTRDevice * self, NSInteger retryCount, MTRAsyncWorkCompletionBlock completion) { - // Sanity check - if (readRequests.count == 0) { - MTR_LOG_ERROR("Read attribute work item [%llu] contained no read requests", workItemID); - completion(MTRAsyncWorkComplete); - return; - } - - // Build the attribute paths from the read requests - NSMutableArray * attributePaths = [NSMutableArray array]; - for (NSArray * readItem in readRequests) { - NSAssert(readItem.count == 2, @"invalid read attribute item"); - [attributePaths addObject:readItem[MTRDeviceReadRequestFieldPathIndex]]; - } - // If param is the NSNull stand-in, then just use nil - id readParamObject = readRequests[0][MTRDeviceReadRequestFieldParamsIndex]; - MTRReadParams * readParams = (![readParamObject isEqual:[NSNull null]]) ? readParamObject : nil; - - MTRBaseDevice * baseDevice = [self newBaseDevice]; - [baseDevice - readAttributePaths:attributePaths - eventPaths:nil - params:readParams - includeDataVersion:YES - queue:self.queue - completion:^(NSArray *> * _Nullable values, NSError * _Nullable error) { - if (values) { - // Since the format is the same data-value dictionary, this looks like an - // attribute report - MTR_LOG("Read attribute work item [%llu] result: %@ [0x%016llX:%@:0x%llX:0x%llX]", workItemID, values, nodeID.unsignedLongLongValue, endpointID, clusterID.unsignedLongLongValue, attributeID.unsignedLongLongValue); - [self _handleAttributeReport:values fromSubscription:NO]; - } - - // TODO: better retry logic - if (error && (retryCount < 2)) { - MTR_LOG_ERROR("Read attribute work item [%llu] failed (will retry): %@ [0x%016llX:%@:0x%llx:0x%llx]", workItemID, error, nodeID.unsignedLongLongValue, endpointID, clusterID.unsignedLongLongValue, attributeID.unsignedLongLongValue); - completion(MTRAsyncWorkNeedsRetry); - } else { - if (error) { - MTR_LOG("Read attribute work item [%llu] failed (giving up): %@ [0x%016llX:%@:0x%llx:0x%llx]", workItemID, error, nodeID.unsignedLongLongValue, endpointID, clusterID.unsignedLongLongValue, attributeID.unsignedLongLongValue); - } - completion(MTRAsyncWorkComplete); - } - }]; - }]; - [_asyncWorkQueue enqueueWorkItem:workItem descriptionWithFormat:@"read %@ 0x%llx 0x%llx", endpointID, clusterID.unsignedLongLongValue, attributeID.unsignedLongLongValue]; - } else { - [self _readThroughSkipped]; - } - - return attributeValueToReturn; +#define ErrorStr "MTRDevice readAttributeWithEndpointID:clusterID:attributeID:params: must be handled by subclasses" + MTR_LOG_ERROR(ErrorStr); +#ifdef DEBUG + NSAssert(NO, @ErrorStr); +#endif // DEBUG + return nil; } - (void)writeAttributeWithEndpointID:(NSNumber *)endpointID @@ -2456,37 +2272,6 @@ - (void)_performScheduledExpirationCheck [self _checkExpiredExpectedValues]; } -// Get attribute value dictionary for an attribute path from the right cache -- (NSDictionary *)_attributeValueDictionaryForAttributePath:(MTRAttributePath *)attributePath -{ - std::lock_guard lock(_lock); - - // First check expected value cache - NSArray * expectedValue = _expectedValueCache[attributePath]; - if (expectedValue) { - NSDate * now = [NSDate date]; - if ([now compare:expectedValue[MTRDeviceExpectedValueFieldExpirationTimeIndex]] == NSOrderedDescending) { - // expired - purge and fall through - _expectedValueCache[attributePath] = nil; - } else { - // not yet expired - return result - return expectedValue[MTRDeviceExpectedValueFieldValueIndex]; - } - } - - // Then check read cache - NSDictionary * cachedAttributeValue = [self _cachedAttributeValueForPath:attributePath]; - if (cachedAttributeValue) { - return cachedAttributeValue; - } else { - // TODO: when not found in cache, generated default values should be used - MTR_LOG("%@ _attributeValueDictionaryForAttributePath: could not find cached attribute values for attribute %@", self, - attributePath); - } - - return nil; -} - - (BOOL)_attributeDataValue:(NSDictionary *)one isEqualToDataValue:(NSDictionary *)theOther { // Sanity check for nil cases From c6710f6268493f600b6d8ed5e7007abaa1c6f39e Mon Sep 17 00:00:00 2001 From: Arkadiusz Bokowy Date: Thu, 22 Aug 2024 21:12:55 +0200 Subject: [PATCH 144/165] Fix paths for fabric apps compiled with build_examples.py (#35123) * Fix paths for fabric apps compiled with build_examples.py * Require RPC to be enabled when building fabric-admin and fabric-bridge --- examples/fabric-admin/scripts/run_fabric_sync.sh | 8 ++++---- examples/fabric-admin/scripts/stop_fabric_sync.sh | 2 +- scripts/build/build/targets.py | 4 ++-- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/examples/fabric-admin/scripts/run_fabric_sync.sh b/examples/fabric-admin/scripts/run_fabric_sync.sh index 8c820d111c..957fe5f3cf 100755 --- a/examples/fabric-admin/scripts/run_fabric_sync.sh +++ b/examples/fabric-admin/scripts/run_fabric_sync.sh @@ -7,14 +7,14 @@ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" DEFAULT_ADMIN_CHOICES=( "./fabric-admin" "out/debug/standalone/fabric-admin" - "out/linux-x64-fabric-admin/fabric-admin" - "out/darwin-arm64-fabric-admin/fabric-admin" + "out/linux-x64-fabric-admin-rpc/fabric-admin" + "out/darwin-arm64-fabric-admin-rpc/fabric-admin" ) DEFAULT_BRIDGE_CHOICES=( "./fabric-bridge-app" "out/debug/standalone/fabric-bridge-app" - "out/linux-x64-fabric-bridge-app/fabric-bridge-app" - "out/darwin-arm64-fabric-bridge-app/fabric-bridge-app" + "out/linux-x64-fabric-bridge-rpc/fabric-bridge-app" + "out/darwin-arm64-fabric-bridge-rpc/fabric-bridge-app" ) FABRIC_ADMIN_LOG="/tmp/fabric_admin.log" FABRIC_BRIDGE_APP_LOG="/tmp/fabric_bridge_app.log" diff --git a/examples/fabric-admin/scripts/stop_fabric_sync.sh b/examples/fabric-admin/scripts/stop_fabric_sync.sh index e947c8992f..faa5c79ce2 100755 --- a/examples/fabric-admin/scripts/stop_fabric_sync.sh +++ b/examples/fabric-admin/scripts/stop_fabric_sync.sh @@ -20,5 +20,5 @@ if [ ! -z "$fabric_bridge_app_pid" ]; then fi # Remove /tmp/chip_* files and directories -sudo rm -rf /tmp/chip_* +rm -rf /tmp/chip_* echo "Removed /tmp/chip_* files and directories" diff --git a/scripts/build/build/targets.py b/scripts/build/build/targets.py index 8ab6e2ca4e..37ede960ac 100755 --- a/scripts/build/build/targets.py +++ b/scripts/build/build/targets.py @@ -128,8 +128,8 @@ def BuildHostTarget(): TargetPart('tv-app', app=HostApp.TV_APP), TargetPart('tv-casting-app', app=HostApp.TV_CASTING), TargetPart('bridge', app=HostApp.BRIDGE), - TargetPart('fabric-admin', app=HostApp.FABRIC_ADMIN), - TargetPart('fabric-bridge', app=HostApp.FABRIC_BRIDGE), + TargetPart('fabric-admin', app=HostApp.FABRIC_ADMIN).OnlyIfRe("-rpc"), + TargetPart('fabric-bridge', app=HostApp.FABRIC_BRIDGE).OnlyIfRe("-rpc"), TargetPart('tests', app=HostApp.TESTS), TargetPart('chip-cert', app=HostApp.CERT_TOOL), TargetPart('address-resolve-tool', app=HostApp.ADDRESS_RESOLVE), From c1403a4f68456eb238ae5d09be85b0699c2df75f Mon Sep 17 00:00:00 2001 From: Arkadiusz Bokowy Date: Thu, 22 Aug 2024 21:14:27 +0200 Subject: [PATCH 145/165] [Fabric-Sync] Allow to specify custom port in fabric-bridge (#35146) --- .../fabric-bridge-common/include/CHIPProjectAppConfig.h | 3 +++ examples/fabric-bridge-app/linux/args.gni | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/examples/fabric-bridge-app/fabric-bridge-common/include/CHIPProjectAppConfig.h b/examples/fabric-bridge-app/fabric-bridge-common/include/CHIPProjectAppConfig.h index 326ddf2857..5340798210 100644 --- a/examples/fabric-bridge-app/fabric-bridge-common/include/CHIPProjectAppConfig.h +++ b/examples/fabric-bridge-app/fabric-bridge-common/include/CHIPProjectAppConfig.h @@ -32,3 +32,6 @@ // include the CHIPProjectConfig from config/standalone #include + +// Allows app options (ports) to be configured on launch of app +#define CHIP_DEVICE_ENABLE_PORT_PARAMS 1 diff --git a/examples/fabric-bridge-app/linux/args.gni b/examples/fabric-bridge-app/linux/args.gni index acbabffb35..592855ea98 100644 --- a/examples/fabric-bridge-app/linux/args.gni +++ b/examples/fabric-bridge-app/linux/args.gni @@ -21,7 +21,7 @@ chip_project_config_include = "" chip_system_project_config_include = "" chip_project_config_include_dirs = - [ "${chip_root}/examples/bridge-app/bridge-common/include" ] + [ "${chip_root}/examples/fabric-bridge-app/fabric-bridge-common/include" ] chip_project_config_include_dirs += [ "${chip_root}/config/standalone" ] matter_enable_tracing_support = true From 339274a3ce9f12cb42549460802a1fb2f4dfed93 Mon Sep 17 00:00:00 2001 From: Jeff Tung <100387939+jtung-apple@users.noreply.github.com> Date: Thu, 22 Aug 2024 14:39:10 -0700 Subject: [PATCH 146/165] [Darwin] XPC invoke should implement bottom-most method (#35159) * [Darwin] XPC invoke should implement bottom-most method * Restyled fix --- .../Framework/CHIP/MTRDeviceController_XPC.mm | 2 +- src/darwin/Framework/CHIP/MTRDevice_XPC.mm | 21 +++++++++++-------- .../CHIP/XPC Protocol/MTRXPCServerProtocol.h | 3 ++- 3 files changed, 15 insertions(+), 11 deletions(-) diff --git a/src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm b/src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm index 7111aa4eb7..67049b280d 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm +++ b/src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm @@ -52,7 +52,7 @@ - (NSXPCInterface *)_interfaceForServerProtocol ]]; [interface setClasses:allowedClasses - forSelector:@selector(deviceController:nodeID:invokeCommandWithEndpointID:clusterID:commandID:commandFields:expectedValues:expectedValueInterval:timedInvokeTimeout:completion:) + forSelector:@selector(deviceController:nodeID:invokeCommandWithEndpointID:clusterID:commandID:commandFields:expectedValues:expectedValueInterval:timedInvokeTimeout:serverSideProcessingTimeout:completion:) argumentIndex:0 ofReply:YES]; return interface; diff --git a/src/darwin/Framework/CHIP/MTRDevice_XPC.mm b/src/darwin/Framework/CHIP/MTRDevice_XPC.mm index 03f318d835..bc3b0a6b26 100644 --- a/src/darwin/Framework/CHIP/MTRDevice_XPC.mm +++ b/src/darwin/Framework/CHIP/MTRDevice_XPC.mm @@ -194,18 +194,20 @@ - (oneway void)deviceConfigurationChanged:(NSNumber *)nodeID : expectedValueInterval timedWriteTimeout : timeout) -- (void)invokeCommandWithEndpointID:(NSNumber *)endpointID - clusterID:(NSNumber *)clusterID - commandID:(NSNumber *)commandID - commandFields:(id)commandFields - expectedValues:(NSArray *> * _Nullable)expectedValues - expectedValueInterval:(NSNumber * _Nullable)expectedValueInterval - timedInvokeTimeout:(NSNumber * _Nullable)timeout - queue:(dispatch_queue_t)queue - completion:(MTRDeviceResponseHandler)completion +- (void)_invokeCommandWithEndpointID:(NSNumber *)endpointID + clusterID:(NSNumber *)clusterID + commandID:(NSNumber *)commandID + commandFields:(id)commandFields + expectedValues:(NSArray *> * _Nullable)expectedValues + expectedValueInterval:(NSNumber * _Nullable)expectedValueInterval + timedInvokeTimeout:(NSNumber * _Nullable)timeout + serverSideProcessingTimeout:(NSNumber * _Nullable)serverSideProcessingTimeout + queue:(dispatch_queue_t)queue + completion:(MTRDeviceResponseHandler)completion { NSXPCConnection * xpcConnection = [(MTRDeviceController_XPC *) [self deviceController] xpcConnection]; + // TODO: use asynchronous XPC and register a block with controller to call for this transaction [[xpcConnection synchronousRemoteObjectProxyWithErrorHandler:^(NSError * _Nonnull error) { MTR_LOG_ERROR("Error: %@", error); }] deviceController:[[self deviceController] uniqueIdentifier] @@ -217,6 +219,7 @@ - (void)invokeCommandWithEndpointID:(NSNumber *)endpointID expectedValues:expectedValues expectedValueInterval:expectedValueInterval timedInvokeTimeout:timeout + serverSideProcessingTimeout:serverSideProcessingTimeout completion:completion]; } diff --git a/src/darwin/Framework/CHIP/XPC Protocol/MTRXPCServerProtocol.h b/src/darwin/Framework/CHIP/XPC Protocol/MTRXPCServerProtocol.h index 1eebb03965..81d6ab930c 100644 --- a/src/darwin/Framework/CHIP/XPC Protocol/MTRXPCServerProtocol.h +++ b/src/darwin/Framework/CHIP/XPC Protocol/MTRXPCServerProtocol.h @@ -29,7 +29,8 @@ MTR_NEWLY_AVAILABLE - (oneway void)deviceController:(NSUUID *)controller nodeID:(NSNumber *)nodeID readAttributeWithEndpointID:(NSNumber *)endpointID clusterID:(NSNumber *)clusterID attributeID:(NSNumber *)attributeID params:(MTRReadParams * _Nullable)params withReply:(void (^)(NSDictionary * _Nullable))reply; - (oneway void)deviceController:(NSUUID *)controller nodeID:(NSNumber *)nodeID writeAttributeWithEndpointID:(NSNumber *)endpointID clusterID:(NSNumber *)clusterID attributeID:(NSNumber *)attributeID value:(id _Nullable)value expectedValueInterval:(NSNumber * _Nullable)expectedValueInterval timedWriteTimeout:(NSNumber * _Nullable)timeout; -- (oneway void)deviceController:(NSUUID *)controller nodeID:(NSNumber *)nodeID invokeCommandWithEndpointID:(NSNumber *)endpointID clusterID:(NSNumber *)clusterID commandID:(NSNumber *)commandID commandFields:(id)commandFields expectedValues:(NSArray *> * _Nullable)expectedValues expectedValueInterval:(NSNumber * _Nullable)expectedValueInterval timedInvokeTimeout:(NSNumber * _Nullable)timeout completion:(MTRDeviceResponseHandler)completion; +- (oneway void)deviceController:(NSUUID *)controller nodeID:(NSNumber *)nodeID invokeCommandWithEndpointID:(NSNumber *)endpointID clusterID:(NSNumber *)clusterID commandID:(NSNumber *)commandID commandFields:(id)commandFields expectedValues:(NSArray *> * _Nullable)expectedValues expectedValueInterval:(NSNumber * _Nullable)expectedValueInterval timedInvokeTimeout:(NSNumber * _Nullable)timeout serverSideProcessingTimeout:(NSNumber * _Nullable)serverSideProcessingTimeout + completion:(MTRDeviceResponseHandler)completion; // Not Supported via XPC //- (oneway void)deviceController:(NSUUID *)controller nodeID:(NSNumber *)nodeID openCommissioningWindowWithSetupPasscode:(NSNumber *)setupPasscode discriminator:(NSNumber *)discriminator duration:(NSNumber *)duration completion:(MTRDeviceOpenCommissioningWindowHandler)completion; From 47b2783152208b40148d66a96f946dadc831986b Mon Sep 17 00:00:00 2001 From: William Date: Thu, 22 Aug 2024 23:46:47 +0100 Subject: [PATCH 147/165] Update PositionTag and AreaDesc field names (#35094) * Updated the PositionTag and AreaDesc field names in the service area XML. * Zap generated after XML update. * Updated the PositionTag and AreaDesc field names in the SDK server code and test scripts. * Restyled by clang-format * Fixed issues caused by merge. * reverted changes in generated code. * encoding --------- Co-authored-by: Restyled.io --- .../rvc-app/linux/RvcAppCommandDelegate.cpp | 4 +- examples/rvc-app/rvc-common/rvc-app.matter | 4 +- .../service-area-cluster-objects.h | 50 ++++---- .../service-area-server.cpp | 8 +- .../data-model/chip/service-area-cluster.xml | 6 +- .../data_model/controller-clusters.matter | 4 +- .../chip/devicecontroller/ChipStructs.java | 44 +++---- .../structs/ServiceAreaClusterAreaStruct.kt | 14 +-- .../ServiceAreaClusterLandmarkInfoStruct.kt | 20 ++-- .../structs/ServiceAreaClusterAreaStruct.kt | 14 +-- .../ServiceAreaClusterLandmarkInfoStruct.kt | 23 ++-- .../CHIPAttributeTLVValueDecoder.cpp | 111 +++++++++--------- .../python/chip/clusters/Objects.py | 8 +- .../MTRAttributeTLVValueDecoder.mm | 38 +++--- .../CHIP/zap-generated/MTRStructsObjc.h | 4 +- .../CHIP/zap-generated/MTRStructsObjc.mm | 12 +- src/python_testing/TC_SEAR_1_2.py | 30 ++--- .../zap-generated/cluster-objects.cpp | 12 +- .../zap-generated/cluster-objects.h | 10 +- .../cluster/ComplexArgumentParser.cpp | 22 ++-- .../cluster/logging/DataModelLogger.cpp | 8 +- 21 files changed, 225 insertions(+), 221 deletions(-) diff --git a/examples/rvc-app/linux/RvcAppCommandDelegate.cpp b/examples/rvc-app/linux/RvcAppCommandDelegate.cpp index 791df4d482..187997f9f8 100644 --- a/examples/rvc-app/linux/RvcAppCommandDelegate.cpp +++ b/examples/rvc-app/linux/RvcAppCommandDelegate.cpp @@ -216,9 +216,9 @@ void RvcAppCommandHandler::OnAddServiceAreaArea(Json::Value jsonValue) if (jsonValue.isMember("LandmarkTag")) { DataModel::Nullable relativePositionTag = DataModel::NullNullable; - if (jsonValue.isMember("PositionTag")) + if (jsonValue.isMember("RelativePositionTag")) { - relativePositionTag = Globals::RelativePositionTag(jsonValue["PositionTag"].asUInt()); + relativePositionTag = Globals::RelativePositionTag(jsonValue["RelativePositionTag"].asUInt()); } area.SetLandmarkInfo(Globals::LandmarkTag(jsonValue["LandmarkTag"].asUInt()), relativePositionTag); diff --git a/examples/rvc-app/rvc-common/rvc-app.matter b/examples/rvc-app/rvc-common/rvc-app.matter index 4467c170ac..29460e1f43 100644 --- a/examples/rvc-app/rvc-common/rvc-app.matter +++ b/examples/rvc-app/rvc-common/rvc-app.matter @@ -1458,7 +1458,7 @@ provisional cluster ServiceArea = 336 { struct LandmarkInfoStruct { LandmarkTag landmarkTag = 0; - nullable RelativePositionTag positionTag = 1; + nullable RelativePositionTag relativePositionTag = 1; } struct AreaInfoStruct { @@ -1469,7 +1469,7 @@ provisional cluster ServiceArea = 336 { struct AreaStruct { int32u areaID = 0; nullable int32u mapID = 1; - AreaInfoStruct areaDesc = 2; + AreaInfoStruct areaInfo = 2; } struct MapStruct { diff --git a/src/app/clusters/service-area-server/service-area-cluster-objects.h b/src/app/clusters/service-area-server/service-area-cluster-objects.h index 69a392a874..470cd09c02 100644 --- a/src/app/clusters/service-area-server/service-area-cluster-objects.h +++ b/src/app/clusters/service-area-server/service-area-cluster-objects.h @@ -68,8 +68,8 @@ struct AreaStructureWrapper : public chip::app::Clusters::ServiceArea::Structs:: { areaID = aOther.areaID; mapID = aOther.mapID; - SetLocationInfo(aOther.areaDesc.locationInfo); - SetLandmarkInfo(aOther.areaDesc.landmarkInfo); + SetLocationInfo(aOther.areaInfo.locationInfo); + SetLandmarkInfo(aOther.areaInfo.landmarkInfo); return *this; } @@ -95,7 +95,7 @@ struct AreaStructureWrapper : public chip::app::Clusters::ServiceArea::Structs:: AreaStructureWrapper & SetLocationInfoNull() { - areaDesc.locationInfo.SetNull(); + areaInfo.locationInfo.SetNull(); return *this; } @@ -108,15 +108,15 @@ struct AreaStructureWrapper : public chip::app::Clusters::ServiceArea::Structs:: AreaStructureWrapper & SetLocationInfo(const CharSpan & locationName, const DataModel::Nullable & floorNumber, const DataModel::Nullable & areaType) { - areaDesc.locationInfo.SetNonNull(); + areaInfo.locationInfo.SetNonNull(); // Copy the name. If the name is larger than kAreaNameMaxSize, truncate it to fit. auto sizeToCopy = std::min(kAreaNameMaxSize, locationName.size()); memcpy(mAreaNameBuffer, locationName.data(), sizeToCopy); - areaDesc.locationInfo.Value().locationName = CharSpan(mAreaNameBuffer, sizeToCopy); + areaInfo.locationInfo.Value().locationName = CharSpan(mAreaNameBuffer, sizeToCopy); - areaDesc.locationInfo.Value().floorNumber = floorNumber; - areaDesc.locationInfo.Value().areaType = areaType; + areaInfo.locationInfo.Value().floorNumber = floorNumber; + areaInfo.locationInfo.Value().areaType = areaType; return *this; } @@ -138,7 +138,7 @@ struct AreaStructureWrapper : public chip::app::Clusters::ServiceArea::Structs:: AreaStructureWrapper & SetLandmarkInfoNull() { - areaDesc.landmarkInfo.SetNull(); + areaInfo.landmarkInfo.SetNull(); return *this; } @@ -150,9 +150,9 @@ struct AreaStructureWrapper : public chip::app::Clusters::ServiceArea::Structs:: AreaStructureWrapper & SetLandmarkInfo(const Globals::LandmarkTag & landmarkTag, const DataModel::Nullable & relativePositionTag) { - areaDesc.landmarkInfo.SetNonNull(); - areaDesc.landmarkInfo.Value().landmarkTag = landmarkTag; - areaDesc.landmarkInfo.Value().positionTag = relativePositionTag; + areaInfo.landmarkInfo.SetNonNull(); + areaInfo.landmarkInfo.Value().landmarkTag = landmarkTag; + areaInfo.landmarkInfo.Value().relativePositionTag = relativePositionTag; return *this; } @@ -167,7 +167,7 @@ struct AreaStructureWrapper : public chip::app::Clusters::ServiceArea::Structs:: return SetLandmarkInfoNull(); } - return SetLandmarkInfo(landmarkInfo.Value().landmarkTag, landmarkInfo.Value().positionTag); + return SetLandmarkInfo(landmarkInfo.Value().landmarkTag, landmarkInfo.Value().relativePositionTag); } /** @@ -178,9 +178,9 @@ struct AreaStructureWrapper : public chip::app::Clusters::ServiceArea::Structs:: */ bool IsNameEqual(const CharSpan & aAreaName) const { - if (!areaDesc.locationInfo.IsNull()) + if (!areaInfo.locationInfo.IsNull()) { - return areaDesc.locationInfo.Value().locationName.data_equal(aAreaName); + return areaInfo.locationInfo.Value().locationName.data_equal(aAreaName); } return false; @@ -215,43 +215,43 @@ struct AreaStructureWrapper : public chip::app::Clusters::ServiceArea::Structs:: return false; } - if (areaDesc.locationInfo.IsNull() != aOther.areaDesc.locationInfo.IsNull()) + if (areaInfo.locationInfo.IsNull() != aOther.areaInfo.locationInfo.IsNull()) { return false; } - if (!areaDesc.locationInfo.IsNull()) + if (!areaInfo.locationInfo.IsNull()) { - if (!IsNameEqual(aOther.areaDesc.locationInfo.Value().locationName)) + if (!IsNameEqual(aOther.areaInfo.locationInfo.Value().locationName)) { return false; } - if (areaDesc.locationInfo.Value().floorNumber != aOther.areaDesc.locationInfo.Value().floorNumber) + if (areaInfo.locationInfo.Value().floorNumber != aOther.areaInfo.locationInfo.Value().floorNumber) { return false; } - if (areaDesc.locationInfo.Value().areaType != aOther.areaDesc.locationInfo.Value().areaType) + if (areaInfo.locationInfo.Value().areaType != aOther.areaInfo.locationInfo.Value().areaType) { return false; } } - if (areaDesc.landmarkInfo.IsNull() != aOther.areaDesc.landmarkInfo.IsNull()) + if (areaInfo.landmarkInfo.IsNull() != aOther.areaInfo.landmarkInfo.IsNull()) { return false; } - if (!areaDesc.landmarkInfo.IsNull()) + if (!areaInfo.landmarkInfo.IsNull()) { - if (areaDesc.landmarkInfo.Value().landmarkTag != aOther.areaDesc.landmarkInfo.Value().landmarkTag) + if (areaInfo.landmarkInfo.Value().landmarkTag != aOther.areaInfo.landmarkInfo.Value().landmarkTag) { return false; } - if (areaDesc.landmarkInfo.Value().positionTag != aOther.areaDesc.landmarkInfo.Value().positionTag) + if (areaInfo.landmarkInfo.Value().relativePositionTag != aOther.areaInfo.landmarkInfo.Value().relativePositionTag) { return false; } @@ -265,12 +265,12 @@ struct AreaStructureWrapper : public chip::app::Clusters::ServiceArea::Structs:: */ CharSpan GetName() { - if (areaDesc.locationInfo.IsNull()) + if (areaInfo.locationInfo.IsNull()) { return { mAreaNameBuffer, 0 }; } - return areaDesc.locationInfo.Value().locationName; + return areaInfo.locationInfo.Value().locationName; } private: diff --git a/src/app/clusters/service-area-server/service-area-server.cpp b/src/app/clusters/service-area-server/service-area-server.cpp index baf56cd4fc..2f2efceddd 100644 --- a/src/app/clusters/service-area-server/service-area-server.cpp +++ b/src/app/clusters/service-area-server/service-area-server.cpp @@ -442,7 +442,7 @@ bool Instance::IsValidSupportedArea(const AreaStructureWrapper & aArea) { // If the LocationInfo field is null, the LandmarkInfo field SHALL NOT be null. // If the LandmarkInfo field is null, the LocationInfo field SHALL NOT be null. - if (aArea.areaDesc.locationInfo.IsNull() && aArea.areaDesc.landmarkInfo.IsNull()) + if (aArea.areaInfo.locationInfo.IsNull() && aArea.areaInfo.landmarkInfo.IsNull()) { ChipLogDetail(Zcl, "IsValidAsSupportedArea %" PRIu32 " - must have locationInfo and/or LandmarkInfo", aArea.areaID); return false; @@ -450,10 +450,10 @@ bool Instance::IsValidSupportedArea(const AreaStructureWrapper & aArea) // If LocationInfo is not null, and its LocationName field is an empty string, at least one of the following SHALL NOT // be null: LocationInfo's FloorNumber field, LocationInfo's AreaType field, the LandmarkInfo - if (!aArea.areaDesc.locationInfo.IsNull()) + if (!aArea.areaInfo.locationInfo.IsNull()) { - if (aArea.areaDesc.locationInfo.Value().locationName.empty() && aArea.areaDesc.locationInfo.Value().floorNumber.IsNull() && - aArea.areaDesc.locationInfo.Value().areaType.IsNull() && aArea.areaDesc.landmarkInfo.IsNull()) + if (aArea.areaInfo.locationInfo.Value().locationName.empty() && aArea.areaInfo.locationInfo.Value().floorNumber.IsNull() && + aArea.areaInfo.locationInfo.Value().areaType.IsNull() && aArea.areaInfo.landmarkInfo.IsNull()) { ChipLogDetail( Zcl, "IsValidAsSupportedArea %" PRIu32 " - AreaName is empty string, FloorNumber, AreaType, LandmarkInfo are null", 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 e2f0199209..e4457c3745 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 @@ -20,8 +20,8 @@ limitations under the License. Data types - - + + @@ -40,7 +40,7 @@ limitations under the License. - + diff --git a/src/controller/data_model/controller-clusters.matter b/src/controller/data_model/controller-clusters.matter index 52f43c048a..ede6f1117e 100644 --- a/src/controller/data_model/controller-clusters.matter +++ b/src/controller/data_model/controller-clusters.matter @@ -6483,7 +6483,7 @@ provisional cluster ServiceArea = 336 { struct LandmarkInfoStruct { LandmarkTag landmarkTag = 0; - nullable RelativePositionTag positionTag = 1; + nullable RelativePositionTag relativePositionTag = 1; } struct AreaInfoStruct { @@ -6494,7 +6494,7 @@ provisional cluster ServiceArea = 336 { struct AreaStruct { int32u areaID = 0; nullable int32u mapID = 1; - AreaInfoStruct areaDesc = 2; + AreaInfoStruct areaInfo = 2; } struct MapStruct { diff --git a/src/controller/java/generated/java/chip/devicecontroller/ChipStructs.java b/src/controller/java/generated/java/chip/devicecontroller/ChipStructs.java index 70e9ba6b1c..7ee8a88f80 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/ChipStructs.java +++ b/src/controller/java/generated/java/chip/devicecontroller/ChipStructs.java @@ -9294,22 +9294,22 @@ public String toString() { } public static class ServiceAreaClusterLandmarkInfoStruct { public Integer landmarkTag; - public @Nullable Integer positionTag; + public @Nullable Integer relativePositionTag; private static final long LANDMARK_TAG_ID = 0L; - private static final long POSITION_TAG_ID = 1L; + private static final long RELATIVE_POSITION_TAG_ID = 1L; public ServiceAreaClusterLandmarkInfoStruct( Integer landmarkTag, - @Nullable Integer positionTag + @Nullable Integer relativePositionTag ) { this.landmarkTag = landmarkTag; - this.positionTag = positionTag; + this.relativePositionTag = relativePositionTag; } public StructType encodeTlv() { ArrayList values = new ArrayList<>(); values.add(new StructElement(LANDMARK_TAG_ID, new UIntType(landmarkTag))); - values.add(new StructElement(POSITION_TAG_ID, positionTag != null ? new UIntType(positionTag) : new NullType())); + values.add(new StructElement(RELATIVE_POSITION_TAG_ID, relativePositionTag != null ? new UIntType(relativePositionTag) : new NullType())); return new StructType(values); } @@ -9319,23 +9319,23 @@ public static ServiceAreaClusterLandmarkInfoStruct decodeTlv(BaseTLVType tlvValu return null; } Integer landmarkTag = null; - @Nullable Integer positionTag = null; + @Nullable Integer relativePositionTag = null; for (StructElement element: ((StructType)tlvValue).value()) { if (element.contextTagNum() == LANDMARK_TAG_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); landmarkTag = castingValue.value(Integer.class); } - } else if (element.contextTagNum() == POSITION_TAG_ID) { + } else if (element.contextTagNum() == RELATIVE_POSITION_TAG_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { UIntType castingValue = element.value(UIntType.class); - positionTag = castingValue.value(Integer.class); + relativePositionTag = castingValue.value(Integer.class); } } } return new ServiceAreaClusterLandmarkInfoStruct( landmarkTag, - positionTag + relativePositionTag ); } @@ -9346,8 +9346,8 @@ public String toString() { output.append("\tlandmarkTag: "); output.append(landmarkTag); output.append("\n"); - output.append("\tpositionTag: "); - output.append(positionTag); + output.append("\trelativePositionTag: "); + output.append(relativePositionTag); output.append("\n"); output.append("}\n"); return output.toString(); @@ -9417,26 +9417,26 @@ public String toString() { public static class ServiceAreaClusterAreaStruct { public Long areaID; public @Nullable Long mapID; - public ChipStructs.ServiceAreaClusterAreaInfoStruct areaDesc; + public ChipStructs.ServiceAreaClusterAreaInfoStruct areaInfo; private static final long AREA_ID_ID = 0L; private static final long MAP_ID_ID = 1L; - private static final long AREA_DESC_ID = 2L; + private static final long AREA_INFO_ID = 2L; public ServiceAreaClusterAreaStruct( Long areaID, @Nullable Long mapID, - ChipStructs.ServiceAreaClusterAreaInfoStruct areaDesc + ChipStructs.ServiceAreaClusterAreaInfoStruct areaInfo ) { this.areaID = areaID; this.mapID = mapID; - this.areaDesc = areaDesc; + this.areaInfo = areaInfo; } public StructType encodeTlv() { ArrayList values = new ArrayList<>(); values.add(new StructElement(AREA_ID_ID, new UIntType(areaID))); values.add(new StructElement(MAP_ID_ID, mapID != null ? new UIntType(mapID) : new NullType())); - values.add(new StructElement(AREA_DESC_ID, areaDesc.encodeTlv())); + values.add(new StructElement(AREA_INFO_ID, areaInfo.encodeTlv())); return new StructType(values); } @@ -9447,7 +9447,7 @@ public static ServiceAreaClusterAreaStruct decodeTlv(BaseTLVType tlvValue) { } Long areaID = null; @Nullable Long mapID = null; - ChipStructs.ServiceAreaClusterAreaInfoStruct areaDesc = null; + ChipStructs.ServiceAreaClusterAreaInfoStruct areaInfo = null; for (StructElement element: ((StructType)tlvValue).value()) { if (element.contextTagNum() == AREA_ID_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { @@ -9459,17 +9459,17 @@ public static ServiceAreaClusterAreaStruct decodeTlv(BaseTLVType tlvValue) { UIntType castingValue = element.value(UIntType.class); mapID = castingValue.value(Long.class); } - } else if (element.contextTagNum() == AREA_DESC_ID) { + } else if (element.contextTagNum() == AREA_INFO_ID) { if (element.value(BaseTLVType.class).type() == TLVType.Struct) { StructType castingValue = element.value(StructType.class); - areaDesc = ChipStructs.ServiceAreaClusterAreaInfoStruct.decodeTlv(castingValue); + areaInfo = ChipStructs.ServiceAreaClusterAreaInfoStruct.decodeTlv(castingValue); } } } return new ServiceAreaClusterAreaStruct( areaID, mapID, - areaDesc + areaInfo ); } @@ -9483,8 +9483,8 @@ public String toString() { output.append("\tmapID: "); output.append(mapID); output.append("\n"); - output.append("\tareaDesc: "); - output.append(areaDesc); + output.append("\tareaInfo: "); + output.append(areaInfo); output.append("\n"); output.append("}\n"); return output.toString(); diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ServiceAreaClusterAreaStruct.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ServiceAreaClusterAreaStruct.kt index fc6405a96c..a5df845ac9 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ServiceAreaClusterAreaStruct.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ServiceAreaClusterAreaStruct.kt @@ -25,13 +25,13 @@ import matter.tlv.TlvWriter class ServiceAreaClusterAreaStruct( val areaID: ULong, val mapID: ULong?, - val areaDesc: ServiceAreaClusterAreaInfoStruct, + val areaInfo: ServiceAreaClusterAreaInfoStruct, ) { override fun toString(): String = buildString { append("ServiceAreaClusterAreaStruct {\n") append("\tareaID : $areaID\n") append("\tmapID : $mapID\n") - append("\tareaDesc : $areaDesc\n") + append("\tareaInfo : $areaInfo\n") append("}\n") } @@ -44,7 +44,7 @@ class ServiceAreaClusterAreaStruct( } else { putNull(ContextSpecificTag(TAG_MAP_ID)) } - areaDesc.toTlv(ContextSpecificTag(TAG_AREA_DESC), this) + areaInfo.toTlv(ContextSpecificTag(TAG_AREA_INFO), this) endStructure() } } @@ -52,7 +52,7 @@ class ServiceAreaClusterAreaStruct( companion object { private const val TAG_AREA_ID = 0 private const val TAG_MAP_ID = 1 - private const val TAG_AREA_DESC = 2 + private const val TAG_AREA_INFO = 2 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): ServiceAreaClusterAreaStruct { tlvReader.enterStructure(tlvTag) @@ -64,12 +64,12 @@ class ServiceAreaClusterAreaStruct( tlvReader.getNull(ContextSpecificTag(TAG_MAP_ID)) null } - val areaDesc = - ServiceAreaClusterAreaInfoStruct.fromTlv(ContextSpecificTag(TAG_AREA_DESC), tlvReader) + val areaInfo = + ServiceAreaClusterAreaInfoStruct.fromTlv(ContextSpecificTag(TAG_AREA_INFO), tlvReader) tlvReader.exitContainer() - return ServiceAreaClusterAreaStruct(areaID, mapID, areaDesc) + return ServiceAreaClusterAreaStruct(areaID, mapID, areaInfo) } } } diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ServiceAreaClusterLandmarkInfoStruct.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ServiceAreaClusterLandmarkInfoStruct.kt index 04970798a2..adf51e8e7c 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ServiceAreaClusterLandmarkInfoStruct.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ServiceAreaClusterLandmarkInfoStruct.kt @@ -22,11 +22,11 @@ import matter.tlv.Tag import matter.tlv.TlvReader import matter.tlv.TlvWriter -class ServiceAreaClusterLandmarkInfoStruct(val landmarkTag: UInt, val positionTag: UInt?) { +class ServiceAreaClusterLandmarkInfoStruct(val landmarkTag: UInt, val relativePositionTag: UInt?) { override fun toString(): String = buildString { append("ServiceAreaClusterLandmarkInfoStruct {\n") append("\tlandmarkTag : $landmarkTag\n") - append("\tpositionTag : $positionTag\n") + append("\trelativePositionTag : $relativePositionTag\n") append("}\n") } @@ -34,10 +34,10 @@ class ServiceAreaClusterLandmarkInfoStruct(val landmarkTag: UInt, val positionTa tlvWriter.apply { startStructure(tlvTag) put(ContextSpecificTag(TAG_LANDMARK_TAG), landmarkTag) - if (positionTag != null) { - put(ContextSpecificTag(TAG_POSITION_TAG), positionTag) + if (relativePositionTag != null) { + put(ContextSpecificTag(TAG_RELATIVE_POSITION_TAG), relativePositionTag) } else { - putNull(ContextSpecificTag(TAG_POSITION_TAG)) + putNull(ContextSpecificTag(TAG_RELATIVE_POSITION_TAG)) } endStructure() } @@ -45,22 +45,22 @@ class ServiceAreaClusterLandmarkInfoStruct(val landmarkTag: UInt, val positionTa companion object { private const val TAG_LANDMARK_TAG = 0 - private const val TAG_POSITION_TAG = 1 + private const val TAG_RELATIVE_POSITION_TAG = 1 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): ServiceAreaClusterLandmarkInfoStruct { tlvReader.enterStructure(tlvTag) val landmarkTag = tlvReader.getUInt(ContextSpecificTag(TAG_LANDMARK_TAG)) - val positionTag = + val relativePositionTag = if (!tlvReader.isNull()) { - tlvReader.getUInt(ContextSpecificTag(TAG_POSITION_TAG)) + tlvReader.getUInt(ContextSpecificTag(TAG_RELATIVE_POSITION_TAG)) } else { - tlvReader.getNull(ContextSpecificTag(TAG_POSITION_TAG)) + tlvReader.getNull(ContextSpecificTag(TAG_RELATIVE_POSITION_TAG)) null } tlvReader.exitContainer() - return ServiceAreaClusterLandmarkInfoStruct(landmarkTag, positionTag) + return ServiceAreaClusterLandmarkInfoStruct(landmarkTag, relativePositionTag) } } } diff --git a/src/controller/java/generated/java/matter/controller/cluster/structs/ServiceAreaClusterAreaStruct.kt b/src/controller/java/generated/java/matter/controller/cluster/structs/ServiceAreaClusterAreaStruct.kt index d310fe5c31..952623c2cf 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/structs/ServiceAreaClusterAreaStruct.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/structs/ServiceAreaClusterAreaStruct.kt @@ -25,13 +25,13 @@ import matter.tlv.TlvWriter class ServiceAreaClusterAreaStruct( val areaID: UInt, val mapID: UInt?, - val areaDesc: ServiceAreaClusterAreaInfoStruct, + val areaInfo: ServiceAreaClusterAreaInfoStruct, ) { override fun toString(): String = buildString { append("ServiceAreaClusterAreaStruct {\n") append("\tareaID : $areaID\n") append("\tmapID : $mapID\n") - append("\tareaDesc : $areaDesc\n") + append("\tareaInfo : $areaInfo\n") append("}\n") } @@ -44,7 +44,7 @@ class ServiceAreaClusterAreaStruct( } else { putNull(ContextSpecificTag(TAG_MAP_ID)) } - areaDesc.toTlv(ContextSpecificTag(TAG_AREA_DESC), this) + areaInfo.toTlv(ContextSpecificTag(TAG_AREA_INFO), this) endStructure() } } @@ -52,7 +52,7 @@ class ServiceAreaClusterAreaStruct( companion object { private const val TAG_AREA_ID = 0 private const val TAG_MAP_ID = 1 - private const val TAG_AREA_DESC = 2 + private const val TAG_AREA_INFO = 2 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): ServiceAreaClusterAreaStruct { tlvReader.enterStructure(tlvTag) @@ -64,12 +64,12 @@ class ServiceAreaClusterAreaStruct( tlvReader.getNull(ContextSpecificTag(TAG_MAP_ID)) null } - val areaDesc = - ServiceAreaClusterAreaInfoStruct.fromTlv(ContextSpecificTag(TAG_AREA_DESC), tlvReader) + val areaInfo = + ServiceAreaClusterAreaInfoStruct.fromTlv(ContextSpecificTag(TAG_AREA_INFO), tlvReader) tlvReader.exitContainer() - return ServiceAreaClusterAreaStruct(areaID, mapID, areaDesc) + return ServiceAreaClusterAreaStruct(areaID, mapID, areaInfo) } } } diff --git a/src/controller/java/generated/java/matter/controller/cluster/structs/ServiceAreaClusterLandmarkInfoStruct.kt b/src/controller/java/generated/java/matter/controller/cluster/structs/ServiceAreaClusterLandmarkInfoStruct.kt index 119667c339..84d369e9a8 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/structs/ServiceAreaClusterLandmarkInfoStruct.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/structs/ServiceAreaClusterLandmarkInfoStruct.kt @@ -22,11 +22,14 @@ import matter.tlv.Tag import matter.tlv.TlvReader import matter.tlv.TlvWriter -class ServiceAreaClusterLandmarkInfoStruct(val landmarkTag: UByte, val positionTag: UByte?) { +class ServiceAreaClusterLandmarkInfoStruct( + val landmarkTag: UByte, + val relativePositionTag: UByte?, +) { override fun toString(): String = buildString { append("ServiceAreaClusterLandmarkInfoStruct {\n") append("\tlandmarkTag : $landmarkTag\n") - append("\tpositionTag : $positionTag\n") + append("\trelativePositionTag : $relativePositionTag\n") append("}\n") } @@ -34,10 +37,10 @@ class ServiceAreaClusterLandmarkInfoStruct(val landmarkTag: UByte, val positionT tlvWriter.apply { startStructure(tlvTag) put(ContextSpecificTag(TAG_LANDMARK_TAG), landmarkTag) - if (positionTag != null) { - put(ContextSpecificTag(TAG_POSITION_TAG), positionTag) + if (relativePositionTag != null) { + put(ContextSpecificTag(TAG_RELATIVE_POSITION_TAG), relativePositionTag) } else { - putNull(ContextSpecificTag(TAG_POSITION_TAG)) + putNull(ContextSpecificTag(TAG_RELATIVE_POSITION_TAG)) } endStructure() } @@ -45,22 +48,22 @@ class ServiceAreaClusterLandmarkInfoStruct(val landmarkTag: UByte, val positionT companion object { private const val TAG_LANDMARK_TAG = 0 - private const val TAG_POSITION_TAG = 1 + private const val TAG_RELATIVE_POSITION_TAG = 1 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): ServiceAreaClusterLandmarkInfoStruct { tlvReader.enterStructure(tlvTag) val landmarkTag = tlvReader.getUByte(ContextSpecificTag(TAG_LANDMARK_TAG)) - val positionTag = + val relativePositionTag = if (!tlvReader.isNull()) { - tlvReader.getUByte(ContextSpecificTag(TAG_POSITION_TAG)) + tlvReader.getUByte(ContextSpecificTag(TAG_RELATIVE_POSITION_TAG)) } else { - tlvReader.getNull(ContextSpecificTag(TAG_POSITION_TAG)) + tlvReader.getNull(ContextSpecificTag(TAG_RELATIVE_POSITION_TAG)) null } tlvReader.exitContainer() - return ServiceAreaClusterLandmarkInfoStruct(landmarkTag, positionTag) + return ServiceAreaClusterLandmarkInfoStruct(landmarkTag, relativePositionTag) } } } diff --git a/src/controller/java/zap-generated/CHIPAttributeTLVValueDecoder.cpp b/src/controller/java/zap-generated/CHIPAttributeTLVValueDecoder.cpp index db775e5d52..cacd15683a 100644 --- a/src/controller/java/zap-generated/CHIPAttributeTLVValueDecoder.cpp +++ b/src/controller/java/zap-generated/CHIPAttributeTLVValueDecoder.cpp @@ -28647,48 +28647,48 @@ jobject DecodeAttributeValue(const app::ConcreteAttributePath & aPath, TLV::TLVR newElement_0_mapIDCtorSignature.c_str(), jninewElement_0_mapID, newElement_0_mapID); } - jobject newElement_0_areaDesc; - jobject newElement_0_areaDesc_locationInfo; - if (entry_0.areaDesc.locationInfo.IsNull()) + jobject newElement_0_areaInfo; + jobject newElement_0_areaInfo_locationInfo; + if (entry_0.areaInfo.locationInfo.IsNull()) { - newElement_0_areaDesc_locationInfo = nullptr; + newElement_0_areaInfo_locationInfo = nullptr; } else { - jobject newElement_0_areaDesc_locationInfo_locationName; + jobject newElement_0_areaInfo_locationInfo_locationName; LogErrorOnFailure(chip::JniReferences::GetInstance().CharToStringUTF( - entry_0.areaDesc.locationInfo.Value().locationName, newElement_0_areaDesc_locationInfo_locationName)); - jobject newElement_0_areaDesc_locationInfo_floorNumber; - if (entry_0.areaDesc.locationInfo.Value().floorNumber.IsNull()) + entry_0.areaInfo.locationInfo.Value().locationName, newElement_0_areaInfo_locationInfo_locationName)); + jobject newElement_0_areaInfo_locationInfo_floorNumber; + if (entry_0.areaInfo.locationInfo.Value().floorNumber.IsNull()) { - newElement_0_areaDesc_locationInfo_floorNumber = nullptr; + newElement_0_areaInfo_locationInfo_floorNumber = nullptr; } else { - std::string newElement_0_areaDesc_locationInfo_floorNumberClassName = "java/lang/Integer"; - std::string newElement_0_areaDesc_locationInfo_floorNumberCtorSignature = "(I)V"; - jint jninewElement_0_areaDesc_locationInfo_floorNumber = - static_cast(entry_0.areaDesc.locationInfo.Value().floorNumber.Value()); + std::string newElement_0_areaInfo_locationInfo_floorNumberClassName = "java/lang/Integer"; + std::string newElement_0_areaInfo_locationInfo_floorNumberCtorSignature = "(I)V"; + jint jninewElement_0_areaInfo_locationInfo_floorNumber = + static_cast(entry_0.areaInfo.locationInfo.Value().floorNumber.Value()); chip::JniReferences::GetInstance().CreateBoxedObject( - newElement_0_areaDesc_locationInfo_floorNumberClassName.c_str(), - newElement_0_areaDesc_locationInfo_floorNumberCtorSignature.c_str(), - jninewElement_0_areaDesc_locationInfo_floorNumber, newElement_0_areaDesc_locationInfo_floorNumber); + newElement_0_areaInfo_locationInfo_floorNumberClassName.c_str(), + newElement_0_areaInfo_locationInfo_floorNumberCtorSignature.c_str(), + jninewElement_0_areaInfo_locationInfo_floorNumber, newElement_0_areaInfo_locationInfo_floorNumber); } - jobject newElement_0_areaDesc_locationInfo_areaType; - if (entry_0.areaDesc.locationInfo.Value().areaType.IsNull()) + jobject newElement_0_areaInfo_locationInfo_areaType; + if (entry_0.areaInfo.locationInfo.Value().areaType.IsNull()) { - newElement_0_areaDesc_locationInfo_areaType = nullptr; + newElement_0_areaInfo_locationInfo_areaType = nullptr; } else { - std::string newElement_0_areaDesc_locationInfo_areaTypeClassName = "java/lang/Integer"; - std::string newElement_0_areaDesc_locationInfo_areaTypeCtorSignature = "(I)V"; - jint jninewElement_0_areaDesc_locationInfo_areaType = - static_cast(entry_0.areaDesc.locationInfo.Value().areaType.Value()); + std::string newElement_0_areaInfo_locationInfo_areaTypeClassName = "java/lang/Integer"; + std::string newElement_0_areaInfo_locationInfo_areaTypeCtorSignature = "(I)V"; + jint jninewElement_0_areaInfo_locationInfo_areaType = + static_cast(entry_0.areaInfo.locationInfo.Value().areaType.Value()); chip::JniReferences::GetInstance().CreateBoxedObject( - newElement_0_areaDesc_locationInfo_areaTypeClassName.c_str(), - newElement_0_areaDesc_locationInfo_areaTypeCtorSignature.c_str(), - jninewElement_0_areaDesc_locationInfo_areaType, newElement_0_areaDesc_locationInfo_areaType); + newElement_0_areaInfo_locationInfo_areaTypeClassName.c_str(), + newElement_0_areaInfo_locationInfo_areaTypeCtorSignature.c_str(), + jninewElement_0_areaInfo_locationInfo_areaType, newElement_0_areaInfo_locationInfo_areaType); } jclass locationDescriptorStructStructClass_4; @@ -28711,42 +28711,43 @@ jobject DecodeAttributeValue(const app::ConcreteAttributePath & aPath, TLV::TLVR return nullptr; } - newElement_0_areaDesc_locationInfo = + newElement_0_areaInfo_locationInfo = env->NewObject(locationDescriptorStructStructClass_4, locationDescriptorStructStructCtor_4, - newElement_0_areaDesc_locationInfo_locationName, - newElement_0_areaDesc_locationInfo_floorNumber, newElement_0_areaDesc_locationInfo_areaType); + newElement_0_areaInfo_locationInfo_locationName, + newElement_0_areaInfo_locationInfo_floorNumber, newElement_0_areaInfo_locationInfo_areaType); } - jobject newElement_0_areaDesc_landmarkInfo; - if (entry_0.areaDesc.landmarkInfo.IsNull()) + jobject newElement_0_areaInfo_landmarkInfo; + if (entry_0.areaInfo.landmarkInfo.IsNull()) { - newElement_0_areaDesc_landmarkInfo = nullptr; + newElement_0_areaInfo_landmarkInfo = nullptr; } else { - jobject newElement_0_areaDesc_landmarkInfo_landmarkTag; - std::string newElement_0_areaDesc_landmarkInfo_landmarkTagClassName = "java/lang/Integer"; - std::string newElement_0_areaDesc_landmarkInfo_landmarkTagCtorSignature = "(I)V"; - jint jninewElement_0_areaDesc_landmarkInfo_landmarkTag = - static_cast(entry_0.areaDesc.landmarkInfo.Value().landmarkTag); + jobject newElement_0_areaInfo_landmarkInfo_landmarkTag; + std::string newElement_0_areaInfo_landmarkInfo_landmarkTagClassName = "java/lang/Integer"; + std::string newElement_0_areaInfo_landmarkInfo_landmarkTagCtorSignature = "(I)V"; + jint jninewElement_0_areaInfo_landmarkInfo_landmarkTag = + static_cast(entry_0.areaInfo.landmarkInfo.Value().landmarkTag); chip::JniReferences::GetInstance().CreateBoxedObject( - newElement_0_areaDesc_landmarkInfo_landmarkTagClassName.c_str(), - newElement_0_areaDesc_landmarkInfo_landmarkTagCtorSignature.c_str(), - jninewElement_0_areaDesc_landmarkInfo_landmarkTag, newElement_0_areaDesc_landmarkInfo_landmarkTag); - jobject newElement_0_areaDesc_landmarkInfo_positionTag; - if (entry_0.areaDesc.landmarkInfo.Value().positionTag.IsNull()) + newElement_0_areaInfo_landmarkInfo_landmarkTagClassName.c_str(), + newElement_0_areaInfo_landmarkInfo_landmarkTagCtorSignature.c_str(), + jninewElement_0_areaInfo_landmarkInfo_landmarkTag, newElement_0_areaInfo_landmarkInfo_landmarkTag); + jobject newElement_0_areaInfo_landmarkInfo_relativePositionTag; + if (entry_0.areaInfo.landmarkInfo.Value().relativePositionTag.IsNull()) { - newElement_0_areaDesc_landmarkInfo_positionTag = nullptr; + newElement_0_areaInfo_landmarkInfo_relativePositionTag = nullptr; } else { - std::string newElement_0_areaDesc_landmarkInfo_positionTagClassName = "java/lang/Integer"; - std::string newElement_0_areaDesc_landmarkInfo_positionTagCtorSignature = "(I)V"; - jint jninewElement_0_areaDesc_landmarkInfo_positionTag = - static_cast(entry_0.areaDesc.landmarkInfo.Value().positionTag.Value()); + std::string newElement_0_areaInfo_landmarkInfo_relativePositionTagClassName = "java/lang/Integer"; + std::string newElement_0_areaInfo_landmarkInfo_relativePositionTagCtorSignature = "(I)V"; + jint jninewElement_0_areaInfo_landmarkInfo_relativePositionTag = + static_cast(entry_0.areaInfo.landmarkInfo.Value().relativePositionTag.Value()); chip::JniReferences::GetInstance().CreateBoxedObject( - newElement_0_areaDesc_landmarkInfo_positionTagClassName.c_str(), - newElement_0_areaDesc_landmarkInfo_positionTagCtorSignature.c_str(), - jninewElement_0_areaDesc_landmarkInfo_positionTag, newElement_0_areaDesc_landmarkInfo_positionTag); + newElement_0_areaInfo_landmarkInfo_relativePositionTagClassName.c_str(), + newElement_0_areaInfo_landmarkInfo_relativePositionTagCtorSignature.c_str(), + jninewElement_0_areaInfo_landmarkInfo_relativePositionTag, + newElement_0_areaInfo_landmarkInfo_relativePositionTag); } jclass landmarkInfoStructStructClass_4; @@ -28769,9 +28770,9 @@ jobject DecodeAttributeValue(const app::ConcreteAttributePath & aPath, TLV::TLVR return nullptr; } - newElement_0_areaDesc_landmarkInfo = env->NewObject( + newElement_0_areaInfo_landmarkInfo = env->NewObject( landmarkInfoStructStructClass_4, landmarkInfoStructStructCtor_4, - newElement_0_areaDesc_landmarkInfo_landmarkTag, newElement_0_areaDesc_landmarkInfo_positionTag); + newElement_0_areaInfo_landmarkInfo_landmarkTag, newElement_0_areaInfo_landmarkInfo_relativePositionTag); } jclass areaInfoStructStructClass_2; @@ -28795,8 +28796,8 @@ jobject DecodeAttributeValue(const app::ConcreteAttributePath & aPath, TLV::TLVR return nullptr; } - newElement_0_areaDesc = env->NewObject(areaInfoStructStructClass_2, areaInfoStructStructCtor_2, - newElement_0_areaDesc_locationInfo, newElement_0_areaDesc_landmarkInfo); + newElement_0_areaInfo = env->NewObject(areaInfoStructStructClass_2, areaInfoStructStructCtor_2, + newElement_0_areaInfo_locationInfo, newElement_0_areaInfo_landmarkInfo); jclass areaStructStructClass_1; err = chip::JniReferences::GetInstance().GetLocalClassRef( @@ -28819,7 +28820,7 @@ jobject DecodeAttributeValue(const app::ConcreteAttributePath & aPath, TLV::TLVR } newElement_0 = env->NewObject(areaStructStructClass_1, areaStructStructCtor_1, newElement_0_areaID, - newElement_0_mapID, newElement_0_areaDesc); + newElement_0_mapID, newElement_0_areaInfo); chip::JniReferences::GetInstance().AddToList(value, newElement_0); } return value; diff --git a/src/controller/python/chip/clusters/Objects.py b/src/controller/python/chip/clusters/Objects.py index 624f42c8e8..391765f383 100644 --- a/src/controller/python/chip/clusters/Objects.py +++ b/src/controller/python/chip/clusters/Objects.py @@ -31392,11 +31392,11 @@ def descriptor(cls) -> ClusterObjectDescriptor: return ClusterObjectDescriptor( Fields=[ ClusterObjectFieldDescriptor(Label="landmarkTag", Tag=0, Type=Globals.Enums.LandmarkTag), - ClusterObjectFieldDescriptor(Label="positionTag", Tag=1, Type=typing.Union[Nullable, Globals.Enums.RelativePositionTag]), + ClusterObjectFieldDescriptor(Label="relativePositionTag", Tag=1, Type=typing.Union[Nullable, Globals.Enums.RelativePositionTag]), ]) landmarkTag: 'Globals.Enums.LandmarkTag' = 0 - positionTag: 'typing.Union[Nullable, Globals.Enums.RelativePositionTag]' = NullValue + relativePositionTag: 'typing.Union[Nullable, Globals.Enums.RelativePositionTag]' = NullValue @dataclass class AreaInfoStruct(ClusterObject): @@ -31419,12 +31419,12 @@ def descriptor(cls) -> ClusterObjectDescriptor: Fields=[ ClusterObjectFieldDescriptor(Label="areaID", Tag=0, Type=uint), ClusterObjectFieldDescriptor(Label="mapID", Tag=1, Type=typing.Union[Nullable, uint]), - ClusterObjectFieldDescriptor(Label="areaDesc", Tag=2, Type=ServiceArea.Structs.AreaInfoStruct), + ClusterObjectFieldDescriptor(Label="areaInfo", Tag=2, Type=ServiceArea.Structs.AreaInfoStruct), ]) areaID: 'uint' = 0 mapID: 'typing.Union[Nullable, uint]' = NullValue - areaDesc: 'ServiceArea.Structs.AreaInfoStruct' = field(default_factory=lambda: ServiceArea.Structs.AreaInfoStruct()) + areaInfo: 'ServiceArea.Structs.AreaInfoStruct' = field(default_factory=lambda: ServiceArea.Structs.AreaInfoStruct()) @dataclass class MapStruct(ClusterObject): diff --git a/src/darwin/Framework/CHIP/zap-generated/MTRAttributeTLVValueDecoder.mm b/src/darwin/Framework/CHIP/zap-generated/MTRAttributeTLVValueDecoder.mm index 472a630d93..4b0e0bb963 100644 --- a/src/darwin/Framework/CHIP/zap-generated/MTRAttributeTLVValueDecoder.mm +++ b/src/darwin/Framework/CHIP/zap-generated/MTRAttributeTLVValueDecoder.mm @@ -11197,37 +11197,37 @@ static id _Nullable DecodeAttributeValueForServiceAreaCluster(AttributeId aAttri } else { newElement_0.mapID = [NSNumber numberWithUnsignedInt:entry_0.mapID.Value()]; } - newElement_0.areaDesc = [MTRServiceAreaClusterAreaInfoStruct new]; - if (entry_0.areaDesc.locationInfo.IsNull()) { - newElement_0.areaDesc.locationInfo = nil; + newElement_0.areaInfo = [MTRServiceAreaClusterAreaInfoStruct new]; + if (entry_0.areaInfo.locationInfo.IsNull()) { + newElement_0.areaInfo.locationInfo = nil; } else { - newElement_0.areaDesc.locationInfo = [MTRDataTypeLocationDescriptorStruct new]; - newElement_0.areaDesc.locationInfo.locationName = AsString(entry_0.areaDesc.locationInfo.Value().locationName); - if (newElement_0.areaDesc.locationInfo.locationName == nil) { + newElement_0.areaInfo.locationInfo = [MTRDataTypeLocationDescriptorStruct new]; + newElement_0.areaInfo.locationInfo.locationName = AsString(entry_0.areaInfo.locationInfo.Value().locationName); + if (newElement_0.areaInfo.locationInfo.locationName == nil) { CHIP_ERROR err = CHIP_ERROR_INVALID_ARGUMENT; *aError = err; return nil; } - if (entry_0.areaDesc.locationInfo.Value().floorNumber.IsNull()) { - newElement_0.areaDesc.locationInfo.floorNumber = nil; + if (entry_0.areaInfo.locationInfo.Value().floorNumber.IsNull()) { + newElement_0.areaInfo.locationInfo.floorNumber = nil; } else { - newElement_0.areaDesc.locationInfo.floorNumber = [NSNumber numberWithShort:entry_0.areaDesc.locationInfo.Value().floorNumber.Value()]; + newElement_0.areaInfo.locationInfo.floorNumber = [NSNumber numberWithShort:entry_0.areaInfo.locationInfo.Value().floorNumber.Value()]; } - if (entry_0.areaDesc.locationInfo.Value().areaType.IsNull()) { - newElement_0.areaDesc.locationInfo.areaType = nil; + if (entry_0.areaInfo.locationInfo.Value().areaType.IsNull()) { + newElement_0.areaInfo.locationInfo.areaType = nil; } else { - newElement_0.areaDesc.locationInfo.areaType = [NSNumber numberWithUnsignedChar:chip::to_underlying(entry_0.areaDesc.locationInfo.Value().areaType.Value())]; + newElement_0.areaInfo.locationInfo.areaType = [NSNumber numberWithUnsignedChar:chip::to_underlying(entry_0.areaInfo.locationInfo.Value().areaType.Value())]; } } - if (entry_0.areaDesc.landmarkInfo.IsNull()) { - newElement_0.areaDesc.landmarkInfo = nil; + if (entry_0.areaInfo.landmarkInfo.IsNull()) { + newElement_0.areaInfo.landmarkInfo = nil; } else { - newElement_0.areaDesc.landmarkInfo = [MTRServiceAreaClusterLandmarkInfoStruct new]; - newElement_0.areaDesc.landmarkInfo.landmarkTag = [NSNumber numberWithUnsignedChar:chip::to_underlying(entry_0.areaDesc.landmarkInfo.Value().landmarkTag)]; - if (entry_0.areaDesc.landmarkInfo.Value().positionTag.IsNull()) { - newElement_0.areaDesc.landmarkInfo.positionTag = nil; + newElement_0.areaInfo.landmarkInfo = [MTRServiceAreaClusterLandmarkInfoStruct new]; + newElement_0.areaInfo.landmarkInfo.landmarkTag = [NSNumber numberWithUnsignedChar:chip::to_underlying(entry_0.areaInfo.landmarkInfo.Value().landmarkTag)]; + if (entry_0.areaInfo.landmarkInfo.Value().relativePositionTag.IsNull()) { + newElement_0.areaInfo.landmarkInfo.relativePositionTag = nil; } else { - newElement_0.areaDesc.landmarkInfo.positionTag = [NSNumber numberWithUnsignedChar:chip::to_underlying(entry_0.areaDesc.landmarkInfo.Value().positionTag.Value())]; + newElement_0.areaInfo.landmarkInfo.relativePositionTag = [NSNumber numberWithUnsignedChar:chip::to_underlying(entry_0.areaInfo.landmarkInfo.Value().relativePositionTag.Value())]; } } [array_0 addObject:newElement_0]; diff --git a/src/darwin/Framework/CHIP/zap-generated/MTRStructsObjc.h b/src/darwin/Framework/CHIP/zap-generated/MTRStructsObjc.h index 35df5cc3e3..fac8e1bdf7 100644 --- a/src/darwin/Framework/CHIP/zap-generated/MTRStructsObjc.h +++ b/src/darwin/Framework/CHIP/zap-generated/MTRStructsObjc.h @@ -1615,7 +1615,7 @@ MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) MTR_PROVISIONALLY_AVAILABLE @interface MTRServiceAreaClusterLandmarkInfoStruct : NSObject @property (nonatomic, copy) NSNumber * _Nonnull landmarkTag MTR_PROVISIONALLY_AVAILABLE; -@property (nonatomic, copy) NSNumber * _Nullable positionTag MTR_PROVISIONALLY_AVAILABLE; +@property (nonatomic, copy) NSNumber * _Nullable relativePositionTag MTR_PROVISIONALLY_AVAILABLE; @end MTR_PROVISIONALLY_AVAILABLE @@ -1628,7 +1628,7 @@ MTR_PROVISIONALLY_AVAILABLE @interface MTRServiceAreaClusterAreaStruct : NSObject @property (nonatomic, copy) NSNumber * _Nonnull areaID MTR_PROVISIONALLY_AVAILABLE; @property (nonatomic, copy) NSNumber * _Nullable mapID MTR_PROVISIONALLY_AVAILABLE; -@property (nonatomic, copy) MTRServiceAreaClusterAreaInfoStruct * _Nonnull areaDesc MTR_PROVISIONALLY_AVAILABLE; +@property (nonatomic, copy) MTRServiceAreaClusterAreaInfoStruct * _Nonnull areaInfo MTR_PROVISIONALLY_AVAILABLE; @end MTR_PROVISIONALLY_AVAILABLE diff --git a/src/darwin/Framework/CHIP/zap-generated/MTRStructsObjc.mm b/src/darwin/Framework/CHIP/zap-generated/MTRStructsObjc.mm index 6c3fc19e9b..f24ca05abf 100644 --- a/src/darwin/Framework/CHIP/zap-generated/MTRStructsObjc.mm +++ b/src/darwin/Framework/CHIP/zap-generated/MTRStructsObjc.mm @@ -6739,7 +6739,7 @@ - (instancetype)init _landmarkTag = @(0); - _positionTag = nil; + _relativePositionTag = nil; } return self; } @@ -6749,14 +6749,14 @@ - (id)copyWithZone:(NSZone * _Nullable)zone auto other = [[MTRServiceAreaClusterLandmarkInfoStruct alloc] init]; other.landmarkTag = self.landmarkTag; - other.positionTag = self.positionTag; + other.relativePositionTag = self.relativePositionTag; return other; } - (NSString *)description { - NSString * descriptionString = [NSString stringWithFormat:@"<%@: landmarkTag:%@; positionTag:%@; >", NSStringFromClass([self class]), _landmarkTag, _positionTag]; + NSString * descriptionString = [NSString stringWithFormat:@"<%@: landmarkTag:%@; relativePositionTag:%@; >", NSStringFromClass([self class]), _landmarkTag, _relativePositionTag]; return descriptionString; } @@ -6801,7 +6801,7 @@ - (instancetype)init _mapID = nil; - _areaDesc = [MTRServiceAreaClusterAreaInfoStruct new]; + _areaInfo = [MTRServiceAreaClusterAreaInfoStruct new]; } return self; } @@ -6812,14 +6812,14 @@ - (id)copyWithZone:(NSZone * _Nullable)zone other.areaID = self.areaID; other.mapID = self.mapID; - other.areaDesc = self.areaDesc; + other.areaInfo = self.areaInfo; return other; } - (NSString *)description { - NSString * descriptionString = [NSString stringWithFormat:@"<%@: areaID:%@; mapID:%@; areaDesc:%@; >", NSStringFromClass([self class]), _areaID, _mapID, _areaDesc]; + NSString * descriptionString = [NSString stringWithFormat:@"<%@: areaID:%@; mapID:%@; areaInfo:%@; >", NSStringFromClass([self class]), _areaID, _mapID, _areaInfo]; return descriptionString; } diff --git a/src/python_testing/TC_SEAR_1_2.py b/src/python_testing/TC_SEAR_1_2.py index 083533277a..c21e831464 100644 --- a/src/python_testing/TC_SEAR_1_2.py +++ b/src/python_testing/TC_SEAR_1_2.py @@ -80,7 +80,7 @@ async def read_and_validate_supported_areas(self, step): asserts.assert_less_equal(len(supported_areas), 255, "SupportedAreas should have max 255 entries") areaid_list = [] - areadesc_s = set() + areainfo_s = set() for a in supported_areas: asserts.assert_true(a.areaID not in areaid_list, "SupportedAreas must have unique AreaID values!") @@ -91,27 +91,27 @@ async def read_and_validate_supported_areas(self, step): f"SupportedAreas entry with AreaID({a.areaID}) should not have null MapID") asserts.assert_true(a.mapID in self.mapid_list, f"SupportedAreas entry with AreaID({a.areaID}) has unknown MapID({a.mapID})") - k = f"mapID:{a.mapID} areaDesc:{a.areaDesc}" - asserts.assert_true(k not in areadesc_s, - f"SupportedAreas must have unique MapID({a.mapID}) + AreaDesc({a.areaDesc}) values!") - areadesc_s.add(k) + k = f"mapID:{a.mapID} areaInfo:{a.areaInfo}" + asserts.assert_true(k not in areainfo_s, + f"SupportedAreas must have unique MapID({a.mapID}) + AreaInfo({a.areaInfo}) values!") + areainfo_s.add(k) else: # empty SupportedMaps asserts.assert_is(a.mapID, NullValue, f"SupportedAreas entry with AreaID({a.areaID}) should have null MapID") - k = f"areaDesc:{a.areaDesc}" - asserts.assert_true(k not in areadesc_s, f"SupportedAreas must have unique AreaDesc({a.areaDesc}) values!") - areadesc_s.add(k) + k = f"areaInfo:{a.areaInfo}" + asserts.assert_true(k not in areainfo_s, f"SupportedAreas must have unique AreaInfo({a.areaInfo}) values!") + areainfo_s.add(k) - if a.areaDesc.locationInfo is NullValue and a.areaDesc.landmarkInfo is NullValue: + if a.areaInfo.locationInfo is NullValue and a.areaInfo.landmarkInfo is NullValue: asserts.assert_true( f"SupportedAreas entry with AreaID({a.areaID}) should not have null LocationInfo and null LandmarkInfo") - if a.areaDesc.landmarkInfo is not NullValue: - asserts.assert_true(a.areaDesc.landmarkInfo.landmarkTag <= self.MAX_LANDMARK_ID, - f"SupportedAreas entry with AreaID({a.areaID}) has invalid LandmarkTag({a.areaDesc.landmarkInfo.landmarkTag})") - asserts.assert_true(a.areaDesc.landmarkInfo.positionTag is NullValue or a - .areaDesc.landmarkInfo.positionTag in range(0, self.MAX_RELPOS_ID), - f"SupportedAreas entry with AreaID({a.areaID}) has invalid PositionTag({a.areaDesc.landmarkInfo.positionTag})") + if a.areaInfo.landmarkInfo is not NullValue: + asserts.assert_true(a.areaInfo.landmarkInfo.landmarkTag <= self.MAX_LANDMARK_ID, + f"SupportedAreas entry with AreaID({a.areaID}) has invalid LandmarkTag({a.areaInfo.landmarkInfo.landmarkTag})") + asserts.assert_true(a.areaInfo.landmarkInfo.relativePositionTag is NullValue or a + .areaInfo.landmarkInfo.relativePositionTag in range(0, self.MAX_RELPOS_ID), + f"SupportedAreas entry with AreaID({a.areaID}) has invalid RelativePositionTag({a.areaInfo.landmarkInfo.relativePositionTag})") # save so other methods can use this if needed self.areaid_list = areaid_list 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 20fdd12651..c2a25ed947 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 @@ -20457,7 +20457,7 @@ CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; encoder.Encode(to_underlying(Fields::kLandmarkTag), landmarkTag); - encoder.Encode(to_underlying(Fields::kPositionTag), positionTag); + encoder.Encode(to_underlying(Fields::kRelativePositionTag), relativePositionTag); return encoder.Finalize(); } @@ -20479,9 +20479,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) { err = DataModel::Decode(reader, landmarkTag); } - else if (__context_tag == to_underlying(Fields::kPositionTag)) + else if (__context_tag == to_underlying(Fields::kRelativePositionTag)) { - err = DataModel::Decode(reader, positionTag); + err = DataModel::Decode(reader, relativePositionTag); } else { @@ -20540,7 +20540,7 @@ CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; encoder.Encode(to_underlying(Fields::kAreaID), areaID); encoder.Encode(to_underlying(Fields::kMapID), mapID); - encoder.Encode(to_underlying(Fields::kAreaDesc), areaDesc); + encoder.Encode(to_underlying(Fields::kAreaInfo), areaInfo); return encoder.Finalize(); } @@ -20566,9 +20566,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) { err = DataModel::Decode(reader, mapID); } - else if (__context_tag == to_underlying(Fields::kAreaDesc)) + else if (__context_tag == to_underlying(Fields::kAreaInfo)) { - err = DataModel::Decode(reader, areaDesc); + err = DataModel::Decode(reader, areaInfo); } else { 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 c2c1697ce2..fc62ada8bd 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 @@ -28428,15 +28428,15 @@ namespace Structs { namespace LandmarkInfoStruct { enum class Fields : uint8_t { - kLandmarkTag = 0, - kPositionTag = 1, + kLandmarkTag = 0, + kRelativePositionTag = 1, }; struct Type { public: Globals::LandmarkTag landmarkTag = static_cast(0); - DataModel::Nullable positionTag; + DataModel::Nullable relativePositionTag; CHIP_ERROR Decode(TLV::TLVReader & reader); @@ -28476,7 +28476,7 @@ enum class Fields : uint8_t { kAreaID = 0, kMapID = 1, - kAreaDesc = 2, + kAreaInfo = 2, }; struct Type @@ -28484,7 +28484,7 @@ struct Type public: uint32_t areaID = static_cast(0); DataModel::Nullable mapID; - Structs::AreaInfoStruct::Type areaDesc; + Structs::AreaInfoStruct::Type areaInfo; CHIP_ERROR Decode(TLV::TLVReader & reader); diff --git a/zzz_generated/chip-tool/zap-generated/cluster/ComplexArgumentParser.cpp b/zzz_generated/chip-tool/zap-generated/cluster/ComplexArgumentParser.cpp index 202a6efcb0..9a1062c23b 100644 --- a/zzz_generated/chip-tool/zap-generated/cluster/ComplexArgumentParser.cpp +++ b/zzz_generated/chip-tool/zap-generated/cluster/ComplexArgumentParser.cpp @@ -4052,17 +4052,17 @@ CHIP_ERROR ComplexArgumentParser::Setup(const char * label, ReturnErrorOnFailure( ComplexArgumentParser::EnsureMemberExist("LandmarkInfoStruct.landmarkTag", "landmarkTag", value.isMember("landmarkTag"))); - ReturnErrorOnFailure( - ComplexArgumentParser::EnsureMemberExist("LandmarkInfoStruct.positionTag", "positionTag", value.isMember("positionTag"))); + ReturnErrorOnFailure(ComplexArgumentParser::EnsureMemberExist("LandmarkInfoStruct.relativePositionTag", "relativePositionTag", + value.isMember("relativePositionTag"))); char labelWithMember[kMaxLabelLength]; snprintf(labelWithMember, sizeof(labelWithMember), "%s.%s", label, "landmarkTag"); ReturnErrorOnFailure(ComplexArgumentParser::Setup(labelWithMember, request.landmarkTag, value["landmarkTag"])); valueCopy.removeMember("landmarkTag"); - snprintf(labelWithMember, sizeof(labelWithMember), "%s.%s", label, "positionTag"); - ReturnErrorOnFailure(ComplexArgumentParser::Setup(labelWithMember, request.positionTag, value["positionTag"])); - valueCopy.removeMember("positionTag"); + snprintf(labelWithMember, sizeof(labelWithMember), "%s.%s", label, "relativePositionTag"); + ReturnErrorOnFailure(ComplexArgumentParser::Setup(labelWithMember, request.relativePositionTag, value["relativePositionTag"])); + valueCopy.removeMember("relativePositionTag"); return ComplexArgumentParser::EnsureNoMembersRemaining(label, valueCopy); } @@ -4070,7 +4070,7 @@ CHIP_ERROR ComplexArgumentParser::Setup(const char * label, void ComplexArgumentParser::Finalize(chip::app::Clusters::ServiceArea::Structs::LandmarkInfoStruct::Type & request) { ComplexArgumentParser::Finalize(request.landmarkTag); - ComplexArgumentParser::Finalize(request.positionTag); + ComplexArgumentParser::Finalize(request.relativePositionTag); } CHIP_ERROR ComplexArgumentParser::Setup(const char * label, @@ -4115,7 +4115,7 @@ CHIP_ERROR ComplexArgumentParser::Setup(const char * label, chip::app::Clusters: ReturnErrorOnFailure(ComplexArgumentParser::EnsureMemberExist("AreaStruct.areaID", "areaID", value.isMember("areaID"))); ReturnErrorOnFailure(ComplexArgumentParser::EnsureMemberExist("AreaStruct.mapID", "mapID", value.isMember("mapID"))); - ReturnErrorOnFailure(ComplexArgumentParser::EnsureMemberExist("AreaStruct.areaDesc", "areaDesc", value.isMember("areaDesc"))); + ReturnErrorOnFailure(ComplexArgumentParser::EnsureMemberExist("AreaStruct.areaInfo", "areaInfo", value.isMember("areaInfo"))); char labelWithMember[kMaxLabelLength]; snprintf(labelWithMember, sizeof(labelWithMember), "%s.%s", label, "areaID"); @@ -4126,9 +4126,9 @@ CHIP_ERROR ComplexArgumentParser::Setup(const char * label, chip::app::Clusters: ReturnErrorOnFailure(ComplexArgumentParser::Setup(labelWithMember, request.mapID, value["mapID"])); valueCopy.removeMember("mapID"); - snprintf(labelWithMember, sizeof(labelWithMember), "%s.%s", label, "areaDesc"); - ReturnErrorOnFailure(ComplexArgumentParser::Setup(labelWithMember, request.areaDesc, value["areaDesc"])); - valueCopy.removeMember("areaDesc"); + snprintf(labelWithMember, sizeof(labelWithMember), "%s.%s", label, "areaInfo"); + ReturnErrorOnFailure(ComplexArgumentParser::Setup(labelWithMember, request.areaInfo, value["areaInfo"])); + valueCopy.removeMember("areaInfo"); return ComplexArgumentParser::EnsureNoMembersRemaining(label, valueCopy); } @@ -4137,7 +4137,7 @@ void ComplexArgumentParser::Finalize(chip::app::Clusters::ServiceArea::Structs:: { ComplexArgumentParser::Finalize(request.areaID); ComplexArgumentParser::Finalize(request.mapID); - ComplexArgumentParser::Finalize(request.areaDesc); + ComplexArgumentParser::Finalize(request.areaInfo); } CHIP_ERROR ComplexArgumentParser::Setup(const char * label, chip::app::Clusters::ServiceArea::Structs::MapStruct::Type & request, 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 3d40f3897e..16248a7ca4 100644 --- a/zzz_generated/chip-tool/zap-generated/cluster/logging/DataModelLogger.cpp +++ b/zzz_generated/chip-tool/zap-generated/cluster/logging/DataModelLogger.cpp @@ -3586,10 +3586,10 @@ CHIP_ERROR DataModelLogger::LogValue(const char * label, size_t indent, } } { - CHIP_ERROR err = LogValue("PositionTag", indent + 1, value.positionTag); + CHIP_ERROR err = LogValue("RelativePositionTag", indent + 1, value.relativePositionTag); if (err != CHIP_NO_ERROR) { - DataModelLogger::LogString(indent + 1, "Struct truncated due to invalid value for 'PositionTag'"); + DataModelLogger::LogString(indent + 1, "Struct truncated due to invalid value for 'RelativePositionTag'"); return err; } } @@ -3644,10 +3644,10 @@ CHIP_ERROR DataModelLogger::LogValue(const char * label, size_t indent, } } { - CHIP_ERROR err = LogValue("AreaDesc", indent + 1, value.areaDesc); + CHIP_ERROR err = LogValue("AreaInfo", indent + 1, value.areaInfo); if (err != CHIP_NO_ERROR) { - DataModelLogger::LogString(indent + 1, "Struct truncated due to invalid value for 'AreaDesc'"); + DataModelLogger::LogString(indent + 1, "Struct truncated due to invalid value for 'AreaInfo'"); return err; } } From bbd21f496615539fdea1f4fb9c11fef32cb2f74a Mon Sep 17 00:00:00 2001 From: mthiesc Date: Fri, 23 Aug 2024 00:59:53 +0200 Subject: [PATCH 148/165] AccountLogin Login/Logout command support (#34162) * AccountLogin Login/Logout command support [Problem] * ContentAppPlatform should send AccountLogin::Login command after successfull commissioning if user was shown setupPIN prompt. * Handling Login/Logout commands is currently not implemented in the Android. [Solution] * Call AccountLoginManager::HandleLogin if commissioning succeeded successfully with setupPIN prompt flow. * Implement HandleLogin (and HandleLogout) for Android AccountLoginManager using the ContentAppCommandDelegate. [Testing] WIP * HandleLogin in ContentAppPlatform::ManageClientAccess * Cache rotating ID in OnUserDirectedCommissioningRequest * Restyled by google-java-format * Restyled by clang-format * Update content app * Restyled by whitespace * Restyled by clang-format * Update response * Update method name * Restyled by google-java-format * Update src/app/app-platform/ContentApp.h Co-authored-by: chrisdecenzo <61757564+chrisdecenzo@users.noreply.github.com> * Update content app platform validation * Update validation logic * Update logic * Update responses * Restyled by clang-format * Simplify logic * Restyled by whitespace * clean up * Update code * Update content app with dynamic pin code * Restyled by google-java-format * Remove getRotatingIdSpan class methods * Restyled by clang-format --------- Co-authored-by: Restyled.io Co-authored-by: Lazar Kovacic Co-authored-by: chrisdecenzo <61757564+chrisdecenzo@users.noreply.github.com> --- .../contentapp/CommandResponseHolder.java | 10 +++ .../receiver/MatterCommandReceiver.java | 17 ++++ .../account-login/AccountLoginManager.cpp | 87 ++++++++++++++++--- examples/tv-app/android/java/AppImpl.cpp | 2 +- .../java/ContentAppCommandDelegate.cpp | 66 +++++++++----- .../android/java/ContentAppCommandDelegate.h | 2 + examples/tv-app/android/java/TVApp-JNI.cpp | 35 +++++--- examples/tv-app/tv-common/src/AppTv.cpp | 37 +++++--- src/app/app-platform/ContentApp.cpp | 13 ++- src/app/app-platform/ContentApp.h | 3 +- src/app/app-platform/ContentAppPlatform.cpp | 26 +++++- src/app/app-platform/ContentAppPlatform.h | 6 +- .../CommissionerDiscoveryController.cpp | 11 ++- .../CommissionerDiscoveryController.h | 7 +- 14 files changed, 254 insertions(+), 68 deletions(-) diff --git a/examples/tv-app/android/App/content-app/src/main/java/com/example/contentapp/CommandResponseHolder.java b/examples/tv-app/android/App/content-app/src/main/java/com/example/contentapp/CommandResponseHolder.java index 61ee303b40..fa49afc312 100644 --- a/examples/tv-app/android/App/content-app/src/main/java/com/example/contentapp/CommandResponseHolder.java +++ b/examples/tv-app/android/App/content-app/src/main/java/com/example/contentapp/CommandResponseHolder.java @@ -31,6 +31,16 @@ private CommandResponseHolder() { Clusters.AccountLogin.Id, Clusters.AccountLogin.Commands.GetSetupPIN.ID, "{\"0\":\"20202021\"}"); + setResponseValue( + Clusters.AccountLogin.Id, + Clusters.AccountLogin.Commands.Login.ID, + // 0 is for success, you can return 1 for failure + "{\"Status\":0}"); + setResponseValue( + Clusters.AccountLogin.Id, + Clusters.AccountLogin.Commands.Logout.ID, + // 0 is for success, you can return 1 for failure + "{\"Status\":0}"); }; public static CommandResponseHolder getInstance() { diff --git a/examples/tv-app/android/App/content-app/src/main/java/com/example/contentapp/receiver/MatterCommandReceiver.java b/examples/tv-app/android/App/content-app/src/main/java/com/example/contentapp/receiver/MatterCommandReceiver.java index 6a4eb77cb4..7134691392 100644 --- a/examples/tv-app/android/App/content-app/src/main/java/com/example/contentapp/receiver/MatterCommandReceiver.java +++ b/examples/tv-app/android/App/content-app/src/main/java/com/example/contentapp/receiver/MatterCommandReceiver.java @@ -4,11 +4,13 @@ import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; +import android.provider.Settings; import android.util.Log; import com.example.contentapp.AttributeHolder; import com.example.contentapp.CommandResponseHolder; import com.example.contentapp.MainActivity; import com.example.contentapp.matter.MatterAgentClient; +import com.matter.tv.app.api.Clusters; import com.matter.tv.app.api.MatterIntentConstants; public class MatterCommandReceiver extends BroadcastReceiver { @@ -44,6 +46,21 @@ public void onReceive(Context context, Intent intent) { .append(command) .toString(); Log.d(TAG, message); + + int pinCode = + Settings.Secure.getInt(context.getContentResolver(), "matter_pin_code", 20202021); + Log.d(TAG, "Retrieved pin code:" + pinCode); + + CommandResponseHolder.getInstance() + .setResponseValue( + Clusters.AccountLogin.Id, + Clusters.AccountLogin.Commands.GetSetupPIN.ID, + "{\"" + + Clusters.AccountLogin.Commands.GetSetupPINResponse.Fields.SetupPIN + + "\":\"" + + pinCode + + "\"}"); + String response = CommandResponseHolder.getInstance().getCommandResponse(clusterId, commandId); diff --git a/examples/tv-app/android/include/account-login/AccountLoginManager.cpp b/examples/tv-app/android/include/account-login/AccountLoginManager.cpp index 12e6ba44df..2aa0b313b0 100644 --- a/examples/tv-app/android/include/account-login/AccountLoginManager.cpp +++ b/examples/tv-app/android/include/account-login/AccountLoginManager.cpp @@ -24,38 +24,105 @@ #include using namespace std; +using namespace chip::app::Clusters; using namespace chip::app::Clusters::AccountLogin; using Status = chip::Protocols::InteractionModel::Status; +namespace { + +const auto loginTempAccountIdentifierFieldId = + to_string(chip::to_underlying(AccountLogin::Commands::Login::Fields::kTempAccountIdentifier)); +const auto loginSetupPINFieldId = to_string(chip::to_underlying(AccountLogin::Commands::Login::Fields::kSetupPIN)); +const auto loginNodeFieldId = to_string(chip::to_underlying(AccountLogin::Commands::Login::Fields::kNode)); +const auto logoutNodeFieldId = to_string(chip::to_underlying(AccountLogin::Commands::Logout::Fields::kNode)); + +string charSpanToString(const CharSpan & charSpan) +{ + return { charSpan.data(), charSpan.size() }; +} + +std::string serializeLoginCommand(AccountLogin::Commands::Login::Type cmd) +{ + return R"({")" + loginTempAccountIdentifierFieldId + R"(":")" + charSpanToString(cmd.tempAccountIdentifier) + R"(",)" + R"(")" + + loginSetupPINFieldId + R"(":")" + charSpanToString(cmd.setupPIN) + R"(",)" + R"(")" + loginNodeFieldId + R"(":")" + + to_string(cmd.node.Value()) + R"("})"; +} + +std::string serializeLogoutCommand(AccountLogin::Commands::Logout::Type cmd) +{ + return R"({")" + logoutNodeFieldId + R"(":")" + to_string(cmd.node.Value()) + R"("})"; +} + +} // namespace + AccountLoginManager::AccountLoginManager(ContentAppCommandDelegate * commandDelegate, const char * setupPin) : mCommandDelegate(commandDelegate) { CopyString(mSetupPin, sizeof(mSetupPin), setupPin); } -bool AccountLoginManager::HandleLogin(const CharSpan & tempAccountIdentifier, const CharSpan & setupPin, +bool AccountLoginManager::HandleLogin(const CharSpan & tempAccountIdentifier, const CharSpan & setupPIN, const chip::Optional & nodeId) { ChipLogProgress(DeviceLayer, "AccountLoginManager::HandleLogin called for endpoint %d", mEndpointId); - string tempAccountIdentifierString(tempAccountIdentifier.data(), tempAccountIdentifier.size()); - string setupPinString(setupPin.data(), setupPin.size()); - if (strcmp(mSetupPin, setupPinString.c_str()) == 0) + if (mCommandDelegate == nullptr) { - ChipLogProgress(Zcl, "AccountLoginManager::HandleLogin success"); - return true; + ChipLogError(Zcl, "CommandDelegate not found"); + return false; } - else + + if (tempAccountIdentifier.empty() || setupPIN.empty() || !nodeId.HasValue()) { - ChipLogProgress(Zcl, "AccountLoginManager::HandleLogin failed expected pin %s", mSetupPin); + ChipLogError(Zcl, "Invalid parameters"); return false; } + + Json::Value response; + bool commandHandled = true; + AccountLogin::Commands::Login::Type cmd = { tempAccountIdentifier, setupPIN, nodeId }; + + auto status = mCommandDelegate->InvokeCommand(mEndpointId, AccountLogin::Id, AccountLogin::Commands::Login::Id, + serializeLoginCommand(cmd), commandHandled, response); + if (status == Status::Success) + { + // Format status response to verify that response is non-failure. + status = mCommandDelegate->FormatStatusResponse(response); + } + ChipLogProgress(Zcl, "AccountLoginManager::HandleLogin command returned with status: %d", chip::to_underlying(status)); + return status == chip::Protocols::InteractionModel::Status::Success; } bool AccountLoginManager::HandleLogout(const chip::Optional & nodeId) { - // TODO: Insert your code here to send logout request - return true; + ChipLogProgress(DeviceLayer, "AccountLoginManager::HandleLogout called for endpoint %d", mEndpointId); + + if (mCommandDelegate == nullptr) + { + ChipLogError(Zcl, "CommandDelegate not found"); + return false; + } + + if (!nodeId.HasValue()) + { + ChipLogError(Zcl, "Invalid parameters"); + return false; + } + + Json::Value response; + bool commandHandled = true; + AccountLogin::Commands::Logout::Type cmd = { nodeId }; + + auto status = mCommandDelegate->InvokeCommand(mEndpointId, AccountLogin::Id, AccountLogin::Commands::Logout::Id, + serializeLogoutCommand(cmd), commandHandled, response); + + if (status == Status::Success) + { + // Format status response to verify that response is non-failure. + status = mCommandDelegate->FormatStatusResponse(response); + } + ChipLogProgress(Zcl, "AccountLoginManager::HandleLogout command returned with status: %d", chip::to_underlying(status)); + return status == chip::Protocols::InteractionModel::Status::Success; } void AccountLoginManager::HandleGetSetupPin(CommandResponseHelper & helper, diff --git a/examples/tv-app/android/java/AppImpl.cpp b/examples/tv-app/android/java/AppImpl.cpp index d7da8ab666..d33949a5d3 100644 --- a/examples/tv-app/android/java/AppImpl.cpp +++ b/examples/tv-app/android/java/AppImpl.cpp @@ -417,7 +417,7 @@ void refreshConnectedClientsAcl(uint16_t vendorId, uint16_t productId, ContentAp for (const auto & allowedVendor : app->GetApplicationBasicDelegate()->GetAllowedVendorList()) { - std::set tempNodeIds = ContentAppPlatform::GetInstance().GetNodeIdsForAllowVendorId(allowedVendor); + std::set tempNodeIds = ContentAppPlatform::GetInstance().GetNodeIdsForAllowedVendorId(allowedVendor); nodeIds.insert(tempNodeIds.begin(), tempNodeIds.end()); } diff --git a/examples/tv-app/android/java/ContentAppCommandDelegate.cpp b/examples/tv-app/android/java/ContentAppCommandDelegate.cpp index 02b4a7e806..caf2d665b8 100644 --- a/examples/tv-app/android/java/ContentAppCommandDelegate.cpp +++ b/examples/tv-app/android/java/ContentAppCommandDelegate.cpp @@ -39,15 +39,9 @@ namespace chip { namespace AppPlatform { -using CommandHandlerInterface = chip::app::CommandHandlerInterface; -using LaunchResponseType = chip::app::Clusters::ContentLauncher::Commands::LauncherResponse::Type; -using PlaybackResponseType = chip::app::Clusters::MediaPlayback::Commands::PlaybackResponse::Type; -using NavigateTargetResponseType = chip::app::Clusters::TargetNavigator::Commands::NavigateTargetResponse::Type; -using GetSetupPINResponseType = chip::app::Clusters::AccountLogin::Commands::GetSetupPINResponse::Type; -using Status = chip::Protocols::InteractionModel::Status; - -const std::string FAILURE_KEY = "PlatformError"; -const std::string FAILURE_STATUS_KEY = "Status"; +const std::string FAILURE_KEY = "PlatformError"; +const std::string FAILURE_STATUS_KEY = "Status"; +const std::string RESPONSE_STATUS_KEY = "Status"; bool isValidJson(const char * response) { @@ -166,6 +160,7 @@ Status ContentAppCommandDelegate::InvokeCommand(EndpointId epId, ClusterId clust ChipLogError(Zcl, "Java exception in ContentAppCommandDelegate::sendCommand"); env->ExceptionDescribe(); env->ExceptionClear(); + return chip::Protocols::InteractionModel::Status::Failure; } else { @@ -198,7 +193,8 @@ Status ContentAppCommandDelegate::InvokeCommand(EndpointId epId, ClusterId clust } env->DeleteLocalRef(resp); - // handle errors from platform-app + // Parse response here in case there is failure response. + // Return non-success error code to indicate to caller it should not parse response. if (!value[FAILURE_KEY].empty()) { value = value[FAILURE_KEY]; @@ -209,7 +205,9 @@ Status ContentAppCommandDelegate::InvokeCommand(EndpointId epId, ClusterId clust return chip::Protocols::InteractionModel::Status::Failure; } - return chip::Protocols::InteractionModel::Status::UnsupportedEndpoint; + // Return success to indicate command has been sent, response returned and parsed successfully. + // Caller has to manually parse value input/output parameter to get response status/object. + return chip::Protocols::InteractionModel::Status::Success; } else { @@ -282,20 +280,31 @@ void ContentAppCommandDelegate::FormatResponseData(CommandHandlerInterface::Hand } case app::Clusters::AccountLogin::Id: { - if (app::Clusters::AccountLogin::Commands::GetSetupPIN::Id != handlerContext.mRequestPath.mCommandId) + switch (handlerContext.mRequestPath.mCommandId) { - // No response for other commands in this cluster + case app::Clusters::AccountLogin::Commands::GetSetupPIN::Id: { + Status status; + GetSetupPINResponseType getSetupPINresponse = FormatGetSetupPINResponse(value, status); + if (status != chip::Protocols::InteractionModel::Status::Success) + { + handlerContext.mCommandHandler.AddStatus(handlerContext.mRequestPath, status); + } + else + { + handlerContext.mCommandHandler.AddResponse(handlerContext.mRequestPath, getSetupPINresponse); + } break; } - Status status; - GetSetupPINResponseType getSetupPINresponse = FormatGetSetupPINResponse(value, status); - if (status != chip::Protocols::InteractionModel::Status::Success) - { - handlerContext.mCommandHandler.AddStatus(handlerContext.mRequestPath, status); + case app::Clusters::AccountLogin::Commands::Login::Id: { + handlerContext.mCommandHandler.AddStatus(handlerContext.mRequestPath, FormatStatusResponse(value)); + break; } - else - { - handlerContext.mCommandHandler.AddResponse(handlerContext.mRequestPath, getSetupPINresponse); + case app::Clusters::AccountLogin::Commands::Logout::Id: { + handlerContext.mCommandHandler.AddStatus(handlerContext.mRequestPath, FormatStatusResponse(value)); + break; + } + default: + break; } break; } @@ -388,10 +397,23 @@ GetSetupPINResponseType ContentAppCommandDelegate::FormatGetSetupPINResponse(Jso } else { - getSetupPINresponse.setupPIN = ""; + status = chip::Protocols::InteractionModel::Status::Failure; } return getSetupPINresponse; } +Status ContentAppCommandDelegate::FormatStatusResponse(Json::Value value) +{ + // check if JSON has "Status" key + if (!value[RESPONSE_STATUS_KEY].empty() && !value[RESPONSE_STATUS_KEY].isUInt()) + { + return static_cast(value.asUInt()); + } + else + { + return chip::Protocols::InteractionModel::Status::Failure; + } +} + } // namespace AppPlatform } // namespace chip diff --git a/examples/tv-app/android/java/ContentAppCommandDelegate.h b/examples/tv-app/android/java/ContentAppCommandDelegate.h index f033b1afa7..49d3e6fda8 100644 --- a/examples/tv-app/android/java/ContentAppCommandDelegate.h +++ b/examples/tv-app/android/java/ContentAppCommandDelegate.h @@ -29,6 +29,7 @@ #include #include #include +#include #include @@ -75,6 +76,7 @@ class ContentAppCommandDelegate : public CommandHandlerInterface LaunchResponseType FormatContentLauncherResponse(Json::Value value, Status & status); NavigateTargetResponseType FormatNavigateTargetResponse(Json::Value value, Status & status); PlaybackResponseType FormatMediaPlaybackResponse(Json::Value value, Status & status); + Status FormatStatusResponse(Json::Value value); private: void InitializeJNIObjects(jobject manager) diff --git a/examples/tv-app/android/java/TVApp-JNI.cpp b/examples/tv-app/android/java/TVApp-JNI.cpp index 0fe1bdef93..228cab60e0 100644 --- a/examples/tv-app/android/java/TVApp-JNI.cpp +++ b/examples/tv-app/android/java/TVApp-JNI.cpp @@ -258,15 +258,15 @@ SampleTvAppInstallationService gSampleTvAppInstallationService; class MyPostCommissioningListener : public PostCommissioningListener { - void CommissioningCompleted(uint16_t vendorId, uint16_t productId, NodeId nodeId, Messaging::ExchangeManager & exchangeMgr, - const SessionHandle & sessionHandle) override + void CommissioningCompleted(uint16_t vendorId, uint16_t productId, NodeId nodeId, CharSpan rotatingId, uint32_t passcode, + Messaging::ExchangeManager & exchangeMgr, const SessionHandle & sessionHandle) override { // read current binding list chip::Controller::ClusterBase cluster(exchangeMgr, sessionHandle, kTargetBindingClusterEndpointId); ContentAppPlatform::GetInstance().StoreNodeIdForContentApp(vendorId, productId, nodeId); - cacheContext(vendorId, productId, nodeId, exchangeMgr, sessionHandle); + cacheContext(vendorId, productId, nodeId, rotatingId, passcode, exchangeMgr, sessionHandle); CHIP_ERROR err = cluster.ReadAttribute(this, OnReadSuccessResponse, OnReadFailureResponse); @@ -350,17 +350,23 @@ class MyPostCommissioningListener : public PostCommissioningListener Optional opt = mSecureSession.Get(); SessionHandle & sessionHandle = opt.Value(); + auto rotatingIdSpan = CharSpan{ mRotatingId.data(), mRotatingId.size() }; ContentAppPlatform::GetInstance().ManageClientAccess(*mExchangeMgr, sessionHandle, mVendorId, mProductId, localNodeId, - bindings, OnSuccessResponse, OnFailureResponse); + rotatingIdSpan, mPasscode, bindings, OnSuccessResponse, + OnFailureResponse); clearContext(); } - void cacheContext(uint16_t vendorId, uint16_t productId, NodeId nodeId, Messaging::ExchangeManager & exchangeMgr, - const SessionHandle & sessionHandle) + void cacheContext(uint16_t vendorId, uint16_t productId, NodeId nodeId, CharSpan rotatingId, uint32_t passcode, + Messaging::ExchangeManager & exchangeMgr, const SessionHandle & sessionHandle) { - mVendorId = vendorId; - mProductId = productId; - mNodeId = nodeId; + mVendorId = vendorId; + mProductId = productId; + mNodeId = nodeId; + mRotatingId = std::string{ + rotatingId.data(), rotatingId.size() + }; // Allocates and copies to string instead of storing span to make sure lifetime is valid. + mPasscode = passcode; mExchangeMgr = &exchangeMgr; mSecureSession.ShiftToSession(sessionHandle); } @@ -370,12 +376,17 @@ class MyPostCommissioningListener : public PostCommissioningListener mVendorId = 0; mProductId = 0; mNodeId = 0; + mRotatingId = {}; + mPasscode = 0; mExchangeMgr = nullptr; mSecureSession.SessionReleased(); } - uint16_t mVendorId = 0; - uint16_t mProductId = 0; - NodeId mNodeId = 0; + + uint16_t mVendorId = 0; + uint16_t mProductId = 0; + NodeId mNodeId = 0; + std::string mRotatingId; + uint32_t mPasscode = 0; Messaging::ExchangeManager * mExchangeMgr = nullptr; SessionHolder mSecureSession; }; diff --git a/examples/tv-app/tv-common/src/AppTv.cpp b/examples/tv-app/tv-common/src/AppTv.cpp index 8d81d9cf6c..794c879b4c 100644 --- a/examples/tv-app/tv-common/src/AppTv.cpp +++ b/examples/tv-app/tv-common/src/AppTv.cpp @@ -158,15 +158,15 @@ MyAppInstallationService gMyAppInstallationService; class MyPostCommissioningListener : public PostCommissioningListener { - void CommissioningCompleted(uint16_t vendorId, uint16_t productId, NodeId nodeId, Messaging::ExchangeManager & exchangeMgr, - const SessionHandle & sessionHandle) override + void CommissioningCompleted(uint16_t vendorId, uint16_t productId, NodeId nodeId, CharSpan rotatingId, uint32_t passcode, + Messaging::ExchangeManager & exchangeMgr, const SessionHandle & sessionHandle) override { // read current binding list chip::Controller::ClusterBase cluster(exchangeMgr, sessionHandle, kTargetBindingClusterEndpointId); ContentAppPlatform::GetInstance().StoreNodeIdForContentApp(vendorId, productId, nodeId); - cacheContext(vendorId, productId, nodeId, exchangeMgr, sessionHandle); + cacheContext(vendorId, productId, nodeId, rotatingId, passcode, exchangeMgr, sessionHandle); CHIP_ERROR err = cluster.ReadAttribute(this, OnReadSuccessResponse, OnReadFailureResponse); @@ -250,17 +250,23 @@ class MyPostCommissioningListener : public PostCommissioningListener Optional opt = mSecureSession.Get(); SessionHandle & sessionHandle = opt.Value(); + auto rotatingIdSpan = CharSpan{ mRotatingId.data(), mRotatingId.size() }; ContentAppPlatform::GetInstance().ManageClientAccess(*mExchangeMgr, sessionHandle, mVendorId, mProductId, localNodeId, - bindings, OnSuccessResponse, OnFailureResponse); + rotatingIdSpan, mPasscode, bindings, OnSuccessResponse, + OnFailureResponse); clearContext(); } - void cacheContext(uint16_t vendorId, uint16_t productId, NodeId nodeId, Messaging::ExchangeManager & exchangeMgr, - const SessionHandle & sessionHandle) + void cacheContext(uint16_t vendorId, uint16_t productId, NodeId nodeId, CharSpan rotatingId, uint32_t passcode, + Messaging::ExchangeManager & exchangeMgr, const SessionHandle & sessionHandle) { - mVendorId = vendorId; - mProductId = productId; - mNodeId = nodeId; + mVendorId = vendorId; + mProductId = productId; + mNodeId = nodeId; + mRotatingId = std::string{ + rotatingId.data(), rotatingId.size() + }; // Allocates and copies to string instead of storing span to make sure lifetime is valid. + mPasscode = passcode; mExchangeMgr = &exchangeMgr; mSecureSession.ShiftToSession(sessionHandle); } @@ -270,12 +276,17 @@ class MyPostCommissioningListener : public PostCommissioningListener mVendorId = 0; mProductId = 0; mNodeId = 0; + mRotatingId = {}; + mPasscode = 0; mExchangeMgr = nullptr; mSecureSession.SessionReleased(); } - uint16_t mVendorId = 0; - uint16_t mProductId = 0; - NodeId mNodeId = 0; + + uint16_t mVendorId = 0; + uint16_t mProductId = 0; + NodeId mNodeId = 0; + std::string mRotatingId; + uint32_t mPasscode = 0; Messaging::ExchangeManager * mExchangeMgr = nullptr; SessionHolder mSecureSession; }; @@ -684,7 +695,7 @@ void ContentAppFactoryImpl::InstallContentApp(uint16_t vendorId, uint16_t produc // update the list of node ids with content apps allowed vendor list for (const auto & allowedVendor : app->GetApplicationBasicDelegate()->GetAllowedVendorList()) { - std::set tempNodeIds = ContentAppPlatform::GetInstance().GetNodeIdsForAllowVendorId(allowedVendor); + std::set tempNodeIds = ContentAppPlatform::GetInstance().GetNodeIdsForAllowedVendorId(allowedVendor); nodeIds.insert(tempNodeIds.begin(), tempNodeIds.end()); } diff --git a/src/app/app-platform/ContentApp.cpp b/src/app/app-platform/ContentApp.cpp index a70965c5f2..4d9268e586 100644 --- a/src/app/app-platform/ContentApp.cpp +++ b/src/app/app-platform/ContentApp.cpp @@ -64,8 +64,17 @@ Status ContentApp::HandleWriteAttribute(ClusterId clusterId, AttributeId attribu return Status::Failure; } -void ContentApp::AddClientNode(NodeId subjectNodeId) +bool ContentApp::AddClientNode(NodeId subjectNodeId) { + for (int i = 0; i < kMaxClientNodes; ++i) + { + if (mClientNodes[i] == subjectNodeId) + { + // avoid storing duplicate nodes + return false; + } + } + mClientNodes[mNextClientNodeIndex++] = subjectNodeId; if (mClientNodeCount < kMaxClientNodes) { @@ -76,6 +85,8 @@ void ContentApp::AddClientNode(NodeId subjectNodeId) // if we exceed the max number, then overwrite the oldest entry mNextClientNodeIndex = 0; } + + return true; } void ContentApp::SendAppObserverCommand(chip::Controller::DeviceCommissioner * commissioner, NodeId clientNodeId, char * data, diff --git a/src/app/app-platform/ContentApp.h b/src/app/app-platform/ContentApp.h index 79c59e45df..ee272c314d 100644 --- a/src/app/app-platform/ContentApp.h +++ b/src/app/app-platform/ContentApp.h @@ -135,7 +135,8 @@ class DLL_EXPORT ContentApp uint16_t maxReadLength); Protocols::InteractionModel::Status HandleWriteAttribute(ClusterId clusterId, AttributeId attributeId, uint8_t * buffer); - void AddClientNode(NodeId clientNodeId); + // returns true only if new node is added. If node was added previously, then false is returned. + bool AddClientNode(NodeId clientNodeId); uint8_t GetClientNodeCount() const { return mClientNodeCount; } NodeId GetClientNode(uint8_t index) const { return mClientNodes[index]; } diff --git a/src/app/app-platform/ContentAppPlatform.cpp b/src/app/app-platform/ContentAppPlatform.cpp index 214af261e2..aa615aaae8 100644 --- a/src/app/app-platform/ContentAppPlatform.cpp +++ b/src/app/app-platform/ContentAppPlatform.cpp @@ -420,7 +420,7 @@ std::set ContentAppPlatform::GetNodeIdsForContentApp(uint16_t vendorId, return {}; } -std::set ContentAppPlatform::GetNodeIdsForAllowVendorId(uint16_t vendorId) +std::set ContentAppPlatform::GetNodeIdsForAllowedVendorId(uint16_t vendorId) { std::set result; std::string vendorPrefix = std::to_string(vendorId) + ":"; @@ -660,6 +660,7 @@ CHIP_ERROR ContentAppPlatform::GetACLEntryIndex(size_t * foundIndex, FabricIndex // and create bindings on the given client so that it knows what it has access to. CHIP_ERROR ContentAppPlatform::ManageClientAccess(Messaging::ExchangeManager & exchangeMgr, SessionHandle & sessionHandle, uint16_t targetVendorId, uint16_t targetProductId, NodeId localNodeId, + CharSpan rotatingId, uint32_t passcode, std::vector bindings, Controller::WriteResponseSuccessCallback successCb, Controller::WriteResponseFailureCallback failureCb) @@ -799,13 +800,32 @@ CHIP_ERROR ContentAppPlatform::ManageClientAccess(Messaging::ExchangeManager & e .cluster = NullOptional, .fabricIndex = kUndefinedFabricIndex, }); + + accessAllowed = true; } - accessAllowed = true; } if (accessAllowed) { // notify content app about this nodeId - app->AddClientNode(subjectNodeId); + bool isNodeAdded = app->AddClientNode(subjectNodeId); + + if (isNodeAdded && rotatingId.size() != 0) + { + // handle login + auto setupPIN = std::to_string(passcode); + auto accountLoginDelegate = app->GetAccountLoginDelegate(); + if (accountLoginDelegate != nullptr) + { + bool condition = accountLoginDelegate->HandleLogin(rotatingId, { setupPIN.data(), setupPIN.size() }, + MakeOptional(subjectNodeId)); + ChipLogProgress(Controller, "AccountLogin::Login command sent and returned: %s", + condition ? "success" : "failure"); + } + else + { + ChipLogError(Controller, "AccountLoginDelegate not found for app"); + } + } } } } diff --git a/src/app/app-platform/ContentAppPlatform.h b/src/app/app-platform/ContentAppPlatform.h index 45615d09ed..b00f9f1bf7 100644 --- a/src/app/app-platform/ContentAppPlatform.h +++ b/src/app/app-platform/ContentAppPlatform.h @@ -165,7 +165,7 @@ class DLL_EXPORT ContentAppPlatform std::set GetNodeIdsForContentApp(uint16_t vendorId, uint16_t productId); // returns set of connected nodes for a given allowed vendor id - std::set GetNodeIdsForAllowVendorId(uint16_t vendorId); + std::set GetNodeIdsForAllowedVendorId(uint16_t vendorId); // store node id for content app after commissioning // node id can be used later on to update ACL @@ -188,6 +188,8 @@ class DLL_EXPORT ContentAppPlatform * @param[in] targetVendorId Vendor ID for the target device. * @param[in] targetProductId Product ID for the target device. * @param[in] localNodeId The NodeId for the local device. + * @param[in] rotatingId The rotating account ID to handle account login. + * @param[in] passcode The passcode to handle account login. * @param[in] bindings Any additional bindings to include. This may include current bindings. * @param[in] successCb The function to be called on success of adding the binding. * @param[in] failureCb The function to be called on failure of adding the binding. @@ -195,7 +197,7 @@ class DLL_EXPORT ContentAppPlatform * @return CHIP_ERROR CHIP_NO_ERROR on success, or corresponding error */ CHIP_ERROR ManageClientAccess(Messaging::ExchangeManager & exchangeMgr, SessionHandle & sessionHandle, uint16_t targetVendorId, - uint16_t targetProductId, NodeId localNodeId, + uint16_t targetProductId, NodeId localNodeId, chip::CharSpan rotatingId, uint32_t passcode, std::vector bindings, Controller::WriteResponseSuccessCallback successCb, Controller::WriteResponseFailureCallback failureCb); diff --git a/src/controller/CommissionerDiscoveryController.cpp b/src/controller/CommissionerDiscoveryController.cpp index 09a22e03e0..baf8e14bfd 100644 --- a/src/controller/CommissionerDiscoveryController.cpp +++ b/src/controller/CommissionerDiscoveryController.cpp @@ -166,6 +166,11 @@ void CommissionerDiscoveryController::OnUserDirectedCommissioningRequest(UDCClie ChipLogError(AppServer, "On UDC: could not convert rotating id to hex"); rotatingIdString[0] = '\0'; } + else + { + // Store rotating ID string. Don't include null terminator character. + mRotatingId = std::string{ rotatingIdString, state.GetRotatingIdLength() * 2 }; + } ChipLogDetail(Controller, "------PROMPT USER: %s is requesting permission to cast to this TV, approve? [" ChipLogFormatMEI @@ -455,6 +460,7 @@ void CommissionerDiscoveryController::InternalHandleContentAppPasscodeResponse() cd, Transport::PeerAddress::UDP(client->GetPeerAddress().GetIPAddress(), client->GetCdPort())); return; } + client->SetCachedCommissionerPasscode(passcode); client->SetUDCClientProcessingState(UDCClientProcessingState::kWaitingForCommissionerPasscodeReady); @@ -630,10 +636,13 @@ void CommissionerDiscoveryController::CommissioningSucceeded(uint16_t vendorId, mVendorId = vendorId; mProductId = productId; mNodeId = nodeId; + if (mPostCommissioningListener != nullptr) { ChipLogDetail(Controller, "CommissionerDiscoveryController calling listener"); - mPostCommissioningListener->CommissioningCompleted(vendorId, productId, nodeId, exchangeMgr, sessionHandle); + auto rotatingIdSpan = CharSpan{ mRotatingId.data(), mRotatingId.size() }; + mPostCommissioningListener->CommissioningCompleted(vendorId, productId, nodeId, rotatingIdSpan, mPasscode, exchangeMgr, + sessionHandle); } else { diff --git a/src/controller/CommissionerDiscoveryController.h b/src/controller/CommissionerDiscoveryController.h index 5f7572b29d..94f172c1d3 100644 --- a/src/controller/CommissionerDiscoveryController.h +++ b/src/controller/CommissionerDiscoveryController.h @@ -232,12 +232,14 @@ class DLL_EXPORT PostCommissioningListener * @param[in] vendorId The vendorid from the DAC of the new node. * @param[in] productId The productid from the DAC of the new node. * @param[in] nodeId The node id for the newly commissioned node. + * @param[in] rotatingId The rotating ID to handle account login. + * @param[in] passcode The passcode to handle account login. * @param[in] exchangeMgr The exchange manager to be used to get an exchange context. * @param[in] sessionHandle A reference to an established session. * */ - virtual void CommissioningCompleted(uint16_t vendorId, uint16_t productId, NodeId nodeId, - chip::Messaging::ExchangeManager & exchangeMgr, + virtual void CommissioningCompleted(uint16_t vendorId, uint16_t productId, NodeId nodeId, chip::CharSpan rotatingId, + uint32_t passcode, chip::Messaging::ExchangeManager & exchangeMgr, const chip::SessionHandle & sessionHandle) = 0; virtual ~PostCommissioningListener() = default; @@ -451,6 +453,7 @@ class CommissionerDiscoveryController : public chip::Protocols::UserDirectedComm uint16_t mProductId = 0; NodeId mNodeId = 0; uint32_t mPasscode = 0; + std::string mRotatingId; UserDirectedCommissioningServer * mUdcServer = nullptr; UserPrompter * mUserPrompter = nullptr; From 05ba80342a0b9949e286a19e02a6f658f0d97add Mon Sep 17 00:00:00 2001 From: Yufeng Wang Date: Thu, 22 Aug 2024 16:17:11 -0700 Subject: [PATCH 149/165] [Fabric-Sync] Symplify the build instructions with build_examples.py (#35162) --- examples/fabric-admin/README.md | 3 ++- examples/fabric-bridge-app/linux/README.md | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/examples/fabric-admin/README.md b/examples/fabric-admin/README.md index 7178ab2c2f..c6b4ba7eb3 100644 --- a/examples/fabric-admin/README.md +++ b/examples/fabric-admin/README.md @@ -14,7 +14,8 @@ fabrics. For Linux host example: ``` -./scripts/examples/gn_build_example.sh examples/fabric-admin out/debug/standalone 'import("//with_pw_rpc.gni")' +source scripts/activate.sh +./scripts/build/build_examples.py --target linux-x64-fabric-admin-rpc build ``` For Raspberry Pi 4 example: diff --git a/examples/fabric-bridge-app/linux/README.md b/examples/fabric-bridge-app/linux/README.md index 6d830cdd98..96e8a2924a 100644 --- a/examples/fabric-bridge-app/linux/README.md +++ b/examples/fabric-bridge-app/linux/README.md @@ -91,7 +91,8 @@ defined: ### For Linux host example: ``` - ./scripts/examples/gn_build_example.sh examples/fabric-bridge-app/linux out/debug/standalone chip_config_network_layer_ble=false 'import("//with_pw_rpc.gni")' + source scripts/activate.sh + ./scripts/build/build_examples.py --target linux-x64-fabric-bridge-rpc build ``` ### For Raspberry Pi 4 example: From daa2a57af16652ce17d7536db7665bf1e2ad40c2 Mon Sep 17 00:00:00 2001 From: Tennessee Carmel-Veilleux Date: Thu, 22 Aug 2024 19:48:46 -0400 Subject: [PATCH 150/165] Fix init of all TC-OCC-* tests (#35001) * Fix init of all TC-OCC-* tests - During TE2 if was found that all TC-OCC-* tests require to pass a `--int-arg endpoint:N` argument which is not the right way to specify endpoint. This is fixed here. - Some pre-steps were done in Step 1 which should have been done after Step 1 so that errors are not marked as Commissioning Failure when it's test failure. Fixes https://github.com/project-chip/matter-test-scripts/issues/340 * More fixes to OCC tests - 3.2 now properly using feature map - Fixed typos - Added queue flushing examples * Restyle * Fix line endings * Restyled by autopep8 * Fix CI --------- Co-authored-by: Restyled.io --- src/python_testing/TC_OCC_2_1.py | 566 ++++++++++--------- src/python_testing/TC_OCC_2_2.py | 264 ++++----- src/python_testing/TC_OCC_2_3.py | 255 ++++----- src/python_testing/TC_OCC_3_1.py | 263 +++++---- src/python_testing/TC_OCC_3_2.py | 411 +++++++------- src/python_testing/matter_testing_support.py | 26 + 6 files changed, 907 insertions(+), 878 deletions(-) diff --git a/src/python_testing/TC_OCC_2_1.py b/src/python_testing/TC_OCC_2_1.py index cf39a7eff5..ddbb34cbf0 100644 --- a/src/python_testing/TC_OCC_2_1.py +++ b/src/python_testing/TC_OCC_2_1.py @@ -1,278 +1,288 @@ -# -# 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. -# -# There are CI issues to be followed up for the test cases below that implements manually controlling sensor device for -# the occupancy state ON/OFF change. -# [TC-OCC-3.1] test procedure step 4 -# [TC-OCC-3.2] test precedure step 3a, 3c - -# See https://github.com/project-chip/connectedhomeip/blob/master/docs/testing/python.md#defining-the-ci-test-arguments -# for details about the block below. -# -# === BEGIN CI TEST ARGUMENTS === -# test-runner-runs: run1 -# test-runner-run/run1/app: ${ALL_CLUSTERS_APP} -# test-runner-run/run1/factoryreset: True -# test-runner-run/run1/quiet: True -# test-runner-run/run1/app-args: --discriminator 1234 --KVS kvs1 --trace-to json:${TRACE_APP}.json -# test-runner-run/run1/script-args: --storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --PICS src/app/tests/suites/certification/ci-pics-values --trace-to json:${TRACE_TEST_JSON}.json --trace-to perfetto:${TRACE_TEST_PERFETTO}.perfetto -# === END CI TEST ARGUMENTS === - -import logging - -import chip.clusters as Clusters -from matter_testing_support import MatterBaseTest, TestStep, async_test_body, default_matter_test_main -from mobly import asserts - - -class TC_OCC_2_1(MatterBaseTest): - async def read_occ_attribute_expect_success(self, endpoint, attribute): - cluster = Clusters.Objects.OccupancySensing - return await self.read_single_attribute_check_success(endpoint=endpoint, cluster=cluster, attribute=attribute) - - def desc_TC_OCC_2_1(self) -> str: - return "[TC-OCC-2.1] Attributes with DUT as Server" - - def steps_TC_OCC_2_1(self) -> list[TestStep]: - steps = [ - TestStep(1, "Commissioning, already done", is_commissioning=True), - TestStep(2, "Read Occupancy attribute."), - TestStep(3, "Read OccupancySensorType attribute."), - TestStep(4, "Read OccupancySensorTypeBitmap attribute."), - TestStep(5, "Read HoldTimeLimits attribute, if supported"), - TestStep(6, "Read HoldTime attribute, if supported"), - TestStep(7, "Read PIROccupiedToUnoccupiedDelay attribute, if supported"), - TestStep(8, "Read PIRUnoccupiedToOccupiedDelay attribute, if supported"), - TestStep(9, "Read PIRUnoccupiedToOccupiedThreshold attribute, if supported"), - TestStep(10, "Read UltrasonicOccupiedToUnoccupiedDelay attribute, if supported"), - TestStep(11, "Read UltrasonicUnoccupiedToOccupiedDelay attribute, if supported"), - TestStep(12, "Read UltrasonicUnoccupiedToOccupiedThreshold attribute, if supported"), - TestStep(13, "Read PhysicalContactOccupiedToUnoccupiedDelay attribute, if supported"), - TestStep(14, "Read PhysicalContactUnoccupiedToOccupiedDelay attribute, if supported"), - TestStep(15, "Read PhysicalContactUnoccupiedToOccupiedThreshold attribute, if supported") - ] - return steps - - def pics_TC_OCC_2_1(self) -> list[str]: - pics = [ - "OCC.S", - ] - return pics - - @async_test_body - async def test_TC_OCC_2_1(self): - - endpoint = self.user_params.get("endpoint", 1) - - self.step(1) - attributes = Clusters.OccupancySensing.Attributes - attribute_list = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.AttributeList) - - self.step(2) - asserts.assert_in(attributes.Occupancy.attribute_id, attribute_list, "Occupancy attribute is mandatory") - occupancy_dut = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.Occupancy) - asserts.assert_less_equal(occupancy_dut, 0b00000001, "Occupancy attribute is not in valid range") - - self.step(3) - asserts.assert_in(attributes.OccupancySensorType.attribute_id, attribute_list, - "OccupancySensorType attribute is a mandatory attribute.") - - occupancy_sensor_type_dut = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.OccupancySensorType) - asserts.assert_less(occupancy_sensor_type_dut, Clusters.Objects.OccupancySensing.Enums.OccupancySensorTypeEnum.kUnknownEnumValue, - "OccupancySensorType is not in valid range") - asserts.assert_in(occupancy_sensor_type_dut, {Clusters.Objects.OccupancySensing.Enums.OccupancySensorTypeEnum.kPir, - Clusters.Objects.OccupancySensing.Enums.OccupancySensorTypeEnum.kUltrasonic, - Clusters.Objects.OccupancySensing.Enums.OccupancySensorTypeEnum.kPIRAndUltrasonic, - Clusters.Objects.OccupancySensing.Enums.OccupancySensorTypeEnum.kPhysicalContact}, "OccupancySensorType is not in valid range") - self.step(4) - asserts.assert_in(attributes.OccupancySensorTypeBitmap.attribute_id, attribute_list, - "OccupancySensorTypeBitmap attribute is a mandatory attribute.") - - occupancy_sensor_type_bitmap_dut = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.OccupancySensorTypeBitmap) - asserts.assert_less_equal(occupancy_sensor_type_bitmap_dut, 0b00000111, - "OccupancySensorTypeBitmap attribute is not in valid range") - - self.step(5) - if attributes.HoldTimeLimits.attribute_id in attribute_list: - asserts.assert_in(attributes.HoldTime.attribute_id, attribute_list, "HoldTime attribute conformance failed.") - hold_time_limits_dut = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.HoldTimeLimits) - asserts.assert_less_equal(hold_time_limits_dut.holdTimeMin, hold_time_limits_dut.holdTimeMax, - "HoldTimeMin is not in valid range") - asserts.assert_greater_equal(hold_time_limits_dut.holdTimeMin, 0, "HoldTimeMin is not in valid range") - asserts.assert_less_equal(hold_time_limits_dut.holdTimeMax, 0xFFFE, "HoldTimeMin is not in valid range") - asserts.assert_greater_equal(hold_time_limits_dut.holdTimeMax, - hold_time_limits_dut.holdTimeMin, "HoldTimeMin is not in valid range") - asserts.assert_less_equal(hold_time_limits_dut.holdTimeDefault, - hold_time_limits_dut.holdTimeMax, "HoldTimeMin is not in valid range") - asserts.assert_greater_equal(hold_time_limits_dut.holdTimeDefault, - hold_time_limits_dut.holdTimeMin, "HoldTimeMin is not in valid range") - else: - logging.info("HoldTimeLimits not supported. Test step skipped") - self.mark_current_step_skipped() - - self.step(6) - if attributes.HoldTime.attribute_id in attribute_list: - hold_time_dut = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.HoldTime) - hold_time_limits_dut = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.HoldTimeLimits) - - asserts.assert_less_equal(hold_time_dut, hold_time_limits_dut.holdTimeMax, "HoldTime attribute is out of range") - asserts.assert_greater_equal(hold_time_dut, hold_time_limits_dut.holdTimeMin, "HoldTime attribute is out of range") - else: - logging.info("HoldTime not supported. The rest of legacy attribute test can be skipped") - self.skip_all_remaining_steps(7) - return - - self.step(7) - if attributes.PIROccupiedToUnoccupiedDelay.attribute_id in attribute_list: - has_pir_bitmap = (occupancy_sensor_type_bitmap_dut & - Clusters.OccupancySensing.Bitmaps.OccupancySensorTypeBitmap.kPir) != 0 - has_ultrasonic_bitmap = (occupancy_sensor_type_bitmap_dut & - Clusters.OccupancySensing.Bitmaps.OccupancySensorTypeBitmap.kUltrasonic) != 0 - has_phy_bitmap = (occupancy_sensor_type_bitmap_dut & - Clusters.OccupancySensing.Bitmaps.OccupancySensorTypeBitmap.kPhysicalContact) != 0 - if has_pir_bitmap or (not has_ultrasonic_bitmap and not has_phy_bitmap): - pir_otou_delay_dut = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.PIROccupiedToUnoccupiedDelay) - asserts.assert_less_equal(pir_otou_delay_dut, 0xFFFE, "PIROccupiedToUnoccupiedDelay is not in valid range") - asserts.assert_greater_equal(pir_otou_delay_dut, 0, "PIROccupiedToUnoccupiedDelay is not in valid range") - else: - logging.info("PIROccupiedToUnoccupiedDelay conformance failed") - asserts.fail( - f"PIROccupiedToUnoccupiedDelay conformance is incorrect: {has_pir_bitmap}, {has_ultrasonic_bitmap}, {has_phy_bitmap}") - else: - logging.info("PIROccupiedToUnoccupiedDelay not supported. Test step skipped") - self.mark_current_step_skipped() - - self.step(8) - if attributes.PIRUnoccupiedToOccupiedDelay.attribute_id in attribute_list: - has_delay = attributes.PIRUnoccupiedToOccupiedDelay.attribute_id in attribute_list - has_threshold = attributes.PIRUnoccupiedToOccupiedThreshold.attribute_id in attribute_list - asserts.assert_equal(has_delay, has_threshold, "PIRUnoccupiedToOccupiedDelay conformance failure") - pir_utoo_delay_dut = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.PIRUnoccupiedToOccupiedDelay) - asserts.assert_less_equal(pir_utoo_delay_dut, 0xFFFE, "PIRUnoccupiedToOccupiedDelay is not in valid range") - asserts.assert_greater_equal(pir_utoo_delay_dut, 0, "PIRUnoccupiedToOccupiedDelay is not in valid range") - else: - logging.info("PIRUnoccupiedToOccupiedDelay not supported. Test step skipped") - self.mark_current_step_skipped() - - self.step(9) - if attributes.PIRUnoccupiedToOccupiedThreshold.attribute_id in attribute_list: - has_delay = attributes.PIRUnoccupiedToOccupiedDelay.attribute_id in attribute_list - has_threshold = attributes.PIRUnoccupiedToOccupiedThreshold.attribute_id in attribute_list - asserts.assert_equal(has_delay, has_threshold, "PIRUnoccupiedToOccupiedThreshold conformance failure") - pir_utoo_threshold_dut = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.PIRUnoccupiedToOccupiedThreshold) - asserts.assert_less_equal(pir_utoo_threshold_dut, 0xFE, "PIRUnoccupiedToOccupiedThreshold is not in valid range") - asserts.assert_greater_equal(pir_utoo_threshold_dut, 0, "PIRUnoccupiedToOccupiedThreshold is not in valid range") - else: - logging.info("PIRUnoccupiedToOccupiedThreshold not supported. Test step skipped") - self.mark_current_step_skipped() - - self.step(10) - if attributes.UltrasonicOccupiedToUnoccupiedDelay.attribute_id in attribute_list: - has_ultrasonic_bitmap = (occupancy_sensor_type_bitmap_dut & - Clusters.OccupancySensing.Enums.OccupancySensorTypeEnum.kUltrasonic) != 0 - has_ultrasonic_delay = attributes.UltrasonicOccupiedToUnoccupiedDelay.attribute_id in attribute_list - asserts.assert_equal(has_ultrasonic_bitmap, has_ultrasonic_delay, "Bad conformance on Ultrasonic bitmap") - - ultrasonic_otou_delay_dut = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.UltrasonicOccupiedToUnoccupiedDelay) - asserts.assert_less_equal(ultrasonic_otou_delay_dut, 0xFFFE, - "UltrasonicOccupiedToUnoccupiedDelay is not in valid range") - asserts.assert_greater_equal(ultrasonic_otou_delay_dut, 0, "UltrasonicOccupiedToUnoccupiedDelay is not in valid range") - - else: - logging.info("UltrasonicOccupiedToUnoccupiedDelay not supported. Test step skipped") - self.mark_current_step_skipped() - - self.step(11) - if attributes.UltrasonicUnoccupiedToOccupiedDelay.attribute_id in attribute_list: - has_delay = attributes.UltrasonicUnoccupiedToOccupiedDelay.attribute_id in attribute_list - has_threshold = attributes.UltrasonicUnoccupiedToOccupiedThreshold.attribute_id in attribute_list - asserts.assert_equal(has_delay, has_threshold, "UltrasonicUnoccupiedToOccupiedDelay conformance failure") - - ultrasonic_utoo_delay_dut = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.UltrasonicUnoccupiedToOccupiedDelay) - asserts.assert_less_equal(ultrasonic_utoo_delay_dut, 0xFFFE, - "UltrasonicUnoccupiedToOccupiedDelay is not in valid range") - asserts.assert_greater_equal(ultrasonic_utoo_delay_dut, 0, "UltrasonicUnoccupiedToOccupiedDelay is not in valid range") - else: - logging.info("UltrasonicUnoccupiedToOccupiedDelay not supported. Test step skipped") - self.mark_current_step_skipped() - - self.step(12) - if attributes.UltrasonicUnoccupiedToOccupiedThreshold.attribute_id in attribute_list: - has_delay = attributes.UltrasonicUnoccupiedToOccupiedDelay.attribute_id in attribute_list - has_threshold = attributes.UltrasonicUnoccupiedToOccupiedThreshold.attribute_id in attribute_list - asserts.assert_equal(has_delay, has_threshold, "UltrasonicUnoccupiedToOccupiedThreshold conformance failure") - - ultrasonic_utoo_threshold_dut = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.UltrasonicUnoccupiedToOccupiedThreshold) - asserts.assert_less_equal(ultrasonic_utoo_threshold_dut, 0xFE, - "UltrasonicUnoccupiedToOccupiedThreshold is not in valid range") - asserts.assert_greater_equal(ultrasonic_utoo_threshold_dut, 0, - "UltrasonicUnoccupiedToOccupiedThreshold is not in valid range") - - else: - logging.info("UltrasonicUnoccupiedToOccupiedThreshold not supported. Test step skipped") - self.mark_current_step_skipped() - - self.step(13) - if attributes.PhysicalContactOccupiedToUnoccupiedDelay.attribute_id in attribute_list: - has_phycon_bitmap = (occupancy_sensor_type_bitmap_dut & - Clusters.OccupancySensing.Enums.OccupancySensorTypeEnum.kPhysicalContact) != 0 - has_phycon_delay = attributes.PhysicalContactOccupiedToUnoccupiedDelay.attribute_id in attribute_list - asserts.assert_equal(has_phycon_bitmap, has_phycon_delay, "Bad conformance on PhysicalContact bitmap") - phycontact_otou_delay_dut = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.PhysicalContactOccupiedToUnoccupiedDelay) - asserts.assert_less_equal(phycontact_otou_delay_dut, 0xFFFE, - "PhysicalContactOccupiedToUnoccupiedDelay is not in valid range") - asserts.assert_greater_equal(phycontact_otou_delay_dut, 0, - "PhysicalContactOccupiedToUnoccupiedDelay is not in valid range") - - else: - logging.info("PhysicalContactOccupiedToUnoccupiedDelay not supported. Test step skipped") - self.mark_current_step_skipped() - - self.step(14) - if attributes.PhysicalContactUnoccupiedToOccupiedDelay.attribute_id in attribute_list: - has_delay = attributes.PhysicalContactUnoccupiedToOccupiedDelay.attribute_id in attribute_list - has_threshold = attributes.PhysicalContactUnoccupiedToOccupiedThreshold.attribute_id in attribute_list - asserts.assert_equal(has_delay, has_threshold, "PhysicalContactUnoccupiedToOccupiedDelay conformance failure") - - phycontact_utoo_delay_dut = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.PhysicalContactUnoccupiedToOccupiedDelay) - asserts.assert_less_equal(phycontact_utoo_delay_dut, 0xFFFE, - "PhysicalContactUnoccupiedToOccupiedDelay is not in valid range") - asserts.assert_greater_equal(phycontact_utoo_delay_dut, 0, - "PhysicalContactUnoccupiedToOccupiedDelay is not in valid range") - - else: - logging.info("PhysicalContactUnoccupiedToOccupiedDelay not supported. Test step skipped") - self.mark_current_step_skipped() - - self.step(15) - if attributes.PhysicalContactUnoccupiedToOccupiedThreshold.attribute_id in attribute_list: - has_delay = attributes.PhysicalContactUnoccupiedToOccupiedDelay.attribute_id in attribute_list - has_threshold = attributes.PhysicalContactUnoccupiedToOccupiedThreshold.attribute_id in attribute_list - asserts.assert_equal(has_delay, has_threshold, "PhysicalContactUnoccupiedToOccupiedThreshold conformance failure") - - phycontact_utoo_threshold_dut = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.PhysicalContactUnoccupiedToOccupiedThreshold) - asserts.assert_less_equal(phycontact_utoo_threshold_dut, 0xFE, - "PhysicalContactUnoccupiedToOccupiedThreshold is not in valid range") - asserts.assert_greater_equal(phycontact_utoo_threshold_dut, 0, - "PhysicalContactUnoccupiedToOccupiedThreshold is not in valid range") - - else: - logging.info("PhysicalContactUnoccupiedToOccupiedThreshold not supported. Test step skipped") - self.mark_current_step_skipped() - - -if __name__ == "__main__": - default_matter_test_main() +# +# 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. +# +# There are CI issues to be followed up for the test cases below that implements manually controlling sensor device for +# the occupancy state ON/OFF change. +# [TC-OCC-3.1] test procedure step 4 +# [TC-OCC-3.2] test precedure step 3a, 3c + +# See https://github.com/project-chip/connectedhomeip/blob/master/docs/testing/python.md#defining-the-ci-test-arguments +# for details about the block below. +# +# === BEGIN CI TEST ARGUMENTS === +# test-runner-runs: run1 +# test-runner-run/run1/app: ${ALL_CLUSTERS_APP} +# test-runner-run/run1/factoryreset: True +# test-runner-run/run1/quiet: True +# test-runner-run/run1/app-args: --discriminator 1234 --KVS kvs1 --trace-to json:${TRACE_APP}.json +# test-runner-run/run1/script-args: --storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --PICS src/app/tests/suites/certification/ci-pics-values --trace-to json:${TRACE_TEST_JSON}.json --trace-to perfetto:${TRACE_TEST_PERFETTO}.perfetto --endpoint 1 +# === END CI TEST ARGUMENTS === + +import logging + +import chip.clusters as Clusters +from matter_testing_support import MatterBaseTest, TestStep, async_test_body, default_matter_test_main +from mobly import asserts + + +class TC_OCC_2_1(MatterBaseTest): + async def read_occ_attribute_expect_success(self, endpoint, attribute): + cluster = Clusters.Objects.OccupancySensing + return await self.read_single_attribute_check_success(endpoint=endpoint, cluster=cluster, attribute=attribute) + + def desc_TC_OCC_2_1(self) -> str: + return "[TC-OCC-2.1] Attributes with DUT as Server" + + def steps_TC_OCC_2_1(self) -> list[TestStep]: + steps = [ + TestStep(1, "Commissioning, already done", is_commissioning=True), + TestStep(2, "Read Occupancy attribute."), + TestStep(3, "Read OccupancySensorType attribute."), + TestStep(4, "Read OccupancySensorTypeBitmap attribute."), + TestStep(5, "Read HoldTimeLimits attribute, if supported"), + TestStep(6, "Read HoldTime attribute, if supported"), + TestStep(7, "Read PIROccupiedToUnoccupiedDelay attribute, if supported"), + TestStep(8, "Read PIRUnoccupiedToOccupiedDelay attribute, if supported"), + TestStep(9, "Read PIRUnoccupiedToOccupiedThreshold attribute, if supported"), + TestStep(10, "Read UltrasonicOccupiedToUnoccupiedDelay attribute, if supported"), + TestStep(11, "Read UltrasonicUnoccupiedToOccupiedDelay attribute, if supported"), + TestStep(12, "Read UltrasonicUnoccupiedToOccupiedThreshold attribute, if supported"), + TestStep(13, "Read PhysicalContactOccupiedToUnoccupiedDelay attribute, if supported"), + TestStep(14, "Read PhysicalContactUnoccupiedToOccupiedDelay attribute, if supported"), + TestStep(15, "Read PhysicalContactUnoccupiedToOccupiedThreshold attribute, if supported") + ] + return steps + + def pics_TC_OCC_2_1(self) -> list[str]: + pics = [ + "OCC.S", + ] + return pics + + @async_test_body + async def test_TC_OCC_2_1(self): + endpoint = self.matter_test_config.endpoint + cluster = Clusters.Objects.OccupancySensing + attributes = cluster.Attributes + + self.step(1) # Already done, immediately go to step 2 + + self.step(2) + + feature_map = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.FeatureMap) + has_feature_pir = (feature_map & cluster.Bitmaps.Feature.kPassiveInfrared) != 0 + has_feature_ultrasonic = (feature_map & cluster.Bitmaps.Feature.kUltrasonic) != 0 + has_feature_contact = (feature_map & cluster.Bitmaps.Feature.kPhysicalContact) != 0 + + logging.info( + f"Feature map: 0x{feature_map:x}. PIR: {has_feature_pir}, US:{has_feature_ultrasonic}, PHY:{has_feature_contact}") + + attribute_list = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.AttributeList) + + asserts.assert_in(attributes.Occupancy.attribute_id, attribute_list, "Occupancy attribute is mandatory") + occupancy_dut = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.Occupancy) + asserts.assert_less_equal(occupancy_dut, 0b00000001, "Occupancy attribute is not in valid range") + + self.step(3) + asserts.assert_in(attributes.OccupancySensorType.attribute_id, attribute_list, + "OccupancySensorType attribute is a mandatory attribute.") + + occupancy_sensor_type_dut = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.OccupancySensorType) + asserts.assert_less(occupancy_sensor_type_dut, Clusters.Objects.OccupancySensing.Enums.OccupancySensorTypeEnum.kUnknownEnumValue, + "OccupancySensorType is not in valid range") + asserts.assert_in(occupancy_sensor_type_dut, {Clusters.Objects.OccupancySensing.Enums.OccupancySensorTypeEnum.kPir, + Clusters.Objects.OccupancySensing.Enums.OccupancySensorTypeEnum.kUltrasonic, + Clusters.Objects.OccupancySensing.Enums.OccupancySensorTypeEnum.kPIRAndUltrasonic, + Clusters.Objects.OccupancySensing.Enums.OccupancySensorTypeEnum.kPhysicalContact}, "OccupancySensorType is not in valid range") + self.step(4) + asserts.assert_in(attributes.OccupancySensorTypeBitmap.attribute_id, attribute_list, + "OccupancySensorTypeBitmap attribute is a mandatory attribute.") + + occupancy_sensor_type_bitmap_dut = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.OccupancySensorTypeBitmap) + asserts.assert_less_equal(occupancy_sensor_type_bitmap_dut, 0b00000111, + "OccupancySensorTypeBitmap attribute is not in valid range") + + self.step(5) + if attributes.HoldTimeLimits.attribute_id in attribute_list: + asserts.assert_in(attributes.HoldTime.attribute_id, attribute_list, "HoldTime attribute conformance failed.") + hold_time_limits_dut = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.HoldTimeLimits) + asserts.assert_less_equal(hold_time_limits_dut.holdTimeMin, hold_time_limits_dut.holdTimeMax, + "HoldTimeMin is not in valid range") + asserts.assert_greater_equal(hold_time_limits_dut.holdTimeMin, 0, "HoldTimeMin is not in valid range") + asserts.assert_less_equal(hold_time_limits_dut.holdTimeMax, 0xFFFE, "HoldTimeMin is not in valid range") + asserts.assert_greater_equal(hold_time_limits_dut.holdTimeMax, + hold_time_limits_dut.holdTimeMin, "HoldTimeMin is not in valid range") + asserts.assert_less_equal(hold_time_limits_dut.holdTimeDefault, + hold_time_limits_dut.holdTimeMax, "HoldTimeMin is not in valid range") + asserts.assert_greater_equal(hold_time_limits_dut.holdTimeDefault, + hold_time_limits_dut.holdTimeMin, "HoldTimeMin is not in valid range") + else: + logging.info("HoldTimeLimits not supported. Test step skipped") + self.mark_current_step_skipped() + + self.step(6) + if attributes.HoldTime.attribute_id in attribute_list: + hold_time_dut = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.HoldTime) + hold_time_limits_dut = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.HoldTimeLimits) + + asserts.assert_less_equal(hold_time_dut, hold_time_limits_dut.holdTimeMax, "HoldTime attribute is out of range") + asserts.assert_greater_equal(hold_time_dut, hold_time_limits_dut.holdTimeMin, "HoldTime attribute is out of range") + else: + logging.info("HoldTime not supported. The rest of legacy attribute test can be skipped") + self.skip_all_remaining_steps(7) + return + + self.step(7) + if attributes.PIROccupiedToUnoccupiedDelay.attribute_id in attribute_list: + has_feature_pir = (occupancy_sensor_type_bitmap_dut & + Clusters.OccupancySensing.Bitmaps.OccupancySensorTypeBitmap.kPir) != 0 + has_feature_ultrasonic = (occupancy_sensor_type_bitmap_dut & + Clusters.OccupancySensing.Bitmaps.OccupancySensorTypeBitmap.kUltrasonic) != 0 + has_feature_contact = (occupancy_sensor_type_bitmap_dut & + Clusters.OccupancySensing.Bitmaps.OccupancySensorTypeBitmap.kPhysicalContact) != 0 + if has_feature_pir or (not has_feature_pir and not has_feature_ultrasonic and not has_feature_contact): + pir_otou_delay_dut = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.PIROccupiedToUnoccupiedDelay) + asserts.assert_less_equal(pir_otou_delay_dut, 0xFFFE, "PIROccupiedToUnoccupiedDelay is not in valid range") + asserts.assert_greater_equal(pir_otou_delay_dut, 0, "PIROccupiedToUnoccupiedDelay is not in valid range") + else: + logging.info("PIROccupiedToUnoccupiedDelay conformance failed") + asserts.fail( + f"PIROccupiedToUnoccupiedDelay conformance is incorrect: {has_feature_pir}, {has_feature_ultrasonic}, {has_feature_contact}") + else: + logging.info("PIROccupiedToUnoccupiedDelay not supported. Test step skipped") + self.mark_current_step_skipped() + + self.step(8) + if attributes.PIRUnoccupiedToOccupiedDelay.attribute_id in attribute_list: + has_delay = attributes.PIRUnoccupiedToOccupiedDelay.attribute_id in attribute_list + has_threshold = attributes.PIRUnoccupiedToOccupiedThreshold.attribute_id in attribute_list + asserts.assert_equal(has_delay, has_threshold, "PIRUnoccupiedToOccupiedDelay conformance failure") + pir_utoo_delay_dut = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.PIRUnoccupiedToOccupiedDelay) + asserts.assert_less_equal(pir_utoo_delay_dut, 0xFFFE, "PIRUnoccupiedToOccupiedDelay is not in valid range") + asserts.assert_greater_equal(pir_utoo_delay_dut, 0, "PIRUnoccupiedToOccupiedDelay is not in valid range") + else: + logging.info("PIRUnoccupiedToOccupiedDelay not supported. Test step skipped") + self.mark_current_step_skipped() + + self.step(9) + if attributes.PIRUnoccupiedToOccupiedThreshold.attribute_id in attribute_list: + has_delay = attributes.PIRUnoccupiedToOccupiedDelay.attribute_id in attribute_list + has_threshold = attributes.PIRUnoccupiedToOccupiedThreshold.attribute_id in attribute_list + asserts.assert_equal(has_delay, has_threshold, "PIRUnoccupiedToOccupiedThreshold conformance failure") + pir_utoo_threshold_dut = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.PIRUnoccupiedToOccupiedThreshold) + asserts.assert_less_equal(pir_utoo_threshold_dut, 0xFE, "PIRUnoccupiedToOccupiedThreshold is not in valid range") + asserts.assert_greater_equal(pir_utoo_threshold_dut, 0, "PIRUnoccupiedToOccupiedThreshold is not in valid range") + else: + logging.info("PIRUnoccupiedToOccupiedThreshold not supported. Test step skipped") + self.mark_current_step_skipped() + + self.step(10) + if attributes.UltrasonicOccupiedToUnoccupiedDelay.attribute_id in attribute_list: + has_feature_ultrasonic = (occupancy_sensor_type_bitmap_dut & + Clusters.OccupancySensing.Enums.OccupancySensorTypeEnum.kUltrasonic) != 0 + has_ultrasonic_delay = attributes.UltrasonicOccupiedToUnoccupiedDelay.attribute_id in attribute_list + asserts.assert_equal(has_feature_ultrasonic, has_ultrasonic_delay, "Bad conformance on Ultrasonic bitmap") + + ultrasonic_otou_delay_dut = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.UltrasonicOccupiedToUnoccupiedDelay) + asserts.assert_less_equal(ultrasonic_otou_delay_dut, 0xFFFE, + "UltrasonicOccupiedToUnoccupiedDelay is not in valid range") + asserts.assert_greater_equal(ultrasonic_otou_delay_dut, 0, "UltrasonicOccupiedToUnoccupiedDelay is not in valid range") + + else: + logging.info("UltrasonicOccupiedToUnoccupiedDelay not supported. Test step skipped") + self.mark_current_step_skipped() + + self.step(11) + if attributes.UltrasonicUnoccupiedToOccupiedDelay.attribute_id in attribute_list: + has_delay = attributes.UltrasonicUnoccupiedToOccupiedDelay.attribute_id in attribute_list + has_threshold = attributes.UltrasonicUnoccupiedToOccupiedThreshold.attribute_id in attribute_list + asserts.assert_equal(has_delay, has_threshold, "UltrasonicUnoccupiedToOccupiedDelay conformance failure") + + ultrasonic_utoo_delay_dut = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.UltrasonicUnoccupiedToOccupiedDelay) + asserts.assert_less_equal(ultrasonic_utoo_delay_dut, 0xFFFE, + "UltrasonicUnoccupiedToOccupiedDelay is not in valid range") + asserts.assert_greater_equal(ultrasonic_utoo_delay_dut, 0, "UltrasonicUnoccupiedToOccupiedDelay is not in valid range") + else: + logging.info("UltrasonicUnoccupiedToOccupiedDelay not supported. Test step skipped") + self.mark_current_step_skipped() + + self.step(12) + if attributes.UltrasonicUnoccupiedToOccupiedThreshold.attribute_id in attribute_list: + has_delay = attributes.UltrasonicUnoccupiedToOccupiedDelay.attribute_id in attribute_list + has_threshold = attributes.UltrasonicUnoccupiedToOccupiedThreshold.attribute_id in attribute_list + asserts.assert_equal(has_delay, has_threshold, "UltrasonicUnoccupiedToOccupiedThreshold conformance failure") + + ultrasonic_utoo_threshold_dut = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.UltrasonicUnoccupiedToOccupiedThreshold) + asserts.assert_less_equal(ultrasonic_utoo_threshold_dut, 0xFE, + "UltrasonicUnoccupiedToOccupiedThreshold is not in valid range") + asserts.assert_greater_equal(ultrasonic_utoo_threshold_dut, 0, + "UltrasonicUnoccupiedToOccupiedThreshold is not in valid range") + + else: + logging.info("UltrasonicUnoccupiedToOccupiedThreshold not supported. Test step skipped") + self.mark_current_step_skipped() + + self.step(13) + if attributes.PhysicalContactOccupiedToUnoccupiedDelay.attribute_id in attribute_list: + has_phycon_bitmap = (occupancy_sensor_type_bitmap_dut & + Clusters.OccupancySensing.Enums.OccupancySensorTypeEnum.kPhysicalContact) != 0 + has_phycon_delay = attributes.PhysicalContactOccupiedToUnoccupiedDelay.attribute_id in attribute_list + asserts.assert_equal(has_phycon_bitmap, has_phycon_delay, "Bad conformance on PhysicalContact bitmap") + phycontact_otou_delay_dut = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.PhysicalContactOccupiedToUnoccupiedDelay) + asserts.assert_less_equal(phycontact_otou_delay_dut, 0xFFFE, + "PhysicalContactOccupiedToUnoccupiedDelay is not in valid range") + asserts.assert_greater_equal(phycontact_otou_delay_dut, 0, + "PhysicalContactOccupiedToUnoccupiedDelay is not in valid range") + + else: + logging.info("PhysicalContactOccupiedToUnoccupiedDelay not supported. Test step skipped") + self.mark_current_step_skipped() + + self.step(14) + if attributes.PhysicalContactUnoccupiedToOccupiedDelay.attribute_id in attribute_list: + has_delay = attributes.PhysicalContactUnoccupiedToOccupiedDelay.attribute_id in attribute_list + has_threshold = attributes.PhysicalContactUnoccupiedToOccupiedThreshold.attribute_id in attribute_list + asserts.assert_equal(has_delay, has_threshold, "PhysicalContactUnoccupiedToOccupiedDelay conformance failure") + + phycontact_utoo_delay_dut = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.PhysicalContactUnoccupiedToOccupiedDelay) + asserts.assert_less_equal(phycontact_utoo_delay_dut, 0xFFFE, + "PhysicalContactUnoccupiedToOccupiedDelay is not in valid range") + asserts.assert_greater_equal(phycontact_utoo_delay_dut, 0, + "PhysicalContactUnoccupiedToOccupiedDelay is not in valid range") + + else: + logging.info("PhysicalContactUnoccupiedToOccupiedDelay not supported. Test step skipped") + self.mark_current_step_skipped() + + self.step(15) + if attributes.PhysicalContactUnoccupiedToOccupiedThreshold.attribute_id in attribute_list: + has_delay = attributes.PhysicalContactUnoccupiedToOccupiedDelay.attribute_id in attribute_list + has_threshold = attributes.PhysicalContactUnoccupiedToOccupiedThreshold.attribute_id in attribute_list + asserts.assert_equal(has_delay, has_threshold, "PhysicalContactUnoccupiedToOccupiedThreshold conformance failure") + + phycontact_utoo_threshold_dut = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.PhysicalContactUnoccupiedToOccupiedThreshold) + asserts.assert_less_equal(phycontact_utoo_threshold_dut, 0xFE, + "PhysicalContactUnoccupiedToOccupiedThreshold is not in valid range") + asserts.assert_greater_equal(phycontact_utoo_threshold_dut, 0, + "PhysicalContactUnoccupiedToOccupiedThreshold is not in valid range") + + else: + logging.info("PhysicalContactUnoccupiedToOccupiedThreshold not supported. Test step skipped") + self.mark_current_step_skipped() + + +if __name__ == "__main__": + default_matter_test_main() diff --git a/src/python_testing/TC_OCC_2_2.py b/src/python_testing/TC_OCC_2_2.py index e27bbf30eb..9914452342 100644 --- a/src/python_testing/TC_OCC_2_2.py +++ b/src/python_testing/TC_OCC_2_2.py @@ -1,132 +1,132 @@ -# -# 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. -# - -# See https://github.com/project-chip/connectedhomeip/blob/master/docs/testing/python.md#defining-the-ci-test-arguments -# for details about the block below. -# -# === BEGIN CI TEST ARGUMENTS === -# test-runner-runs: run1 -# test-runner-run/run1/app: ${ALL_CLUSTERS_APP} -# test-runner-run/run1/factoryreset: True -# test-runner-run/run1/quiet: True -# test-runner-run/run1/app-args: --discriminator 1234 --KVS kvs1 --trace-to json:${TRACE_APP}.json -# test-runner-run/run1/script-args: --storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --PICS src/app/tests/suites/certification/ci-pics-values --trace-to json:${TRACE_TEST_JSON}.json --trace-to perfetto:${TRACE_TEST_PERFETTO}.perfetto -# === END CI TEST ARGUMENTS === - -import chip.clusters as Clusters -from matter_testing_support import MatterBaseTest, TestStep, async_test_body, default_matter_test_main -from mobly import asserts - - -class TC_OCC_2_2(MatterBaseTest): - async def read_occ_attribute_expect_success(self, endpoint, attribute): - cluster = Clusters.Objects.OccupancySensing - return await self.read_single_attribute_check_success(endpoint=endpoint, cluster=cluster, attribute=attribute) - - def desc_TC_OCC_2_2(self) -> str: - return "[TC-OCC-2.2] OccupancySensorTypeBitmap and OccupancySensorType interdependency with server as DUT" - - def steps_TC_OCC_2_2(self) -> list[TestStep]: - steps = [ - TestStep(1, "Commissioning, already done", is_commissioning=True), - TestStep(2, "Read OccupancySensorType attribute selection based on FeatureMap Bitmap."), - TestStep(3, "Read OccupancySensorTypeBitmap attribute selection based on FeatureMap Bitmap.") - ] - return steps - - def pics_TC_OCC_2_2(self) -> list[str]: - pics = [ - "OCC.S", - ] - return pics - - @async_test_body - async def test_TC_OCC_2_2(self): - - endpoint = self.user_params.get("endpoint", 1) - - attributes = Clusters.OccupancySensing.Attributes - feature_map = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.FeatureMap) - - self.step(1) - attribute_list = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.AttributeList) - - self.step(2) - # OccupancySensorType will be determined by FeatureMap matching table at 2.7.6.2. - asserts.assert_in(attributes.OccupancySensorType.attribute_id, attribute_list, - "OccupancySensorType attribute is a mandatory attribute.") - occupancy_sensor_type_dut = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.OccupancySensorType) - - # For validation purposes, 2.7.6.2 table describes what feature flags map to what type of sensors - TypeEnum = Clusters.OccupancySensing.Enums.OccupancySensorTypeEnum - - Y = True - N = False - # Map is PIR, US, PHY => expected sensor type - # odd Y/N mapping to make the table align nicely - mappings = { - (N, N, N): TypeEnum.kPir, - (Y, N, N): TypeEnum.kPir, - (N, Y, N): TypeEnum.kUltrasonic, - (Y, Y, N): TypeEnum.kPIRAndUltrasonic, - (N, N, Y): TypeEnum.kPhysicalContact, - (Y, N, Y): TypeEnum.kPir, - (N, Y, Y): TypeEnum.kUltrasonic, - (Y, Y, Y): TypeEnum.kPIRAndUltrasonic, - } - - FeatureBit = Clusters.OccupancySensing.Bitmaps.Feature - expected = mappings.get( - ( - (feature_map & FeatureBit.kPassiveInfrared) != 0, - (feature_map & FeatureBit.kUltrasonic) != 0, - (feature_map & FeatureBit.kPhysicalContact) != 0 - )) - - asserts.assert_equal( - occupancy_sensor_type_dut, - expected, - f"Sensor Type should be f{expected}" - ) - - self.step(3) - # OccupancySensorTypeBitmap will be determined by FeatureMap matching table at 2.7.6.2. - asserts.assert_in(attributes.OccupancySensorTypeBitmap.attribute_id, attribute_list, - "OccupancySensorTypeBitmap attribute is a mandatory attribute.") - - occupancy_sensor_type_bitmap_dut = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.OccupancySensorTypeBitmap) - - # Feature map must match the sensor type bitmap - must_match_bits = [ - (Clusters.OccupancySensing.Bitmaps.OccupancySensorTypeBitmap.kPir, - Clusters.OccupancySensing.Bitmaps.Feature.kPassiveInfrared, "PIR"), - (Clusters.OccupancySensing.Bitmaps.OccupancySensorTypeBitmap.kUltrasonic, - Clusters.OccupancySensing.Bitmaps.Feature.kUltrasonic, "Ultrasonic"), - (Clusters.OccupancySensing.Bitmaps.OccupancySensorTypeBitmap.kPhysicalContact, - Clusters.OccupancySensing.Bitmaps.Feature.kPhysicalContact, "Physical contact"), - ] - - for sensor_bit, feature_bit, name in must_match_bits: - asserts.assert_equal( - (occupancy_sensor_type_bitmap_dut & sensor_bit) != 0, - (feature_map & feature_bit) != 0, - f"Feature bit and sensor bitmap must be equal for {name} (BITMAP: 0x{occupancy_sensor_type_bitmap_dut:02X}, FEATUREMAP: 0x{feature_map:02X})" - ) - - -if __name__ == "__main__": - default_matter_test_main() +# +# 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. +# + +# See https://github.com/project-chip/connectedhomeip/blob/master/docs/testing/python.md#defining-the-ci-test-arguments +# for details about the block below. +# +# === BEGIN CI TEST ARGUMENTS === +# test-runner-runs: run1 +# test-runner-run/run1/app: ${ALL_CLUSTERS_APP} +# test-runner-run/run1/factoryreset: True +# test-runner-run/run1/quiet: True +# test-runner-run/run1/app-args: --discriminator 1234 --KVS kvs1 --trace-to json:${TRACE_APP}.json +# test-runner-run/run1/script-args: --storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --PICS src/app/tests/suites/certification/ci-pics-values --trace-to json:${TRACE_TEST_JSON}.json --trace-to perfetto:${TRACE_TEST_PERFETTO}.perfetto --endpoint 1 +# === END CI TEST ARGUMENTS === + +import chip.clusters as Clusters +from matter_testing_support import MatterBaseTest, TestStep, async_test_body, default_matter_test_main +from mobly import asserts + + +class TC_OCC_2_2(MatterBaseTest): + async def read_occ_attribute_expect_success(self, endpoint, attribute): + cluster = Clusters.Objects.OccupancySensing + return await self.read_single_attribute_check_success(endpoint=endpoint, cluster=cluster, attribute=attribute) + + def desc_TC_OCC_2_2(self) -> str: + return "[TC-OCC-2.2] OccupancySensorTypeBitmap and OccupancySensorType interdependency with server as DUT" + + def steps_TC_OCC_2_2(self) -> list[TestStep]: + steps = [ + TestStep(1, "Commissioning, already done", is_commissioning=True), + TestStep(2, "Read OccupancySensorType attribute selection based on FeatureMap Bitmap."), + TestStep(3, "Read OccupancySensorTypeBitmap attribute selection based on FeatureMap Bitmap.") + ] + return steps + + def pics_TC_OCC_2_2(self) -> list[str]: + pics = [ + "OCC.S", + ] + return pics + + @async_test_body + async def test_TC_OCC_2_2(self): + endpoint = self.matter_test_config.endpoint + + self.step(1) # Already done, immediately go to step 2 + + self.step(2) + + attributes = Clusters.OccupancySensing.Attributes + feature_map = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.FeatureMap) + attribute_list = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.AttributeList) + + # OccupancySensorType will be determined by FeatureMap matching table at 2.7.6.2. + asserts.assert_in(attributes.OccupancySensorType.attribute_id, attribute_list, + "OccupancySensorType attribute is a mandatory attribute.") + occupancy_sensor_type_dut = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.OccupancySensorType) + + # For validation purposes, 2.7.6.2 table describes what feature flags map to what type of sensors + TypeEnum = Clusters.OccupancySensing.Enums.OccupancySensorTypeEnum + + Y = True + N = False + # Map is PIR, US, PHY => expected sensor type + # odd Y/N mapping to make the table align nicely + mappings = { + (N, N, N): TypeEnum.kPir, + (Y, N, N): TypeEnum.kPir, + (N, Y, N): TypeEnum.kUltrasonic, + (Y, Y, N): TypeEnum.kPIRAndUltrasonic, + (N, N, Y): TypeEnum.kPhysicalContact, + (Y, N, Y): TypeEnum.kPir, + (N, Y, Y): TypeEnum.kUltrasonic, + (Y, Y, Y): TypeEnum.kPIRAndUltrasonic, + } + + FeatureBit = Clusters.OccupancySensing.Bitmaps.Feature + expected = mappings.get( + ( + (feature_map & FeatureBit.kPassiveInfrared) != 0, + (feature_map & FeatureBit.kUltrasonic) != 0, + (feature_map & FeatureBit.kPhysicalContact) != 0 + )) + + asserts.assert_equal( + occupancy_sensor_type_dut, + expected, + f"Sensor Type should be f{expected}" + ) + + self.step(3) + # OccupancySensorTypeBitmap will be determined by FeatureMap matching table at 2.7.6.2. + asserts.assert_in(attributes.OccupancySensorTypeBitmap.attribute_id, attribute_list, + "OccupancySensorTypeBitmap attribute is a mandatory attribute.") + + occupancy_sensor_type_bitmap_dut = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.OccupancySensorTypeBitmap) + + # Feature map must match the sensor type bitmap + must_match_bits = [ + (Clusters.OccupancySensing.Bitmaps.OccupancySensorTypeBitmap.kPir, + Clusters.OccupancySensing.Bitmaps.Feature.kPassiveInfrared, "PIR"), + (Clusters.OccupancySensing.Bitmaps.OccupancySensorTypeBitmap.kUltrasonic, + Clusters.OccupancySensing.Bitmaps.Feature.kUltrasonic, "Ultrasonic"), + (Clusters.OccupancySensing.Bitmaps.OccupancySensorTypeBitmap.kPhysicalContact, + Clusters.OccupancySensing.Bitmaps.Feature.kPhysicalContact, "Physical contact"), + ] + + for sensor_bit, feature_bit, name in must_match_bits: + asserts.assert_equal( + (occupancy_sensor_type_bitmap_dut & sensor_bit) != 0, + (feature_map & feature_bit) != 0, + f"Feature bit and sensor bitmap must be equal for {name} (BITMAP: 0x{occupancy_sensor_type_bitmap_dut:02X}, FEATUREMAP: 0x{feature_map:02X})" + ) + + +if __name__ == "__main__": + default_matter_test_main() diff --git a/src/python_testing/TC_OCC_2_3.py b/src/python_testing/TC_OCC_2_3.py index 0184b670c6..63e973b159 100644 --- a/src/python_testing/TC_OCC_2_3.py +++ b/src/python_testing/TC_OCC_2_3.py @@ -1,127 +1,128 @@ -# -# 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. -# - -# See https://github.com/project-chip/connectedhomeip/blob/master/docs/testing/python.md#defining-the-ci-test-arguments -# for details about the block below. -# -# === BEGIN CI TEST ARGUMENTS === -# test-runner-runs: run1 -# test-runner-run/run1/app: ${ALL_CLUSTERS_APP} -# test-runner-run/run1/factoryreset: True -# test-runner-run/run1/quiet: True -# test-runner-run/run1/app-args: --discriminator 1234 --KVS kvs1 --trace-to json:${TRACE_APP}.json -# test-runner-run/run1/script-args: --storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --PICS src/app/tests/suites/certification/ci-pics-values --trace-to json:${TRACE_TEST_JSON}.json --trace-to perfetto:${TRACE_TEST_PERFETTO}.perfetto -# === END CI TEST ARGUMENTS === - -import logging - -import chip.clusters as Clusters -from matter_testing_support import MatterBaseTest, TestStep, async_test_body, default_matter_test_main -from mobly import asserts - - -class TC_OCC_2_3(MatterBaseTest): - async def read_occ_attribute_expect_success(self, endpoint, attribute): - cluster = Clusters.Objects.OccupancySensing - return await self.read_single_attribute_check_success(endpoint=endpoint, cluster=cluster, attribute=attribute) - - def desc_TC_OCC_2_3(self) -> str: - return "[TC-OCC-2.3] HoldTime Backward Compatibility Test with server as DUT" - - def steps_TC_OCC_2_3(self) -> list[TestStep]: - steps = [ - TestStep(1, "Commission DUT to TH", is_commissioning=True), - TestStep(2, "DUT supports HoldTime attribute. If DUT doesn’t support it, then stop and exit this test case."), - TestStep(3, "Based on the feature flag value table, read OccupancySensorType attribute from DUT"), - TestStep(4, "If TH reads 0 - PIR, TH reads PIROccupiedToUnoccupiedDelay attribute and its value should be same as HoldTime"), - TestStep(5, "If TH reads 1 - Ultrasonic, TH reads UltrasonicOccupiedToUnoccupiedDelay attribute and its value should be same as HoldTime"), - TestStep(6, "If TH reads 2 - PHY, TH reads PhysicalContactOccupiedToUnoccupiedDelay attribute and its value should be same as HoldTime") - ] - return steps - - def pics_TC_OCC_2_3(self) -> list[str]: - pics = [ - "OCC.S", - ] - return pics - - @async_test_body - async def test_TC_OCC_2_3(self): - - endpoint = self.user_params.get("endpoint", 1) - - self.step(1) - attributes = Clusters.OccupancySensing.Attributes - attribute_list = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.AttributeList) - - self.step(2) - if attributes.HoldTime.attribute_id in attribute_list: - occupancy_hold_time_dut = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.HoldTime) - else: - logging.info("No HoldTime attribute supports. Terminate this test case") - - self.step(3) - if attributes.OccupancySensorType.attribute_id in attribute_list: - occupancy_sensor_type_dut = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.OccupancySensorType) - - asserts.assert_less_equal(occupancy_sensor_type_dut, 3, "OccupancySensorType attribute is out of range") - asserts.assert_greater_equal(occupancy_sensor_type_dut, 0, "OccupancySensorType attribute is out of range") - else: - logging.info("OccupancySensorType attribute doesn't exist. Test step skipped") - - if occupancy_sensor_type_dut == Clusters.OccupancySensing.Enums.OccupancySensorTypeEnum.kPir: - self.step(4) - occupancy_pir_otou_delay_dut = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.PIROccupiedToUnoccupiedDelay) - - asserts.assert_equal(occupancy_pir_otou_delay_dut, occupancy_hold_time_dut, - "HoldTime attribute value is not equal to PIROccupiedToUnoccupiedDelay") - self.skip_step(5) - self.skip_step(6) - - elif occupancy_sensor_type_dut == Clusters.OccupancySensing.Enums.OccupancySensorTypeEnum.kUltrasonic: - self.step(4) - occupancy_pir_otou_delay_dut = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.PIROccupiedToUnoccupiedDelay) - - asserts.assert_equal(occupancy_pir_otou_delay_dut, occupancy_hold_time_dut, - "HoldTime attribute value is not equal to PIROccupiedToUnoccupiedDelay") - self.step(5) - occupancy_us_otou_delay_dut = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.UltrasonicOccupiedToUnoccupiedDelay) - - asserts.assert_equal(occupancy_us_otou_delay_dut, occupancy_hold_time_dut, - "HoldTime attribute value is not equal to UltrasonicOccupiedToUnoccupiedDelay") - self.skip_step(6) - - elif occupancy_sensor_type_dut == Clusters.OccupancySensing.Enums.OccupancySensorTypeEnum.kPIRAndUltrasonic: - occupancy_pirus_otou_delay_dut = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.PIROccupiedToUnoccupiedDelay) - - asserts.assert_equal(occupancy_pirus_otou_delay_dut, occupancy_hold_time_dut, - "HoldTime attribute value is not equal to PIROccupiedToUnoccupiedDelay") - - elif occupancy_sensor_type_dut == Clusters.OccupancySensing.Enums.OccupancySensorTypeEnum.kPhysicalContact: - self.skip_step(4) - self.skip_step(5) - self.step(6) - occupancy_phy_otou_delay_dut = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.PhysicalContactOccupiedToUnoccupiedDelay) - - asserts.assert_equal(occupancy_phy_otou_delay_dut, occupancy_hold_time_dut, - "HoldTime attribute value is not equal to PhysicalContactOccupiedToUnoccupiedDelay") - else: - logging.info("OccupancySensorType attribute value is out of range") - - -if __name__ == "__main__": - default_matter_test_main() +# +# 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. +# + +# See https://github.com/project-chip/connectedhomeip/blob/master/docs/testing/python.md#defining-the-ci-test-arguments +# for details about the block below. +# +# === BEGIN CI TEST ARGUMENTS === +# test-runner-runs: run1 +# test-runner-run/run1/app: ${ALL_CLUSTERS_APP} +# test-runner-run/run1/factoryreset: True +# test-runner-run/run1/quiet: True +# test-runner-run/run1/app-args: --discriminator 1234 --KVS kvs1 --trace-to json:${TRACE_APP}.json +# test-runner-run/run1/script-args: --storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --PICS src/app/tests/suites/certification/ci-pics-values --trace-to json:${TRACE_TEST_JSON}.json --trace-to perfetto:${TRACE_TEST_PERFETTO}.perfetto --endpoint 1 +# === END CI TEST ARGUMENTS === + +import logging + +import chip.clusters as Clusters +from matter_testing_support import MatterBaseTest, TestStep, async_test_body, default_matter_test_main +from mobly import asserts + + +class TC_OCC_2_3(MatterBaseTest): + async def read_occ_attribute_expect_success(self, endpoint, attribute): + cluster = Clusters.Objects.OccupancySensing + return await self.read_single_attribute_check_success(endpoint=endpoint, cluster=cluster, attribute=attribute) + + def desc_TC_OCC_2_3(self) -> str: + return "[TC-OCC-2.3] HoldTime Backward Compatibility Test with server as DUT" + + def steps_TC_OCC_2_3(self) -> list[TestStep]: + steps = [ + TestStep(1, "Commission DUT to TH", is_commissioning=True), + TestStep(2, "DUT supports HoldTime attribute. If DUT doesn’t support it, then stop and exit this test case."), + TestStep(3, "Based on the feature flag value table, read OccupancySensorType attribute from DUT"), + TestStep(4, "If TH reads 0 - PIR, TH reads PIROccupiedToUnoccupiedDelay attribute and its value should be same as HoldTime"), + TestStep(5, "If TH reads 1 - Ultrasonic, TH reads UltrasonicOccupiedToUnoccupiedDelay attribute and its value should be same as HoldTime"), + TestStep(6, "If TH reads 2 - PHY, TH reads PhysicalContactOccupiedToUnoccupiedDelay attribute and its value should be same as HoldTime") + ] + return steps + + def pics_TC_OCC_2_3(self) -> list[str]: + pics = [ + "OCC.S", + ] + return pics + + @async_test_body + async def test_TC_OCC_2_3(self): + endpoint = self.matter_test_config.endpoint + + self.step(1) # Already done, immediately go to step 2 + + self.step(2) + + attributes = Clusters.OccupancySensing.Attributes + attribute_list = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.AttributeList) + + if attributes.HoldTime.attribute_id in attribute_list: + occupancy_hold_time_dut = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.HoldTime) + else: + logging.info("No HoldTime attribute supports. Terminate this test case") + + self.step(3) + if attributes.OccupancySensorType.attribute_id in attribute_list: + occupancy_sensor_type_dut = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.OccupancySensorType) + + asserts.assert_less_equal(occupancy_sensor_type_dut, 3, "OccupancySensorType attribute is out of range") + asserts.assert_greater_equal(occupancy_sensor_type_dut, 0, "OccupancySensorType attribute is out of range") + else: + logging.info("OccupancySensorType attribute doesn't exist. Test step skipped") + + if occupancy_sensor_type_dut == Clusters.OccupancySensing.Enums.OccupancySensorTypeEnum.kPir: + self.step(4) + occupancy_pir_otou_delay_dut = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.PIROccupiedToUnoccupiedDelay) + + asserts.assert_equal(occupancy_pir_otou_delay_dut, occupancy_hold_time_dut, + "HoldTime attribute value is not equal to PIROccupiedToUnoccupiedDelay") + self.skip_step(5) + self.skip_step(6) + + elif occupancy_sensor_type_dut == Clusters.OccupancySensing.Enums.OccupancySensorTypeEnum.kUltrasonic: + self.step(4) + occupancy_pir_otou_delay_dut = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.PIROccupiedToUnoccupiedDelay) + + asserts.assert_equal(occupancy_pir_otou_delay_dut, occupancy_hold_time_dut, + "HoldTime attribute value is not equal to PIROccupiedToUnoccupiedDelay") + self.step(5) + occupancy_us_otou_delay_dut = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.UltrasonicOccupiedToUnoccupiedDelay) + + asserts.assert_equal(occupancy_us_otou_delay_dut, occupancy_hold_time_dut, + "HoldTime attribute value is not equal to UltrasonicOccupiedToUnoccupiedDelay") + self.skip_step(6) + + elif occupancy_sensor_type_dut == Clusters.OccupancySensing.Enums.OccupancySensorTypeEnum.kPIRAndUltrasonic: + occupancy_pirus_otou_delay_dut = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.PIROccupiedToUnoccupiedDelay) + + asserts.assert_equal(occupancy_pirus_otou_delay_dut, occupancy_hold_time_dut, + "HoldTime attribute value is not equal to PIROccupiedToUnoccupiedDelay") + + elif occupancy_sensor_type_dut == Clusters.OccupancySensing.Enums.OccupancySensorTypeEnum.kPhysicalContact: + self.skip_step(4) + self.skip_step(5) + self.step(6) + occupancy_phy_otou_delay_dut = await self.read_occ_attribute_expect_success(endpoint=endpoint, attribute=attributes.PhysicalContactOccupiedToUnoccupiedDelay) + + asserts.assert_equal(occupancy_phy_otou_delay_dut, occupancy_hold_time_dut, + "HoldTime attribute value is not equal to PhysicalContactOccupiedToUnoccupiedDelay") + else: + logging.info("OccupancySensorType attribute value is out of range") + + +if __name__ == "__main__": + default_matter_test_main() diff --git a/src/python_testing/TC_OCC_3_1.py b/src/python_testing/TC_OCC_3_1.py index 3fd082a62b..246e3a13f2 100644 --- a/src/python_testing/TC_OCC_3_1.py +++ b/src/python_testing/TC_OCC_3_1.py @@ -1,134 +1,129 @@ -# -# 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. -# -# === BEGIN CI TEST ARGUMENTS === -# test-runner-runs: run1 -# test-runner-run/run1/app: ${ALL_CLUSTERS_APP} -# test-runner-run/run1/factoryreset: True -# test-runner-run/run1/quiet: True -# test-runner-run/run1/app-args: --discriminator 1234 --KVS kvs1 --trace-to json:${TRACE_APP}.json -# test-runner-run/run1/script-args: --storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --trace-to json:${TRACE_TEST_JSON}.json --trace-to perfetto:${TRACE_TEST_PERFETTO}.perfetto --endpoint 1 -# === END CI TEST ARGUMENTS === -# There are CI issues to be followed up for the test cases below that implements manually controlling sensor device for -# the occupancy state ON/OFF change. -# [TC-OCC-3.1] test procedure step 4 -# [TC-OCC-3.2] test precedure step 3c - -import logging -import time -from typing import Any, Optional - -import chip.clusters as Clusters -from chip.interaction_model import Status -from matter_testing_support import MatterBaseTest, TestStep, async_test_body, default_matter_test_main -from mobly import asserts - - -class TC_OCC_3_1(MatterBaseTest): - async def read_occ_attribute_expect_success(self, attribute): - cluster = Clusters.Objects.OccupancySensing - endpoint = self.matter_test_config.endpoint - return await self.read_single_attribute_check_success(endpoint=endpoint, cluster=cluster, attribute=attribute) - - async def write_hold_time(self, hold_time: Optional[Any]) -> Status: - dev_ctrl = self.default_controller - node_id = self.dut_node_id - endpoint = self.matter_test_config.endpoint - - cluster = Clusters.OccupancySensing - write_result = await dev_ctrl.WriteAttribute(node_id, [(endpoint, cluster.Attributes.HoldTime(hold_time))]) - return write_result[0].Status - - def desc_TC_OCC_3_1(self) -> str: - return "[TC-OCC-3.1] Primary functionality with server as DUT" - - def steps_TC_OCC_3_1(self) -> list[TestStep]: - steps = [ - TestStep(1, "Commission DUT to TH and obtain DUT attribute list.", is_commissioning=True), - TestStep(2, "Change DUT HoldTime attribute value to 10 seconds."), - TestStep(3, "Do not trigger DUT occupancy sensing for the period of HoldTime. TH reads Occupancy attribute from DUT."), - TestStep(4, "Trigger DUT occupancy sensing to change the occupancy state and start a timer."), - TestStep(5, "After 10 seconds, TH reads Occupancy attribute from DUT.") - ] - return steps - - def pics_TC_OCC_3_1(self) -> list[str]: - pics = [ - "OCC.S", - ] - return pics - - @async_test_body - async def test_TC_OCC_3_1(self): - hold_time = 10 # 10 seconds for occupancy state hold time - - self.step(1) # commissioning and getting cluster attribute list - cluster = Clusters.OccupancySensing - attributes = cluster.Attributes - attribute_list = await self.read_occ_attribute_expect_success(attribute=attributes.AttributeList) - - has_hold_time = attributes.HoldTime.attribute_id in attribute_list - - self.step(2) - if has_hold_time: - # write 10 as a HoldTime attribute - await self.write_single_attribute(cluster.Attributes.HoldTime(hold_time)) - else: - logging.info("No HoldTime attribute supports. Will test only occupancy attribute triggering functionality") - - self.step(3) - # check if Occupancy attribute is 0 - occupancy_dut = await self.read_occ_attribute_expect_success(attribute=attributes.Occupancy) - - # if occupancy is on, then wait until the sensor occupancy state is 0. - if occupancy_dut == 1: - # Don't trigger occupancy sensor to render occupancy attribute to 0 - if has_hold_time: - time.sleep(hold_time + 2.0) # add some extra 2 seconds to ensure hold time has passed. - else: # a user wait until a sensor specific time to change occupancy attribute to 0. This is the case where the sensor doesn't support HoldTime. - self.wait_for_user_input( - prompt_msg="Type any letter and press ENTER after the sensor occupancy is detection ready state (occupancy attribute = 0)") - - # check sensor occupancy state is 0 for the next test step - occupancy_dut = await self.read_occ_attribute_expect_success(attribute=attributes.Occupancy) - asserts.assert_equal(occupancy_dut, 0, "Occupancy attribute is still 1.") - - self.step(4) - # Trigger occupancy sensor to change Occupancy attribute value to 1 => TESTER ACTION on DUT - self.wait_for_user_input(prompt_msg="Type any letter and press ENTER after a sensor occupancy is triggered.") - - # And then check if Occupancy attribute has changed. - occupancy_dut = await self.read_occ_attribute_expect_success(attribute=attributes.Occupancy) - asserts.assert_equal(occupancy_dut, 1, "Occupancy state is not changed to 1") - - self.step(5) - # check if Occupancy attribute is back to 0 after HoldTime attribute period - # Tester should not be triggering the sensor for this test step. - if has_hold_time: - - # Start a timer based on HoldTime - time.sleep(hold_time + 2.0) # add some extra 2 seconds to ensure hold time has passed. - - occupancy_dut = await self.read_occ_attribute_expect_success(attribute=attributes.Occupancy) - asserts.assert_equal(occupancy_dut, 0, "Occupancy state is not 0 after HoldTime period") - - else: - logging.info("HoldTime attribute not supported. Skip this return to 0 timing test procedure.") - self.skip_step(5) - - -if __name__ == "__main__": - default_matter_test_main() +# +# 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. +# + +# There are CI issues to be followed up for the test cases below that implements manually controlling sensor device for +# the occupancy state ON/OFF change. +# [TC-OCC-3.1] test procedure step 4 +# [TC-OCC-3.2] test precedure step 3c + +import logging +import time +from typing import Any, Optional + +import chip.clusters as Clusters +from chip.interaction_model import Status +from matter_testing_support import MatterBaseTest, TestStep, async_test_body, default_matter_test_main +from mobly import asserts + + +class TC_OCC_3_1(MatterBaseTest): + async def read_occ_attribute_expect_success(self, attribute): + cluster = Clusters.Objects.OccupancySensing + endpoint = self.matter_test_config.endpoint + return await self.read_single_attribute_check_success(endpoint=endpoint, cluster=cluster, attribute=attribute) + + async def write_hold_time(self, hold_time: Optional[Any]) -> Status: + dev_ctrl = self.default_controller + node_id = self.dut_node_id + endpoint = self.matter_test_config.endpoint + + cluster = Clusters.OccupancySensing + write_result = await dev_ctrl.WriteAttribute(node_id, [(endpoint, cluster.Attributes.HoldTime(hold_time))]) + return write_result[0].Status + + def desc_TC_OCC_3_1(self) -> str: + return "[TC-OCC-3.1] Primary functionality with server as DUT" + + def steps_TC_OCC_3_1(self) -> list[TestStep]: + steps = [ + TestStep(1, "Commission DUT to TH and obtain DUT attribute list.", is_commissioning=True), + TestStep(2, "Change DUT HoldTime attribute value to 10 seconds."), + TestStep(3, "Do not trigger DUT occupancy sensing for the period of HoldTime. TH reads Occupancy attribute from DUT."), + TestStep(4, "Trigger DUT occupancy sensing to change the occupancy state and start a timer."), + TestStep(5, "After 10 seconds, TH reads Occupancy attribute from DUT.") + ] + return steps + + def pics_TC_OCC_3_1(self) -> list[str]: + pics = [ + "OCC.S", + ] + return pics + + @async_test_body + async def test_TC_OCC_3_1(self): + hold_time = 10 # 10 seconds for occupancy state hold time + + self.step(1) # Commissioning already done + + self.step(2) + + cluster = Clusters.OccupancySensing + attributes = cluster.Attributes + attribute_list = await self.read_occ_attribute_expect_success(attribute=attributes.AttributeList) + + has_hold_time = attributes.HoldTime.attribute_id in attribute_list + + if has_hold_time: + # write 10 as a HoldTime attribute + await self.write_single_attribute(cluster.Attributes.HoldTime(hold_time)) + else: + logging.info("No HoldTime attribute supports. Will test only occupancy attribute triggering functionality") + + self.step(3) + # check if Occupancy attribute is 0 + occupancy_dut = await self.read_occ_attribute_expect_success(attribute=attributes.Occupancy) + + # if occupancy is on, then wait until the sensor occupancy state is 0. + if occupancy_dut == 1: + # Don't trigger occupancy sensor to render occupancy attribute to 0 + if has_hold_time: + time.sleep(hold_time + 2.0) # add some extra 2 seconds to ensure hold time has passed. + else: # a user wait until a sensor specific time to change occupancy attribute to 0. This is the case where the sensor doesn't support HoldTime. + self.wait_for_user_input( + prompt_msg="Type any letter and press ENTER after the sensor occupancy is detection ready state (occupancy attribute = 0)") + + # check sensor occupancy state is 0 for the next test step + occupancy_dut = await self.read_occ_attribute_expect_success(attribute=attributes.Occupancy) + asserts.assert_equal(occupancy_dut, 0, "Occupancy attribute is still 1.") + + self.step(4) + # Trigger occupancy sensor to change Occupancy attribute value to 1 => TESTER ACTION on DUT + self.wait_for_user_input(prompt_msg="Type any letter and press ENTER after a sensor occupancy is triggered.") + + # And then check if Occupancy attribute has changed. + occupancy_dut = await self.read_occ_attribute_expect_success(attribute=attributes.Occupancy) + asserts.assert_equal(occupancy_dut, 1, "Occupancy state is not changed to 1") + + self.step(5) + # check if Occupancy attribute is back to 0 after HoldTime attribute period + # Tester should not be triggering the sensor for this test step. + if has_hold_time: + + # Start a timer based on HoldTime + time.sleep(hold_time + 2.0) # add some extra 2 seconds to ensure hold time has passed. + + occupancy_dut = await self.read_occ_attribute_expect_success(attribute=attributes.Occupancy) + asserts.assert_equal(occupancy_dut, 0, "Occupancy state is not 0 after HoldTime period") + + else: + logging.info("HoldTime attribute not supported. Skip this return to 0 timing test procedure.") + self.skip_step(5) + + +if __name__ == "__main__": + default_matter_test_main() diff --git a/src/python_testing/TC_OCC_3_2.py b/src/python_testing/TC_OCC_3_2.py index 7e811362e2..64a588b6eb 100644 --- a/src/python_testing/TC_OCC_3_2.py +++ b/src/python_testing/TC_OCC_3_2.py @@ -1,207 +1,204 @@ -# -# Copyright (c) 2024 Project CHIP (Matter) 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. -# -# See https://github.com/project-chip/connectedhomeip/blob/master/docs/testing/python.md#defining-the-ci-test-arguments -# for details about the block below. -# -# === BEGIN CI TEST ARGUMENTS === -# test-runner-runs: run1 -# test-runner-run/run1/app: ${ALL_CLUSTERS_APP} -# test-runner-run/run1/factoryreset: True -# test-runner-run/run1/quiet: True -# test-runner-run/run1/app-args: --discriminator 1234 --KVS kvs1 --trace-to json:${TRACE_APP}.json -# test-runner-run/run1/script-args: --storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --trace-to json:${TRACE_TEST_JSON}.json --trace-to perfetto:${TRACE_TEST_PERFETTO}.perfetto --endpoint 1 -# === END CI TEST ARGUMENTS === - -# TODO: There are CI issues to be followed up for the test cases below that implements manually controlling sensor device for -# the occupancy state ON/OFF change. -# [TC-OCC-3.1] test procedure step 4 -# [TC-OCC-3.2] test precedure step 3a, 3c - -import logging - -import chip.clusters as Clusters -from matter_testing_support import (ClusterAttributeChangeAccumulator, MatterBaseTest, TestStep, async_test_body, - await_sequence_of_reports, default_matter_test_main) -from mobly import asserts - - -class TC_OCC_3_2(MatterBaseTest): - async def read_occ_attribute_expect_success(self, attribute): - cluster = Clusters.Objects.OccupancySensing - endpoint_id = self.matter_test_config.endpoint - return await self.read_single_attribute_check_success(endpoint=endpoint_id, cluster=cluster, attribute=attribute) - - def desc_TC_OCC_3_2(self) -> str: - return "[TC-OCC-3.2] Subscription Report Verification with server as DUT" - - def steps_TC_OCC_3_2(self) -> list[TestStep]: - steps = [ - TestStep(1, "Commission DUT to TH if not already done", is_commissioning=True), - TestStep(2, "TH establishes a wildcard subscription to all attributes on Occupancy Sensing Cluster on the endpoint under test. Subscription min interval = 0 and max interval = 30 seconds."), - TestStep("3a", "Do not trigger DUT for occupancy state change."), - TestStep("3b", "TH reads DUT Occupancy attribute and saves the initial value as initial"), - TestStep("3c", "Trigger DUT to change the occupancy state."), - TestStep("3d", "TH awaits a ReportDataMessage containing an attribute report for DUT Occupancy attribute."), - TestStep("4a", "Check if DUT supports HoldTime attribute, If not supported, then stop and skip the rest of test cases."), - TestStep("4b", "TH reads DUT HoldTime attribute and saves the initial value as initial"), - TestStep("4c", "TH writes a different value to DUT HoldTime attribute."), - TestStep("4d", "TH awaits a ReportDataMessage containing an attribute report for DUT HoldTime attribute."), - TestStep("5a", "Check if DUT supports DUT feature flag PIR or OTHER, If not supported, then stop and skip to 6a."), - TestStep("5b", "TH reads DUT PIROccupiedToUnoccupiedDelay attribute and saves the initial value as initial"), - TestStep("5c", "TH writes a different value to DUT PIROccupiedToUnoccupiedDelay attribute."), - TestStep("5d", "TH awaits a ReportDataMessage containing an attribute report for DUT PIROccupiedToUnoccupiedDelay attribute."), - TestStep("6a", "Check if DUT supports DUT feature flag US, If not supported, then stop and skip to 7a."), - TestStep("6b", "TH reads DUT UltrasonicOccupiedToUnoccupiedDelay attribute and saves the initial value as initial"), - TestStep("6c", "TH writes a different value to DUT UltrasonicOccupiedToUnoccupiedDelay attribute."), - TestStep("6d", "TH awaits a ReportDataMessage containing an attribute report for DUT UltrasonicOccupiedToUnoccupiedDelay attribute."), - TestStep("7a", "Check if DUT supports DUT feature flag PHY, If not supported, terminate this test case."), - TestStep("7b", "TH reads DUT PhysicalContactOccupiedToUnoccupiedDelay attribute and saves the initial value as initial"), - TestStep("7c", "TH writes a different value to DUT PhysicalContactOccupiedToUnoccupiedDelay attribute."), - TestStep("7d", "TH awaits a ReportDataMessage containing an attribute report for DUT PhysicalContactOccupiedToUnoccupiedDelay attribute.") - ] - return steps - - def pics_TC_OCC_3_2(self) -> list[str]: - pics = [ - "OCC.S", - ] - return pics - - @async_test_body - async def test_TC_OCC_3_2(self): - endpoint_id = self.matter_test_config.endpoint - node_id = self.dut_node_id - dev_ctrl = self.default_controller - - post_prompt_settle_delay_seconds = 10.0 - cluster = Clusters.Objects.OccupancySensing - attributes = cluster.Attributes - - self.step(1) - - occupancy_sensor_type_bitmap_dut = await self.read_occ_attribute_expect_success(attribute=attributes.OccupancySensorTypeBitmap) - has_type_pir = ((occupancy_sensor_type_bitmap_dut & cluster.Enums.OccupancySensorTypeEnum.kPir) != 0) or \ - ((occupancy_sensor_type_bitmap_dut & cluster.Enums.OccupancySensorTypeEnum.kPIRAndUltrasonic) != 0) - has_type_ultrasonic = ((occupancy_sensor_type_bitmap_dut & cluster.Enums.OccupancySensorTypeEnum.kUltrasonic) != 0) or \ - ((occupancy_sensor_type_bitmap_dut & cluster.Enums.OccupancySensorTypeEnum.kPIRAndUltrasonic) != 0) - has_type_contact = (occupancy_sensor_type_bitmap_dut & cluster.Enums.OccupancySensorTypeEnum.kPhysicalContact) != 0 - - attribute_list = await self.read_occ_attribute_expect_success(attribute=attributes.AttributeList) - has_pir_timing_attrib = attributes.PIROccupiedToUnoccupiedDelay.attribute_id in attribute_list - has_ultrasonic_timing_attrib = attributes.UltrasonicOccupiedToUnoccupiedDelay.attribute_id in attribute_list - has_contact_timing_attrib = attributes.PhysicalContactOccupiedToUnoccupiedDelay.attribute_id in attribute_list - - self.step(2) - # min interval = 0, and max interval = 30 seconds - attrib_listener = ClusterAttributeChangeAccumulator(Clusters.Objects.OccupancySensing) - await attrib_listener.start(dev_ctrl, node_id, endpoint=endpoint_id, min_interval_sec=0, max_interval_sec=30) - - # TODO - Will add Namepiped to assimilate the manual sensor untrigger here - self.step("3a") - self.wait_for_user_input(prompt_msg="Type any letter and press ENTER after DUT goes back to unoccupied state.") - - self.step("3b") - if attributes.Occupancy.attribute_id in attribute_list: - initial_dut = await self.read_occ_attribute_expect_success(attribute=attributes.Occupancy) - asserts.assert_equal(initial_dut, 0, "Occupancy attribute is still detected state") - - # TODO - Will add Namepiped to assimilate the manual sensor trigger here - self.step("3c") - self.wait_for_user_input( - prompt_msg="Type any letter and press ENTER after the sensor occupancy is triggered and its occupancy state changed.") - - self.step("3d") - await_sequence_of_reports(report_queue=attrib_listener.attribute_queue, endpoint_id=endpoint_id, attribute=cluster.Attributes.Occupancy, sequence=[ - 0, 1], timeout_sec=post_prompt_settle_delay_seconds) - - self.step("4a") - if attributes.HoldTime.attribute_id not in attribute_list: - logging.info("No HoldTime attribute supports. Terminate this test case") - self.skip_all_remaining_steps("4b") - - self.step("4b") - initial_dut = await self.read_occ_attribute_expect_success(attribute=attributes.HoldTime) - - self.step("4c") - # write a different a HoldTime attribute value - diff_val = 12 - await self.write_single_attribute(attributes.HoldTime(diff_val)) - - self.step("4d") - await_sequence_of_reports(report_queue=attrib_listener.attribute_queue, endpoint_id=endpoint_id, attribute=cluster.Attributes.HoldTime, sequence=[ - initial_dut, diff_val], timeout_sec=post_prompt_settle_delay_seconds) - - self.step("5a") - if not has_type_pir or not has_pir_timing_attrib: - logging.info("No PIR timing attribute support. Skip this steps 5b, 5c, 5d") - self.skip_step("5b") - self.skip_step("5c") - self.skip_step("5d") - else: - self.step("5b") - initial_dut = await self.read_occ_attribute_expect_success(attribute=attributes.PIROccupiedToUnoccupiedDelay) - - self.step("5c") - # write the new attribute value - diff_val = 11 - await self.write_single_attribute(attributes.PIROccupiedToUnoccupiedDelay(diff_val)) - - self.step("5d") - await_sequence_of_reports(report_queue=attrib_listener.attribute_queue, endpoint_id=endpoint_id, attribute=cluster.Attributes.PIROccupiedToUnoccupiedDelay, sequence=[ - initial_dut, diff_val], timeout_sec=post_prompt_settle_delay_seconds) - - self.step("6a") - if not has_type_ultrasonic or not has_ultrasonic_timing_attrib: - logging.info("No Ultrasonic timing attribute supports. Skip steps 6b, 6c, 6d") - self.skip_step("6b") - self.skip_step("6c") - self.skip_step("6d") - else: - self.step("6b") - initial_dut = await self.read_occ_attribute_expect_success(attribute=attributes.UltrasonicOccupiedToUnoccupiedDelay) - - self.step("6c") - # write the new attribute value - diff_val = 14 - await self.write_single_attribute(attributes.UltrasonicOccupiedToUnoccupiedDelay(diff_val)) - - self.step("6d") - await_sequence_of_reports(report_queue=attrib_listener.attribute_queue, endpoint_id=endpoint_id, attribute=cluster.Attributes.UltrasonicOccupiedToUnoccupiedDelay, sequence=[ - initial_dut, diff_val], timeout_sec=post_prompt_settle_delay_seconds) - - self.step("7a") - if not has_type_contact or not has_contact_timing_attrib: - logging.info("No Physical contact timing attribute supports. Skip this test case") - self.skip_step("7b") - self.skip_step("7c") - self.skip_step("7d") - else: - self.step("7b") - initial_dut = await self.read_occ_attribute_expect_success(attribute=attributes.PhysicalContactOccupiedToUnoccupiedDelay) - - self.step("7c") - # write the new attribute value - diff_val = 9 - await self.write_single_attribute(attributes.PhysicalContactOccupiedToUnoccupiedDelay(diff_val)) - - self.step("7d") - await_sequence_of_reports(report_queue=attrib_listener.attribute_queue, endpoint_id=endpoint_id, attribute=cluster.Attributes.PhysicalContactOccupiedToUnoccupiedDelay, sequence=[ - initial_dut, diff_val], timeout_sec=post_prompt_settle_delay_seconds) - - -if __name__ == "__main__": - default_matter_test_main() +# +# Copyright (c) 2024 Project CHIP (Matter) 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. +# + +# TODO: There are CI issues to be followed up for the test cases below that implements manually controlling sensor device for +# the occupancy state ON/OFF change. +# [TC-OCC-3.1] test procedure step 4 +# [TC-OCC-3.2] test precedure step 3a, 3c + +import logging + +import chip.clusters as Clusters +from matter_testing_support import (ClusterAttributeChangeAccumulator, MatterBaseTest, TestStep, async_test_body, + await_sequence_of_reports, default_matter_test_main) +from mobly import asserts + + +class TC_OCC_3_2(MatterBaseTest): + async def read_occ_attribute_expect_success(self, attribute): + cluster = Clusters.Objects.OccupancySensing + endpoint_id = self.matter_test_config.endpoint + return await self.read_single_attribute_check_success(endpoint=endpoint_id, cluster=cluster, attribute=attribute) + + def desc_TC_OCC_3_2(self) -> str: + return "[TC-OCC-3.2] Subscription Report Verification with server as DUT" + + def steps_TC_OCC_3_2(self) -> list[TestStep]: + steps = [ + TestStep(1, "Commission DUT to TH if not already done", is_commissioning=True), + TestStep(2, "TH establishes a wildcard subscription to all attributes on Occupancy Sensing Cluster on the endpoint under test. Subscription min interval = 0 and max interval = 30 seconds."), + TestStep("3a", "Do not trigger DUT for occupancy state change."), + TestStep("3b", "TH reads DUT Occupancy attribute and saves the initial value as initial"), + TestStep("3c", "Trigger DUT to change the occupancy state."), + TestStep("3d", "TH awaits a ReportDataMessage containing an attribute report for DUT Occupancy attribute."), + TestStep("4a", "Check if DUT supports HoldTime attribute, If not supported, then stop and skip the rest of test cases."), + TestStep("4b", "TH reads DUT HoldTime attribute and saves the initial value as initial"), + TestStep("4c", "TH writes a different value to DUT HoldTime attribute."), + TestStep("4d", "TH awaits a ReportDataMessage containing an attribute report for DUT HoldTime attribute."), + TestStep("5a", "Check if DUT supports DUT feature flag PIR or (!PIR & !US & !PHY) and has the PIROccupiedToUnoccupiedDelay attribute, If not supported, then skip 5b, 5c, 5d."), + TestStep("5b", "TH reads DUT PIROccupiedToUnoccupiedDelay attribute and saves the initial value as initial"), + TestStep("5c", "TH writes a different value to DUT PIROccupiedToUnoccupiedDelay attribute."), + TestStep("5d", "TH awaits a ReportDataMessage containing an attribute report for DUT PIROccupiedToUnoccupiedDelay attribute."), + TestStep("6a", "Check if DUT supports DUT feature flag US and has the UltrasonicOccupiedToUnoccupiedDelay attribute. If not supported, then skip 6b, 6c, 6d."), + TestStep("6b", "TH reads DUT UltrasonicOccupiedToUnoccupiedDelay attribute and saves the initial value as initial"), + TestStep("6c", "TH writes a different value to DUT UltrasonicOccupiedToUnoccupiedDelay attribute."), + TestStep("6d", "TH awaits a ReportDataMessage containing an attribute report for DUT UltrasonicOccupiedToUnoccupiedDelay attribute."), + TestStep("7a", "Check if DUT supports DUT feature flag PHY and has the PhysicalContactOccupiedToUnoccupiedDelay attribute. If not supported, skip 7b, 7c, 7d."), + TestStep("7b", "TH reads DUT PhysicalContactOccupiedToUnoccupiedDelay attribute and saves the initial value as initial"), + TestStep("7c", "TH writes a different value to DUT PhysicalContactOccupiedToUnoccupiedDelay attribute."), + TestStep("7d", "TH awaits a ReportDataMessage containing an attribute report for DUT PhysicalContactOccupiedToUnoccupiedDelay attribute.") + ] + return steps + + def pics_TC_OCC_3_2(self) -> list[str]: + pics = [ + "OCC.S", + ] + return pics + + @async_test_body + async def test_TC_OCC_3_2(self): + endpoint_id = self.matter_test_config.endpoint + node_id = self.dut_node_id + dev_ctrl = self.default_controller + + post_prompt_settle_delay_seconds = 10.0 + cluster = Clusters.Objects.OccupancySensing + attributes = cluster.Attributes + + self.step(1) # Commissioning already done + + self.step(2) + feature_map = await self.read_occ_attribute_expect_success(attribute=attributes.FeatureMap) + has_feature_pir = (feature_map & cluster.Bitmaps.Feature.kPassiveInfrared) != 0 + has_feature_ultrasonic = (feature_map & cluster.Bitmaps.Feature.kUltrasonic) != 0 + has_feature_contact = (feature_map & cluster.Bitmaps.Feature.kPhysicalContact) != 0 + + logging.info( + f"Feature map: 0x{feature_map:x}. PIR: {has_feature_pir}, US:{has_feature_ultrasonic}, PHY:{has_feature_contact}") + + attribute_list = await self.read_occ_attribute_expect_success(attribute=attributes.AttributeList) + has_pir_timing_attrib = attributes.PIROccupiedToUnoccupiedDelay.attribute_id in attribute_list + has_ultrasonic_timing_attrib = attributes.UltrasonicOccupiedToUnoccupiedDelay.attribute_id in attribute_list + has_contact_timing_attrib = attributes.PhysicalContactOccupiedToUnoccupiedDelay.attribute_id in attribute_list + logging.info(f"Attribute list: {attribute_list}") + logging.info(f"--> Has PIROccupiedToUnoccupiedDelay: {has_pir_timing_attrib}") + logging.info(f"--> Has UltrasonicOccupiedToUnoccupiedDelay: {has_ultrasonic_timing_attrib}") + logging.info(f"--> Has PhysicalContactOccupiedToUnoccupiedDelay: {has_contact_timing_attrib}") + + # min interval = 0, and max interval = 30 seconds + attrib_listener = ClusterAttributeChangeAccumulator(Clusters.Objects.OccupancySensing) + await attrib_listener.start(dev_ctrl, node_id, endpoint=endpoint_id, min_interval_sec=0, max_interval_sec=30) + + # TODO - Will add Namepiped to assimilate the manual sensor untrigger here + self.step("3a") + self.wait_for_user_input(prompt_msg="Type any letter and press ENTER after DUT goes back to unoccupied state.") + + self.step("3b") + if attributes.Occupancy.attribute_id in attribute_list: + initial_dut = await self.read_occ_attribute_expect_success(attribute=attributes.Occupancy) + asserts.assert_equal(initial_dut, 0, "Occupancy attribute is still detected state") + + # TODO - Will add Namepiped to assimilate the manual sensor trigger here + self.step("3c") + self.wait_for_user_input( + prompt_msg="Type any letter and press ENTER after the sensor occupancy is triggered and its occupancy state changed.") + + self.step("3d") + await_sequence_of_reports(report_queue=attrib_listener.attribute_queue, endpoint_id=endpoint_id, attribute=cluster.Attributes.Occupancy, sequence=[ + 1], timeout_sec=post_prompt_settle_delay_seconds) + + self.step("4a") + if attributes.HoldTime.attribute_id not in attribute_list: + logging.info("No HoldTime attribute supports. Terminate this test case") + self.skip_all_remaining_steps("4b") + + self.step("4b") + initial_dut = await self.read_occ_attribute_expect_success(attribute=attributes.HoldTime) + + self.step("4c") + # write a different a HoldTime attribute value + diff_val = 12 + await self.write_single_attribute(attributes.HoldTime(diff_val)) + + self.step("4d") + await_sequence_of_reports(report_queue=attrib_listener.attribute_queue, endpoint_id=endpoint_id, attribute=cluster.Attributes.HoldTime, sequence=[ + diff_val], timeout_sec=post_prompt_settle_delay_seconds) + + self.step("5a") + + has_no_legacy_features = ((not has_feature_pir) and (not has_feature_ultrasonic) and (not has_feature_contact)) + + if has_pir_timing_attrib and (has_feature_pir or has_no_legacy_features): + self.step("5b") + initial_dut = await self.read_occ_attribute_expect_success(attribute=attributes.PIROccupiedToUnoccupiedDelay) + + self.step("5c") + # write the new attribute value + diff_val = 11 + await self.write_single_attribute(attributes.PIROccupiedToUnoccupiedDelay(diff_val)) + + self.step("5d") + await_sequence_of_reports(report_queue=attrib_listener.attribute_queue, endpoint_id=endpoint_id, attribute=cluster.Attributes.PIROccupiedToUnoccupiedDelay, sequence=[ + diff_val], timeout_sec=post_prompt_settle_delay_seconds) + else: + logging.info("No PIR timing attribute support. Skipping steps 5b, 5c, 5d") + self.skip_step("5b") + self.skip_step("5c") + self.skip_step("5d") + + self.step("6a") + if not has_feature_ultrasonic or not has_ultrasonic_timing_attrib: + logging.info("No Ultrasonic timing attribute supports. Skipping steps 6b, 6c, 6d") + self.skip_step("6b") + self.skip_step("6c") + self.skip_step("6d") + else: + self.step("6b") + initial_dut = await self.read_occ_attribute_expect_success(attribute=attributes.UltrasonicOccupiedToUnoccupiedDelay) + + self.step("6c") + # write the new attribute value + diff_val = 14 + await self.write_single_attribute(attributes.UltrasonicOccupiedToUnoccupiedDelay(diff_val)) + + self.step("6d") + await_sequence_of_reports(report_queue=attrib_listener.attribute_queue, endpoint_id=endpoint_id, attribute=cluster.Attributes.UltrasonicOccupiedToUnoccupiedDelay, sequence=[ + diff_val], timeout_sec=post_prompt_settle_delay_seconds) + + self.step("7a") + if not has_feature_contact or not has_contact_timing_attrib: + logging.info("No Physical contact timing attribute supports. Skipping steps 7b, 7c, 7d") + self.skip_step("7b") + self.skip_step("7c") + self.skip_step("7d") + else: + self.step("7b") + initial_dut = await self.read_occ_attribute_expect_success(attribute=attributes.PhysicalContactOccupiedToUnoccupiedDelay) + + self.step("7c") + # write the new attribute value + diff_val = 9 + await self.write_single_attribute(attributes.PhysicalContactOccupiedToUnoccupiedDelay(diff_val)) + + self.step("7d") + await_sequence_of_reports(report_queue=attrib_listener.attribute_queue, endpoint_id=endpoint_id, attribute=cluster.Attributes.PhysicalContactOccupiedToUnoccupiedDelay, sequence=[ + diff_val], timeout_sec=post_prompt_settle_delay_seconds) + + +if __name__ == "__main__": + default_matter_test_main() diff --git a/src/python_testing/matter_testing_support.py b/src/python_testing/matter_testing_support.py index eb8a6ba20d..d3d810149c 100644 --- a/src/python_testing/matter_testing_support.py +++ b/src/python_testing/matter_testing_support.py @@ -334,6 +334,15 @@ def wait_for_report(self): asserts.fail(f"[AttributeChangeCallback] Attribute {self._expected_attribute} not found in returned report") +def clear_queue(report_queue: queue.Queue): + """Flush all contents of a report queue. Useful to get back to empty point.""" + while not report_queue.empty(): + try: + report_queue.get(block=False) + except queue.Empty: + break + + def await_sequence_of_reports(report_queue: queue.Queue, endpoint_id: int, attribute: TypedAttributePath, sequence: list[Any], timeout_sec: float): """Given a queue.Queue hooked-up to an attribute change accumulator, await a given expected sequence of attribute reports. @@ -344,6 +353,9 @@ def await_sequence_of_reports(report_queue: queue.Queue, endpoint_id: int, attri - sequence: list of attribute values in order that are expected. - timeout_sec: number of seconds to wait for. + *** WARNING: The queue contains every report since the sub was established. Use + clear_queue to make it empty. *** + This will fail current Mobly test with assertion failure if the data is not as expected in order. Returns nothing on success so the test can go on. @@ -446,6 +458,20 @@ def attribute_report_counts(self) -> dict[ClusterObjects.ClusterAttributeDescrip def attribute_reports(self) -> dict[ClusterObjects.ClusterAttributeDescriptor, AttributeValue]: return self._attribute_reports + def get_last_report(self) -> Optional[Any]: + """Flush entire queue, returning last (newest) report only.""" + last_report: Optional[Any] = None + while True: + try: + last_report = self._q.get(block=False) + except queue.Empty: + return last_report + + def flush_reports(self) -> None: + """Flush entire queue, returning nothing.""" + _ = self.get_last_report() + return + class InternalTestRunnerHooks(TestRunnerHooks): From 010d9821daceb60e601c5174986cb648e62705d1 Mon Sep 17 00:00:00 2001 From: William Date: Fri, 23 Aug 2024 07:46:55 +0100 Subject: [PATCH 151/165] Remove DuplicatedAreas error (#35126) * Removed the DuplicatedAreas error from the XML * Generated code after XML update. * The service are server ignores any duplicate values before calling the delegate. Example was updated accodingly. * Updated test SEAR-1.3 following changes to the duplicated areas error. * Restyled by clang-format * Made select areas const. --------- Co-authored-by: Restyled.io --- .../include/rvc-service-area-delegate.h | 4 +- examples/rvc-app/rvc-common/rvc-app.matter | 5 +- .../src/rvc-service-area-delegate.cpp | 63 +++++------- .../service-area-delegate.h | 6 +- .../service-area-server.cpp | 99 ++++++++++--------- .../data-model/chip/service-area-cluster.xml | 5 +- .../data_model/controller-clusters.matter | 5 +- .../python/chip/clusters/Objects.py | 7 +- .../CHIP/zap-generated/MTRBaseClusters.h | 5 +- src/python_testing/TC_SEAR_1_3.py | 26 ++--- .../zap-generated/cluster-enums-check.h | 1 - .../app-common/zap-generated/cluster-enums.h | 7 +- 12 files changed, 108 insertions(+), 125 deletions(-) diff --git a/examples/rvc-app/rvc-common/include/rvc-service-area-delegate.h b/examples/rvc-app/rvc-common/include/rvc-service-area-delegate.h index c6be8aa5bb..a87d345cb5 100644 --- a/examples/rvc-app/rvc-common/include/rvc-service-area-delegate.h +++ b/examples/rvc-app/rvc-common/include/rvc-service-area-delegate.h @@ -79,8 +79,8 @@ class RvcServiceAreaDelegate : public Delegate // command support bool IsSetSelectedAreasAllowed(MutableCharSpan & statusText) override; - bool IsValidSelectAreasSet(const ServiceArea::Commands::SelectAreas::DecodableType & req, - ServiceArea::SelectAreasStatus & areaStatus, MutableCharSpan & statusText) override; + bool IsValidSelectAreasSet(const Span & selectedAreas, ServiceArea::SelectAreasStatus & areaStatus, + MutableCharSpan & statusText) override; bool HandleSkipArea(uint32_t skippedArea, MutableCharSpan & skipStatusText) override; diff --git a/examples/rvc-app/rvc-common/rvc-app.matter b/examples/rvc-app/rvc-common/rvc-app.matter index 29460e1f43..ee4d751919 100644 --- a/examples/rvc-app/rvc-common/rvc-app.matter +++ b/examples/rvc-app/rvc-common/rvc-app.matter @@ -1438,9 +1438,8 @@ provisional cluster ServiceArea = 336 { enum SelectAreasStatus : enum8 { kSuccess = 0; kUnsupportedArea = 1; - kDuplicatedAreas = 2; - kInvalidInMode = 3; - kInvalidSet = 4; + kInvalidInMode = 2; + kInvalidSet = 3; } enum SkipAreaStatus : enum8 { diff --git a/examples/rvc-app/rvc-common/src/rvc-service-area-delegate.cpp b/examples/rvc-app/rvc-common/src/rvc-service-area-delegate.cpp index 9041efd3d9..2f2594e17d 100644 --- a/examples/rvc-app/rvc-common/src/rvc-service-area-delegate.cpp +++ b/examples/rvc-app/rvc-common/src/rvc-service-area-delegate.cpp @@ -113,23 +113,12 @@ bool RvcServiceAreaDelegate::IsSetSelectedAreasAllowed(MutableCharSpan & statusT return (mIsSetSelectedAreasAllowedDeviceInstance->*mIsSetSelectedAreasAllowedCallback)(statusText); }; -bool RvcServiceAreaDelegate::IsValidSelectAreasSet(const Commands::SelectAreas::DecodableType & req, SelectAreasStatus & areaStatus, +bool RvcServiceAreaDelegate::IsValidSelectAreasSet(const Span & selectedAreas, SelectAreasStatus & areaStatus, MutableCharSpan & statusText) { - // if req is empty list return true. + if (selectedAreas.empty()) { - size_t reqSize; - if (req.newAreas.ComputeSize(&reqSize) != CHIP_NO_ERROR) - { - areaStatus = SelectAreasStatus::kInvalidSet; // todo Not sure this is the correct error to use here - CopyCharSpanToMutableCharSpan("error computing number of selected areas"_span, statusText); - return false; - } - - if (reqSize == 0) - { - return true; - } + return true; } // If there is 1 or 0 supported maps, any combination of areas is valid. @@ -139,42 +128,34 @@ bool RvcServiceAreaDelegate::IsValidSelectAreasSet(const Commands::SelectAreas:: } // Check that all the requested areas are in the same map. - auto newAreasIter = req.newAreas.begin(); - newAreasIter.Next(); - - AreaStructureWrapper tempArea; - uint32_t ignoredIndex; - if (!GetSupportedAreaById(newAreasIter.GetValue(), ignoredIndex, tempArea)) { - areaStatus = SelectAreasStatus::kUnsupportedArea; - CopyCharSpanToMutableCharSpan("unable to find selected area in supported areas"_span, statusText); - return false; - } - - auto mapId = tempArea.mapID.Value(); // It is safe to call `.Value()` as we confirmed that there are at least 2 maps. - - while (newAreasIter.Next()) - { - if (!GetSupportedAreaById(newAreasIter.GetValue(), ignoredIndex, tempArea)) + AreaStructureWrapper tempArea; + uint32_t ignoredIndex; + if (!GetSupportedAreaById(selectedAreas[0], ignoredIndex, tempArea)) { areaStatus = SelectAreasStatus::kUnsupportedArea; CopyCharSpanToMutableCharSpan("unable to find selected area in supported areas"_span, statusText); return false; } - if (tempArea.mapID.Value() != mapId) + auto mapId = tempArea.mapID.Value(); // It is safe to call `.Value()` as we confirmed that there are at least 2 maps. + + for (const auto & areaId : selectedAreas.SubSpan(1)) { - areaStatus = SelectAreasStatus::kInvalidSet; - CopyCharSpanToMutableCharSpan("all selected areas must be in the same map"_span, statusText); - return false; - } - } + if (!GetSupportedAreaById(areaId, ignoredIndex, tempArea)) + { + areaStatus = SelectAreasStatus::kUnsupportedArea; + CopyCharSpanToMutableCharSpan("unable to find selected area in supported areas"_span, statusText); + return false; + } - if (CHIP_NO_ERROR != newAreasIter.GetStatus()) - { - areaStatus = SelectAreasStatus::kInvalidSet; - CopyCharSpanToMutableCharSpan("error processing new areas."_span, statusText); - return false; + if (tempArea.mapID.Value() != mapId) + { + areaStatus = SelectAreasStatus::kInvalidSet; + CopyCharSpanToMutableCharSpan("all selected areas must be in the same map"_span, statusText); + return false; + } + } } return true; diff --git a/src/app/clusters/service-area-server/service-area-delegate.h b/src/app/clusters/service-area-server/service-area-delegate.h index 2e9422840a..7fe40bb8fe 100644 --- a/src/app/clusters/service-area-server/service-area-delegate.h +++ b/src/app/clusters/service-area-server/service-area-delegate.h @@ -80,10 +80,10 @@ class Delegate * If the set of locations is invalid, the locationStatus should be set to InvalidSet and * the statusText SHALL include a vendor-defined error description. * - * The caller of this method will ensure that there are no duplicates is the list + * The caller of this method will ensure that there are no duplicates in the list * and that all the locations in the set are valid supported locations. * - * @param[in] req List of new selected locations. + * @param[in] selectedAreas List of new selected locations. * @param[out] locationStatus Success if all checks pass, error code if failure. * @param[out] statusText text describing failure (see description above), size kMaxSizeStatusText. * @return true if success. @@ -91,7 +91,7 @@ class Delegate * @note If the SelectAreas command is allowed when the device is operating and the selected locations change to none, the * device must stop. */ - virtual bool IsValidSelectAreasSet(const Commands::SelectAreas::DecodableType & req, SelectAreasStatus & locationStatus, + virtual bool IsValidSelectAreasSet(const Span & selectedAreas, SelectAreasStatus & locationStatus, MutableCharSpan & statusText) = 0; /** diff --git a/src/app/clusters/service-area-server/service-area-server.cpp b/src/app/clusters/service-area-server/service-area-server.cpp index 2f2efceddd..4de8f942e0 100644 --- a/src/app/clusters/service-area-server/service-area-server.cpp +++ b/src/app/clusters/service-area-server/service-area-server.cpp @@ -240,64 +240,72 @@ void Instance::HandleSelectAreasCmd(HandlerContext & ctx, const Commands::Select } } + uint32_t selectedAreasBuffer[kMaxNumSelectedAreas]; + auto selectedAreasSpan = Span(selectedAreasBuffer, kMaxNumSelectedAreas); + uint32_t numberOfSelectedAreas = 0; + + // Closure for checking if an area ID exists in the selectedAreasSpan + auto areaAlreadyExists = [&numberOfSelectedAreas, &selectedAreasSpan](uint32_t areaId) { + for (uint32_t i = 0; i < numberOfSelectedAreas; i++) + { + if (areaId == selectedAreasSpan[i]) + { + return true; + } + } + return false; + }; + // if number of selected locations in parameter matches number in attribute - the locations *might* be the same bool matchesCurrentSelectedAreas = (numberOfAreas == mDelegate->GetNumberOfSelectedAreas()); + // do as much parameter validation as we can if (numberOfAreas != 0) { - // do as much parameter validation as we can + uint32_t ignoredIndex = 0; + uint32_t oldSelectedArea; + auto iAreaIter = req.newAreas.begin(); + while (iAreaIter.Next()) { - uint32_t ignoredIndex = 0; - uint32_t oldSelectedArea; - uint32_t i = 0; - auto iAreaIter = req.newAreas.begin(); - while (iAreaIter.Next()) - { - uint32_t aSelectedArea = iAreaIter.GetValue(); + uint32_t selectedArea = iAreaIter.GetValue(); - // each item in this list SHALL match the AreaID field of an entry on the SupportedAreas attribute's list - // If the Status field is set to UnsupportedArea, the StatusText field SHALL be an empty string. - if (!IsSupportedArea(aSelectedArea)) - { - exitResponse(SelectAreasStatus::kUnsupportedArea, ""_span); - return; - } + // If aSelectedArea is already in selectedAreasSpan skip + if (areaAlreadyExists(selectedArea)) + { + continue; + } - // Checking for duplicate locations. - uint32_t j = 0; - auto jAreaIter = req.newAreas.begin(); - while (j < i) - { - jAreaIter.Next(); // Since j < i and i is valid, we can safely call Next() without checking the return value. - if (jAreaIter.GetValue() == aSelectedArea) - { - exitResponse(SelectAreasStatus::kDuplicatedAreas, ""_span); - return; - } - j += 1; - } + // each item in this list SHALL match the AreaID field of an entry on the SupportedAreas attribute's list + // If the Status field is set to UnsupportedArea, the StatusText field SHALL be an empty string. + if (!IsSupportedArea(selectedArea)) + { + exitResponse(SelectAreasStatus::kUnsupportedArea, ""_span); + return; + } - // check to see if parameter list and attribute still match - if (matchesCurrentSelectedAreas) + // check to see if parameter list and attribute still match + if (matchesCurrentSelectedAreas) + { + if (!mDelegate->GetSelectedAreaByIndex(ignoredIndex, oldSelectedArea) || (selectedArea != oldSelectedArea)) { - if (!mDelegate->GetSelectedAreaByIndex(ignoredIndex, oldSelectedArea) || (aSelectedArea != oldSelectedArea)) - { - matchesCurrentSelectedAreas = false; - } + matchesCurrentSelectedAreas = false; } - - i += 1; } - // after iterating with Next through DecodableType - check for failure - if (CHIP_NO_ERROR != iAreaIter.GetStatus()) - { - ctx.mCommandHandler.AddStatus(ctx.mRequestPath, Status::InvalidCommand); - return; - } + selectedAreasSpan[numberOfSelectedAreas] = selectedArea; + numberOfSelectedAreas += 1; + } + + // after iterating with Next through DecodableType - check for failure + if (CHIP_NO_ERROR != iAreaIter.GetStatus()) + { + ctx.mCommandHandler.AddStatus(ctx.mRequestPath, Status::InvalidCommand); + return; } } + selectedAreasSpan.reduce_size(numberOfSelectedAreas); + // If the newAreas field is the same as the value of the SelectedAreas attribute // the SelectAreasResponse command SHALL have the Status field set to Success and // the StatusText field MAY be supplied with a human-readable string or include an empty string. @@ -327,7 +335,7 @@ void Instance::HandleSelectAreasCmd(HandlerContext & ctx, const Commands::Select // ask the device to handle SelectAreas Command // (note - locationStatusText to be filled out by delegated function for kInvalidInMode and InvalidSet) auto locationStatus = SelectAreasStatus::kSuccess; - if (!mDelegate->IsValidSelectAreasSet(req, locationStatus, delegateStatusText)) + if (!mDelegate->IsValidSelectAreasSet(selectedAreasSpan, locationStatus, delegateStatusText)) { exitResponse(locationStatus, delegateStatusText); return; @@ -342,11 +350,10 @@ void Instance::HandleSelectAreasCmd(HandlerContext & ctx, const Commands::Select if (numberOfAreas != 0) { - auto locationIter = req.newAreas.begin(); uint32_t ignored; - while (locationIter.Next()) + for (uint32_t areaId : selectedAreasSpan) { - mDelegate->AddSelectedArea(locationIter.GetValue(), ignored); + mDelegate->AddSelectedArea(areaId, ignored); } } 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 e4457c3745..8c2ba832c8 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 @@ -63,9 +63,8 @@ limitations under the License. - - - + + diff --git a/src/controller/data_model/controller-clusters.matter b/src/controller/data_model/controller-clusters.matter index ede6f1117e..1413833c1b 100644 --- a/src/controller/data_model/controller-clusters.matter +++ b/src/controller/data_model/controller-clusters.matter @@ -6463,9 +6463,8 @@ provisional cluster ServiceArea = 336 { enum SelectAreasStatus : enum8 { kSuccess = 0; kUnsupportedArea = 1; - kDuplicatedAreas = 2; - kInvalidInMode = 3; - kInvalidSet = 4; + kInvalidInMode = 2; + kInvalidSet = 3; } enum SkipAreaStatus : enum8 { diff --git a/src/controller/python/chip/clusters/Objects.py b/src/controller/python/chip/clusters/Objects.py index 391765f383..9808b113f2 100644 --- a/src/controller/python/chip/clusters/Objects.py +++ b/src/controller/python/chip/clusters/Objects.py @@ -31358,14 +31358,13 @@ class OperationalStatusEnum(MatterIntEnum): class SelectAreasStatus(MatterIntEnum): kSuccess = 0x00 kUnsupportedArea = 0x01 - kDuplicatedAreas = 0x02 - kInvalidInMode = 0x03 - kInvalidSet = 0x04 + kInvalidInMode = 0x02 + kInvalidSet = 0x03 # All received enum values that are not listed above will be mapped # to kUnknownEnumValue. This is a helper enum value that should only # be used by code to process how it handles receiving an unknown # enum value. This specific value should never be transmitted. - kUnknownEnumValue = 5, + kUnknownEnumValue = 4, class SkipAreaStatus(MatterIntEnum): kSuccess = 0x00 diff --git a/src/darwin/Framework/CHIP/zap-generated/MTRBaseClusters.h b/src/darwin/Framework/CHIP/zap-generated/MTRBaseClusters.h index c00233470f..f15337ff56 100644 --- a/src/darwin/Framework/CHIP/zap-generated/MTRBaseClusters.h +++ b/src/darwin/Framework/CHIP/zap-generated/MTRBaseClusters.h @@ -19787,9 +19787,8 @@ typedef NS_ENUM(uint8_t, MTRServiceAreaOperationalStatus) { typedef NS_ENUM(uint8_t, MTRServiceAreaSelectAreasStatus) { MTRServiceAreaSelectAreasStatusSuccess MTR_PROVISIONALLY_AVAILABLE = 0x00, MTRServiceAreaSelectAreasStatusUnsupportedArea MTR_PROVISIONALLY_AVAILABLE = 0x01, - MTRServiceAreaSelectAreasStatusDuplicatedAreas MTR_PROVISIONALLY_AVAILABLE = 0x02, - MTRServiceAreaSelectAreasStatusInvalidInMode MTR_PROVISIONALLY_AVAILABLE = 0x03, - MTRServiceAreaSelectAreasStatusInvalidSet MTR_PROVISIONALLY_AVAILABLE = 0x04, + MTRServiceAreaSelectAreasStatusInvalidInMode MTR_PROVISIONALLY_AVAILABLE = 0x02, + MTRServiceAreaSelectAreasStatusInvalidSet MTR_PROVISIONALLY_AVAILABLE = 0x03, } MTR_PROVISIONALLY_AVAILABLE; typedef NS_ENUM(uint8_t, MTRServiceAreaSkipAreaStatus) { diff --git a/src/python_testing/TC_SEAR_1_3.py b/src/python_testing/TC_SEAR_1_3.py index 2ea2e86b7d..867cdcbe23 100644 --- a/src/python_testing/TC_SEAR_1_3.py +++ b/src/python_testing/TC_SEAR_1_3.py @@ -109,15 +109,17 @@ async def test_TC_SEAR_1_3(self): duplicated_areas = [valid_area_id, valid_area_id] - # FIXME need to check if this is the correct name of this status code - await self.send_cmd_select_areas_expect_response(step=3, new_areas=duplicated_areas, expected_response=Clusters.ServiceArea.Enums.SelectAreasStatus.kDuplicatedAreas) + await self.send_cmd_select_areas_expect_response(step=3, new_areas=duplicated_areas, expected_response=Clusters.ServiceArea.Enums.SelectAreasStatus.kSuccess) - await self.send_cmd_select_areas_expect_response(step=4, new_areas=[], expected_response=Clusters.ServiceArea.Enums.SelectAreasStatus.kSuccess) + selected_areas = await self.read_selected_areas(step=4) + asserts.assert_true(selected_areas == [valid_area_id], "SelectedAreas should be empty") - selected_areas = await self.read_selected_areas(step=5) + await self.send_cmd_select_areas_expect_response(step=5, new_areas=[], expected_response=Clusters.ServiceArea.Enums.SelectAreasStatus.kSuccess) + + selected_areas = await self.read_selected_areas(step=6) asserts.assert_true(len(selected_areas) == 0, "SelectedAreas should be empty") - await self.send_cmd_select_areas_expect_response(step=6, new_areas=[invalid_area_id], expected_response=Clusters.ServiceArea.Enums.SelectAreasStatus.kUnsupportedArea) + await self.send_cmd_select_areas_expect_response(step=8, new_areas=[invalid_area_id], expected_response=Clusters.ServiceArea.Enums.SelectAreasStatus.kUnsupportedArea) if self.check_pics("SEAR.S.M.INVALID_STATE_FOR_SELECT_AREAS") and self.check_pics("SEAR.S.M.HAS_MANUAL_SELAREA_STATE_CONTROL"): test_step = "Manually intervene to put the device in a state that prevents it from executing the SelectAreas command" @@ -127,7 +129,7 @@ async def test_TC_SEAR_1_3(self): else: self.wait_for_user_input(prompt_msg=f"{test_step}, and press Enter when done.\n") - await self.send_cmd_select_areas_expect_response(step=8, new_areas=[valid_area_id], expected_response=Clusters.ServiceArea.Enums.SelectAreasStatus.kInvalidInMode) + await self.send_cmd_select_areas_expect_response(step=10, new_areas=[valid_area_id], expected_response=Clusters.ServiceArea.Enums.SelectAreasStatus.kInvalidInMode) if self.check_pics("SEAR.S.M.VALID_STATE_FOR_SELECT_AREAS") and self.check_pics("SEAR.S.M.HAS_MANUAL_SELAREA_STATE_CONTROL"): test_step = f"Manually intervene to put the device in a state that allows it to execute the SelectAreas({supported_area_ids}) command" @@ -137,17 +139,17 @@ async def test_TC_SEAR_1_3(self): else: self.wait_for_user_input(prompt_msg=f"{test_step}, and press Enter when done.\n") - await self.send_cmd_select_areas_expect_response(step=10, new_areas=supported_area_ids, expected_response=Clusters.ServiceArea.Enums.SelectAreasStatus.kSuccess) + await self.send_cmd_select_areas_expect_response(step=11, new_areas=supported_area_ids, expected_response=Clusters.ServiceArea.Enums.SelectAreasStatus.kSuccess) - selected_areas = await self.read_selected_areas(step=11) + selected_areas = await self.read_selected_areas(step=12) asserts.assert_true(len(selected_areas) == len(supported_area_ids), f"SelectedAreas({selected_areas}) should match SupportedAreas({supported_area_ids})") - await self.send_cmd_select_areas_expect_response(step=12, new_areas=supported_area_ids, expected_response=Clusters.ServiceArea.Enums.SelectAreasStatus.kSuccess) + await self.send_cmd_select_areas_expect_response(step=13, new_areas=supported_area_ids, expected_response=Clusters.ServiceArea.Enums.SelectAreasStatus.kSuccess) if self.check_pics("SEAR.S.M.VALID_STATE_FOR_SELECT_AREAS") and self.check_pics("SEAR.S.M.HAS_MANUAL_SELAREA_STATE_CONTROL") and self.check_pics("SEAR.S.M.SELECT_AREAS_WHILE_NON_IDLE"): test_step = f"Manually intervene to put the device in a state that allows it to execute the SelectAreas({valid_area_id}) command, and put the device in a non-idle state" - self.print_step("13", test_step) + self.print_step("14", test_step) if self.is_ci: self.write_to_app_pipe('{"Name": "Reset"}') await self.send_single_cmd(cmd=Clusters.Objects.RvcRunMode.Commands.ChangeToMode(newMode=1), endpoint=self.endpoint) @@ -155,9 +157,9 @@ async def test_TC_SEAR_1_3(self): self.wait_for_user_input(prompt_msg=f"{test_step}, and press Enter when done.\n") if self.check_pics("SEAR.S.F00"): - await self.send_cmd_select_areas_expect_response(step=14, new_areas=[valid_area_id], expected_response=Clusters.ServiceArea.Enums.SelectAreasStatus.kSuccess) + await self.send_cmd_select_areas_expect_response(step=15, new_areas=[valid_area_id], expected_response=Clusters.ServiceArea.Enums.SelectAreasStatus.kSuccess) else: - await self.send_cmd_select_areas_expect_response(step=14, new_areas=[valid_area_id], expected_response=Clusters.ServiceArea.Enums.SelectAreasStatus.kInvalidInMode) + await self.send_cmd_select_areas_expect_response(step=15, new_areas=[valid_area_id], expected_response=Clusters.ServiceArea.Enums.SelectAreasStatus.kInvalidInMode) if __name__ == "__main__": diff --git a/zzz_generated/app-common/app-common/zap-generated/cluster-enums-check.h b/zzz_generated/app-common/app-common/zap-generated/cluster-enums-check.h index f63782c221..90d399b8e6 100644 --- a/zzz_generated/app-common/app-common/zap-generated/cluster-enums-check.h +++ b/zzz_generated/app-common/app-common/zap-generated/cluster-enums-check.h @@ -2598,7 +2598,6 @@ static auto __attribute__((unused)) EnsureKnownEnumValue(ServiceArea::SelectArea { case EnumType::kSuccess: case EnumType::kUnsupportedArea: - case EnumType::kDuplicatedAreas: case EnumType::kInvalidInMode: case EnumType::kInvalidSet: return val; 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 e78f8f4d06..998a3c931b 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 @@ -3825,14 +3825,13 @@ enum class SelectAreasStatus : uint8_t { kSuccess = 0x00, kUnsupportedArea = 0x01, - kDuplicatedAreas = 0x02, - kInvalidInMode = 0x03, - kInvalidSet = 0x04, + kInvalidInMode = 0x02, + kInvalidSet = 0x03, // All received enum values that are not listed above will be mapped // to kUnknownEnumValue. This is a helper enum value that should only // be used by code to process how it handles receiving and unknown // enum value. This specific should never be transmitted. - kUnknownEnumValue = 5, + kUnknownEnumValue = 4, }; // Enum for SkipAreaStatus From 79a6aa350f845ffd1746c43a2ddcbd6e831f8027 Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Fri, 23 Aug 2024 03:55:01 -0400 Subject: [PATCH 152/165] Mark return types nullable in MTRDevice_XPC when nil can be returned. (#35152) --- src/darwin/Framework/CHIP/MTRDevice_XPC.mm | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/darwin/Framework/CHIP/MTRDevice_XPC.mm b/src/darwin/Framework/CHIP/MTRDevice_XPC.mm index bc3b0a6b26..85be0db343 100644 --- a/src/darwin/Framework/CHIP/MTRDevice_XPC.mm +++ b/src/darwin/Framework/CHIP/MTRDevice_XPC.mm @@ -163,10 +163,10 @@ - (oneway void)deviceConfigurationChanged:(NSNumber *)nodeID 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 *, nil, getEstimatedStartTimeWithReply) -MTR_DEVICE_SIMPLE_REMOTE_XPC_GETTER(estimatedSubscriptionLatency, NSNumber *, nil, getEstimatedSubscriptionLatencyWithReply) +MTR_DEVICE_SIMPLE_REMOTE_XPC_GETTER(estimatedStartTime, NSDate * _Nullable, nil, getEstimatedStartTimeWithReply) +MTR_DEVICE_SIMPLE_REMOTE_XPC_GETTER(estimatedSubscriptionLatency, NSNumber * _Nullable, nil, getEstimatedSubscriptionLatencyWithReply) -typedef NSDictionary * readAttributeResponseType; +typedef NSDictionary * _Nullable readAttributeResponseType; MTR_DEVICE_COMPLEX_REMOTE_XPC_GETTER(readAttributeWithEndpointID : (NSNumber *) endpointID clusterID : (NSNumber *) clusterID attributeID @@ -226,7 +226,7 @@ - (void)_invokeCommandWithEndpointID:(NSNumber *)endpointID // Not Supported via XPC //- (oneway void)deviceController:(NSUUID *)controller nodeID:(NSNumber *)nodeID openCommissioningWindowWithSetupPasscode:(NSNumber *)setupPasscode discriminator:(NSNumber *)discriminator duration:(NSNumber *)duration completion:(MTRDeviceOpenCommissioningWindowHandler)completion; -MTR_DEVICE_SIMPLE_REMOTE_XPC_GETTER(clientDataKeys, NSArray *, nil, getClientDataKeysWithReply) +MTR_DEVICE_SIMPLE_REMOTE_XPC_GETTER(clientDataKeys, NSArray * _Nullable, nil, getClientDataKeysWithReply) MTR_DEVICE_COMPLEX_REMOTE_XPC_GETTER(clientDataForKey : (NSString *) key, id _Nullable, nil, clientDataForKey : key withReply) From 9462066993f3c4f7cbecb12832617c3a3b930af4 Mon Sep 17 00:00:00 2001 From: C Freeman Date: Fri, 23 Aug 2024 04:23:38 -0400 Subject: [PATCH 153/165] check (#34998) --- src/python_testing/matter_testing_support.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/python_testing/matter_testing_support.py b/src/python_testing/matter_testing_support.py index d3d810149c..4127ead64c 100644 --- a/src/python_testing/matter_testing_support.py +++ b/src/python_testing/matter_testing_support.py @@ -1838,6 +1838,14 @@ def whole_node_runner(self: MatterBaseTest, *args, **kwargs): EndpointCheckFunction = typing.Callable[[Clusters.Attribute.AsyncReadTransaction.ReadResponse, int], bool] +def get_cluster_from_attribute(attribute: ClusterObjects.ClusterAttributeDescriptor) -> ClusterObjects.Cluster: + return ClusterObjects.ALL_CLUSTERS[attribute.cluster_id] + + +def get_cluster_from_command(command: ClusterObjects.ClusterCommand) -> ClusterObjects.Cluster: + return ClusterObjects.ALL_CLUSTERS[command.cluster_id] + + def _has_cluster(wildcard, endpoint, cluster: ClusterObjects.Cluster) -> bool: try: return cluster in wildcard.attributes[endpoint] @@ -1870,7 +1878,7 @@ def has_cluster(cluster: ClusterObjects.ClusterObjectDescriptor) -> EndpointChec def _has_attribute(wildcard, endpoint, attribute: ClusterObjects.ClusterAttributeDescriptor) -> bool: - cluster = getattr(Clusters, attribute.__qualname__.split('.')[-3]) + cluster = get_cluster_from_attribute(attribute) try: attr_list = wildcard.attributes[endpoint][cluster][cluster.Attributes.AttributeList] return attribute.attribute_id in attr_list From aa3e9fcb48ee0d1d22448fd5296bdd8f80d482d4 Mon Sep 17 00:00:00 2001 From: Wang Qixiang <43193572+wqx6@users.noreply.github.com> Date: Fri, 23 Aug 2024 16:39:40 +0800 Subject: [PATCH 154/165] minimal_mdns: Fix filter for Compressed Fabric Id when browsing operational nodes (#35063) * minimal_mdns: Fix filter for Compressed Fabric Id when browsing operational nodes * Add check for subtype number --- src/lib/dnssd/Resolver_ImplMinimalMdns.cpp | 12 +++++++++++- src/lib/shell/commands/Dns.cpp | 16 +++++++++++++--- 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/src/lib/dnssd/Resolver_ImplMinimalMdns.cpp b/src/lib/dnssd/Resolver_ImplMinimalMdns.cpp index 8b2b30e318..8e913f2add 100644 --- a/src/lib/dnssd/Resolver_ImplMinimalMdns.cpp +++ b/src/lib/dnssd/Resolver_ImplMinimalMdns.cpp @@ -544,7 +544,17 @@ CHIP_ERROR MinMdnsResolver::BuildQuery(QueryBuilder & builder, const ActiveResol switch (data.type) { case DiscoveryType::kOperational: - qname = CheckAndAllocateQName(kOperationalServiceName, kOperationalProtocol, kLocalDomain); + if (data.filter.type == DiscoveryFilterType::kCompressedFabricId) + { + char subtypeStr[Common::kSubTypeMaxLength + 1]; + ReturnErrorOnFailure(MakeServiceSubtype(subtypeStr, sizeof(subtypeStr), data.filter)); + qname = CheckAndAllocateQName(subtypeStr, kSubtypeServiceNamePart, kOperationalServiceName, kOperationalProtocol, + kLocalDomain); + } + else + { + qname = CheckAndAllocateQName(kOperationalServiceName, kOperationalProtocol, kLocalDomain); + } break; case DiscoveryType::kCommissionableNode: if (data.filter.type == DiscoveryFilterType::kNone) diff --git a/src/lib/shell/commands/Dns.cpp b/src/lib/shell/commands/Dns.cpp index 18e0841dcc..917f94f849 100644 --- a/src/lib/shell/commands/Dns.cpp +++ b/src/lib/shell/commands/Dns.cpp @@ -214,13 +214,23 @@ bool ParseSubType(int argc, char ** argv, Dnssd::DiscoveryFilter & filter) case 'C': filterType = Dnssd::DiscoveryFilterType::kCommissioningMode; break; + case 'I': + filterType = Dnssd::DiscoveryFilterType::kCompressedFabricId; + break; default: return false; } - uint16_t code; - VerifyOrReturnError(ArgParser::ParseInt(subtype + 2, code), false); - + uint64_t code = 0; + if (filterType == Dnssd::DiscoveryFilterType::kCompressedFabricId) + { + VerifyOrReturnError(ArgParser::ParseInt(subtype + 2, code, 16), false); + VerifyOrReturnValue(code != 0, false); + } + else + { + VerifyOrReturnError(ArgParser::ParseInt(subtype + 2, code), false); + } filter = Dnssd::DiscoveryFilter(filterType, code); return true; } From 085138295acd3af46931a8197d9e564dc11becac Mon Sep 17 00:00:00 2001 From: C Freeman Date: Fri, 23 Aug 2024 04:39:55 -0400 Subject: [PATCH 155/165] Docs re-organization (#34765) * Docs re-organization The second phase of the handbook involves linking over to the SDK docs from the handbook site. Before we do this, the SDK documentation needs a re-org and an update. This is a continuation of the re-org, following the platform updates. Remaining: Zap, tools, examples, IDs. Done in this PR: - remove API - this is a 4 year old design doc for a test dispatch system that was never implemented. This does not make sense to keep in the docs folder since it gives the incorrect impression that this system was implemented at some point. In reality, our testing is quite different and is decently well documented in the testing section. - rename discussion to product consideration. This contains only the ipv6 considerations doc, which isn't a discussion. Instead, we're going to use this location to land documents related to product considerations that affect matter, but are provided outside of the SDK, ex. required network stack support (current doc), and factory considerations (coming later) for things like DACs, individually provisioned values, QR codes, config options, certification declaration inclusion, DCL. - move designing cluster for testing and portability from testing to cluster design - it just makes more sense there. - Creating a tips and troubleshooting section to land small guides, move in avahi troubleshooting and guide around discovery from a host computer. - remove quick start guide - everything in here is outdated, we have a getting started guide and a readme that covers all the getting started material. Added references to that in the readme - * couple more refs * remove readme --- docs/QUICK_START.md | 52 ----- docs/README.md | 4 + docs/api/device_runner.md | 103 ---------- docs/api/device_runner_dispatch.md | 183 ------------------ docs/api/index.md | 7 - .../img/plant_uml_source.txt | 0 .../img/unit_testable_clusters.png | Bin .../unit_testable_clusters_all_classes.png | Bin .../img/unit_testable_clusters_context.png | Bin .../img/unit_testable_clusters_driver.png | Bin .../img/unit_testable_clusters_logic.png | Bin .../img/unit_testable_clusters_server.png | Bin docs/cluster_and_device_type_dev/index.md | 1 + .../unit_testing_clusters.md | 0 docs/getting_started/index.md | 1 - docs/guides/README.md | 56 ------ docs/guides/index.md | 4 - docs/index.md | 5 +- .../index.md | 0 .../lwip_ipv6.md | 0 docs/testing/index.md | 1 - docs/testing/integration_test_utilities.md | 7 +- .../discovery_from_a_host_computer.md | 0 docs/tips_and_troubleshooting/index.md | 8 + .../troubleshooting_avahi.md | 0 25 files changed, 19 insertions(+), 413 deletions(-) delete mode 100644 docs/QUICK_START.md delete mode 100644 docs/api/device_runner.md delete mode 100644 docs/api/device_runner_dispatch.md delete mode 100644 docs/api/index.md rename docs/{testing => cluster_and_device_type_dev}/img/plant_uml_source.txt (100%) rename docs/{testing => cluster_and_device_type_dev}/img/unit_testable_clusters.png (100%) rename docs/{testing => cluster_and_device_type_dev}/img/unit_testable_clusters_all_classes.png (100%) rename docs/{testing => cluster_and_device_type_dev}/img/unit_testable_clusters_context.png (100%) rename docs/{testing => cluster_and_device_type_dev}/img/unit_testable_clusters_driver.png (100%) rename docs/{testing => cluster_and_device_type_dev}/img/unit_testable_clusters_logic.png (100%) rename docs/{testing => cluster_and_device_type_dev}/img/unit_testable_clusters_server.png (100%) rename docs/{testing => cluster_and_device_type_dev}/unit_testing_clusters.md (100%) delete mode 100644 docs/guides/README.md rename docs/{discussion => product_considerations}/index.md (100%) rename docs/{discussion => product_considerations}/lwip_ipv6.md (100%) rename docs/{getting_started => tips_and_troubleshooting}/discovery_from_a_host_computer.md (100%) create mode 100644 docs/tips_and_troubleshooting/index.md rename docs/{guides => tips_and_troubleshooting}/troubleshooting_avahi.md (100%) diff --git a/docs/QUICK_START.md b/docs/QUICK_START.md deleted file mode 100644 index d5d80703c5..0000000000 --- a/docs/QUICK_START.md +++ /dev/null @@ -1,52 +0,0 @@ -# Quick Start - -## Demo Overview - -The Matter reference implementation contains support for a number of examples -and platforms. - -## Wi-Fi Nodes - -|

Controller / Admin
|
Node
| Description | -| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| [**chip-tool**](https://github.com/project-chip/connectedhomeip/blob/master/examples/chip-tool/README.md) (Linux / Mac)
Includes docs for all the cluster commands supported
| **all-clusters-app**
  • [M5Stack](https://github.com/project-chip/connectedhomeip/blob/master/examples/all-clusters-app/esp32/README.md) (ESP)
  • [Linux](https://github.com/project-chip/connectedhomeip/tree/master/examples/all-clusters-app/linux) simulation | Use the command line tool on a laptop to pair with and control an embedded Wi-Fi platform. This demo supports the “all-clusters-app”, so it provides the basic onoff light test and more. | -| [**chip-repl**](https://github.com/project-chip/connectedhomeip/blob/master/src/controller/python/README.md) | **all-clusters-app**
  • [M5Stack](https://github.com/project-chip/connectedhomeip/blob/master/examples/all-clusters-app/esp32/README.md) (ESP)
  • [Linux](https://github.com/project-chip/connectedhomeip/tree/master/examples/all-clusters-app/linux) simulation | Same as above, but uses the Python CHIP REPL as Controller Node. | - -## Thread Nodes - -Use one of the controllers listed above and then a Border Router and Node -combination listed below. - -|
    Border Router
    |
    Node
    | Description | -| -------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| [**ot-br**](https://openthread.io/guides/border-router/build)
    Thread Border Router
  • RasPi
  • BeagleBone | **lighting-app**
  • [Nordic nRF5x](https://github.com/project-chip/connectedhomeip/tree/master/examples/lighting-app/nrfconnect/README.md)
  • [NXP K32W](https://github.com/project-chip/connectedhomeip/tree/master/examples/lighting-app/nxp/k32w0/README.md)
  • [Qorvo QPG6100](https://github.com/project-chip/connectedhomeip/tree/master/examples/lighting-app/qpg)
  • [Silicon Labs EFR32](https://github.com/project-chip/connectedhomeip/tree/master/examples/lighting-app/silabs/README.md) | The Lighting example is supported by many of the available Thread platforms. See the chip-tool controller instructions for how to actuate the light on/off cluster. | -| [**ot-br**](https://openthread.io/guides/border-router/build)
    Thread Border Router
  • RasPi
  • BeagleBone | **lock-app**
  • [Nordic nRF5x](https://github.com/project-chip/connectedhomeip/tree/master/examples/lock-app/nrfconnect/README.md)
  • [Qorvo QPG6100](https://github.com/project-chip/connectedhomeip/tree/master/examples/lock-app/qpg)
  • [Silicon Labs EFR32](https://github.com/project-chip/connectedhomeip/tree/master/examples/lock-app/efr32/README.md)
  • [TI CC13x2x7](https://github.com/project-chip/connectedhomeip/tree/master/examples/lock-app/cc13x2x7_26x2x7/README.md) | The Lock example is supported by many of the available Thread and Wi-Fi platforms. | - -## Controllers - -### chip-tool - -This section summarizes how to run some common scenarios with the -[**chip-tool**](https://github.com/project-chip/connectedhomeip/blob/master/examples/chip-tool/README.md) -controller. - -#### IP Pairing - -`chip-tool pairing onnetwork ${NODE_ID_TO_ASSIGN} 20202021` will use PASE over -IP to commission a device and assign `${NODE_ID_TO_ASSIGN}` (which must be a -decimal number or a 0x-prefixed hex number) as its node id. - -NOTE: On Linux, if the device is actually running after unit tests ran you have -to use `chip-tool pairing onnetwork desired-node-id 34567890`, because the unit -tests change the device configuration. - -NOTE: to run both the Node and Controller as separate processes on the same -Linux or Mac machine, build the all-clusters-app with Bluetooth LE disabled as -follows: - -`scripts/examples/gn_build_example.sh examples/all-clusters-app/linux out/debug/standalone/ chip_config_network_layer_ble=false` - -#### Automated CASE tests - -`chip-tool tests Test_TC_OO_1_1` will run a suite of tests that use CASE To -communicate with a paired `all-clusters-app` peer node. diff --git a/docs/README.md b/docs/README.md index e4ec9c8f3a..e5aad317e6 100644 --- a/docs/README.md +++ b/docs/README.md @@ -2,6 +2,10 @@ ## Building and Developing +- A quick start guide to building a demo application and controller is + available in the [Getting started](./getting_started/) guide +- A guide to new cluster and device type development is available in the + [New Cluster and Device Type Developement Guide](./cluster_and_device_type_dev/) - Documentation about building from the command line can be found in [the build guide](guides/BUILDING.md) - Documentation about running [cirque](https://github.com/openweave/cirque) diff --git a/docs/api/device_runner.md b/docs/api/device_runner.md deleted file mode 100644 index db9c5993ef..0000000000 --- a/docs/api/device_runner.md +++ /dev/null @@ -1,103 +0,0 @@ -# CHIP on-device testing - -_Requirements and high-level design_ - -## Background - -The ability to run tests on actual and emulated hardware is paramount in -embedded projects. CHIP is no exception. We want on-device testing to be a first -class goal of CHIP architecture. On-device testing requirements apply both to -Continuous Integration testing for main CHIP software stack development and to -eventual CHIP product certification. This document explores the requirements and -evaluates potential solutions. - -## Overview of requirements - -A good device test infrastructure is built on four pillars. - -### Pillar 1: Using a test framework - -A test framework provides a testing structure that developers can follow and -potentially reduces some of the burden of test setup and teardown (less -boilerplate). Support for state-oriented and asynchronous structuring of tests -would be beneficial. Many test frameworks leverage scripting languages such as -Python to simplify the quick development of tests and to leverage rich sets of -libraries for device/systems access and results generation. - -### Pillar 2: Dispatching tests - -Tests can run on lab machines or on the developer's local workstation. Tests can -be triggered manually by the developer or as a result of completion of a -changeset built on a continuous integration (CI) server. CHIP involves multiple -stakeholders, many of which will want to contribute to the testing efforts with -lab capacity. The infrastructure therefore must be prepared for -cross-organization test dispatch. - -To facilitate uniform dispatch of tests we will probably need a simple -request/response protocol. Potentially HTTPS based and RESTful. Due to the long -running nature of device tests the response for a test scheduling request could -be a test ID, not the test result. That ID could be used to query the test -status, subscribe for notifications on status changes and to pull the test -results. Core aspects of such a scheme include the conventions for request -artifacts contents and minimum expected results contents once the run is -complete. - -### Pillar 3: Interacting with devices - -The test host environment has to reset devices, flash images on them, issue -commands, monitor status and collect test results. It may also need to integrate -both virtual (simulated) and real devices together. This can at first be done in -an ad-hoc way per platform but eventually we can go into device access -abstraction, i.e. define a common device testing interface which CHIP-compliant -devices can expose. The test host has to be prepared for driving multiple -devices at the same time for a single test, e.g. for tests that check -communication between multiple devices. - -### Pillar 4: Collecting results - -Ideally, test results are output in standard formats and similar or analogous -results between different devices and tests are output the same way. This -ensures reusability of code that processes similar data while allowing -aggregation of results across different dimensions. Failed tests must propagate -errors from device platform layers all the way to the CHIP stack and present -errors and potential stack traces in a standard result format. As the purpose of -on-device tests is to capture bugs, it is important that the test outputs -highlight the failure reason(s) and developers don't have to browse through -thousands of lines of logs to find the one line that sheds light on why a test -failed. - -## Priorities - -In the spirit of CHIP's charter, it would be great to see something taking-off -as soon as possible, to support continuous testing of the evolving CHIP stack. -We could then improve on that first iteration, even if we have to throw away -some temporary concepts and code. - -Test dispatch (Pillar 2) arises as the highest priority, because all other -pillars can have ad-hoc solutions. The first need is an interface between a -CircleCI job and a test execution host at a participating organization. This -would enable dispatching tests to a variety of existing in-house infrastructure, -while retaining common request/response protocols to shield the CI system from -implementation details of each lab. - -The next most important goal is to provide a test framework (Pillar 1). With a -standard framework developers can start writing tests, even if those tests will -be device specific and of ad-hoc input and output format. The general structure -of tests will however be present and later the tests can be adapted to standard -interactions (Pillar 3) and result formats (Pillar 4). - -Specifying result formats (Pillar 4) for the most common outputs -(success/failure, failure reason, stack trace, memory and CPU usage time series, -pcaps of network traffic, etc.) will be an ongoing effort. The simplest output -formats can be specified together with the test framework. - -Lastly, we want to look into a common device interaction interface that would -enable reusing tests between different devices. - -## Baseline hardware platforms for CHIP - -The TSG is targeting the following platforms/boards for early bringup: - -- Nordic nRF52 board -- SiLabs `XXXX` board -- Espressif ESP32 `XXXX` board diff --git a/docs/api/device_runner_dispatch.md b/docs/api/device_runner_dispatch.md deleted file mode 100644 index fff2634b41..0000000000 --- a/docs/api/device_runner_dispatch.md +++ /dev/null @@ -1,183 +0,0 @@ -# CHIP on-device test dispatch - -This document expands on and provides design for on-device test dispatch. The -CHIP on-device testing document states that dispatching should involve a HTTPS -based RESTful protocol that could be integrated with CircleCI. - -## Definitions - -**Test run**: Tests instantiation on a test host, consisting of host-side test -binaries and test scripts as well as one or more device-side binaries. - -**Test host**: A computing execution environment provided for the purposes of -running tests by a party participating in the scheme. - -## Scope - -The scope of this proposal is to support running tests against a known set of -canonical devices and platforms for the purposes of developing core common code -in the CHIP project GitHub repository. - -This proposal does not preclude a stakeholder running their own tests against -their own hardware or lab in any way they see fit. The goal is merely to provide -a common way for volunteer organizations to register test infrastructure and -dispatch capabilities to be used by the wider CHIP developer community. - -Authentication is not considered strictly part of the test dispatch protocol. -However it is mandated that some form of authentication takes place before any -of the test dispatch operations are issued. Throughout this document it is -assumed that proper authentication and authorization is ensured by the server -hosting the test dispatch service. - -## Objectives - -- **Provide a centralized API** for the dispatching of tests against - potentially distributed lab infrastructure, which CI systems (i.e. CircleCI) - or individual developers may not be directly configured to access. -- **Decouple test execution from the CI environment**, especially for tests - requiring complex setups, such as radio traffic capture. -- **Enable** common adoption of **aligned methodologies** for both - certification-style tests and development-support tests (pre/post-submit - testing in pull requests). - -### Certification or pre-certification tests - -Certification tests are required to have canonical test suite names. - -Here the host side test binaries and scripts are fixed and the device-side -binary can vary by device type. The objective of certification testing is to run -a known fixed set of tests against new and existing devices. Dispatching of -certification tests involves specifying the canonical test suite name and -providing the requisite arguments, such as device-side binary and device type. - -### Development support tests - -Development support test suites are required to have canonical names, but they -may, during execution, check-out the actual test script from a given PR, or from -the artifacts uploaded for the test job. - -The test is executed against a pull request and may target many device types. -Therefore, both host-side and device-side artifacts may vary and have to be -uploaded in the respective argument to test dispatch operation. Dispatching of -development support test suites therefore involves specifying a canonical test -suite name, the PR URL, pre-built artifacts (host side and device-side) and -optional test-specific arguments. - -### Common constraints for dispatch - -In order to support running tests, some common arguments are required to -determine during dispatch whether a given combination of targets can be -supported. - -These constraints include: - -- A canonical device type list to determine whether a target runner has all - the targets needed. (Note that new hardware developers may provide a - non-canonical device type for running their own certification on their own - lab. Canonical device types exist for development support tests.) -- An optional node ID (unique UUID) to force execution on a given registered - infrastructure for test purposes. - -Example of canonical test suite names: - -- RendezVousTest: loads binaries on HW, validates that assumptions about - RendezVous advertising payload are still valid. -- BasicCHIPRegression: loads binaries on HW, validates against regressions on - multiple axes of the test. Potentially runs updated tests scripts from the - PR itself. - -## Aggregator Dispatch Interface API - -We conceptualize an aggregator service where all the tests are sent to be -further dispatched to or pulled by participating infrastructure/lab providers. - -For the prototype phase the aggregator may be the same service that runs tests -as well, i.e. further dispatch/pull/registration may not happen in the -prototype. - -This is the API which CircleCI and individual test developers can use. There may -be other APIs (e.g. administrator API) to the aggregator that provide richer -functionality. For now we don't discuss those. The API for communication between -the aggregator and test labs is to be specified at a later time. - -The goal of decoupling dispatch from execution is to avoid coupling running the -tests to a given lab’s or organization’s infrastructure. The dispatch interface -API provides a separation of concerns of “what to run”/“what happened” versus -“how to run”/“where to run”. - -### Resources and operations - -/available_test_suites - Collection resource, all the canonical test suite -names. - -- GET gets the list of known canonical test suite names - -/dispatch - Collection resource, all the currently running test executions. - -- POST dispatches a new test, returning its URI with the test run identifier - 'job_id'. - Arguments - Canonical Test Suite name e.g. - "CHIP_basic_test_suite" - ZIP file upload of artifacts (device-side and, if - needed, host-side) - Some common required inputs (see section below) - - Test-suite-specific configuration/contents may also be provided for the test - suite executor to use. - Maximum time the client is willing to wait for - results (seconds) - In case of execution timed out, the test job would be - considered FAILED, due to time-out. - Maximum time the client is willing to - wait for test to start (seconds) - In case of time-out to dispatch, the test - job would be considered ABORTED in the results as opposed to FAILED - - Authentication requirements may cause a given requestor to be throttled by - internal logic. - -/status/ - Member resource, an individual test. - -- GET returns the status of the test: scheduled, running, finished, aborted. -- DELETE cancels the test. - -/status//results - Collection resource, all the files resulting from the -test run. - -- GET returns the list of (file_name, file_id) pairs. - - Only mandatory file: - - test_suite_results.json - - Normalized test results, see section below. - -/status//results/ - Member resource, and individual result -file. - -- GET returns the contents of the file. - -### /dispatch arguments - -**test_suite_name**: _Required_. Name of the test suite. - -**host_artifacts**: _Only required for development support tests_. A file (most -likely a ZIP file) corresponding to all the scripts and binaries to be run by -the test host. The test host must be able to unzip, recognize and execute -contents. - -**device_artifacts**: _Required_. A file (most likely a ZIP file) corresponding -to all the binaries to be flashed on the device. The test host must be able to -unzip, recognize and flash contents. - -**timeout_for_results_seconds**: _Required_. The maximum amount of time in -seconds the client is willing to wait for results. After this much time the test -can be killed by the test host. - -**timeout_for_start_seconds**: _Required_. The maximum amount of time in seconds -the client is willing to wait for the test to start. If after dispatch the test -does not start after this much time the test can be descheduled by the -aggregator. - -### test_suite_results.json contents - -TBD. - -### Aggregator-to-lab dispatch API - -TBD. - -### Lab Registration Interface API - -Once agreement on the dispatch API is cemented, the API to register a given -executor with certain tests and devices capabilities can be defined. - -TBD. diff --git a/docs/api/index.md b/docs/api/index.md deleted file mode 100644 index c139642dc4..0000000000 --- a/docs/api/index.md +++ /dev/null @@ -1,7 +0,0 @@ -# API - -```{toctree} -:glob: - -* -``` diff --git a/docs/testing/img/plant_uml_source.txt b/docs/cluster_and_device_type_dev/img/plant_uml_source.txt similarity index 100% rename from docs/testing/img/plant_uml_source.txt rename to docs/cluster_and_device_type_dev/img/plant_uml_source.txt diff --git a/docs/testing/img/unit_testable_clusters.png b/docs/cluster_and_device_type_dev/img/unit_testable_clusters.png similarity index 100% rename from docs/testing/img/unit_testable_clusters.png rename to docs/cluster_and_device_type_dev/img/unit_testable_clusters.png diff --git a/docs/testing/img/unit_testable_clusters_all_classes.png b/docs/cluster_and_device_type_dev/img/unit_testable_clusters_all_classes.png similarity index 100% rename from docs/testing/img/unit_testable_clusters_all_classes.png rename to docs/cluster_and_device_type_dev/img/unit_testable_clusters_all_classes.png diff --git a/docs/testing/img/unit_testable_clusters_context.png b/docs/cluster_and_device_type_dev/img/unit_testable_clusters_context.png similarity index 100% rename from docs/testing/img/unit_testable_clusters_context.png rename to docs/cluster_and_device_type_dev/img/unit_testable_clusters_context.png diff --git a/docs/testing/img/unit_testable_clusters_driver.png b/docs/cluster_and_device_type_dev/img/unit_testable_clusters_driver.png similarity index 100% rename from docs/testing/img/unit_testable_clusters_driver.png rename to docs/cluster_and_device_type_dev/img/unit_testable_clusters_driver.png diff --git a/docs/testing/img/unit_testable_clusters_logic.png b/docs/cluster_and_device_type_dev/img/unit_testable_clusters_logic.png similarity index 100% rename from docs/testing/img/unit_testable_clusters_logic.png rename to docs/cluster_and_device_type_dev/img/unit_testable_clusters_logic.png diff --git a/docs/testing/img/unit_testable_clusters_server.png b/docs/cluster_and_device_type_dev/img/unit_testable_clusters_server.png similarity index 100% rename from docs/testing/img/unit_testable_clusters_server.png rename to docs/cluster_and_device_type_dev/img/unit_testable_clusters_server.png diff --git a/docs/cluster_and_device_type_dev/index.md b/docs/cluster_and_device_type_dev/index.md index 9159cdb3e5..cf43d02651 100644 --- a/docs/cluster_and_device_type_dev/index.md +++ b/docs/cluster_and_device_type_dev/index.md @@ -14,3 +14,4 @@ types in the SDK. - [Cluster and device type development](./cluster_and_device_type_dev.md) - [How To Add New Device Types & Clusters](how_to_add_new_dts_and_clusters.md) +- [Cluster Server design](./unit_testing_clusters.md) diff --git a/docs/testing/unit_testing_clusters.md b/docs/cluster_and_device_type_dev/unit_testing_clusters.md similarity index 100% rename from docs/testing/unit_testing_clusters.md rename to docs/cluster_and_device_type_dev/unit_testing_clusters.md diff --git a/docs/getting_started/index.md b/docs/getting_started/index.md index cca67e19b0..ea881141ff 100644 --- a/docs/getting_started/index.md +++ b/docs/getting_started/index.md @@ -14,4 +14,3 @@ The following docs are a brief introduction to SDK development. - [Running your first example](./first_example.md) - [SDK Basics](./SDKBasics.md) - [ZAP](./zap.md) -- [Discover from a host computer](./discovery_from_a_host_computer.md) diff --git a/docs/guides/README.md b/docs/guides/README.md deleted file mode 100644 index a00cc83e28..0000000000 --- a/docs/guides/README.md +++ /dev/null @@ -1,56 +0,0 @@ -# Guides - -## Platform Guides - -- [Android - Building](./android_building.md) -- [Apple - Testing with iPhone, iPad, macOS, Apple TV, HomePod, Watch, etc](./darwin.md) -- [ASR - Getting Started Guide](./asr_getting_started_guide.md) -- [Espressif (ESP32) - Getting Started Guide](./esp32/README.md) -- [Infineon PSoC6 - Software Update](./infineon_psoc6_software_update.md) -- [Infineon Trust M Provisioning](./infineon_trustm_provisioning.md) -- [Linux - Simulated Devices](./simulated_device_linux.md) -- [mbedOS - Adding a new target](./mbedos_add_new_target.md) -- [mbedOS - Commissioning](./mbedos_commissioning.md) -- [mbedOS - Platform Overview](./mbedos_platform_overview.md) -- [nRF Connect - Android Commissioning](./nrfconnect_android_commissioning.md) -- [nRF Connect - CLI Guide](./nrfconnect_examples_cli.md) -- [nRF Connect - Configuration](./nrfconnect_examples_configuration.md) -- [nRF Connect - Factory Data Configuration](./nrfconnect_factory_data_configuration.md) -- [nRF Connect - Platform Overview](./nrfconnect_platform_overview.md) -- [nRF Connect - Software Update](./nrfconnect_examples_software_update.md) -- [NXP - Getting Started Guide](./nxp/README.md) -- [Silicon Labs - Documentation](https://siliconlabs.github.io/matter/latest/index.html) -- [Silicon Labs - Getting Started](./silabs_getting_started.md) -- [Silicon Labs - Software Update](./silabs_efr32_software_update.md) -- [Silicon Labs - CLI Guide](./silabs_cli_guide.md) -- [STMicroelectronics (STM32)](./stm32_getting_started_guide.md) -- [TI - Platform Overview](./ti/ti_matter_overview.md) -- [Open IoT SDK - Platform Overview](./openiotsdk_platform_overview.md) -- [Open IoT SDK - Examples](./openiotsdk_examples.md) -- [Open IoT SDK - Unit Tests](./openiotsdk_unit_tests.md) -- [Open IoT SDK - Commissioning](./openiotsdk_commissioning.md) -- [Open IoT SDK - Software Update](./openiotsdk_examples_software_update.md) - -## Development Guides - -- [Access Control](./access-control-guide.md) - -## Setup Guides - -- [Open Thread - Hardware suggestions](./openthread_rcp_nrf_dongle.md) -- [Open Thread - Setting up a Pi as a border router](./openthread_border_router_pi.md) - -## Troubleshooting Guides - -- [Avahi - Troubleshooting](./troubleshooting_avahi.md) - -## Tool Guides - -- [chip-tool](./chip_tool_guide.md) -- [Python Matter-Repl](./matter-repl.md) -- [python-chip-controller - Advanced](./python_chip_controller_advanced_usage.md) -- [python-chip-controller - Building](./python_chip_controller_building.md) - -## Build Guides - -- [Building](./BUILDING.md) diff --git a/docs/guides/index.md b/docs/guides/index.md index 8f747ab27e..14d9caf7e2 100644 --- a/docs/guides/index.md +++ b/docs/guides/index.md @@ -60,7 +60,3 @@ ti/ti_matter_overview - [Open Thread - Hardware suggestions](./openthread_rcp_nrf_dongle.md) - [Open Thread - Setting up a Raspberry Pi as a Border Router](./openthread_border_router_pi.md) - -## Troubleshooting Guides - -- [Avahi - Troubleshooting](./troubleshooting_avahi.md) diff --git a/docs/index.md b/docs/index.md index 1f8e806dc4..f4b4062271 100644 --- a/docs/index.md +++ b/docs/index.md @@ -5,18 +5,17 @@ :caption: Contents :hidden: -QUICK_START PROJECT_FLOW VSCODE_DEVELOPMENT -api/index ci-cd/index -discussion/index getting_started/index cluster_and_device_type_dev/index guides/index style/index examples/index +product_considerations/index testing/index +tips_and_troubleshooting/index tools/index BUG_REPORT code_generation diff --git a/docs/discussion/index.md b/docs/product_considerations/index.md similarity index 100% rename from docs/discussion/index.md rename to docs/product_considerations/index.md diff --git a/docs/discussion/lwip_ipv6.md b/docs/product_considerations/lwip_ipv6.md similarity index 100% rename from docs/discussion/lwip_ipv6.md rename to docs/product_considerations/lwip_ipv6.md diff --git a/docs/testing/index.md b/docs/testing/index.md index d8ebe92da4..b3124f8349 100644 --- a/docs/testing/index.md +++ b/docs/testing/index.md @@ -37,7 +37,6 @@ from the global ember and message delivery layers. ![](./img/unit_tests.png) - [Unit tests](./unit_testing.md) -- [Designing clusters for unit testing and portability](./unit_testing_clusters.md) ## PICS and PIXIT diff --git a/docs/testing/integration_test_utilities.md b/docs/testing/integration_test_utilities.md index e50ad511ca..019a3cf44b 100644 --- a/docs/testing/integration_test_utilities.md +++ b/docs/testing/integration_test_utilities.md @@ -6,9 +6,10 @@ on devices for the purposes of testing. When using any of these utilities it is important to inject the errors at the point where they are running through the MOST code that they can. -If the cluster uses the [ClusterLogic](./unit_testing_clusters.md) pattern, this -means injecting errors as close as possible to the driver layer, rather than -catching errors in the server. +If the cluster uses the +[ClusterLogic](../cluster_and_device_type_dev/unit_testing_clusters.md) pattern, +this means injecting errors as close as possible to the driver layer, rather +than catching errors in the server. ## TestEventTriggers diff --git a/docs/getting_started/discovery_from_a_host_computer.md b/docs/tips_and_troubleshooting/discovery_from_a_host_computer.md similarity index 100% rename from docs/getting_started/discovery_from_a_host_computer.md rename to docs/tips_and_troubleshooting/discovery_from_a_host_computer.md diff --git a/docs/tips_and_troubleshooting/index.md b/docs/tips_and_troubleshooting/index.md new file mode 100644 index 0000000000..f2f4a7a417 --- /dev/null +++ b/docs/tips_and_troubleshooting/index.md @@ -0,0 +1,8 @@ +# Tips and Troubleshooting + +```{toctree} +:glob: +:maxdepth: 1 + +* +``` diff --git a/docs/guides/troubleshooting_avahi.md b/docs/tips_and_troubleshooting/troubleshooting_avahi.md similarity index 100% rename from docs/guides/troubleshooting_avahi.md rename to docs/tips_and_troubleshooting/troubleshooting_avahi.md From c17fd97dad04a154ce6d26b0a8ffc4e868fdfa23 Mon Sep 17 00:00:00 2001 From: Hasty Granbery Date: Fri, 23 Aug 2024 06:57:11 -0700 Subject: [PATCH 156/165] [HVAC] Sync atomic write error order with spec (#34936) * Add support for Presets attributes and commands to the Thermostat cluster Clean up the Thermostat cluster and remove the TemperatureSetpointHoldPolicy attribute and SetTemperatureSetpointHoldPolicy command * Restyled by whitespace * Restyled by clang-format * Restyled by gn. * Fix build error for Linux configure build of all-clusters-app * Fix Darwin CI issues Editorial fixes * Restyled by clang-format * More fixes * Restyled by clang-format * BUILD.gn fixes for CI * Apply suggestions from code review Co-authored-by: Boris Zbarsky * Address review comments. * Restyled by clang-format * Regenerate Thermostat XML from spec * Move atomic enum to global-enums.xml, actually # Conflicts: # src/app/zap-templates/zcl/data-model/chip/global-structs.xml * Regenerate XML and convert thermostat-server to atomic writes * Pull in ACCapacityFormat typo un-fix * Update Test_TC_TSTAT_1_1 to know about AtomicResponse command. * Restyled patch * Fix weird merge with upstream * Fix emberAfIsTypeSigned not understanding temperature type * Merge fixes from atomic write branch * Relocate thermostat-manager sample code to all-clusters-common * Fix g++ build error on linux * Fix C formatter for long int, cast whole expression * Sync cast fix with master * Add thermostat-common dependency to thermostat app under linux * Remove MatterPostAttributeChangeCallback from thermostat-manager, as it conflicts with other implementations * Convert Atomic enums and structs to global * Restyled patch * Apply suggestions from code review Co-authored-by: Boris Zbarsky * Regen with alchemy 0.6.1 * Updates based on comments * Add TC_MCORE_FS_1_3.py test implementation (#34650) * Fix most TC-SWTCH-2.4 remaining issues (#34677) - Move 2.4 in a better place in the file - Add test steps properly - Allow default button press position override Issue #34656 Testing done: - Test still passes on DUT with automation * Initial test script for Fabric Sync TC_MCORE_FS_1_2 (#34675) * Initial test script for Fabric Sync TC_MCORE_FS_1_2 * Apply suggestions from code review Co-authored-by: C Freeman * Address Review Comments * Address review comments * Fix default timeout after other timeouts changed * Restyled by autopep8 * Fix linter error --------- Co-authored-by: C Freeman Co-authored-by: Restyled.io * Test automation for FabricSync ICD BridgedDeviceBasicInfoCluster (#34628) * WIP Bridged ICD, commissioning to both fabrics * wip testing sending KeepActive * wip most steps implemented * using SIGSTOP and SIGCONT to control ICD server pausing * Update src/python_testing/TC_BRBINFO_4_1.py Co-authored-by: Terence Hampson * comments addressed * more comments addressed * lint pass * Update src/python_testing/TC_BRBINFO_4_1.py Co-authored-by: C Freeman * comments addressed, incl TH_SERVER configurable * added setupQRCode and setupManualCode as options for DUT commissioning * Restyled by autopep8 * Restyled by isort * Update src/python_testing/TC_BRBINFO_4_1.py Co-authored-by: Terence Hampson * Update src/python_testing/TC_BRBINFO_4_1.py Co-authored-by: Terence Hampson * Update src/python_testing/TC_BRBINFO_4_1.py Co-authored-by: Terence Hampson * comments addressed * Restyled by autopep8 --------- Co-authored-by: Terence Hampson Co-authored-by: C Freeman Co-authored-by: Restyled.io * ServiceArea test scripts (#34548) * initial commit * fix bugs * fix issues reported by the linter * fix bug in checking for unique areaDesc * add TC 1.5 * Update src/python_testing/TC_SEAR_1_2.py Co-authored-by: William * Update src/python_testing/TC_SEAR_1_2.py Co-authored-by: William * address code review comments * fix issue introduced by the previous commit * address code review feedback * Update src/python_testing/TC_SEAR_1_2.py Co-authored-by: Kiel Oleson * address code review feedback * remove PICS checked by the TC_SEAR_1.6 * more code review updates * Restyled by autopep8 --------- Co-authored-by: William Co-authored-by: Kiel Oleson Co-authored-by: Restyled.io * Remove manual tests for Thermostat presets (#34679) * Dump details about leaked ExchangeContexts before aborting (#34617) * Dump details about leaked ExchangeContexts before aborting This is implemented via a VerifyOrDieWithObject() variant of the existing VerifyOrDie() macro that calls a DumpToLog() method on the provided object if it exists (otherwise this is simply a no-op). If CHIP_CONFIG_VERBOSE_VERIFY_OR_DIE is not enabled, VerifyOrDieWithObject() simply behaves like a plain VerifyOrDie(). DumpToLog() implementations can use ChipLogFormatRtti to log type information about an object (usually a delegate); if RTTI is disabled this simply outputs whether the object was null or not. * Address review comments * Make gcc happy and improve documentation * Remove unused include * Fix compile error without CHIP_CONFIG_VERBOSE_VERIFY_OR_DIE * Avoid unused parameter warning * [TI] CC13x4_26x4 build fixes (#34682) * lwip pbuf, map file, and hex creation when OTA is disabled * added cc13x4 family define around the non OTA hex creation * whitespace fix * reversed custom factoy data flash with cc13x4 check * more whitespace fixes * [ICD] Add missing polling function to NoWifi connectivity manager (#34684) * Add missing polling function to NoWifi connectivity manager * Update GenericConnectivityManagerImpl_NoWiFi.h Co-authored-by: Boris Zbarsky --------- Co-authored-by: Boris Zbarsky * [OPSTATE] Add Q test script for CountdownTime (#34632) * Add Q test * Added test to test set * Remove unused var * Restyled by autopep8 * Restyled by isort * Fix name * Use pics over other method * Removed unused stuff * Added pipe commands * Fix reset * Get example to report appropriate changes. * WiP * Added some comments * Changes to make things work * Removed dev msgs * Missed some * Removed dev msgs * Straggler * Restyled by clang-format * Restyled by autopep8 * Restyled by isort * Commented unused var * Update examples/all-clusters-app/linux/AllClustersCommandDelegate.cpp * Fix bug --------- Co-authored-by: Restyled.io * YAML update to BRBINFO, ProductId (#34513) * Bridged Device Information Cluster, Attribute ProductID test reflects marking as O, not X * Update src/app/tests/suites/certification/Test_TC_BRBINFO_2_1.yaml Co-authored-by: Terence Hampson * corrected pics * corrected pics * WIP Bridged ICD, commissioning to both fabrics * wip testing sending KeepActive * update to bridged-device-basic-information.xml and zap generated files * removed unrelated file --------- Co-authored-by: Terence Hampson Co-authored-by: Andrei Litvin * Fix simplified Linux tv-casting-app gn build error. (#34692) * adding parallel execution to restyle-diff (#34663) * adding parallel execution to restyle-diff * using xargs to call restyle-paths * fixing Copyright year * restyle the restyler * Add some bits to exercise global structs/enums to Unit Testing cluster. (#34540) * Adds things to the Unit Testing cluster XML. * This requires those things to be enabled in all-clusters-app, all-clusters-minimal-app, and one of the chef contact sensors to pass CI. * That requires an implementation in test-cluster-server * At which point might as well add a YAML test to exercise it all. * [Silabs] Port platform specific Multi-Chip OTA work (#34440) * Pull request #1836: Cherry multi ota Merge in WMN_TOOLS/matter from cherry-multi-ota to silabs_slc_1.3 Squashed commit of the following: commit 4320bb46571658bc44fb82345348265def394991 Author: Michael Rupp Date: Fri May 10 14:26:07 2024 -0400 remove some unwanted diffs in provision files commit be160931dc600de7e7ead378b70d6a43c3945e46 Author: Michael Rupp Date: Fri May 10 14:24:25 2024 -0400 revert changes to generator.project.mak commit 14b6605887166e6d5284a61feb2bf407d850bdcf Author: Michael Rupp Date: Fri May 10 13:06:12 2024 -0400 revert NVM key changes and script changes ... and 8 more commits * Restyled by whitespace * Restyled by clang-format * Restyled by gn * Restyled by autopep8 * remove unused libs caught by linter * update doctree with new readmes * rerun CI, cirque failing for unknown reasons * fix include guards in provision examples * Restyled by clang-format --------- Co-authored-by: Restyled.io * Add python tests for Thermostat presets feature (#34693) * Add python tests for Thermostat presets feature * Restyled by autopep8 * Restyled by isort * Update the PICS code for presets attribute --------- Co-authored-by: Restyled.io * removing unneccessary git fetch (#34698) * Restyle patch * Regen to fix ordering of global structs * Apply suggestions from code review Co-authored-by: Boris Zbarsky * Return correct AtomicResponse when committing or rolling back * Patch tests for atomic write of presets * Fix tests to work with the new setup. Specific changes: * Enable SetActivePresetRequest command in all-clusters-app. * Fix assignment of a PresetStructWithOwnedMembers to another PresetStructWithOwnedMembers to actually work correctly. * Move constraint checks that happen on write from commit to write. * Fix sending of atomic responses to not have use-stack-after-return. * Fix PICS for the tests involved. * Fix PICS values for atomic requests * Remove PresetsSchedulesEditable and QueuedPreset from various places * Restyled patch * Restyled patch, again * Remove PICS value for PresetsSchedulesEditable * clang-tidy fixes * clang-tidy fixes * Clear associated atomic writes when fabric is removed * Add tests for fabric removal and lockout of clients outside of atomic write * Python linter * Restyled patch * Clear timer when fabric is removed * Check for open atomic write before resetting * Revert auto delegate declaration on lines where there's no collision * Allow Thermostat delegate to provide timeout for atomic requests * Relocate thermostat example code to thermostat-common * Remove thermostat-manager code, replace with thermostat delegate * Sync atomic write error order with spec * Restyle patch * Drop memset of atomic write sessions * Add PreCommit stage to allow rollback of multiple attributes when only one fails * Separate OnTimerExpired method, vs ResetWrite * Method documentation * Apply suggestions from code review Co-authored-by: Nivi Sarkar <55898241+nivi-apple@users.noreply.github.com> * Remove unused InWrite check * Drop imcode alias * Switch AtomicWriteState to enum class * DRY up atomic write manager * Apply suggestions from code review Co-authored-by: Nivi Sarkar <55898241+nivi-apple@users.noreply.github.com> * Drop duplicate doc comments * Rename GetAtomicWriteScopedNodeId to GetAtomicWriteOriginatorScopedNodeId * Updates based on comments * Add MatterReportingAttributeChangeCallback calls for updated attributes * Relocate thermostat example code to thermostat-common, and remove thermostat-manager * Merge atomic write code back into thermostat-server * Apply suggestions from code review Co-authored-by: Boris Zbarsky * Fix build after suggestions * Actually track attribute IDs associated with atomic write * Only commit presets if all attribute precommits were successful * Fix scope on err * Add documentation to methods * Remove duplicate preset check. * Move various functions into anonymous namespaces, or Thermostat namespace * Drop impossible non-atomic attribute status after rollback * Namespace workaround for compilers on other platforms * Apply suggestions from code review --------- Co-authored-by: Nivedita Sarkar Co-authored-by: Restyled.io Co-authored-by: Nivi Sarkar <55898241+nivi-apple@users.noreply.github.com> Co-authored-by: Boris Zbarsky Co-authored-by: Terence Hampson Co-authored-by: Tennessee Carmel-Veilleux Co-authored-by: Chris Letnick Co-authored-by: C Freeman Co-authored-by: Douglas Rocha Ferraz Co-authored-by: Petru Lauric <81822411+plauric@users.noreply.github.com> Co-authored-by: William Co-authored-by: Kiel Oleson Co-authored-by: Karsten Sperling <113487422+ksperling-apple@users.noreply.github.com> Co-authored-by: Anu Biradar <104591549+abiradarti@users.noreply.github.com> Co-authored-by: mkardous-silabs <84793247+mkardous-silabs@users.noreply.github.com> Co-authored-by: Rob Bultman Co-authored-by: Andrei Litvin Co-authored-by: Shao Ling Tan <161761051+shaoltan-amazon@users.noreply.github.com> Co-authored-by: Amine Alami <43780877+Alami-Amine@users.noreply.github.com> Co-authored-by: Michael Rupp <95718139+mykrupp@users.noreply.github.com> --- examples/all-clusters-app/linux/BUILD.gn | 4 +- examples/thermostat/linux/BUILD.gn | 8 +- .../linux/include/thermostat-manager.h | 73 -- examples/thermostat/linux/main.cpp | 16 +- .../thermostat/linux/thermostat-manager.cpp | 497 -------- .../thermostat/thermostat-common/BUILD.gn | 4 + .../include/thermostat-delegate-impl.h | 6 +- .../src}/thermostat-delegate-impl.cpp | 88 +- src/app/chip_data_model.gni | 2 + .../thermostat-server/thermostat-delegate.h | 13 +- .../thermostat-server-atomic.cpp | 644 ++++++++++ .../thermostat-server-presets.cpp | 546 ++++++++ .../thermostat-server/thermostat-server.cpp | 1113 ++--------------- .../thermostat-server/thermostat-server.h | 163 ++- src/python_testing/TC_TSTAT_4_2.py | 50 +- 15 files changed, 1542 insertions(+), 1685 deletions(-) delete mode 100644 examples/thermostat/linux/include/thermostat-manager.h delete mode 100644 examples/thermostat/linux/thermostat-manager.cpp rename examples/thermostat/{linux => thermostat-common}/include/thermostat-delegate-impl.h (92%) rename examples/thermostat/{linux => thermostat-common/src}/thermostat-delegate-impl.cpp (75%) create mode 100644 src/app/clusters/thermostat-server/thermostat-server-atomic.cpp create mode 100644 src/app/clusters/thermostat-server/thermostat-server-presets.cpp diff --git a/examples/all-clusters-app/linux/BUILD.gn b/examples/all-clusters-app/linux/BUILD.gn index ed228b51b2..baac52014d 100644 --- a/examples/all-clusters-app/linux/BUILD.gn +++ b/examples/all-clusters-app/linux/BUILD.gn @@ -75,7 +75,7 @@ source_set("chip-all-clusters-common") { "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/src/EnergyEvseTargetsStore.cpp", "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/src/energy-evse-mode.cpp", "${chip_root}/examples/energy-management-app/energy-management-common/energy-reporting/src/ElectricalPowerMeasurementDelegate.cpp", - "${chip_root}/examples/thermostat/linux/thermostat-delegate-impl.cpp", + "${chip_root}/examples/thermostat/thermostat-common/src/thermostat-delegate-impl.cpp", "AllClustersCommandDelegate.cpp", "AllClustersCommandDelegate.h", "AppOptions.cpp", @@ -102,7 +102,7 @@ source_set("chip-all-clusters-common") { "${chip_root}/examples/energy-management-app/energy-management-common/device-energy-management/include", "${chip_root}/examples/energy-management-app/energy-management-common/energy-evse/include", "${chip_root}/examples/energy-management-app/energy-management-common/energy-reporting/include", - "${chip_root}/examples/thermostat/linux/include", + "${chip_root}/examples/thermostat/thermostat-common/include", ] if (chip_enable_pw_rpc) { diff --git a/examples/thermostat/linux/BUILD.gn b/examples/thermostat/linux/BUILD.gn index 71c0eccfcf..0683b39abb 100644 --- a/examples/thermostat/linux/BUILD.gn +++ b/examples/thermostat/linux/BUILD.gn @@ -17,11 +17,10 @@ import("//build_overrides/chip.gni") executable("thermostat-app") { sources = [ + "${chip_root}/examples/thermostat/thermostat-common/src/thermostat-delegate-impl.cpp", "include/low-power/LowPowerManager.cpp", "include/low-power/LowPowerManager.h", "main.cpp", - "thermostat-delegate-impl.cpp", - "thermostat-manager.cpp", ] deps = [ @@ -30,7 +29,10 @@ executable("thermostat-app") { "${chip_root}/src/lib", ] - include_dirs = [ "include" ] + include_dirs = [ + "include", + "${chip_root}/examples/thermostat/thermostat-common/include", + ] cflags = [ "-Wconversion" ] diff --git a/examples/thermostat/linux/include/thermostat-manager.h b/examples/thermostat/linux/include/thermostat-manager.h deleted file mode 100644 index 274f66c669..0000000000 --- a/examples/thermostat/linux/include/thermostat-manager.h +++ /dev/null @@ -1,73 +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 - -class ThermostatManager -{ -public: - CHIP_ERROR Init(); - - /// @brief Callback called when any attribute changed on the device - void AttributeChangeHandler(chip::EndpointId endpointId, chip::ClusterId clusterId, chip::AttributeId attributeId, - uint8_t * value, uint16_t size); - - chip::app::Clusters::Thermostat::SystemModeEnum GetSystemMode(); - chip::app::Clusters::Thermostat::ThermostatRunningModeEnum GetRunningMode(); - int16_t GetCurrentTemperature(); - int16_t GetCurrentHeatingSetPoint(); - int16_t GetCurrentCoolingSetPoint(); - uint8_t GetNumberOfPresets(); - CHIP_ERROR SetSystemMode(chip::app::Clusters::Thermostat::SystemModeEnum systemMode); - CHIP_ERROR SetRunningMode(chip::app::Clusters::Thermostat::ThermostatRunningModeEnum runningMode); - CHIP_ERROR SetCurrentTemperature(int16_t temperature); - CHIP_ERROR SetCurrentHeatingSetPoint(int16_t heatingSetpoint); - CHIP_ERROR SetCurrentCoolingSetPoint(int16_t coolingSetpoint); - -private: - friend ThermostatManager & ThermostatMgr(); - - chip::app::Clusters::Thermostat::SystemModeEnum mSystemMode; - chip::app::Clusters::Thermostat::ThermostatRunningModeEnum mRunningMode; - int16_t mLocalTemperature; - int16_t mOccupiedCoolingSetpoint; - int16_t mOccupiedHeatingSetpoint; - uint8_t mOccupiedSetback; - - static ThermostatManager sThermostatMgr; - - /// @brief attribute handler for the thermostat endpoint - void ThermostatEndpointAttributeChangeHandler(chip::ClusterId clusterId, chip::AttributeId attributeId, uint8_t * value, - uint16_t size); - void ThermostatClusterAttributeChangeHandler(chip::AttributeId attributeId, uint8_t * value, uint16_t size); - void LocalTemperatureMeasurementEndpointAttributeChangeHandler(chip::ClusterId clusterId, chip::AttributeId attributeId, - uint8_t * value, uint16_t size); - void LocalTemperatureMeasurementClusterAttributeChangeHandler(chip::AttributeId attributeId, uint8_t * value, uint16_t size); - - /// @brief Main method that evaluates the current thermostat state and updates attributes - void EvalThermostatState(); - void UpdateRunningModeForHeating(); - void UpdateRunningModeForCooling(); -}; - -inline ThermostatManager & ThermostatMgr() -{ - return ThermostatManager::sThermostatMgr; -} diff --git a/examples/thermostat/linux/main.cpp b/examples/thermostat/linux/main.cpp index 2279f02bef..b9f82696e8 100644 --- a/examples/thermostat/linux/main.cpp +++ b/examples/thermostat/linux/main.cpp @@ -22,8 +22,6 @@ #include #include -#include "thermostat-manager.h" - using namespace chip; using namespace chip::app; // using namespace chip::app::Clusters; @@ -76,19 +74,7 @@ void ApplicationShutdown() {} int main(int argc, char * argv[]) { - if (ChipLinuxAppInit(argc, argv) != 0) - { - return -1; - } - ChipLogProgress(Zcl, "Starting Thermostat Manager"); - CHIP_ERROR err = ThermostatManager().Init(); - - if (err != CHIP_NO_ERROR) - { - ChipLogError(AppServer, "Failed to initialize thermostat manager: %" CHIP_ERROR_FORMAT, err.Format()); - chip::DeviceLayer::PlatformMgr().Shutdown(); - return -1; - } + VerifyOrDie(ChipLinuxAppInit(argc, argv) == 0); ChipLinuxAppMainLoop(); return 0; } diff --git a/examples/thermostat/linux/thermostat-manager.cpp b/examples/thermostat/linux/thermostat-manager.cpp deleted file mode 100644 index ea1f4375c1..0000000000 --- a/examples/thermostat/linux/thermostat-manager.cpp +++ /dev/null @@ -1,497 +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. - */ - -/********************************************************** - * Includes - *********************************************************/ - -#include -#include - -#include -#include -#include -#include - -/********************************************************** - * Defines and Constants - *********************************************************/ - -using namespace chip; -using namespace chip::app; -using namespace chip::app::DataModel; -using namespace chip::Controller; -using namespace chip::app::Clusters; -using namespace chip::app::Clusters::Thermostat; -using namespace chip::app::Clusters::Thermostat::Structs; -using namespace chip::app::Clusters::Thermostat::Attributes; -using namespace chip::app::Clusters::TemperatureMeasurement; -using namespace chip::app::Clusters::TemperatureMeasurement::Attributes; -using namespace Protocols::InteractionModel; - -using namespace chip::DeviceLayer; - -static constexpr EndpointId kThermostatEndpoint = 1; - -static constexpr uint16_t kMaxIntervalCeilingSeconds = 3600; - -static const char * SystemModeString(SystemModeEnum systemMode); -static const char * RunningModeString(ThermostatRunningModeEnum runningMode); - -/********************************************************** - * Variable declarations - *********************************************************/ - -ThermostatManager ThermostatManager::sThermostatMgr; - -namespace { - -template -static void OnAttributeChangeReported(const ConcreteDataAttributePath & path, const DecodableAttributeType & value); - -template <> -void OnAttributeChangeReported(const ConcreteDataAttributePath & path, - const MeasuredValue::TypeInfo::DecodableType & value) -{ - ClusterId clusterId = path.mClusterId; - if (clusterId != TemperatureMeasurement::Id) - { - ChipLogError(AppServer, - "Attribute change reported for TemperatureMeasurement cluster on incorrect cluster id " ChipLogFormatMEI, - ChipLogValueMEI(clusterId)); - return; - } - - AttributeId attributeId = path.mAttributeId; - if (attributeId != MeasuredValue::Id) - { - ChipLogError(AppServer, - "Attribute change reported for TemperatureMeasurement cluster for incorrect attribute" ChipLogFormatMEI, - ChipLogValueMEI(attributeId)); - return; - } - - if (!value.IsNull()) - { - ChipLogDetail(AppServer, "Attribute change reported for TemperatureMeasurement cluster - MeasuredValue is %d", - value.Value()); - } -} - -static void OnError(const ConcreteDataAttributePath * path, ChipError err) -{ - ChipLogError(AppServer, - "Subscribing to cluster Id " ChipLogFormatMEI " and attribute Id " ChipLogFormatMEI - " failed with error %" CHIP_ERROR_FORMAT, - ChipLogValueMEI(path->mClusterId), ChipLogValueMEI(path->mAttributeId), err.Format()); -} - -static void OnSubscriptionEstablished(const ReadClient & client, unsigned int value) -{ - ChipLogDetail(AppServer, "OnSubscriptionEstablished with subscription Id: %d", value); -} - -template -void SubscribeToAttribute(ClusterId clusterId, AttributeId attributeId, const EmberBindingTableEntry & binding, - OperationalDeviceProxy * peer_device) -{ - VerifyOrReturn(peer_device->GetSecureSession().HasValue(), - ChipLogError(AppServer, "SubscribeToAttribute failed. Secure session is null")); - - SubscribeAttribute( - peer_device->GetExchangeManager(), peer_device->GetSecureSession().Value(), binding.remote, clusterId, attributeId, - &OnAttributeChangeReported, &OnError, 0, kMaxIntervalCeilingSeconds, &OnSubscriptionEstablished, - nullptr, true /* fabricFiltered */, false /* keepExistingSubscription */); -} - -static void ThermostatBoundDeviceChangedHandler(const EmberBindingTableEntry & binding, OperationalDeviceProxy * peer_device, - void * context) -{ - VerifyOrReturn(binding.clusterId.has_value(), ChipLogError(AppServer, "Cluster Id is null")); - ClusterId clusterId = binding.clusterId.value(); - - switch (clusterId) - { - case TemperatureMeasurement::Id: - - // Subscribe to the MeasuredValue attribute - SubscribeToAttribute(clusterId, MeasuredValue::Id, binding, peer_device); - break; - default: - ChipLogError(AppServer, "Unsupported Cluster Id"); - break; - } -} - -void NotifyBoundClusterChangedForAllClusters() -{ - BindingManager::GetInstance().NotifyBoundClusterChanged(kThermostatEndpoint, TemperatureMeasurement::Id, nullptr); -} - -static void OnPlatformChipDeviceEvent(const DeviceLayer::ChipDeviceEvent * event, intptr_t arg) -{ - if (event->Type == DeviceLayer::DeviceEventType::kBindingsChangedViaCluster) - { - NotifyBoundClusterChangedForAllClusters(); - } -} - -void InitBindingManager(intptr_t context) -{ - auto & server = Server::GetInstance(); - CHIP_ERROR error = BindingManager::GetInstance().Init( - { &server.GetFabricTable(), server.GetCASESessionManager(), &server.GetPersistentStorage() }); - - if (error != CHIP_NO_ERROR) - { - ChipLogError(AppServer, "Failed to init binding manager"); - } - - BindingManager::GetInstance().RegisterBoundDeviceChangedHandler(ThermostatBoundDeviceChangedHandler); - NotifyBoundClusterChangedForAllClusters(); -} - -} // anonymous namespace - -CHIP_ERROR ThermostatManager::Init() -{ - // Init binding manager - - DeviceLayer::PlatformMgr().AddEventHandler(OnPlatformChipDeviceEvent, reinterpret_cast(this)); - DeviceLayer::PlatformMgr().ScheduleWork(InitBindingManager); - - mLocalTemperature = GetCurrentTemperature(); - mSystemMode = GetSystemMode(); - mRunningMode = GetRunningMode(); - mOccupiedCoolingSetpoint = GetCurrentCoolingSetPoint(); - mOccupiedHeatingSetpoint = GetCurrentHeatingSetPoint(); - // TODO: Gotta expose this properly on attribute - mOccupiedSetback = 5; // 0.5 C - - ChipLogError(AppServer, - "Initialized a thermostat with \n " - "mSystemMode: %u (%s) \n mRunningMode: %u (%s) \n mLocalTemperature: %d \n mOccupiedHeatingSetpoint: %d \n " - "mOccupiedCoolingSetpoint: %d" - "NumberOfPresets: %d", - to_underlying(mSystemMode), SystemModeString(mSystemMode), to_underlying(mRunningMode), - RunningModeString(mRunningMode), mLocalTemperature, mOccupiedHeatingSetpoint, mOccupiedCoolingSetpoint, - GetNumberOfPresets()); - - // TODO: Should this be called later? - EvalThermostatState(); - - return CHIP_NO_ERROR; -} - -void ThermostatManager::AttributeChangeHandler(EndpointId endpointId, ClusterId clusterId, AttributeId attributeId, uint8_t * value, - uint16_t size) -{ - switch (endpointId) - { - case kThermostatEndpoint: - ThermostatEndpointAttributeChangeHandler(clusterId, attributeId, value, size); - break; - - default: - ChipLogError(AppServer, "Attribute change reported for Thermostat on incorrect endpoint. Ignoring."); - break; - } -} - -void ThermostatManager::ThermostatEndpointAttributeChangeHandler(ClusterId clusterId, AttributeId attributeId, uint8_t * value, - uint16_t size) -{ - switch (clusterId) - { - case Thermostat::Id: - ThermostatClusterAttributeChangeHandler(attributeId, value, size); - break; - - default: - ChipLogError(AppServer, - "Attribute change reported for Thermostat on incorrect cluster for the thermostat endpoint. Ignoring."); - break; - } -} - -void ThermostatManager::ThermostatClusterAttributeChangeHandler(AttributeId attributeId, uint8_t * value, uint16_t size) -{ - switch (attributeId) - { - case LocalTemperature::Id: { - memcpy(&mLocalTemperature, value, size); - ChipLogError(AppServer, "Local temperature changed to %d", mLocalTemperature); - EvalThermostatState(); - } - break; - - case OccupiedCoolingSetpoint::Id: { - memcpy(&mOccupiedCoolingSetpoint, value, size); - ChipLogError(AppServer, "Cooling temperature changed to %d", mOccupiedCoolingSetpoint); - EvalThermostatState(); - } - break; - - case OccupiedHeatingSetpoint::Id: { - memcpy(&mOccupiedHeatingSetpoint, value, size); - ChipLogError(AppServer, "Heating temperature changed to %d", mOccupiedHeatingSetpoint); - EvalThermostatState(); - } - break; - - case SystemMode::Id: { - mSystemMode = static_cast(*value); - ChipLogError(AppServer, "System mode changed to %u (%s)", *value, SystemModeString(mSystemMode)); - EvalThermostatState(); - } - break; - - case ThermostatRunningMode::Id: { - mRunningMode = static_cast(*value); - ChipLogError(AppServer, "Running mode changed to %u (%s)", *value, RunningModeString(mRunningMode)); - } - break; - - default: { - ChipLogError(AppServer, "Unhandled thermostat attribute %u", static_cast(attributeId)); - return; - } - break; - } -} - -SystemModeEnum ThermostatManager::GetSystemMode() -{ - SystemModeEnum systemMode; - SystemMode::Get(kThermostatEndpoint, &systemMode); - return systemMode; -} - -ThermostatRunningModeEnum ThermostatManager::GetRunningMode() -{ - ThermostatRunningModeEnum runningMode; - ThermostatRunningMode::Get(kThermostatEndpoint, &runningMode); - return runningMode; -} - -int16_t ThermostatManager::GetCurrentTemperature() -{ - DataModel::Nullable currentTemperature; - currentTemperature.SetNull(); - LocalTemperature::Get(kThermostatEndpoint, currentTemperature); - return currentTemperature.ValueOr(0); -} - -int16_t ThermostatManager::GetCurrentHeatingSetPoint() -{ - int16_t heatingSetpoint; - OccupiedHeatingSetpoint::Get(kThermostatEndpoint, &heatingSetpoint); - return heatingSetpoint; -} - -int16_t ThermostatManager::GetCurrentCoolingSetPoint() -{ - int16_t coolingSetpoint; - OccupiedCoolingSetpoint::Get(kThermostatEndpoint, &coolingSetpoint); - return coolingSetpoint; -} - -uint8_t ThermostatManager::GetNumberOfPresets() -{ - return ThermostatDelegate::GetInstance().GetNumberOfPresets(); -} - -CHIP_ERROR ThermostatManager::SetSystemMode(SystemModeEnum systemMode) -{ - uint8_t systemModeValue = to_underlying(systemMode); - if (mSystemMode == systemMode) - { - ChipLogDetail(AppServer, "Already in system mode: %u (%s)", systemModeValue, SystemModeString(systemMode)); - return CHIP_NO_ERROR; - } - - ChipLogError(AppServer, "Setting system mode: %u (%s)", systemModeValue, SystemModeString(systemMode)); - return CHIP_ERROR_IM_GLOBAL_STATUS_VALUE(SystemMode::Set(kThermostatEndpoint, systemMode)); -} - -CHIP_ERROR ThermostatManager::SetRunningMode(ThermostatRunningModeEnum runningMode) -{ - uint8_t runningModeValue = to_underlying(runningMode); - if (mRunningMode == runningMode) - { - ChipLogDetail(AppServer, "Already in running mode: %u (%s)", runningModeValue, RunningModeString(runningMode)); - return CHIP_NO_ERROR; - } - - ChipLogError(AppServer, "Setting running mode: %u (%s)", runningModeValue, RunningModeString(runningMode)); - return CHIP_ERROR_IM_GLOBAL_STATUS_VALUE(ThermostatRunningMode::Set(kThermostatEndpoint, runningMode)); -} - -CHIP_ERROR ThermostatManager::SetCurrentTemperature(int16_t temperature) -{ - return CHIP_ERROR_IM_GLOBAL_STATUS_VALUE(LocalTemperature::Set(kThermostatEndpoint, temperature)); -} - -CHIP_ERROR ThermostatManager::SetCurrentHeatingSetPoint(int16_t heatingSetpoint) -{ - return CHIP_ERROR_IM_GLOBAL_STATUS_VALUE(OccupiedHeatingSetpoint::Set(kThermostatEndpoint, heatingSetpoint)); -} - -CHIP_ERROR ThermostatManager::SetCurrentCoolingSetPoint(int16_t coolingSetpoint) -{ - return CHIP_ERROR_IM_GLOBAL_STATUS_VALUE(OccupiedCoolingSetpoint::Set(kThermostatEndpoint, coolingSetpoint)); -} - -void ThermostatManager::EvalThermostatState() -{ - ChipLogError(AppServer, - "Eval Thermostat Running Mode \n " - "mSystemMode: %u (%s) \n mRunningMode: %u (%s) \n mLocalTemperature: %d \n mOccupiedHeatingSetpoint: %d \n " - "mOccupiedCoolingSetpoint: %d", - to_underlying(mSystemMode), SystemModeString(mSystemMode), to_underlying(mRunningMode), - RunningModeString(mRunningMode), mLocalTemperature, mOccupiedHeatingSetpoint, mOccupiedCoolingSetpoint); - - switch (mSystemMode) - { - case SystemModeEnum::kOff: { - SetRunningMode(ThermostatRunningModeEnum::kOff); - break; - } - case SystemModeEnum::kHeat: { - UpdateRunningModeForHeating(); - break; - } - case SystemModeEnum::kCool: { - UpdateRunningModeForCooling(); - break; - } - case SystemModeEnum::kAuto: { - UpdateRunningModeForHeating(); - UpdateRunningModeForCooling(); - break; - } - default: - break; - } -} - -void ThermostatManager::UpdateRunningModeForHeating() -{ - const int16_t heatingOnThreshold = mOccupiedHeatingSetpoint - static_cast(mOccupiedSetback * 10); - const int16_t heatingOffThreshold = mOccupiedHeatingSetpoint + static_cast(mOccupiedSetback * 10); - - if (mRunningMode == ThermostatRunningModeEnum::kHeat) - { - if (mLocalTemperature >= heatingOffThreshold) - { - ChipLogDetail(AppServer, "Eval Heat - Turning off"); - SetRunningMode(ThermostatRunningModeEnum::kOff); - } - else - { - ChipLogDetail(AppServer, "Eval Heat - Keep Heating"); - } - } - else - { - if (mLocalTemperature <= heatingOnThreshold) - { - ChipLogDetail(AppServer, "Eval Heat - Turn on"); - SetRunningMode(ThermostatRunningModeEnum::kHeat); - } - else - { - ChipLogDetail(AppServer, "Eval Heat - Nothing to do"); - } - } -} - -void ThermostatManager::UpdateRunningModeForCooling() -{ - const int16_t coolingOffThreshold = mOccupiedCoolingSetpoint - static_cast(mOccupiedSetback * 10); - const int16_t coolingOnThreshold = mOccupiedCoolingSetpoint + static_cast(mOccupiedSetback * 10); - - if (mRunningMode == ThermostatRunningModeEnum::kCool) - { - if (mLocalTemperature <= coolingOffThreshold) - { - ChipLogDetail(AppServer, "Eval Cool - Turning off"); - SetRunningMode(ThermostatRunningModeEnum::kOff); - } - else - { - ChipLogDetail(AppServer, "Eval Cool - Keep Cooling"); - } - } - else - { - if (mLocalTemperature >= coolingOnThreshold) - { - ChipLogDetail(AppServer, "Eval Cool - Turn on"); - SetRunningMode(ThermostatRunningModeEnum::kCool); - } - else - { - ChipLogDetail(AppServer, "Eval Cool - Nothing to do"); - } - } -} - -static const char * SystemModeString(SystemModeEnum systemMode) -{ - switch (systemMode) - { - case SystemModeEnum::kOff: - return "Off"; - case SystemModeEnum::kAuto: - return "Auto"; - case SystemModeEnum::kCool: - return "Cool"; - case SystemModeEnum::kHeat: - return "Heat"; - default: - return "Unknown"; - } -} - -static const char * RunningModeString(ThermostatRunningModeEnum runningMode) -{ - switch (runningMode) - { - case ThermostatRunningModeEnum::kOff: - return "Off"; - case ThermostatRunningModeEnum::kCool: - return "Cool"; - case ThermostatRunningModeEnum::kHeat: - return "Heat"; - default: - return "Unknown"; - } -} - -void emberAfThermostatClusterInitCallback(EndpointId endpoint) -{ - ChipLogProgress(Zcl, "Starting Thermostat Manager"); - ThermostatManager().Init(); - - // Register the delegate for the Thermostat - auto & delegate = ThermostatDelegate::GetInstance(); - // Set the default delegate for endpoint kThermostatEndpoint. - VerifyOrDie(endpoint == kThermostatEndpoint); - SetDefaultDelegate(endpoint, &delegate); -} diff --git a/examples/thermostat/thermostat-common/BUILD.gn b/examples/thermostat/thermostat-common/BUILD.gn index 93a0c7540f..1f8f839b4a 100644 --- a/examples/thermostat/thermostat-common/BUILD.gn +++ b/examples/thermostat/thermostat-common/BUILD.gn @@ -16,6 +16,10 @@ import("//build_overrides/chip.gni") import("${chip_root}/src/app/chip_data_model.gni") +config("config") { + include_dirs = [ "include" ] +} + chip_data_model("thermostat-common") { zap_file = "thermostat.zap" is_server = true diff --git a/examples/thermostat/linux/include/thermostat-delegate-impl.h b/examples/thermostat/thermostat-common/include/thermostat-delegate-impl.h similarity index 92% rename from examples/thermostat/linux/include/thermostat-delegate-impl.h rename to examples/thermostat/thermostat-common/include/thermostat-delegate-impl.h index 6bf9d02cea..9edf13f839 100644 --- a/examples/thermostat/linux/include/thermostat-delegate-impl.h +++ b/examples/thermostat/thermostat-common/include/thermostat-delegate-impl.h @@ -44,9 +44,7 @@ class ThermostatDelegate : public Delegate public: static inline ThermostatDelegate & GetInstance() { return sInstance; } - std::optional - GetAtomicWriteTimeout(DataModel::DecodableList attributeRequests, - System::Clock::Milliseconds16 timeoutRequest) override; + std::optional GetMaxAtomicWriteTimeout(chip::AttributeId attributeId) override; CHIP_ERROR GetPresetTypeAtIndex(size_t index, Structs::PresetTypeStruct::Type & presetType) override; @@ -64,7 +62,7 @@ class ThermostatDelegate : public Delegate CHIP_ERROR GetPendingPresetAtIndex(size_t index, PresetStructWithOwnedMembers & preset) override; - CHIP_ERROR ApplyPendingPresets() override; + CHIP_ERROR CommitPendingPresets() override; void ClearPendingPresetList() override; diff --git a/examples/thermostat/linux/thermostat-delegate-impl.cpp b/examples/thermostat/thermostat-common/src/thermostat-delegate-impl.cpp similarity index 75% rename from examples/thermostat/linux/thermostat-delegate-impl.cpp rename to examples/thermostat/thermostat-common/src/thermostat-delegate-impl.cpp index b931db20b7..8c411cd5a9 100644 --- a/examples/thermostat/linux/thermostat-delegate-impl.cpp +++ b/examples/thermostat/thermostat-common/src/thermostat-delegate-impl.cpp @@ -17,7 +17,6 @@ */ #include -#include #include #include @@ -36,34 +35,12 @@ ThermostatDelegate::ThermostatDelegate() mNextFreeIndexInPresetsList = 0; mNextFreeIndexInPendingPresetsList = 0; - InitializePresetTypes(); InitializePresets(); memset(mActivePresetHandleData, 0, sizeof(mActivePresetHandleData)); mActivePresetHandleDataSize = 0; } -void ThermostatDelegate::InitializePresetTypes() -{ - PresetScenarioEnum presetScenarioEnumArray[kMaxNumberOfPresetTypes] = { - PresetScenarioEnum::kOccupied, PresetScenarioEnum::kUnoccupied, PresetScenarioEnum::kSleep, - PresetScenarioEnum::kWake, PresetScenarioEnum::kVacation, PresetScenarioEnum::kGoingToSleep - }; - static_assert(ArraySize(presetScenarioEnumArray) <= ArraySize(mPresetTypes)); - - uint8_t index = 0; - for (PresetScenarioEnum presetScenario : presetScenarioEnumArray) - { - mPresetTypes[index].presetScenario = presetScenario; - mPresetTypes[index].numberOfPresets = kMaxNumberOfPresetsOfEachType; - mPresetTypes[index].presetTypeFeatures = - (presetScenario == PresetScenarioEnum::kOccupied || presetScenario == PresetScenarioEnum::kUnoccupied) - ? PresetTypeFeaturesBitmap::kAutomatic - : PresetTypeFeaturesBitmap::kSupportsNames; - index++; - } -} - void ThermostatDelegate::InitializePresets() { // Initialize the presets with 2 built in presets - occupied and unoccupied. @@ -94,9 +71,26 @@ void ThermostatDelegate::InitializePresets() CHIP_ERROR ThermostatDelegate::GetPresetTypeAtIndex(size_t index, PresetTypeStruct::Type & presetType) { - if (index < ArraySize(mPresetTypes)) + static PresetTypeStruct::Type presetTypes[] = { + { .presetScenario = PresetScenarioEnum::kOccupied, + .numberOfPresets = kMaxNumberOfPresetsOfEachType, + .presetTypeFeatures = to_underlying(PresetTypeFeaturesBitmap::kAutomatic) }, + { .presetScenario = PresetScenarioEnum::kUnoccupied, + .numberOfPresets = kMaxNumberOfPresetsOfEachType, + .presetTypeFeatures = to_underlying(PresetTypeFeaturesBitmap::kAutomatic) }, + { .presetScenario = PresetScenarioEnum::kSleep, + .numberOfPresets = kMaxNumberOfPresetsOfEachType, + .presetTypeFeatures = to_underlying(PresetTypeFeaturesBitmap::kSupportsNames) }, + { .presetScenario = PresetScenarioEnum::kWake, + .numberOfPresets = kMaxNumberOfPresetsOfEachType, + .presetTypeFeatures = to_underlying(PresetTypeFeaturesBitmap::kSupportsNames) }, + { .presetScenario = PresetScenarioEnum::kVacation, + .numberOfPresets = kMaxNumberOfPresetsOfEachType, + .presetTypeFeatures = to_underlying(PresetTypeFeaturesBitmap::kSupportsNames) }, + }; + if (index < ArraySize(presetTypes)) { - presetType = mPresetTypes[index]; + presetType = presetTypes[index]; return CHIP_NO_ERROR; } return CHIP_ERROR_PROVIDER_LIST_EXHAUSTED; @@ -158,45 +152,19 @@ CHIP_ERROR ThermostatDelegate::SetActivePresetHandle(const DataModel::Nullable -ThermostatDelegate::GetAtomicWriteTimeout(DataModel::DecodableList attributeRequests, - System::Clock::Milliseconds16 timeoutRequest) +std::optional ThermostatDelegate::GetMaxAtomicWriteTimeout(chip::AttributeId attributeId) { - auto attributeIdsIter = attributeRequests.begin(); - bool requestedPresets = false, requestedSchedules = false; - while (attributeIdsIter.Next()) - { - auto & attributeId = attributeIdsIter.GetValue(); - - switch (attributeId) - { - case Attributes::Presets::Id: - requestedPresets = true; - break; - case Attributes::Schedules::Id: - requestedSchedules = true; - break; - default: - return System::Clock::Milliseconds16(0); - } - } - if (attributeIdsIter.GetStatus() != CHIP_NO_ERROR) - { - return System::Clock::Milliseconds16(0); - } - auto timeout = System::Clock::Milliseconds16(0); - if (requestedPresets) + switch (attributeId) { + case Attributes::Presets::Id: // If the client expects to edit the presets, then we'll give it 3 seconds to do so - timeout += std::chrono::milliseconds(3000); - } - if (requestedSchedules) - { + return std::chrono::milliseconds(3000); + case Attributes::Schedules::Id: // If the client expects to edit the schedules, then we'll give it 9 seconds to do so - timeout += std::chrono::milliseconds(9000); + return std::chrono::milliseconds(9000); + default: + return std::nullopt; } - // If the client requested an even smaller timeout, then use that one - return std::min(timeoutRequest, timeout); } void ThermostatDelegate::InitializePendingPresets() @@ -238,7 +206,7 @@ CHIP_ERROR ThermostatDelegate::GetPendingPresetAtIndex(size_t index, PresetStruc return CHIP_ERROR_PROVIDER_LIST_EXHAUSTED; } -CHIP_ERROR ThermostatDelegate::ApplyPendingPresets() +CHIP_ERROR ThermostatDelegate::CommitPendingPresets() { mNextFreeIndexInPresetsList = 0; for (uint8_t indexInPendingPresets = 0; indexInPendingPresets < mNextFreeIndexInPendingPresetsList; indexInPendingPresets++) diff --git a/src/app/chip_data_model.gni b/src/app/chip_data_model.gni index 3e4448a3be..01d47a47cb 100644 --- a/src/app/chip_data_model.gni +++ b/src/app/chip_data_model.gni @@ -428,6 +428,8 @@ template("chip_data_model") { ] } else if (cluster == "thermostat-server") { sources += [ + "${_app_root}/clusters/${cluster}/${cluster}-atomic.cpp", + "${_app_root}/clusters/${cluster}/${cluster}-presets.cpp", "${_app_root}/clusters/${cluster}/${cluster}.cpp", "${_app_root}/clusters/${cluster}/${cluster}.h", "${_app_root}/clusters/${cluster}/PresetStructWithOwnedMembers.cpp", diff --git a/src/app/clusters/thermostat-server/thermostat-delegate.h b/src/app/clusters/thermostat-server/thermostat-delegate.h index 0f89f69468..ccb690a34f 100644 --- a/src/app/clusters/thermostat-server/thermostat-delegate.h +++ b/src/app/clusters/thermostat-server/thermostat-delegate.h @@ -39,15 +39,12 @@ class Delegate virtual ~Delegate() = default; /** - * @brief Get the maximum timeout for atomically writing to a set of attributes + * @brief Get the maximum timeout for atomically writing to an attribute * - * @param[in] attributeRequests The list of attributes to write to. - * @param[out] timeoutRequest The timeout proposed by the client. - * @return The maximum allowed timeout; zero if the request is invalid. + * @param[in] attributeId The attribute to write to. + * @return The maximum allowed timeout; nullopt if the request is invalid. */ - virtual std::optional - GetAtomicWriteTimeout(DataModel::DecodableList attributeRequests, - System::Clock::Milliseconds16 timeoutRequest) = 0; + virtual std::optional GetMaxAtomicWriteTimeout(chip::AttributeId attributeId) = 0; /** * @brief Get the preset type at a given index in the PresetTypes attribute @@ -129,7 +126,7 @@ class Delegate * @return CHIP_ERROR if the updates to the presets attribute failed to commit for some reason. * */ - virtual CHIP_ERROR ApplyPendingPresets() = 0; + virtual CHIP_ERROR CommitPendingPresets() = 0; /** * @brief Clears the pending presets list. diff --git a/src/app/clusters/thermostat-server/thermostat-server-atomic.cpp b/src/app/clusters/thermostat-server/thermostat-server-atomic.cpp new file mode 100644 index 0000000000..2a6e52e504 --- /dev/null +++ b/src/app/clusters/thermostat-server/thermostat-server-atomic.cpp @@ -0,0 +1,644 @@ +/** + * + * 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 "thermostat-server.h" + +#include + +using namespace chip; +using namespace chip::app; +using namespace chip::app::Clusters; +using namespace chip::app::Clusters::Thermostat; +using namespace chip::app::Clusters::Thermostat::Attributes; +using namespace chip::app::Clusters::Thermostat::Structs; +using namespace chip::app::Clusters::Globals::Structs; +using namespace chip::Protocols::InteractionModel; + +namespace chip { +namespace app { +namespace Clusters { +namespace Thermostat { + +extern ThermostatAttrAccess gThermostatAttrAccess; + +/** + * @brief Callback that is called when the timeout for editing the presets expires. + * + * @param[in] systemLayer The system layer. + * @param[in] callbackContext The context passed to the timer callback. + */ +void TimerExpiredCallback(System::Layer * systemLayer, void * callbackContext) +{ + EndpointId endpoint = static_cast(reinterpret_cast(callbackContext)); + gThermostatAttrAccess.ResetAtomicWrite(endpoint); +} + +/** + * @brief Schedules a timer for the given timeout in milliseconds. + * + * @param[in] endpoint The endpoint to use. + * @param[in] timeoutMilliseconds The timeout in milliseconds. + */ +void ScheduleTimer(EndpointId endpoint, System::Clock::Milliseconds16 timeout) +{ + DeviceLayer::SystemLayer().StartTimer(timeout, TimerExpiredCallback, + reinterpret_cast(static_cast(endpoint))); +} + +/** + * @brief Clears the currently scheduled timer. + * + * @param[in] endpoint The endpoint to use. + */ +void ClearTimer(EndpointId endpoint) +{ + DeviceLayer::SystemLayer().CancelTimer(TimerExpiredCallback, reinterpret_cast(static_cast(endpoint))); +} + +/** + * @brief Get the source scoped node id. + * + * @param[in] commandObj The command handler object. + * + * @return The scoped node id of the source node. If the scoped node id is not retreived, return ScopedNodeId(). + */ +ScopedNodeId GetSourceScopedNodeId(CommandHandler * commandObj) +{ + ScopedNodeId sourceNodeId = ScopedNodeId(); + auto sessionHandle = commandObj->GetExchangeContext()->GetSessionHandle(); + + if (sessionHandle->IsSecureSession()) + { + sourceNodeId = sessionHandle->AsSecureSession()->GetPeer(); + } + else if (sessionHandle->IsGroupSession()) + { + sourceNodeId = sessionHandle->AsIncomingGroupSession()->GetPeer(); + } + return sourceNodeId; +} + +/** + * @brief Counts the number of attribute requests + * + * @param attributeRequests The decodable list of attribute IDs + * @param attributeRequestCount The total number of attribute requests + * @param requestedPresets Whether the Presets attribute was requested + * @param requestedSchedules Whether the Schedules attribute was requested + * @return true if the attribute list was counted + * @return false if there was an error reading the list + */ +bool CountAttributeRequests(const DataModel::DecodableList attributeRequests, size_t & attributeRequestCount, + bool & requestedPresets, bool & requestedSchedules) +{ + attributeRequestCount = 0; + requestedPresets = false; + requestedSchedules = false; + auto attributeIdsIter = attributeRequests.begin(); + while (attributeIdsIter.Next()) + { + auto & attributeId = attributeIdsIter.GetValue(); + switch (attributeId) + { + case Presets::Id: + requestedPresets = true; + break; + case Schedules::Id: + requestedSchedules = true; + break; + default: + break; + } + attributeRequestCount++; + } + return attributeIdsIter.GetStatus() == CHIP_NO_ERROR; +} + +/// @brief Builds the list of attribute statuses to return from an AtomicRequest invocation +/// @param endpoint The associated endpoint for the AtomicRequest invocation +/// @param attributeRequests The list of requested attributes +/// @param attributeStatusCount The number of attribute statuses in attributeStatuses +/// @param attributeStatuses The status of each requested attribute, plus additional attributes if needed +/// @return Status::Success if the request is valid, an error status if it is not +Status BuildAttributeStatuses(const EndpointId endpoint, const DataModel::DecodableList attributeRequests, + Platform::ScopedMemoryBufferWithSize & attributeStatuses) +{ + + bool requestedPresets = false, requestedSchedules = false; + size_t attributeStatusCount = 0; + if (!CountAttributeRequests(attributeRequests, attributeStatusCount, requestedPresets, requestedSchedules)) + { + // We errored reading the list + return Status::InvalidCommand; + } + if (attributeStatusCount == 0) + { + // List can't be empty + return Status::InvalidCommand; + } + attributeStatuses.Alloc(attributeStatusCount); + for (size_t i = 0; i < attributeStatusCount; ++i) + { + attributeStatuses[i].attributeID = kInvalidAttributeId; + attributeStatuses[i].statusCode = 0; + } + auto attributeIdsIter = attributeRequests.begin(); + size_t index = 0; + while (attributeIdsIter.Next()) + { + auto & attributeId = attributeIdsIter.GetValue(); + + for (size_t i = 0; i < index; ++i) + { + auto & attributeStatus = attributeStatuses[i]; + if (attributeStatus.attributeID == attributeId) + { + // Double-requesting an attribute is invalid + return Status::InvalidCommand; + } + } + attributeStatuses[index].attributeID = attributeId; + attributeStatuses[index].statusCode = to_underlying(Status::Success); + index++; + } + if (attributeIdsIter.GetStatus() != CHIP_NO_ERROR) + { + return Status::InvalidCommand; + } + for (size_t i = 0; i < index; ++i) + { + auto & attributeStatus = attributeStatuses[i]; + const EmberAfAttributeMetadata * metadata = + emberAfLocateAttributeMetadata(endpoint, Thermostat::Id, attributeStatus.attributeID); + + if (metadata == nullptr) + { + // This is not a valid attribute on the Thermostat cluster on the supplied endpoint + return Status::InvalidCommand; + } + } + return Status::Success; +} + +bool ThermostatAttrAccess::InAtomicWrite(EndpointId endpoint, Optional attributeId) +{ + + uint16_t ep = + emberAfGetClusterServerEndpointIndex(endpoint, Thermostat::Id, MATTER_DM_THERMOSTAT_CLUSTER_SERVER_ENDPOINT_COUNT); + + if (ep >= ArraySize(mAtomicWriteSessions)) + { + return false; + } + auto & atomicWriteSession = mAtomicWriteSessions[ep]; + if (atomicWriteSession.state != AtomicWriteState::Open) + { + return false; + } + if (!attributeId.HasValue()) + { + return true; + } + for (size_t i = 0; i < atomicWriteSession.attributeIds.AllocatedSize(); ++i) + { + if (atomicWriteSession.attributeIds[i] == attributeId.Value()) + { + return true; + } + } + return false; +} + +bool ThermostatAttrAccess::InAtomicWrite(EndpointId endpoint, const Access::SubjectDescriptor & subjectDescriptor, + Optional attributeId) +{ + if (!InAtomicWrite(endpoint, attributeId)) + { + return false; + } + return subjectDescriptor.authMode == Access::AuthMode::kCase && + GetAtomicWriteOriginatorScopedNodeId(endpoint) == ScopedNodeId(subjectDescriptor.subject, subjectDescriptor.fabricIndex); +} + +bool ThermostatAttrAccess::InAtomicWrite(EndpointId endpoint, CommandHandler * commandObj, Optional attributeId) +{ + if (!InAtomicWrite(endpoint, attributeId)) + { + return false; + } + ScopedNodeId sourceNodeId = GetSourceScopedNodeId(commandObj); + return GetAtomicWriteOriginatorScopedNodeId(endpoint) == sourceNodeId; +} + +bool ThermostatAttrAccess::InAtomicWrite( + EndpointId endpoint, CommandHandler * commandObj, + Platform::ScopedMemoryBufferWithSize & attributeStatuses) +{ + uint16_t ep = + emberAfGetClusterServerEndpointIndex(endpoint, Thermostat::Id, MATTER_DM_THERMOSTAT_CLUSTER_SERVER_ENDPOINT_COUNT); + + if (ep >= ArraySize(mAtomicWriteSessions)) + { + return false; + } + auto & atomicWriteSession = mAtomicWriteSessions[ep]; + if (atomicWriteSession.state != AtomicWriteState::Open) + { + return false; + } + if (atomicWriteSession.attributeIds.AllocatedSize() == 0 || + atomicWriteSession.attributeIds.AllocatedSize() != attributeStatuses.AllocatedSize()) + { + return false; + } + for (size_t i = 0; i < atomicWriteSession.attributeIds.AllocatedSize(); ++i) + { + bool hasAttribute = false; + auto attributeId = atomicWriteSession.attributeIds[i]; + for (size_t j = 0; j < attributeStatuses.AllocatedSize(); ++j) + { + auto & attributeStatus = attributeStatuses[j]; + if (attributeStatus.attributeID == attributeId) + { + hasAttribute = true; + break; + } + } + if (!hasAttribute) + { + return false; + } + } + return true; +} + +bool ThermostatAttrAccess::SetAtomicWrite( + EndpointId endpoint, ScopedNodeId originatorNodeId, AtomicWriteState state, + Platform::ScopedMemoryBufferWithSize & attributeStatuses) +{ + uint16_t ep = + emberAfGetClusterServerEndpointIndex(endpoint, Thermostat::Id, MATTER_DM_THERMOSTAT_CLUSTER_SERVER_ENDPOINT_COUNT); + + if (ep >= ArraySize(mAtomicWriteSessions)) + { + return false; + } + + auto & atomicWriteSession = mAtomicWriteSessions[ep]; + atomicWriteSession.endpointId = endpoint; + if (!atomicWriteSession.attributeIds.Alloc(attributeStatuses.AllocatedSize())) + { + atomicWriteSession.state = AtomicWriteState::Closed; + atomicWriteSession.nodeId = ScopedNodeId(); + return false; + } + + atomicWriteSession.state = state; + atomicWriteSession.nodeId = originatorNodeId; + + for (size_t i = 0; i < attributeStatuses.AllocatedSize(); ++i) + { + atomicWriteSession.attributeIds[i] = attributeStatuses[i].attributeID; + } + return true; +} + +void ThermostatAttrAccess::ResetAtomicWrite(EndpointId endpoint) +{ + auto delegate = GetDelegate(endpoint); + if (delegate != nullptr) + { + delegate->ClearPendingPresetList(); + } + ClearTimer(endpoint); + uint16_t ep = + emberAfGetClusterServerEndpointIndex(endpoint, Thermostat::Id, MATTER_DM_THERMOSTAT_CLUSTER_SERVER_ENDPOINT_COUNT); + + if (ep >= ArraySize(mAtomicWriteSessions)) + { + return; + } + auto & atomicWriteSession = mAtomicWriteSessions[ep]; + atomicWriteSession.state = AtomicWriteState::Closed; + atomicWriteSession.endpointId = endpoint; + atomicWriteSession.nodeId = ScopedNodeId(); + atomicWriteSession.attributeIds.Free(); +} + +ScopedNodeId ThermostatAttrAccess::GetAtomicWriteOriginatorScopedNodeId(const EndpointId endpoint) +{ + ScopedNodeId originatorNodeId = ScopedNodeId(); + uint16_t ep = + emberAfGetClusterServerEndpointIndex(endpoint, Thermostat::Id, MATTER_DM_THERMOSTAT_CLUSTER_SERVER_ENDPOINT_COUNT); + + if (ep < ArraySize(mAtomicWriteSessions)) + { + originatorNodeId = mAtomicWriteSessions[ep].nodeId; + } + return originatorNodeId; +} + +void SendAtomicResponse(CommandHandler * commandObj, const ConcreteCommandPath & commandPath, Status status, + const Platform::ScopedMemoryBufferWithSize & attributeStatuses, + Optional timeout = NullOptional) +{ + Commands::AtomicResponse::Type response; + response.statusCode = to_underlying(status); + response.attributeStatus = + DataModel::List(attributeStatuses.Get(), attributeStatuses.AllocatedSize()); + response.timeout = timeout; + commandObj->AddResponse(commandPath, response); +} + +void ThermostatAttrAccess::BeginAtomicWrite(CommandHandler * commandObj, const ConcreteCommandPath & commandPath, + const Commands::AtomicRequest::DecodableType & commandData) +{ + EndpointId endpoint = commandPath.mEndpointId; + + auto delegate = GetDelegate(endpoint); + + if (delegate == nullptr) + { + ChipLogError(Zcl, "Delegate is null"); + commandObj->AddStatus(commandPath, Status::InvalidInState); + return; + } + + Platform::ScopedMemoryBufferWithSize attributeStatuses; + auto status = BuildAttributeStatuses(endpoint, commandData.attributeRequests, attributeStatuses); + if (status != Status::Success) + { + commandObj->AddStatus(commandPath, status); + return; + } + + if (InAtomicWrite(endpoint, commandObj)) + { + // This client already has an open atomic write + commandObj->AddStatus(commandPath, Status::InvalidInState); + return; + } + + if (!commandData.timeout.HasValue()) + { + commandObj->AddStatus(commandPath, Status::InvalidCommand); + return; + } + + auto maximumTimeout = System::Clock::Milliseconds16(0); + auto attributeIdsIter = commandData.attributeRequests.begin(); + while (attributeIdsIter.Next()) + { + auto & attributeId = attributeIdsIter.GetValue(); + switch (attributeId) + { + case Presets::Id: + case Schedules::Id: + auto attributeTimeout = delegate->GetMaxAtomicWriteTimeout(attributeId); + + if (attributeTimeout.has_value()) + { + // Add to the maximum timeout + maximumTimeout += attributeTimeout.value(); + } + break; + } + } + + status = Status::Success; + for (size_t i = 0; i < attributeStatuses.AllocatedSize(); ++i) + { + auto & attributeStatus = attributeStatuses[i]; + auto statusCode = Status::Success; + switch (attributeStatus.attributeID) + { + case Presets::Id: + case Schedules::Id: + statusCode = InAtomicWrite(endpoint, MakeOptional(attributeStatus.attributeID)) ? Status::Busy : Status::Success; + break; + default: + statusCode = Status::InvalidCommand; + break; + } + if (statusCode != Status::Success) + { + status = Status::Failure; + } + attributeStatus.statusCode = to_underlying(statusCode); + } + + auto timeout = std::min(System::Clock::Milliseconds16(commandData.timeout.Value()), maximumTimeout); + if (timeout.count() == 0) + { + commandObj->AddStatus(commandPath, Status::InvalidInState); + return; + } + + if (status == Status::Success) + { + if (!SetAtomicWrite(endpoint, GetSourceScopedNodeId(commandObj), AtomicWriteState::Open, attributeStatuses)) + { + for (size_t i = 0; i < attributeStatuses.AllocatedSize(); ++i) + { + attributeStatuses[i].statusCode = to_underlying(Status::ResourceExhausted); + } + status = Status::Failure; + } + else + { + // This is a valid request to open an atomic write. Tell the delegate it + // needs to keep track of a pending preset list now. + delegate->InitializePendingPresets(); + ScheduleTimer(endpoint, timeout); + } + } + + SendAtomicResponse(commandObj, commandPath, status, attributeStatuses, MakeOptional(timeout.count())); +} + +void ThermostatAttrAccess::CommitAtomicWrite(CommandHandler * commandObj, const ConcreteCommandPath & commandPath, + const Commands::AtomicRequest::DecodableType & commandData) +{ + EndpointId endpoint = commandPath.mEndpointId; + auto delegate = GetDelegate(endpoint); + + if (delegate == nullptr) + { + ChipLogError(Zcl, "Delegate is null"); + commandObj->AddStatus(commandPath, Status::InvalidInState); + return; + } + + Platform::ScopedMemoryBufferWithSize attributeStatuses; + auto status = BuildAttributeStatuses(endpoint, commandData.attributeRequests, attributeStatuses); + if (status != Status::Success) + { + commandObj->AddStatus(commandPath, status); + return; + } + + if (!InAtomicWrite(endpoint, commandObj, attributeStatuses)) + { + commandObj->AddStatus(commandPath, Status::InvalidInState); + return; + } + + status = Status::Success; + for (size_t i = 0; i < attributeStatuses.AllocatedSize(); ++i) + { + auto & attributeStatus = attributeStatuses[i]; + auto statusCode = Status::Success; + switch (attributeStatus.attributeID) + { + case Presets::Id: + statusCode = PrecommitPresets(endpoint); + break; + case Schedules::Id: + statusCode = Status::Success; + break; + default: + commandObj->AddStatus(commandPath, Status::InvalidInState); + return; + } + attributeStatus.statusCode = to_underlying(statusCode); + if (statusCode != Status::Success) + { + status = Status::Failure; + } + } + + if (status == Status::Success) + { + for (size_t i = 0; i < attributeStatuses.AllocatedSize(); ++i) + { + auto & attributeStatus = attributeStatuses[i]; + auto statusCode = Status::Success; + CHIP_ERROR err; + switch (attributeStatus.attributeID) + { + case Presets::Id: + err = delegate->CommitPendingPresets(); + if (err != CHIP_NO_ERROR) + { + statusCode = Status::InvalidInState; + } + break; + case Schedules::Id: + break; + default: + // Not reachable, since we returned in this situation above. + break; + } + attributeStatus.statusCode = to_underlying(statusCode); + if (statusCode != Status::Success) + { + status = Status::Failure; + } + } + } + + ResetAtomicWrite(endpoint); + SendAtomicResponse(commandObj, commandPath, status, attributeStatuses); +} + +void ThermostatAttrAccess::RollbackAtomicWrite(CommandHandler * commandObj, const ConcreteCommandPath & commandPath, + const Commands::AtomicRequest::DecodableType & commandData) +{ + + EndpointId endpoint = commandPath.mEndpointId; + auto delegate = GetDelegate(endpoint); + + if (delegate == nullptr) + { + ChipLogError(Zcl, "Delegate is null"); + commandObj->AddStatus(commandPath, Status::InvalidInState); + return; + } + + Platform::ScopedMemoryBufferWithSize attributeStatuses; + auto status = BuildAttributeStatuses(endpoint, commandData.attributeRequests, attributeStatuses); + if (status != Status::Success) + { + commandObj->AddStatus(commandPath, status); + return; + } + + if (!InAtomicWrite(endpoint, commandObj, attributeStatuses)) + { + // There's no open atomic write + commandObj->AddStatus(commandPath, Status::InvalidInState); + return; + } + + ResetAtomicWrite(endpoint); + + for (size_t i = 0; i < attributeStatuses.AllocatedSize(); ++i) + { + attributeStatuses[i].statusCode = to_underlying(Status::Success); + } + + SendAtomicResponse(commandObj, commandPath, status, attributeStatuses); +} + +void MatterThermostatClusterServerShutdownCallback(EndpointId endpoint) +{ + ChipLogProgress(Zcl, "Shutting down thermostat server cluster on endpoint %d", endpoint); + gThermostatAttrAccess.ResetAtomicWrite(endpoint); +} + +bool emberAfThermostatClusterAtomicRequestCallback(CommandHandler * commandObj, const ConcreteCommandPath & commandPath, + const Clusters::Thermostat::Commands::AtomicRequest::DecodableType & commandData) +{ + auto & requestType = commandData.requestType; + + // If we've gotten this far, then the client has manage permission to call AtomicRequest, which is also the + // privilege necessary to write to the atomic attributes, so no need to check + + switch (requestType) + { + case Globals::AtomicRequestTypeEnum::kBeginWrite: + gThermostatAttrAccess.BeginAtomicWrite(commandObj, commandPath, commandData); + return true; + case Globals::AtomicRequestTypeEnum::kCommitWrite: + gThermostatAttrAccess.CommitAtomicWrite(commandObj, commandPath, commandData); + return true; + case Globals::AtomicRequestTypeEnum::kRollbackWrite: + gThermostatAttrAccess.RollbackAtomicWrite(commandObj, commandPath, commandData); + return true; + case Globals::AtomicRequestTypeEnum::kUnknownEnumValue: + commandObj->AddStatus(commandPath, Status::InvalidCommand); + return true; + } + + return false; +} + +} // namespace Thermostat +} // namespace Clusters +} // namespace app +} // namespace chip + +bool emberAfThermostatClusterAtomicRequestCallback(CommandHandler * commandObj, const ConcreteCommandPath & commandPath, + const Clusters::Thermostat::Commands::AtomicRequest::DecodableType & commandData) +{ + return Thermostat::emberAfThermostatClusterAtomicRequestCallback(commandObj, commandPath, commandData); +} + +void MatterThermostatClusterServerShutdownCallback(EndpointId endpoint) +{ + Thermostat::MatterThermostatClusterServerShutdownCallback(endpoint); +} diff --git a/src/app/clusters/thermostat-server/thermostat-server-presets.cpp b/src/app/clusters/thermostat-server/thermostat-server-presets.cpp new file mode 100644 index 0000000000..e57c2f9c95 --- /dev/null +++ b/src/app/clusters/thermostat-server/thermostat-server-presets.cpp @@ -0,0 +1,546 @@ +/** + * + * 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 "thermostat-server.h" + +#include + +using namespace chip; +using namespace chip::app; +using namespace chip::app::Clusters; +using namespace chip::app::Clusters::Thermostat; +using namespace chip::app::Clusters::Thermostat::Attributes; +using namespace chip::app::Clusters::Thermostat::Structs; +using namespace chip::app::Clusters::Globals::Structs; +using namespace chip::Protocols::InteractionModel; + +namespace { + +/** + * @brief Check if a preset is valid. + * + * @param[in] preset The preset to check. + * + * @return true If the preset is valid i.e the PresetHandle (if not null) fits within size constraints and the presetScenario enum + * value is valid. Otherwise, return false. + */ +bool IsValidPresetEntry(const PresetStruct::Type & preset) +{ + // Check that the preset handle is not too long. + if (!preset.presetHandle.IsNull() && preset.presetHandle.Value().size() > kPresetHandleSize) + { + return false; + } + + // Ensure we have a valid PresetScenario. + return (preset.presetScenario != PresetScenarioEnum::kUnknownEnumValue); +} + +/** + * @brief Checks if the preset is built-in + * + * @param[in] preset The preset to check. + * + * @return true If the preset is built-in, false otherwise. + */ +bool IsBuiltIn(const PresetStructWithOwnedMembers & preset) +{ + return preset.GetBuiltIn().ValueOr(false); +} + +/** + * @brief Checks if the presets are matching i.e the presetHandles are the same. + * + * @param[in] preset The preset to check. + * @param[in] presetToMatch The preset to match with. + * + * @return true If the presets match, false otherwise. If both preset handles are null, returns false + */ +bool PresetHandlesExistAndMatch(const PresetStructWithOwnedMembers & preset, const PresetStructWithOwnedMembers & presetToMatch) +{ + return !preset.GetPresetHandle().IsNull() && !presetToMatch.GetPresetHandle().IsNull() && + preset.GetPresetHandle().Value().data_equal(presetToMatch.GetPresetHandle().Value()); +} + +/** + * @brief Finds an entry in the pending presets list that matches a preset. + * The presetHandle of the two presets must match. + * + * @param[in] delegate The delegate to use. + * @param[in] presetToMatch The preset to match with. + * + * @return true if a matching entry was found in the pending presets list, false otherwise. + */ +bool MatchingPendingPresetExists(Delegate * delegate, const PresetStructWithOwnedMembers & presetToMatch) +{ + VerifyOrReturnValue(delegate != nullptr, false); + + for (uint8_t i = 0; true; i++) + { + PresetStructWithOwnedMembers preset; + CHIP_ERROR err = delegate->GetPendingPresetAtIndex(i, preset); + + if (err == CHIP_ERROR_PROVIDER_LIST_EXHAUSTED) + { + break; + } + if (err != CHIP_NO_ERROR) + { + ChipLogError(Zcl, "MatchingPendingPresetExists: GetPendingPresetAtIndex failed with error %" CHIP_ERROR_FORMAT, + err.Format()); + return false; + } + + if (PresetHandlesExistAndMatch(preset, presetToMatch)) + { + return true; + } + } + return false; +} + +/** + * @brief Finds and returns an entry in the Presets attribute list that matches + * a preset, if such an entry exists. The presetToMatch must have a preset handle. + * + * @param[in] delegate The delegate to use. + * @param[in] presetToMatch The preset to match with. + * @param[out] matchingPreset The preset in the Presets attribute list that has the same PresetHandle as the presetToMatch. + * + * @return true if a matching entry was found in the presets attribute list, false otherwise. + */ +bool GetMatchingPresetInPresets(Delegate * delegate, const PresetStruct::Type & presetToMatch, + PresetStructWithOwnedMembers & matchingPreset) +{ + VerifyOrReturnValue(delegate != nullptr, false); + + for (uint8_t i = 0; true; i++) + { + CHIP_ERROR err = delegate->GetPresetAtIndex(i, matchingPreset); + + if (err == CHIP_ERROR_PROVIDER_LIST_EXHAUSTED) + { + break; + } + if (err != CHIP_NO_ERROR) + { + ChipLogError(Zcl, "GetMatchingPresetInPresets: GetPresetAtIndex failed with error %" CHIP_ERROR_FORMAT, err.Format()); + return false; + } + + // Note: presets coming from our delegate always have a handle. + if (presetToMatch.presetHandle.Value().data_equal(matchingPreset.GetPresetHandle().Value())) + { + return true; + } + } + return false; +} + +/** + * @brief Returns the length of the list of presets if the pending presets were to be applied. The size of the pending presets list + * calculated, after all the constraint checks are done, is the new size of the updated Presets attribute since the pending + * preset list is expected to have all existing presets with or without edits plus new presets. + * This is called before changes are actually applied. + * + * @param[in] delegate The delegate to use. + * + * @return count of the updated Presets attribute if the pending presets were applied to it. Return 0 for error cases. + */ +uint8_t CountNumberOfPendingPresets(Delegate * delegate) +{ + uint8_t numberOfPendingPresets = 0; + + VerifyOrReturnValue(delegate != nullptr, 0); + + for (uint8_t i = 0; true; i++) + { + PresetStructWithOwnedMembers pendingPreset; + CHIP_ERROR err = delegate->GetPendingPresetAtIndex(i, pendingPreset); + + if (err == CHIP_ERROR_PROVIDER_LIST_EXHAUSTED) + { + break; + } + if (err != CHIP_NO_ERROR) + { + ChipLogError(Zcl, "CountNumberOfPendingPresets: GetPendingPresetAtIndex failed with error %" CHIP_ERROR_FORMAT, + err.Format()); + return 0; + } + numberOfPendingPresets++; + } + + return numberOfPendingPresets; +} + +/** + * @brief Checks if the presetScenario is present in the PresetTypes attribute. + * + * @param[in] delegate The delegate to use. + * @param[in] presetScenario The presetScenario to match with. + * + * @return true if the presetScenario is found, false otherwise. + */ +bool PresetScenarioExistsInPresetTypes(Delegate * delegate, PresetScenarioEnum presetScenario) +{ + VerifyOrReturnValue(delegate != nullptr, false); + + for (uint8_t i = 0; true; i++) + { + PresetTypeStruct::Type presetType; + auto err = delegate->GetPresetTypeAtIndex(i, presetType); + if (err != CHIP_NO_ERROR) + { + return false; + } + + if (presetType.presetScenario == presetScenario) + { + return true; + } + } + return false; +} + +/** + * @brief Returns the count of preset entries in the pending presets list that have the matching presetHandle. + * @param[in] delegate The delegate to use. + * @param[in] presetHandleToMatch The preset handle to match. + * + * @return count of the number of presets found with the matching presetHandle. Returns 0 if no matching presets were found. + */ +uint8_t CountPresetsInPendingListWithPresetHandle(Delegate * delegate, const ByteSpan & presetHandleToMatch) +{ + uint8_t count = 0; + VerifyOrReturnValue(delegate != nullptr, count); + + for (uint8_t i = 0; true; i++) + { + PresetStructWithOwnedMembers preset; + auto err = delegate->GetPendingPresetAtIndex(i, preset); + if (err != CHIP_NO_ERROR) + { + return count; + } + + DataModel::Nullable presetHandle = preset.GetPresetHandle(); + if (!presetHandle.IsNull() && presetHandle.Value().data_equal(presetHandleToMatch)) + { + count++; + } + } + return count; +} + +/** + * @brief Checks if the presetType for the given preset scenario supports name in the presetTypeFeatures bitmap. + * + * @param[in] delegate The delegate to use. + * @param[in] presetScenario The presetScenario to match with. + * + * @return true if the presetType for the given preset scenario supports name, false otherwise. + */ +bool PresetTypeSupportsNames(Delegate * delegate, PresetScenarioEnum scenario) +{ + VerifyOrReturnValue(delegate != nullptr, false); + + for (uint8_t i = 0; true; i++) + { + PresetTypeStruct::Type presetType; + auto err = delegate->GetPresetTypeAtIndex(i, presetType); + if (err != CHIP_NO_ERROR) + { + return false; + } + + if (presetType.presetScenario == scenario) + { + return (presetType.presetTypeFeatures.Has(PresetTypeFeaturesBitmap::kSupportsNames)); + } + } + return false; +} + +/** + * @brief Checks if the given preset handle is present in the presets attribute + * @param[in] delegate The delegate to use. + * @param[in] presetHandleToMatch The preset handle to match with. + * + * @return true if the given preset handle is present in the presets attribute list, false otherwise. + */ +bool IsPresetHandlePresentInPresets(Delegate * delegate, const ByteSpan & presetHandleToMatch) +{ + VerifyOrReturnValue(delegate != nullptr, false); + + PresetStructWithOwnedMembers matchingPreset; + for (uint8_t i = 0; true; i++) + { + CHIP_ERROR err = delegate->GetPresetAtIndex(i, matchingPreset); + + if (err == CHIP_ERROR_PROVIDER_LIST_EXHAUSTED) + { + return false; + } + + if (err != CHIP_NO_ERROR) + { + ChipLogError(Zcl, "IsPresetHandlePresentInPresets: GetPresetAtIndex failed with error %" CHIP_ERROR_FORMAT, + err.Format()); + return false; + } + + if (!matchingPreset.GetPresetHandle().IsNull() && matchingPreset.GetPresetHandle().Value().data_equal(presetHandleToMatch)) + { + return true; + } + } + return false; +} + +} // namespace + +namespace chip { +namespace app { +namespace Clusters { +namespace Thermostat { + +extern ThermostatAttrAccess gThermostatAttrAccess; +extern int16_t EnforceHeatingSetpointLimits(int16_t HeatingSetpoint, EndpointId endpoint); +extern int16_t EnforceCoolingSetpointLimits(int16_t CoolingSetpoint, EndpointId endpoint); + +Status ThermostatAttrAccess::SetActivePreset(EndpointId endpoint, DataModel::Nullable presetHandle) +{ + + auto delegate = GetDelegate(endpoint); + + if (delegate == nullptr) + { + ChipLogError(Zcl, "Delegate is null"); + return Status::InvalidInState; + } + + // If the preset handle passed in the command is not present in the Presets attribute, return INVALID_COMMAND. + if (!presetHandle.IsNull() && !IsPresetHandlePresentInPresets(delegate, presetHandle.Value())) + { + return Status::InvalidCommand; + } + + CHIP_ERROR err = delegate->SetActivePresetHandle(presetHandle); + + if (err != CHIP_NO_ERROR) + { + ChipLogError(Zcl, "Failed to set ActivePresetHandle with error %" CHIP_ERROR_FORMAT, err.Format()); + return StatusIB(err).mStatus; + } + + return Status::Success; +} + +CHIP_ERROR ThermostatAttrAccess::AppendPendingPreset(Thermostat::Delegate * delegate, const PresetStruct::Type & preset) +{ + if (!IsValidPresetEntry(preset)) + { + return CHIP_IM_GLOBAL_STATUS(ConstraintError); + } + + if (preset.presetHandle.IsNull()) + { + if (IsBuiltIn(preset)) + { + return CHIP_IM_GLOBAL_STATUS(ConstraintError); + } + } + else + { + auto & presetHandle = preset.presetHandle.Value(); + + // Per spec we need to check that: + // (a) There is an existing non-pending preset with this handle. + PresetStructWithOwnedMembers matchingPreset; + if (!GetMatchingPresetInPresets(delegate, preset, matchingPreset)) + { + return CHIP_IM_GLOBAL_STATUS(NotFound); + } + + // (b) There is no existing pending preset with this handle. + if (CountPresetsInPendingListWithPresetHandle(delegate, presetHandle) > 0) + { + return CHIP_IM_GLOBAL_STATUS(ConstraintError); + } + + // (c)/(d) The built-in fields do not have a mismatch. + // TODO: What's the story with nullability on the BuiltIn field? + if (!preset.builtIn.IsNull() && !matchingPreset.GetBuiltIn().IsNull() && + preset.builtIn.Value() != matchingPreset.GetBuiltIn().Value()) + { + return CHIP_IM_GLOBAL_STATUS(ConstraintError); + } + } + + if (!PresetScenarioExistsInPresetTypes(delegate, preset.presetScenario)) + { + return CHIP_IM_GLOBAL_STATUS(ConstraintError); + } + + if (preset.name.HasValue() && !PresetTypeSupportsNames(delegate, preset.presetScenario)) + { + return CHIP_IM_GLOBAL_STATUS(ConstraintError); + } + + return delegate->AppendToPendingPresetList(preset); +} + +Status ThermostatAttrAccess::PrecommitPresets(EndpointId endpoint) +{ + auto delegate = GetDelegate(endpoint); + + if (delegate == nullptr) + { + ChipLogError(Zcl, "Delegate is null"); + return Status::InvalidInState; + } + + CHIP_ERROR err = CHIP_NO_ERROR; + + // For each preset in the presets attribute, check that the matching preset in the pending presets list does not + // violate any spec constraints. + for (uint8_t i = 0; true; i++) + { + PresetStructWithOwnedMembers preset; + err = delegate->GetPresetAtIndex(i, preset); + + if (err == CHIP_ERROR_PROVIDER_LIST_EXHAUSTED) + { + break; + } + if (err != CHIP_NO_ERROR) + { + ChipLogError(Zcl, + "emberAfThermostatClusterCommitPresetsSchedulesRequestCallback: GetPresetAtIndex failed with error " + "%" CHIP_ERROR_FORMAT, + err.Format()); + return Status::InvalidInState; + } + + bool found = MatchingPendingPresetExists(delegate, preset); + + // If a built in preset in the Presets attribute list is removed and not found in the pending presets list, return + // CONSTRAINT_ERROR. + if (IsBuiltIn(preset) && !found) + { + return Status::ConstraintError; + } + } + + // If there is an ActivePresetHandle set, find the preset in the pending presets list that matches the ActivePresetHandle + // attribute. If a preset is not found with the same presetHandle, return INVALID_IN_STATE. If there is no ActivePresetHandle + // attribute set, continue with other checks. + uint8_t buffer[kPresetHandleSize]; + MutableByteSpan activePresetHandleSpan(buffer); + auto activePresetHandle = DataModel::MakeNullable(activePresetHandleSpan); + + err = delegate->GetActivePresetHandle(activePresetHandle); + + if (err != CHIP_NO_ERROR) + { + return Status::InvalidInState; + } + + if (!activePresetHandle.IsNull()) + { + uint8_t count = CountPresetsInPendingListWithPresetHandle(delegate, activePresetHandle.Value()); + if (count == 0) + { + return Status::InvalidInState; + } + } + + // For each preset in the pending presets list, check that the preset does not violate any spec constraints. + for (uint8_t i = 0; true; i++) + { + PresetStructWithOwnedMembers pendingPreset; + err = delegate->GetPendingPresetAtIndex(i, pendingPreset); + + if (err == CHIP_ERROR_PROVIDER_LIST_EXHAUSTED) + { + break; + } + if (err != CHIP_NO_ERROR) + { + ChipLogError(Zcl, + "emberAfThermostatClusterCommitPresetsSchedulesRequestCallback: GetPendingPresetAtIndex failed with error " + "%" CHIP_ERROR_FORMAT, + err.Format()); + return Status::InvalidInState; + } + + // Enforce the Setpoint Limits for both the cooling and heating setpoints in the pending preset. + // TODO: This code does not work, because it's modifying our temporary copy. + Optional coolingSetpointValue = pendingPreset.GetCoolingSetpoint(); + if (coolingSetpointValue.HasValue()) + { + pendingPreset.SetCoolingSetpoint(MakeOptional(EnforceCoolingSetpointLimits(coolingSetpointValue.Value(), endpoint))); + } + + Optional heatingSetpointValue = pendingPreset.GetHeatingSetpoint(); + if (heatingSetpointValue.HasValue()) + { + pendingPreset.SetHeatingSetpoint(MakeOptional(EnforceHeatingSetpointLimits(heatingSetpointValue.Value(), endpoint))); + } + } + + uint8_t totalCount = CountNumberOfPendingPresets(delegate); + + uint8_t numberOfPresetsSupported = delegate->GetNumberOfPresets(); + + if (numberOfPresetsSupported == 0) + { + ChipLogError(Zcl, "emberAfThermostatClusterCommitPresetsSchedulesRequestCallback: Failed to get NumberOfPresets"); + return Status::InvalidInState; + } + + // If the expected length of the presets attribute with the applied changes exceeds the total number of presets supported, + // return RESOURCE_EXHAUSTED. Note that the changes are not yet applied. + if (numberOfPresetsSupported > 0 && totalCount > numberOfPresetsSupported) + { + return Status::ResourceExhausted; + } + + // TODO: Check if the number of presets for each presetScenario exceeds the max number of presets supported for that + // scenario. We plan to support only one preset for each presetScenario for our use cases so defer this for re-evaluation. + return Status::Success; +} + +bool emberAfThermostatClusterSetActivePresetRequestCallback(CommandHandler * commandObj, const ConcreteCommandPath & commandPath, + const Commands::SetActivePresetRequest::DecodableType & commandData) +{ + auto status = gThermostatAttrAccess.SetActivePreset(commandPath.mEndpointId, commandData.presetHandle); + commandObj->AddStatus(commandPath, status); + return true; +} + +} // namespace Thermostat +} // namespace Clusters +} // namespace app +} // namespace chip + +bool emberAfThermostatClusterSetActivePresetRequestCallback(CommandHandler * commandObj, const ConcreteCommandPath & commandPath, + const Commands::SetActivePresetRequest::DecodableType & commandData) +{ + return Thermostat::emberAfThermostatClusterSetActivePresetRequestCallback(commandObj, commandPath, commandData); +} diff --git a/src/app/clusters/thermostat-server/thermostat-server.cpp b/src/app/clusters/thermostat-server/thermostat-server.cpp index 8fe70211ee..fe8ccf8aab 100644 --- a/src/app/clusters/thermostat-server/thermostat-server.cpp +++ b/src/app/clusters/thermostat-server/thermostat-server.cpp @@ -30,7 +30,6 @@ #include #include #include -#include using namespace chip; using namespace chip::app; @@ -38,8 +37,7 @@ using namespace chip::app::Clusters; using namespace chip::app::Clusters::Thermostat; using namespace chip::app::Clusters::Thermostat::Structs; using namespace chip::app::Clusters::Thermostat::Attributes; - -using imcode = Protocols::InteractionModel::Status; +using namespace Protocols::InteractionModel; constexpr int16_t kDefaultAbsMinHeatSetpointLimit = 700; // 7C (44.5 F) is the default constexpr int16_t kDefaultAbsMaxHeatSetpointLimit = 3000; // 30C (86 F) is the default @@ -69,381 +67,16 @@ constexpr int8_t kDefaultDeadBand = 25; // 2.5C is the default #define FEATURE_MAP_DEFAULT FEATURE_MAP_HEAT | FEATURE_MAP_COOL | FEATURE_MAP_AUTO -namespace { - -ThermostatAttrAccess gThermostatAttrAccess; - static_assert(kThermostatEndpointCount <= kEmberInvalidEndpointIndex, "Thermostat Delegate table size error"); Delegate * gDelegateTable[kThermostatEndpointCount] = { nullptr }; -Delegate * GetDelegate(EndpointId endpoint) -{ - uint16_t ep = - emberAfGetClusterServerEndpointIndex(endpoint, Thermostat::Id, MATTER_DM_THERMOSTAT_CLUSTER_SERVER_ENDPOINT_COUNT); - return (ep >= ArraySize(gDelegateTable) ? nullptr : gDelegateTable[ep]); -} - -/** - * @brief Check if a preset is valid. - * - * @param[in] preset The preset to check. - * - * @return true If the preset is valid i.e the PresetHandle (if not null) fits within size constraints and the presetScenario enum - * value is valid. Otherwise, return false. - */ -bool IsValidPresetEntry(const PresetStruct::Type & preset) -{ - // Check that the preset handle is not too long. - if (!preset.presetHandle.IsNull() && preset.presetHandle.Value().size() > kPresetHandleSize) - { - return false; - } - - // Ensure we have a valid PresetScenario. - return (preset.presetScenario != PresetScenarioEnum::kUnknownEnumValue); -} - -/** - * @brief Callback that is called when the timeout for editing the presets expires. - * - * @param[in] systemLayer The system layer. - * @param[in] callbackContext The context passed to the timer callback. - */ -void TimerExpiredCallback(System::Layer * systemLayer, void * callbackContext) -{ - EndpointId endpoint = static_cast(reinterpret_cast(callbackContext)); - - Delegate * delegate = GetDelegate(endpoint); - VerifyOrReturn(delegate != nullptr, ChipLogError(Zcl, "Delegate is null. Unable to handle timer expired")); - - delegate->ClearPendingPresetList(); - gThermostatAttrAccess.SetAtomicWrite(endpoint, ScopedNodeId(), kAtomicWriteState_Closed); -} - -/** - * @brief Schedules a timer for the given timeout in milliseconds. - * - * @param[in] endpoint The endpoint to use. - * @param[in] timeoutMilliseconds The timeout in milliseconds. - */ -void ScheduleTimer(EndpointId endpoint, System::Clock::Milliseconds16 timeout) -{ - DeviceLayer::SystemLayer().StartTimer(timeout, TimerExpiredCallback, - reinterpret_cast(static_cast(endpoint))); -} - -/** - * @brief Clears the currently scheduled timer. - * - * @param[in] endpoint The endpoint to use. - */ -void ClearTimer(EndpointId endpoint) -{ - DeviceLayer::SystemLayer().CancelTimer(TimerExpiredCallback, reinterpret_cast(static_cast(endpoint))); -} - -/** - * @brief Checks if the preset is built-in - * - * @param[in] preset The preset to check. - * - * @return true If the preset is built-in, false otherwise. - */ -bool IsBuiltIn(const PresetStructWithOwnedMembers & preset) -{ - return preset.GetBuiltIn().ValueOr(false); -} - -/** - * @brief Checks if the presets are matching i.e the presetHandles are the same. - * - * @param[in] preset The preset to check. - * @param[in] presetToMatch The preset to match with. - * - * @return true If the presets match, false otherwise. If both preset handles are null, returns false - */ -bool PresetHandlesExistAndMatch(const PresetStructWithOwnedMembers & preset, const PresetStructWithOwnedMembers & presetToMatch) -{ - return !preset.GetPresetHandle().IsNull() && !presetToMatch.GetPresetHandle().IsNull() && - preset.GetPresetHandle().Value().data_equal(presetToMatch.GetPresetHandle().Value()); -} - -/** - * @brief Get the source scoped node id. - * - * @param[in] commandObj The command handler object. - * - * @return The scoped node id of the source node. If the scoped node id is not retreived, return ScopedNodeId(). - */ -ScopedNodeId GetSourceScopedNodeId(CommandHandler * commandObj) -{ - ScopedNodeId sourceNodeId = ScopedNodeId(); - auto sessionHandle = commandObj->GetExchangeContext()->GetSessionHandle(); - - if (sessionHandle->IsSecureSession()) - { - sourceNodeId = sessionHandle->AsSecureSession()->GetPeer(); - } - else if (sessionHandle->IsGroupSession()) - { - sourceNodeId = sessionHandle->AsIncomingGroupSession()->GetPeer(); - } - return sourceNodeId; -} - -/** - * @brief Discards pending atomic writes and atomic state. - * - * @param[in] delegate The delegate to use. - * @param[in] endpoint The endpoint to use. - * - */ -void resetAtomicWrite(Delegate * delegate, EndpointId endpoint) -{ - if (delegate != nullptr) - { - delegate->ClearPendingPresetList(); - } - ClearTimer(endpoint); - gThermostatAttrAccess.SetAtomicWrite(endpoint, ScopedNodeId(), kAtomicWriteState_Closed); -} - -/** - * @brief Finds an entry in the pending presets list that matches a preset. - * The presetHandle of the two presets must match. - * - * @param[in] delegate The delegate to use. - * @param[in] presetToMatch The preset to match with. - * - * @return true if a matching entry was found in the pending presets list, false otherwise. - */ -bool MatchingPendingPresetExists(Delegate * delegate, const PresetStructWithOwnedMembers & presetToMatch) -{ - VerifyOrReturnValue(delegate != nullptr, false); - - for (uint8_t i = 0; true; i++) - { - PresetStructWithOwnedMembers preset; - CHIP_ERROR err = delegate->GetPendingPresetAtIndex(i, preset); - - if (err == CHIP_ERROR_PROVIDER_LIST_EXHAUSTED) - { - break; - } - if (err != CHIP_NO_ERROR) - { - ChipLogError(Zcl, "MatchingPendingPresetExists: GetPendingPresetAtIndex failed with error %" CHIP_ERROR_FORMAT, - err.Format()); - return false; - } - - if (PresetHandlesExistAndMatch(preset, presetToMatch)) - { - return true; - } - } - return false; -} - -/** - * @brief Finds and returns an entry in the Presets attribute list that matches - * a preset, if such an entry exists. The presetToMatch must have a preset handle. - * - * @param[in] delegate The delegate to use. - * @param[in] presetToMatch The preset to match with. - * @param[out] matchingPreset The preset in the Presets attribute list that has the same PresetHandle as the presetToMatch. - * - * @return true if a matching entry was found in the presets attribute list, false otherwise. - */ -bool GetMatchingPresetInPresets(Delegate * delegate, const PresetStruct::Type & presetToMatch, - PresetStructWithOwnedMembers & matchingPreset) -{ - VerifyOrReturnValue(delegate != nullptr, false); - - for (uint8_t i = 0; true; i++) - { - CHIP_ERROR err = delegate->GetPresetAtIndex(i, matchingPreset); - - if (err == CHIP_ERROR_PROVIDER_LIST_EXHAUSTED) - { - break; - } - if (err != CHIP_NO_ERROR) - { - ChipLogError(Zcl, "GetMatchingPresetInPresets: GetPresetAtIndex failed with error %" CHIP_ERROR_FORMAT, err.Format()); - return false; - } - - // Note: presets coming from our delegate always have a handle. - if (presetToMatch.presetHandle.Value().data_equal(matchingPreset.GetPresetHandle().Value())) - { - return true; - } - } - return false; -} - -/** - * @brief Checks if the given preset handle is present in the presets attribute - * @param[in] delegate The delegate to use. - * @param[in] presetHandleToMatch The preset handle to match with. - * - * @return true if the given preset handle is present in the presets attribute list, false otherwise. - */ -bool IsPresetHandlePresentInPresets(Delegate * delegate, const ByteSpan & presetHandleToMatch) -{ - VerifyOrReturnValue(delegate != nullptr, false); - - PresetStructWithOwnedMembers matchingPreset; - for (uint8_t i = 0; true; i++) - { - CHIP_ERROR err = delegate->GetPresetAtIndex(i, matchingPreset); - - if (err == CHIP_ERROR_PROVIDER_LIST_EXHAUSTED) - { - return false; - } - - if (err != CHIP_NO_ERROR) - { - ChipLogError(Zcl, "IsPresetHandlePresentInPresets: GetPresetAtIndex failed with error %" CHIP_ERROR_FORMAT, - err.Format()); - return false; - } - - if (!matchingPreset.GetPresetHandle().IsNull() && matchingPreset.GetPresetHandle().Value().data_equal(presetHandleToMatch)) - { - return true; - } - } - return false; -} - -/** - * @brief Returns the length of the list of presets if the pending presets were to be applied. The size of the pending presets list - * calculated, after all the constraint checks are done, is the new size of the updated Presets attribute since the pending - * preset list is expected to have all existing presets with or without edits plus new presets. - * This is called before changes are actually applied. - * - * @param[in] delegate The delegate to use. - * - * @return count of the updated Presets attribute if the pending presets were applied to it. Return 0 for error cases. - */ -uint8_t CountNumberOfPendingPresets(Delegate * delegate) -{ - uint8_t numberOfPendingPresets = 0; - - VerifyOrReturnValue(delegate != nullptr, 0); - - for (uint8_t i = 0; true; i++) - { - PresetStructWithOwnedMembers pendingPreset; - CHIP_ERROR err = delegate->GetPendingPresetAtIndex(i, pendingPreset); - - if (err == CHIP_ERROR_PROVIDER_LIST_EXHAUSTED) - { - break; - } - if (err != CHIP_NO_ERROR) - { - ChipLogError(Zcl, "CountNumberOfPendingPresets: GetPendingPresetAtIndex failed with error %" CHIP_ERROR_FORMAT, - err.Format()); - return 0; - } - numberOfPendingPresets++; - } - - return numberOfPendingPresets; -} - -/** - * @brief Checks if the presetScenario is present in the PresetTypes attribute. - * - * @param[in] delegate The delegate to use. - * @param[in] presetScenario The presetScenario to match with. - * - * @return true if the presetScenario is found, false otherwise. - */ -bool PresetScenarioExistsInPresetTypes(Delegate * delegate, PresetScenarioEnum presetScenario) -{ - VerifyOrReturnValue(delegate != nullptr, false); - - for (uint8_t i = 0; true; i++) - { - PresetTypeStruct::Type presetType; - auto err = delegate->GetPresetTypeAtIndex(i, presetType); - if (err != CHIP_NO_ERROR) - { - return false; - } - - if (presetType.presetScenario == presetScenario) - { - return true; - } - } - return false; -} - -/** - * @brief Returns the count of preset entries in the pending presets list that have the matching presetHandle. - * @param[in] delegate The delegate to use. - * @param[in] presetHandleToMatch The preset handle to match. - * - * @return count of the number of presets found with the matching presetHandle. Returns 0 if no matching presets were found. - */ -uint8_t CountPresetsInPendingListWithPresetHandle(Delegate * delegate, const ByteSpan & presetHandleToMatch) -{ - uint8_t count = 0; - VerifyOrReturnValue(delegate != nullptr, count); - - for (uint8_t i = 0; true; i++) - { - PresetStructWithOwnedMembers preset; - auto err = delegate->GetPendingPresetAtIndex(i, preset); - if (err != CHIP_NO_ERROR) - { - return count; - } - - DataModel::Nullable presetHandle = preset.GetPresetHandle(); - if (!presetHandle.IsNull() && presetHandle.Value().data_equal(presetHandleToMatch)) - { - count++; - } - } - return count; -} - -/** - * @brief Checks if the presetType for the given preset scenario supports name in the presetTypeFeatures bitmap. - * - * @param[in] delegate The delegate to use. - * @param[in] presetScenario The presetScenario to match with. - * - * @return true if the presetType for the given preset scenario supports name, false otherwise. - */ -bool PresetTypeSupportsNames(Delegate * delegate, PresetScenarioEnum scenario) -{ - VerifyOrReturnValue(delegate != nullptr, false); - - for (uint8_t i = 0; true; i++) - { - PresetTypeStruct::Type presetType; - auto err = delegate->GetPresetTypeAtIndex(i, presetType); - if (err != CHIP_NO_ERROR) - { - return false; - } +namespace chip { +namespace app { +namespace Clusters { +namespace Thermostat { - if (presetType.presetScenario == scenario) - { - return (presetType.presetTypeFeatures.Has(PresetTypeFeaturesBitmap::kSupportsNames)); - } - } - return false; -} +ThermostatAttrAccess gThermostatAttrAccess; int16_t EnforceHeatingSetpointLimits(int16_t HeatingSetpoint, EndpointId endpoint) { @@ -461,7 +94,7 @@ int16_t EnforceHeatingSetpointLimits(int16_t HeatingSetpoint, EndpointId endpoin // Note that the limits are initialized above per the spec limits // if they are not present Get() will not update the value so the defaults are used - imcode status; + Status status; // https://github.com/CHIP-Specifications/connectedhomeip-spec/issues/3724 // behavior is not specified when Abs * values are not present and user values are present @@ -471,24 +104,24 @@ int16_t EnforceHeatingSetpointLimits(int16_t HeatingSetpoint, EndpointId endpoin // if a attribute is not present then it's default shall be used. status = AbsMinHeatSetpointLimit::Get(endpoint, &AbsMinHeatSetpointLimit); - if (status != imcode::Success) + if (status != Status::Success) { ChipLogError(Zcl, "Warning: AbsMinHeatSetpointLimit missing using default"); } status = AbsMaxHeatSetpointLimit::Get(endpoint, &AbsMaxHeatSetpointLimit); - if (status != imcode::Success) + if (status != Status::Success) { ChipLogError(Zcl, "Warning: AbsMaxHeatSetpointLimit missing using default"); } status = MinHeatSetpointLimit::Get(endpoint, &MinHeatSetpointLimit); - if (status != imcode::Success) + if (status != Status::Success) { MinHeatSetpointLimit = AbsMinHeatSetpointLimit; } status = MaxHeatSetpointLimit::Get(endpoint, &MaxHeatSetpointLimit); - if (status != imcode::Success) + if (status != Status::Success) { MaxHeatSetpointLimit = AbsMaxHeatSetpointLimit; } @@ -532,7 +165,7 @@ int16_t EnforceCoolingSetpointLimits(int16_t CoolingSetpoint, EndpointId endpoin // Note that the limits are initialized above per the spec limits // if they are not present Get() will not update the value so the defaults are used - imcode status; + Status status; // https://github.com/CHIP-Specifications/connectedhomeip-spec/issues/3724 // behavior is not specified when Abs * values are not present and user values are present @@ -542,25 +175,25 @@ int16_t EnforceCoolingSetpointLimits(int16_t CoolingSetpoint, EndpointId endpoin // if a attribute is not present then it's default shall be used. status = AbsMinCoolSetpointLimit::Get(endpoint, &AbsMinCoolSetpointLimit); - if (status != imcode::Success) + if (status != Status::Success) { ChipLogError(Zcl, "Warning: AbsMinCoolSetpointLimit missing using default"); } status = AbsMaxCoolSetpointLimit::Get(endpoint, &AbsMaxCoolSetpointLimit); - if (status != imcode::Success) + if (status != Status::Success) { ChipLogError(Zcl, "Warning: AbsMaxCoolSetpointLimit missing using default"); } status = MinCoolSetpointLimit::Get(endpoint, &MinCoolSetpointLimit); - if (status != imcode::Success) + if (status != Status::Success) { MinCoolSetpointLimit = AbsMinCoolSetpointLimit; } status = MaxCoolSetpointLimit::Get(endpoint, &MaxCoolSetpointLimit); - if (status != imcode::Success) + if (status != Status::Success) { MaxCoolSetpointLimit = AbsMaxCoolSetpointLimit; } @@ -587,81 +220,22 @@ int16_t EnforceCoolingSetpointLimits(int16_t CoolingSetpoint, EndpointId endpoin return CoolingSetpoint; } -} // anonymous namespace - -namespace chip { -namespace app { -namespace Clusters { -namespace Thermostat { - -void SetDefaultDelegate(EndpointId endpoint, Delegate * delegate) -{ - uint16_t ep = - emberAfGetClusterServerEndpointIndex(endpoint, Thermostat::Id, MATTER_DM_THERMOSTAT_CLUSTER_SERVER_ENDPOINT_COUNT); - // if endpoint is found, add the delegate in the delegate table - if (ep < ArraySize(gDelegateTable)) - { - gDelegateTable[ep] = delegate; - } -} - -void ThermostatAttrAccess::SetAtomicWrite(EndpointId endpoint, ScopedNodeId originatorNodeId, AtomicWriteState state) -{ - uint16_t ep = - emberAfGetClusterServerEndpointIndex(endpoint, Thermostat::Id, MATTER_DM_THERMOSTAT_CLUSTER_SERVER_ENDPOINT_COUNT); - - if (ep < ArraySize(mAtomicWriteSessions)) - { - mAtomicWriteSessions[ep].state = state; - mAtomicWriteSessions[ep].endpointId = endpoint; - mAtomicWriteSessions[ep].nodeId = originatorNodeId; - } -} - -bool ThermostatAttrAccess::InAtomicWrite(EndpointId endpoint) +Delegate * GetDelegate(EndpointId endpoint) { - bool inAtomicWrite = false; uint16_t ep = emberAfGetClusterServerEndpointIndex(endpoint, Thermostat::Id, MATTER_DM_THERMOSTAT_CLUSTER_SERVER_ENDPOINT_COUNT); - - if (ep < ArraySize(mAtomicWriteSessions)) - { - inAtomicWrite = (mAtomicWriteSessions[ep].state == kAtomicWriteState_Open); - } - return inAtomicWrite; -} - -bool ThermostatAttrAccess::InAtomicWrite(const Access::SubjectDescriptor & subjectDescriptor, EndpointId endpoint) -{ - if (!InAtomicWrite(endpoint)) - { - return false; - } - return subjectDescriptor.authMode == Access::AuthMode::kCase && - GetAtomicWriteScopedNodeId(endpoint) == ScopedNodeId(subjectDescriptor.subject, subjectDescriptor.fabricIndex); -} - -bool ThermostatAttrAccess::InAtomicWrite(CommandHandler * commandObj, EndpointId endpoint) -{ - if (!InAtomicWrite(endpoint)) - { - return false; - } - ScopedNodeId sourceNodeId = GetSourceScopedNodeId(commandObj); - return GetAtomicWriteScopedNodeId(endpoint) == sourceNodeId; + return (ep >= ArraySize(gDelegateTable) ? nullptr : gDelegateTable[ep]); } -ScopedNodeId ThermostatAttrAccess::GetAtomicWriteScopedNodeId(EndpointId endpoint) +void SetDefaultDelegate(EndpointId endpoint, Delegate * delegate) { - ScopedNodeId originatorNodeId = ScopedNodeId(); uint16_t ep = emberAfGetClusterServerEndpointIndex(endpoint, Thermostat::Id, MATTER_DM_THERMOSTAT_CLUSTER_SERVER_ENDPOINT_COUNT); - - if (ep < ArraySize(mAtomicWriteSessions)) + // if endpoint is found, add the delegate in the delegate table + if (ep < ArraySize(gDelegateTable)) { - originatorNodeId = mAtomicWriteSessions[ep].nodeId; + gDelegateTable[ep] = delegate; } - return originatorNodeId; } CHIP_ERROR ThermostatAttrAccess::Read(const ConcreteReadAttributePath & aPath, AttributeValueEncoder & aEncoder) @@ -669,7 +243,7 @@ CHIP_ERROR ThermostatAttrAccess::Read(const ConcreteReadAttributePath & aPath, A VerifyOrDie(aPath.mClusterId == Thermostat::Id); uint32_t ourFeatureMap; - bool localTemperatureNotExposedSupported = (FeatureMap::Get(aPath.mEndpointId, &ourFeatureMap) == imcode::Success) && + bool localTemperatureNotExposedSupported = (FeatureMap::Get(aPath.mEndpointId, &ourFeatureMap) == Status::Success) && ((ourFeatureMap & to_underlying(Feature::kLocalTemperatureNotExposed)) != 0); switch (aPath.mAttributeId) @@ -684,8 +258,8 @@ CHIP_ERROR ThermostatAttrAccess::Read(const ConcreteReadAttributePath & aPath, A if (localTemperatureNotExposedSupported) { BitMask valueRemoteSensing; - imcode status = RemoteSensing::Get(aPath.mEndpointId, &valueRemoteSensing); - if (status != imcode::Success) + Status status = RemoteSensing::Get(aPath.mEndpointId, &valueRemoteSensing); + if (status != Status::Success) { StatusIB statusIB(status); return statusIB.ToChipError(); @@ -725,7 +299,7 @@ CHIP_ERROR ThermostatAttrAccess::Read(const ConcreteReadAttributePath & aPath, A VerifyOrReturnError(delegate != nullptr, CHIP_ERROR_INCORRECT_STATE, ChipLogError(Zcl, "Delegate is null")); auto & subjectDescriptor = aEncoder.GetSubjectDescriptor(); - if (InAtomicWrite(subjectDescriptor, aPath.mEndpointId)) + if (InAtomicWrite(aPath.mEndpointId, subjectDescriptor, MakeOptional(aPath.mAttributeId))) { return aEncoder.EncodeList([delegate](const auto & encoder) -> CHIP_ERROR { for (uint8_t i = 0; true; i++) @@ -801,12 +375,12 @@ CHIP_ERROR ThermostatAttrAccess::Write(const ConcreteDataAttributePath & aPath, VerifyOrReturnError(delegate != nullptr, CHIP_ERROR_INCORRECT_STATE, ChipLogError(Zcl, "Delegate is null")); // Presets are not editable, return INVALID_IN_STATE. - VerifyOrReturnError(InAtomicWrite(endpoint), CHIP_IM_GLOBAL_STATUS(InvalidInState), + VerifyOrReturnError(InAtomicWrite(endpoint, MakeOptional(aPath.mAttributeId)), CHIP_IM_GLOBAL_STATUS(InvalidInState), ChipLogError(Zcl, "Presets are not editable")); // OK, we're in an atomic write, make sure the requesting node is the same one that started the atomic write, // otherwise return BUSY. - if (!InAtomicWrite(subjectDescriptor, endpoint)) + if (!InAtomicWrite(endpoint, subjectDescriptor, MakeOptional(aPath.mAttributeId))) { ChipLogError(Zcl, "Another node is editing presets. Server is busy. Try again later"); return CHIP_IM_GLOBAL_STATUS(Busy); @@ -848,14 +422,14 @@ CHIP_ERROR ThermostatAttrAccess::Write(const ConcreteDataAttributePath & aPath, } // This is not an atomic attribute, so check to make sure we don't have an atomic write going for this client - if (InAtomicWrite(subjectDescriptor, endpoint)) + if (InAtomicWrite(endpoint, subjectDescriptor)) { ChipLogError(Zcl, "Can not write to non-atomic attributes during atomic write"); return CHIP_IM_GLOBAL_STATUS(InvalidInState); } uint32_t ourFeatureMap; - bool localTemperatureNotExposedSupported = (FeatureMap::Get(aPath.mEndpointId, &ourFeatureMap) == imcode::Success) && + bool localTemperatureNotExposedSupported = (FeatureMap::Get(aPath.mEndpointId, &ourFeatureMap) == Status::Success) && ((ourFeatureMap & to_underlying(Feature::kLocalTemperatureNotExposed)) != 0); switch (aPath.mAttributeId) @@ -869,7 +443,7 @@ CHIP_ERROR ThermostatAttrAccess::Write(const ConcreteDataAttributePath & aPath, { return CHIP_IM_GLOBAL_STATUS(ConstraintError); } - imcode status = RemoteSensing::Set(aPath.mEndpointId, valueRemoteSensing); + Status status = RemoteSensing::Set(aPath.mEndpointId, valueRemoteSensing); StatusIB statusIB(status); return statusIB.ToChipError(); } @@ -882,73 +456,14 @@ CHIP_ERROR ThermostatAttrAccess::Write(const ConcreteDataAttributePath & aPath, return CHIP_NO_ERROR; } -CHIP_ERROR ThermostatAttrAccess::AppendPendingPreset(Thermostat::Delegate * delegate, const PresetStruct::Type & preset) -{ - if (!IsValidPresetEntry(preset)) - { - return CHIP_IM_GLOBAL_STATUS(ConstraintError); - } - - if (preset.presetHandle.IsNull()) - { - if (IsBuiltIn(preset)) - { - return CHIP_IM_GLOBAL_STATUS(ConstraintError); - } - } - else - { - auto & presetHandle = preset.presetHandle.Value(); - - // Per spec we need to check that: - // (a) There is an existing non-pending preset with this handle. - PresetStructWithOwnedMembers matchingPreset; - if (!GetMatchingPresetInPresets(delegate, preset, matchingPreset)) - { - return CHIP_IM_GLOBAL_STATUS(NotFound); - } - - // (b) There is no existing pending preset with this handle. - if (CountPresetsInPendingListWithPresetHandle(delegate, presetHandle) > 0) - { - return CHIP_IM_GLOBAL_STATUS(ConstraintError); - } - - // (c)/(d) The built-in fields do not have a mismatch. - // TODO: What's the story with nullability on the BuiltIn field? - if (!preset.builtIn.IsNull() && !matchingPreset.GetBuiltIn().IsNull() && - preset.builtIn.Value() != matchingPreset.GetBuiltIn().Value()) - { - return CHIP_IM_GLOBAL_STATUS(ConstraintError); - } - } - - if (!PresetScenarioExistsInPresetTypes(delegate, preset.presetScenario)) - { - return CHIP_IM_GLOBAL_STATUS(ConstraintError); - } - - if (preset.name.HasValue() && !PresetTypeSupportsNames(delegate, preset.presetScenario)) - { - return CHIP_IM_GLOBAL_STATUS(ConstraintError); - } - - return delegate->AppendToPendingPresetList(preset); -} - void ThermostatAttrAccess::OnFabricRemoved(const FabricTable & fabricTable, FabricIndex fabricIndex) { for (size_t i = 0; i < ArraySize(mAtomicWriteSessions); ++i) { - auto atomicWriteState = mAtomicWriteSessions[i]; - if (atomicWriteState.state == kAtomicWriteState_Open && atomicWriteState.nodeId.GetFabricIndex() == fabricIndex) + auto & atomicWriteState = mAtomicWriteSessions[i]; + if (atomicWriteState.state == AtomicWriteState::Open && atomicWriteState.nodeId.GetFabricIndex() == fabricIndex) { - auto delegate = GetDelegate(atomicWriteState.endpointId); - if (delegate == nullptr) - { - continue; - } - resetAtomicWrite(delegate, atomicWriteState.endpointId); + ResetAtomicWrite(atomicWriteState.endpointId); } } } @@ -1003,7 +518,7 @@ MatterThermostatClusterServerPreAttributeChangedCallback(const app::ConcreteAttr bool CoolSupported = false; bool OccupancySupported = false; - if (FeatureMap::Get(endpoint, &OurFeatureMap) != imcode::Success) + if (FeatureMap::Get(endpoint, &OurFeatureMap) != Status::Success) OurFeatureMap = FEATURE_MAP_DEFAULT; if (OurFeatureMap & 1 << 5) // Bit 5 is Auto Mode supported @@ -1020,63 +535,63 @@ MatterThermostatClusterServerPreAttributeChangedCallback(const app::ConcreteAttr if (AutoSupported) { - if (MinSetpointDeadBand::Get(endpoint, &DeadBand) != imcode::Success) + if (MinSetpointDeadBand::Get(endpoint, &DeadBand) != Status::Success) { DeadBand = kDefaultDeadBand; } DeadBandTemp = static_cast(DeadBand * 10); } - if (AbsMinCoolSetpointLimit::Get(endpoint, &AbsMinCoolSetpointLimit) != imcode::Success) + if (AbsMinCoolSetpointLimit::Get(endpoint, &AbsMinCoolSetpointLimit) != Status::Success) AbsMinCoolSetpointLimit = kDefaultAbsMinCoolSetpointLimit; - if (AbsMaxCoolSetpointLimit::Get(endpoint, &AbsMaxCoolSetpointLimit) != imcode::Success) + if (AbsMaxCoolSetpointLimit::Get(endpoint, &AbsMaxCoolSetpointLimit) != Status::Success) AbsMaxCoolSetpointLimit = kDefaultAbsMaxCoolSetpointLimit; - if (MinCoolSetpointLimit::Get(endpoint, &MinCoolSetpointLimit) != imcode::Success) + if (MinCoolSetpointLimit::Get(endpoint, &MinCoolSetpointLimit) != Status::Success) MinCoolSetpointLimit = AbsMinCoolSetpointLimit; - if (MaxCoolSetpointLimit::Get(endpoint, &MaxCoolSetpointLimit) != imcode::Success) + if (MaxCoolSetpointLimit::Get(endpoint, &MaxCoolSetpointLimit) != Status::Success) MaxCoolSetpointLimit = AbsMaxCoolSetpointLimit; - if (AbsMinHeatSetpointLimit::Get(endpoint, &AbsMinHeatSetpointLimit) != imcode::Success) + if (AbsMinHeatSetpointLimit::Get(endpoint, &AbsMinHeatSetpointLimit) != Status::Success) AbsMinHeatSetpointLimit = kDefaultAbsMinHeatSetpointLimit; - if (AbsMaxHeatSetpointLimit::Get(endpoint, &AbsMaxHeatSetpointLimit) != imcode::Success) + if (AbsMaxHeatSetpointLimit::Get(endpoint, &AbsMaxHeatSetpointLimit) != Status::Success) AbsMaxHeatSetpointLimit = kDefaultAbsMaxHeatSetpointLimit; - if (MinHeatSetpointLimit::Get(endpoint, &MinHeatSetpointLimit) != imcode::Success) + if (MinHeatSetpointLimit::Get(endpoint, &MinHeatSetpointLimit) != Status::Success) MinHeatSetpointLimit = AbsMinHeatSetpointLimit; - if (MaxHeatSetpointLimit::Get(endpoint, &MaxHeatSetpointLimit) != imcode::Success) + if (MaxHeatSetpointLimit::Get(endpoint, &MaxHeatSetpointLimit) != Status::Success) MaxHeatSetpointLimit = AbsMaxHeatSetpointLimit; if (CoolSupported) - if (OccupiedCoolingSetpoint::Get(endpoint, &OccupiedCoolingSetpoint) != imcode::Success) + if (OccupiedCoolingSetpoint::Get(endpoint, &OccupiedCoolingSetpoint) != Status::Success) { ChipLogError(Zcl, "Error: Can not read Occupied Cooling Setpoint"); - return imcode::Failure; + return Status::Failure; } if (HeatSupported) - if (OccupiedHeatingSetpoint::Get(endpoint, &OccupiedHeatingSetpoint) != imcode::Success) + if (OccupiedHeatingSetpoint::Get(endpoint, &OccupiedHeatingSetpoint) != Status::Success) { ChipLogError(Zcl, "Error: Can not read Occupied Heating Setpoint"); - return imcode::Failure; + return Status::Failure; } if (CoolSupported && OccupancySupported) - if (UnoccupiedCoolingSetpoint::Get(endpoint, &UnoccupiedCoolingSetpoint) != imcode::Success) + if (UnoccupiedCoolingSetpoint::Get(endpoint, &UnoccupiedCoolingSetpoint) != Status::Success) { ChipLogError(Zcl, "Error: Can not read Unoccupied Cooling Setpoint"); - return imcode::Failure; + return Status::Failure; } if (HeatSupported && OccupancySupported) - if (UnoccupiedHeatingSetpoint::Get(endpoint, &UnoccupiedHeatingSetpoint) != imcode::Success) + if (UnoccupiedHeatingSetpoint::Get(endpoint, &UnoccupiedHeatingSetpoint) != Status::Success) { ChipLogError(Zcl, "Error: Can not read Unoccupied Heating Setpoint"); - return imcode::Failure; + return Status::Failure; } switch (attributePath.mAttributeId) @@ -1084,143 +599,143 @@ MatterThermostatClusterServerPreAttributeChangedCallback(const app::ConcreteAttr case OccupiedHeatingSetpoint::Id: { requested = static_cast(chip::Encoding::LittleEndian::Get16(value)); if (!HeatSupported) - return imcode::UnsupportedAttribute; + return Status::UnsupportedAttribute; if (requested < AbsMinHeatSetpointLimit || requested < MinHeatSetpointLimit || requested > AbsMaxHeatSetpointLimit || requested > MaxHeatSetpointLimit) - return imcode::InvalidValue; + return Status::InvalidValue; if (AutoSupported) { if (requested > OccupiedCoolingSetpoint - DeadBandTemp) - return imcode::InvalidValue; + return Status::InvalidValue; } - return imcode::Success; + return Status::Success; } case OccupiedCoolingSetpoint::Id: { requested = static_cast(chip::Encoding::LittleEndian::Get16(value)); if (!CoolSupported) - return imcode::UnsupportedAttribute; + return Status::UnsupportedAttribute; if (requested < AbsMinCoolSetpointLimit || requested < MinCoolSetpointLimit || requested > AbsMaxCoolSetpointLimit || requested > MaxCoolSetpointLimit) - return imcode::InvalidValue; + return Status::InvalidValue; if (AutoSupported) { if (requested < OccupiedHeatingSetpoint + DeadBandTemp) - return imcode::InvalidValue; + return Status::InvalidValue; } - return imcode::Success; + return Status::Success; } case UnoccupiedHeatingSetpoint::Id: { requested = static_cast(chip::Encoding::LittleEndian::Get16(value)); if (!(HeatSupported && OccupancySupported)) - return imcode::UnsupportedAttribute; + return Status::UnsupportedAttribute; if (requested < AbsMinHeatSetpointLimit || requested < MinHeatSetpointLimit || requested > AbsMaxHeatSetpointLimit || requested > MaxHeatSetpointLimit) - return imcode::InvalidValue; + return Status::InvalidValue; if (AutoSupported) { if (requested > UnoccupiedCoolingSetpoint - DeadBandTemp) - return imcode::InvalidValue; + return Status::InvalidValue; } - return imcode::Success; + return Status::Success; } case UnoccupiedCoolingSetpoint::Id: { requested = static_cast(chip::Encoding::LittleEndian::Get16(value)); if (!(CoolSupported && OccupancySupported)) - return imcode::UnsupportedAttribute; + return Status::UnsupportedAttribute; if (requested < AbsMinCoolSetpointLimit || requested < MinCoolSetpointLimit || requested > AbsMaxCoolSetpointLimit || requested > MaxCoolSetpointLimit) - return imcode::InvalidValue; + return Status::InvalidValue; if (AutoSupported) { if (requested < UnoccupiedHeatingSetpoint + DeadBandTemp) - return imcode::InvalidValue; + return Status::InvalidValue; } - return imcode::Success; + return Status::Success; } case MinHeatSetpointLimit::Id: { requested = static_cast(chip::Encoding::LittleEndian::Get16(value)); if (!HeatSupported) - return imcode::UnsupportedAttribute; + return Status::UnsupportedAttribute; if (requested < AbsMinHeatSetpointLimit || requested > MaxHeatSetpointLimit || requested > AbsMaxHeatSetpointLimit) - return imcode::InvalidValue; + return Status::InvalidValue; if (AutoSupported) { if (requested > MinCoolSetpointLimit - DeadBandTemp) - return imcode::InvalidValue; + return Status::InvalidValue; } - return imcode::Success; + return Status::Success; } case MaxHeatSetpointLimit::Id: { requested = static_cast(chip::Encoding::LittleEndian::Get16(value)); if (!HeatSupported) - return imcode::UnsupportedAttribute; + return Status::UnsupportedAttribute; if (requested < AbsMinHeatSetpointLimit || requested < MinHeatSetpointLimit || requested > AbsMaxHeatSetpointLimit) - return imcode::InvalidValue; + return Status::InvalidValue; if (AutoSupported) { if (requested > MaxCoolSetpointLimit - DeadBandTemp) - return imcode::InvalidValue; + return Status::InvalidValue; } - return imcode::Success; + return Status::Success; } case MinCoolSetpointLimit::Id: { requested = static_cast(chip::Encoding::LittleEndian::Get16(value)); if (!CoolSupported) - return imcode::UnsupportedAttribute; + return Status::UnsupportedAttribute; if (requested < AbsMinCoolSetpointLimit || requested > MaxCoolSetpointLimit || requested > AbsMaxCoolSetpointLimit) - return imcode::InvalidValue; + return Status::InvalidValue; if (AutoSupported) { if (requested < MinHeatSetpointLimit + DeadBandTemp) - return imcode::InvalidValue; + return Status::InvalidValue; } - return imcode::Success; + return Status::Success; } case MaxCoolSetpointLimit::Id: { requested = static_cast(chip::Encoding::LittleEndian::Get16(value)); if (!CoolSupported) - return imcode::UnsupportedAttribute; + return Status::UnsupportedAttribute; if (requested < AbsMinCoolSetpointLimit || requested < MinCoolSetpointLimit || requested > AbsMaxCoolSetpointLimit) - return imcode::InvalidValue; + return Status::InvalidValue; if (AutoSupported) { if (requested < MaxHeatSetpointLimit + DeadBandTemp) - return imcode::InvalidValue; + return Status::InvalidValue; } - return imcode::Success; + return Status::Success; } case MinSetpointDeadBand::Id: { requested = *value; if (!AutoSupported) - return imcode::UnsupportedAttribute; + return Status::UnsupportedAttribute; if (requested < 0 || requested > 25) - return imcode::InvalidValue; - return imcode::Success; + return Status::InvalidValue; + return Status::Success; } case ControlSequenceOfOperation::Id: { uint8_t requestedCSO; requestedCSO = *value; if (requestedCSO > to_underlying(ControlSequenceOfOperationEnum::kCoolingAndHeatingWithReheat)) - return imcode::InvalidValue; - return imcode::Success; + return Status::InvalidValue; + return Status::Success; } case SystemMode::Id: { ControlSequenceOfOperationEnum ControlSequenceOfOperation; - imcode status = ControlSequenceOfOperation::Get(endpoint, &ControlSequenceOfOperation); - if (status != imcode::Success) + Status status = ControlSequenceOfOperation::Get(endpoint, &ControlSequenceOfOperation); + if (status != Status::Success) { - return imcode::InvalidValue; + return Status::InvalidValue; } auto RequestedSystemMode = static_cast(*value); if (ControlSequenceOfOperation > ControlSequenceOfOperationEnum::kCoolingAndHeatingWithReheat || RequestedSystemMode > SystemModeEnum::kFanOnly) { - return imcode::InvalidValue; + return Status::InvalidValue; } switch (ControlSequenceOfOperation) @@ -1228,22 +743,22 @@ MatterThermostatClusterServerPreAttributeChangedCallback(const app::ConcreteAttr case ControlSequenceOfOperationEnum::kCoolingOnly: case ControlSequenceOfOperationEnum::kCoolingWithReheat: if (RequestedSystemMode == SystemModeEnum::kHeat || RequestedSystemMode == SystemModeEnum::kEmergencyHeat) - return imcode::InvalidValue; + return Status::InvalidValue; else - return imcode::Success; + return Status::Success; case ControlSequenceOfOperationEnum::kHeatingOnly: case ControlSequenceOfOperationEnum::kHeatingWithReheat: if (RequestedSystemMode == SystemModeEnum::kCool || RequestedSystemMode == SystemModeEnum::kPrecooling) - return imcode::InvalidValue; + return Status::InvalidValue; else - return imcode::Success; + return Status::Success; default: - return imcode::Success; + return Status::Success; } } default: - return imcode::Success; + return Status::Success; } } @@ -1279,363 +794,6 @@ bool emberAfThermostatClusterSetActiveScheduleRequestCallback( return false; } -bool emberAfThermostatClusterSetActivePresetRequestCallback( - CommandHandler * commandObj, const ConcreteCommandPath & commandPath, - const Clusters::Thermostat::Commands::SetActivePresetRequest::DecodableType & commandData) -{ - EndpointId endpoint = commandPath.mEndpointId; - Delegate * delegate = GetDelegate(endpoint); - - if (delegate == nullptr) - { - ChipLogError(Zcl, "Delegate is null"); - commandObj->AddStatus(commandPath, imcode::InvalidInState); - return true; - } - - DataModel::Nullable newPresetHandle = commandData.presetHandle; - - // If the preset handle passed in the command is not present in the Presets attribute, return INVALID_COMMAND. - if (!newPresetHandle.IsNull() && !IsPresetHandlePresentInPresets(delegate, newPresetHandle.Value())) - { - commandObj->AddStatus(commandPath, imcode::InvalidCommand); - return true; - } - - CHIP_ERROR err = delegate->SetActivePresetHandle(newPresetHandle); - - if (err != CHIP_NO_ERROR) - { - ChipLogError(Zcl, "Failed to set ActivePresetHandle with error %" CHIP_ERROR_FORMAT, err.Format()); - commandObj->AddStatus(commandPath, StatusIB(err).mStatus); - return true; - } - - commandObj->AddStatus(commandPath, imcode::Success); - return true; -} - -bool validAtomicAttributes(const Commands::AtomicRequest::DecodableType & commandData, bool requireBoth) -{ - auto attributeIdsIter = commandData.attributeRequests.begin(); - bool requestedPresets = false, requestedSchedules = false; - while (attributeIdsIter.Next()) - { - auto & attributeId = attributeIdsIter.GetValue(); - - switch (attributeId) - { - case Presets::Id: - if (requestedPresets) // Double-requesting an attribute is invalid - { - return false; - } - requestedPresets = true; - break; - case Schedules::Id: - if (requestedSchedules) // Double-requesting an attribute is invalid - { - return false; - } - requestedSchedules = true; - break; - default: - return false; - } - } - if (attributeIdsIter.GetStatus() != CHIP_NO_ERROR) - { - return false; - } - if (requireBoth) - { - return (requestedPresets && requestedSchedules); - } - // If the atomic request doesn't contain at least one of these attributes, it's invalid - return (requestedPresets || requestedSchedules); -} - -void sendAtomicResponse(CommandHandler * commandObj, const ConcreteCommandPath & commandPath, imcode status, imcode presetsStatus, - imcode schedulesStatus, Optional timeout = NullOptional) -{ - Commands::AtomicResponse::Type response; - Globals::Structs::AtomicAttributeStatusStruct::Type attributeStatus[] = { - { .attributeID = Presets::Id, .statusCode = to_underlying(presetsStatus) }, - { .attributeID = Schedules::Id, .statusCode = to_underlying(schedulesStatus) } - }; - response.statusCode = to_underlying(status); - response.attributeStatus = attributeStatus; - response.timeout = timeout; - commandObj->AddResponse(commandPath, response); -} - -void handleAtomicBegin(CommandHandler * commandObj, const ConcreteCommandPath & commandPath, - const Commands::AtomicRequest::DecodableType & commandData) -{ - EndpointId endpoint = commandPath.mEndpointId; - - Delegate * delegate = GetDelegate(endpoint); - - if (delegate == nullptr) - { - ChipLogError(Zcl, "Delegate is null"); - commandObj->AddStatus(commandPath, imcode::InvalidInState); - return; - } - - if (gThermostatAttrAccess.InAtomicWrite(commandObj, endpoint)) - { - // This client already has an open atomic write - commandObj->AddStatus(commandPath, imcode::InvalidInState); - return; - } - - if (!commandData.timeout.HasValue()) - { - commandObj->AddStatus(commandPath, imcode::InvalidCommand); - return; - } - - if (!validAtomicAttributes(commandData, false)) - { - commandObj->AddStatus(commandPath, imcode::InvalidCommand); - return; - } - - if (gThermostatAttrAccess.InAtomicWrite(endpoint)) - { - sendAtomicResponse(commandObj, commandPath, imcode::Failure, imcode::Busy, imcode::Busy); - return; - } - - // This is a valid request to open an atomic write. Tell the delegate it - // needs to keep track of a pending preset list now. - delegate->InitializePendingPresets(); - - auto timeout = - delegate->GetAtomicWriteTimeout(commandData.attributeRequests, System::Clock::Milliseconds16(commandData.timeout.Value())); - - if (!timeout.has_value()) - { - commandObj->AddStatus(commandPath, imcode::InvalidCommand); - return; - } - ScheduleTimer(endpoint, timeout.value()); - gThermostatAttrAccess.SetAtomicWrite(endpoint, GetSourceScopedNodeId(commandObj), kAtomicWriteState_Open); - sendAtomicResponse(commandObj, commandPath, imcode::Success, imcode::Success, imcode::Success, - MakeOptional(timeout.value().count())); -} - -imcode commitPresets(Delegate * delegate, EndpointId endpoint) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - - // For each preset in the presets attribute, check that the matching preset in the pending presets list does not - // violate any spec constraints. - for (uint8_t i = 0; true; i++) - { - PresetStructWithOwnedMembers preset; - err = delegate->GetPresetAtIndex(i, preset); - - if (err == CHIP_ERROR_PROVIDER_LIST_EXHAUSTED) - { - break; - } - if (err != CHIP_NO_ERROR) - { - ChipLogError(Zcl, - "emberAfThermostatClusterCommitPresetsSchedulesRequestCallback: GetPresetAtIndex failed with error " - "%" CHIP_ERROR_FORMAT, - err.Format()); - return imcode::InvalidInState; - } - - bool found = MatchingPendingPresetExists(delegate, preset); - - // If a built in preset in the Presets attribute list is removed and not found in the pending presets list, return - // CONSTRAINT_ERROR. - if (IsBuiltIn(preset) && !found) - { - return imcode::ConstraintError; - } - } - - // If there is an ActivePresetHandle set, find the preset in the pending presets list that matches the ActivePresetHandle - // attribute. If a preset is not found with the same presetHandle, return INVALID_IN_STATE. If there is no ActivePresetHandle - // attribute set, continue with other checks. - uint8_t buffer[kPresetHandleSize]; - MutableByteSpan activePresetHandleSpan(buffer); - auto activePresetHandle = DataModel::MakeNullable(activePresetHandleSpan); - - err = delegate->GetActivePresetHandle(activePresetHandle); - - if (err != CHIP_NO_ERROR) - { - return imcode::InvalidInState; - } - - if (!activePresetHandle.IsNull()) - { - uint8_t count = CountPresetsInPendingListWithPresetHandle(delegate, activePresetHandle.Value()); - if (count == 0) - { - return imcode::InvalidInState; - } - } - - // For each preset in the pending presets list, check that the preset does not violate any spec constraints. - for (uint8_t i = 0; true; i++) - { - PresetStructWithOwnedMembers pendingPreset; - err = delegate->GetPendingPresetAtIndex(i, pendingPreset); - - if (err == CHIP_ERROR_PROVIDER_LIST_EXHAUSTED) - { - break; - } - if (err != CHIP_NO_ERROR) - { - ChipLogError(Zcl, - "emberAfThermostatClusterCommitPresetsSchedulesRequestCallback: GetPendingPresetAtIndex failed with error " - "%" CHIP_ERROR_FORMAT, - err.Format()); - return imcode::InvalidInState; - } - - // Enforce the Setpoint Limits for both the cooling and heating setpoints in the pending preset. - // TODO: This code does not work, because it's modifying our temporary copy. - Optional coolingSetpointValue = pendingPreset.GetCoolingSetpoint(); - if (coolingSetpointValue.HasValue()) - { - pendingPreset.SetCoolingSetpoint(MakeOptional(EnforceCoolingSetpointLimits(coolingSetpointValue.Value(), endpoint))); - } - - Optional heatingSetpointValue = pendingPreset.GetHeatingSetpoint(); - if (heatingSetpointValue.HasValue()) - { - pendingPreset.SetHeatingSetpoint(MakeOptional(EnforceHeatingSetpointLimits(heatingSetpointValue.Value(), endpoint))); - } - } - - uint8_t totalCount = CountNumberOfPendingPresets(delegate); - - uint8_t numberOfPresetsSupported = delegate->GetNumberOfPresets(); - - if (numberOfPresetsSupported == 0) - { - ChipLogError(Zcl, "emberAfThermostatClusterCommitPresetsSchedulesRequestCallback: Failed to get NumberOfPresets"); - return imcode::InvalidInState; - } - - // If the expected length of the presets attribute with the applied changes exceeds the total number of presets supported, - // return RESOURCE_EXHAUSTED. Note that the changes are not yet applied. - if (numberOfPresetsSupported > 0 && totalCount > numberOfPresetsSupported) - { - return imcode::ResourceExhausted; - } - - // TODO: Check if the number of presets for each presetScenario exceeds the max number of presets supported for that - // scenario. We plan to support only one preset for each presetScenario for our use cases so defer this for re-evaluation. - - // Call the delegate API to apply the pending presets to the presets attribute and update it. - err = delegate->ApplyPendingPresets(); - - if (err != CHIP_NO_ERROR) - { - return imcode::InvalidInState; - } - - return imcode::Success; -} - -void handleAtomicCommit(CommandHandler * commandObj, const ConcreteCommandPath & commandPath, - const Commands::AtomicRequest::DecodableType & commandData) -{ - if (!validAtomicAttributes(commandData, true)) - { - commandObj->AddStatus(commandPath, imcode::InvalidCommand); - return; - } - EndpointId endpoint = commandPath.mEndpointId; - bool inAtomicWrite = gThermostatAttrAccess.InAtomicWrite(commandObj, endpoint); - if (!inAtomicWrite) - { - commandObj->AddStatus(commandPath, imcode::InvalidInState); - return; - } - - Delegate * delegate = GetDelegate(endpoint); - - if (delegate == nullptr) - { - ChipLogError(Zcl, "Delegate is null"); - commandObj->AddStatus(commandPath, imcode::InvalidInState); - return; - } - - auto presetsStatus = commitPresets(delegate, endpoint); - // TODO: copy over schedules code - auto schedulesStatus = imcode::Success; - resetAtomicWrite(delegate, endpoint); - imcode status = (presetsStatus == imcode::Success && schedulesStatus == imcode::Success) ? imcode::Success : imcode::Failure; - sendAtomicResponse(commandObj, commandPath, status, presetsStatus, schedulesStatus); -} - -void handleAtomicRollback(CommandHandler * commandObj, const ConcreteCommandPath & commandPath, - const Commands::AtomicRequest::DecodableType & commandData) -{ - if (!validAtomicAttributes(commandData, true)) - { - commandObj->AddStatus(commandPath, imcode::InvalidCommand); - return; - } - EndpointId endpoint = commandPath.mEndpointId; - bool inAtomicWrite = gThermostatAttrAccess.InAtomicWrite(commandObj, endpoint); - if (!inAtomicWrite) - { - commandObj->AddStatus(commandPath, imcode::InvalidInState); - return; - } - - Delegate * delegate = GetDelegate(endpoint); - - if (delegate == nullptr) - { - ChipLogError(Zcl, "Delegate is null"); - commandObj->AddStatus(commandPath, imcode::InvalidInState); - return; - } - resetAtomicWrite(delegate, endpoint); - sendAtomicResponse(commandObj, commandPath, imcode::Success, imcode::Success, imcode::Success); -} - -bool emberAfThermostatClusterAtomicRequestCallback(CommandHandler * commandObj, const ConcreteCommandPath & commandPath, - const Clusters::Thermostat::Commands::AtomicRequest::DecodableType & commandData) -{ - auto & requestType = commandData.requestType; - - // If we've gotten this far, then the client has manage permission to call AtomicRequest, which is also the - // privilege necessary to write to the atomic attributes, so no need to check - - switch (requestType) - { - case Globals::AtomicRequestTypeEnum::kBeginWrite: - handleAtomicBegin(commandObj, commandPath, commandData); - return true; - case Globals::AtomicRequestTypeEnum::kCommitWrite: - handleAtomicCommit(commandObj, commandPath, commandData); - return true; - case Globals::AtomicRequestTypeEnum::kRollbackWrite: - handleAtomicRollback(commandObj, commandPath, commandData); - return true; - case Globals::AtomicRequestTypeEnum::kUnknownEnumValue: - commandObj->AddStatus(commandPath, imcode::InvalidCommand); - return true; - } - - return false; -} - bool emberAfThermostatClusterSetpointRaiseLowerCallback(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, const Commands::SetpointRaiseLower::DecodableType & commandData) @@ -1646,9 +804,9 @@ bool emberAfThermostatClusterSetpointRaiseLowerCallback(app::CommandHandler * co EndpointId aEndpointId = commandPath.mEndpointId; int16_t HeatingSetpoint = kDefaultHeatingSetpoint, CoolingSetpoint = kDefaultCoolingSetpoint; // Set to defaults to be safe - imcode status = imcode::Failure; - imcode WriteCoolingSetpointStatus = imcode::Failure; - imcode WriteHeatingSetpointStatus = imcode::Failure; + Status status = Status::Failure; + Status WriteCoolingSetpointStatus = Status::Failure; + Status WriteHeatingSetpointStatus = Status::Failure; int16_t DeadBandTemp = 0; int8_t DeadBand = 0; uint32_t OurFeatureMap; @@ -1656,7 +814,7 @@ bool emberAfThermostatClusterSetpointRaiseLowerCallback(app::CommandHandler * co bool HeatSupported = false; bool CoolSupported = false; - if (FeatureMap::Get(aEndpointId, &OurFeatureMap) != imcode::Success) + if (FeatureMap::Get(aEndpointId, &OurFeatureMap) != Status::Success) OurFeatureMap = FEATURE_MAP_DEFAULT; if (OurFeatureMap & 1 << 5) // Bit 5 is Auto Mode supported @@ -1670,7 +828,7 @@ bool emberAfThermostatClusterSetpointRaiseLowerCallback(app::CommandHandler * co if (AutoSupported) { - if (MinSetpointDeadBand::Get(aEndpointId, &DeadBand) != imcode::Success) + if (MinSetpointDeadBand::Get(aEndpointId, &DeadBand) != Status::Success) DeadBand = kDefaultDeadBand; DeadBandTemp = static_cast(DeadBand * 10); } @@ -1681,13 +839,13 @@ bool emberAfThermostatClusterSetpointRaiseLowerCallback(app::CommandHandler * co if (HeatSupported && CoolSupported) { int16_t DesiredCoolingSetpoint, CoolLimit, DesiredHeatingSetpoint, HeatLimit; - if (OccupiedCoolingSetpoint::Get(aEndpointId, &CoolingSetpoint) == imcode::Success) + if (OccupiedCoolingSetpoint::Get(aEndpointId, &CoolingSetpoint) == Status::Success) { DesiredCoolingSetpoint = static_cast(CoolingSetpoint + amount * 10); CoolLimit = static_cast(DesiredCoolingSetpoint - EnforceCoolingSetpointLimits(DesiredCoolingSetpoint, aEndpointId)); { - if (OccupiedHeatingSetpoint::Get(aEndpointId, &HeatingSetpoint) == imcode::Success) + if (OccupiedHeatingSetpoint::Get(aEndpointId, &HeatingSetpoint) == Status::Success) { DesiredHeatingSetpoint = static_cast(HeatingSetpoint + amount * 10); HeatLimit = static_cast(DesiredHeatingSetpoint - @@ -1709,12 +867,12 @@ bool emberAfThermostatClusterSetpointRaiseLowerCallback(app::CommandHandler * co } } WriteCoolingSetpointStatus = OccupiedCoolingSetpoint::Set(aEndpointId, DesiredCoolingSetpoint); - if (WriteCoolingSetpointStatus != imcode::Success) + if (WriteCoolingSetpointStatus != Status::Success) { ChipLogError(Zcl, "Error: SetOccupiedCoolingSetpoint failed!"); } WriteHeatingSetpointStatus = OccupiedHeatingSetpoint::Set(aEndpointId, DesiredHeatingSetpoint); - if (WriteHeatingSetpointStatus != imcode::Success) + if (WriteHeatingSetpointStatus != Status::Success) { ChipLogError(Zcl, "Error: SetOccupiedHeatingSetpoint failed!"); } @@ -1726,12 +884,12 @@ bool emberAfThermostatClusterSetpointRaiseLowerCallback(app::CommandHandler * co if (CoolSupported && !HeatSupported) { - if (OccupiedCoolingSetpoint::Get(aEndpointId, &CoolingSetpoint) == imcode::Success) + if (OccupiedCoolingSetpoint::Get(aEndpointId, &CoolingSetpoint) == Status::Success) { CoolingSetpoint = static_cast(CoolingSetpoint + amount * 10); CoolingSetpoint = EnforceCoolingSetpointLimits(CoolingSetpoint, aEndpointId); WriteCoolingSetpointStatus = OccupiedCoolingSetpoint::Set(aEndpointId, CoolingSetpoint); - if (WriteCoolingSetpointStatus != imcode::Success) + if (WriteCoolingSetpointStatus != Status::Success) { ChipLogError(Zcl, "Error: SetOccupiedCoolingSetpoint failed!"); } @@ -1740,34 +898,34 @@ bool emberAfThermostatClusterSetpointRaiseLowerCallback(app::CommandHandler * co if (HeatSupported && !CoolSupported) { - if (OccupiedHeatingSetpoint::Get(aEndpointId, &HeatingSetpoint) == imcode::Success) + if (OccupiedHeatingSetpoint::Get(aEndpointId, &HeatingSetpoint) == Status::Success) { HeatingSetpoint = static_cast(HeatingSetpoint + amount * 10); HeatingSetpoint = EnforceHeatingSetpointLimits(HeatingSetpoint, aEndpointId); WriteHeatingSetpointStatus = OccupiedHeatingSetpoint::Set(aEndpointId, HeatingSetpoint); - if (WriteHeatingSetpointStatus != imcode::Success) + if (WriteHeatingSetpointStatus != Status::Success) { ChipLogError(Zcl, "Error: SetOccupiedHeatingSetpoint failed!"); } } } - if ((!HeatSupported || WriteHeatingSetpointStatus == imcode::Success) && - (!CoolSupported || WriteCoolingSetpointStatus == imcode::Success)) - status = imcode::Success; + if ((!HeatSupported || WriteHeatingSetpointStatus == Status::Success) && + (!CoolSupported || WriteCoolingSetpointStatus == Status::Success)) + status = Status::Success; break; case SetpointRaiseLowerModeEnum::kCool: if (CoolSupported) { - if (OccupiedCoolingSetpoint::Get(aEndpointId, &CoolingSetpoint) == imcode::Success) + if (OccupiedCoolingSetpoint::Get(aEndpointId, &CoolingSetpoint) == Status::Success) { CoolingSetpoint = static_cast(CoolingSetpoint + amount * 10); CoolingSetpoint = EnforceCoolingSetpointLimits(CoolingSetpoint, aEndpointId); if (AutoSupported) { // Need to check if we can move the cooling setpoint while maintaining the dead band - if (OccupiedHeatingSetpoint::Get(aEndpointId, &HeatingSetpoint) == imcode::Success) + if (OccupiedHeatingSetpoint::Get(aEndpointId, &HeatingSetpoint) == Status::Success) { if (CoolingSetpoint - HeatingSetpoint < DeadBandTemp) { @@ -1778,10 +936,10 @@ bool emberAfThermostatClusterSetpointRaiseLowerCallback(app::CommandHandler * co { // Desired cooling setpoint is enforcable // Set the new cooling and heating setpoints - if (OccupiedHeatingSetpoint::Set(aEndpointId, HeatingSetpoint) == imcode::Success) + if (OccupiedHeatingSetpoint::Set(aEndpointId, HeatingSetpoint) == Status::Success) { - if (OccupiedCoolingSetpoint::Set(aEndpointId, CoolingSetpoint) == imcode::Success) - status = imcode::Success; + if (OccupiedCoolingSetpoint::Set(aEndpointId, CoolingSetpoint) == Status::Success) + status = Status::Success; } else ChipLogError(Zcl, "Error: SetOccupiedHeatingSetpoint failed!"); @@ -1789,7 +947,7 @@ bool emberAfThermostatClusterSetpointRaiseLowerCallback(app::CommandHandler * co else { ChipLogError(Zcl, "Error: Could Not adjust heating setpoint to maintain dead band!"); - status = imcode::InvalidCommand; + status = Status::InvalidCommand; } } else @@ -1807,20 +965,20 @@ bool emberAfThermostatClusterSetpointRaiseLowerCallback(app::CommandHandler * co ChipLogError(Zcl, "Error: GetOccupiedCoolingSetpoint failed!"); } else - status = imcode::InvalidCommand; + status = Status::InvalidCommand; break; case SetpointRaiseLowerModeEnum::kHeat: if (HeatSupported) { - if (OccupiedHeatingSetpoint::Get(aEndpointId, &HeatingSetpoint) == imcode::Success) + if (OccupiedHeatingSetpoint::Get(aEndpointId, &HeatingSetpoint) == Status::Success) { HeatingSetpoint = static_cast(HeatingSetpoint + amount * 10); HeatingSetpoint = EnforceHeatingSetpointLimits(HeatingSetpoint, aEndpointId); if (AutoSupported) { // Need to check if we can move the cooling setpoint while maintaining the dead band - if (OccupiedCoolingSetpoint::Get(aEndpointId, &CoolingSetpoint) == imcode::Success) + if (OccupiedCoolingSetpoint::Get(aEndpointId, &CoolingSetpoint) == Status::Success) { if (CoolingSetpoint - HeatingSetpoint < DeadBandTemp) { @@ -1831,10 +989,10 @@ bool emberAfThermostatClusterSetpointRaiseLowerCallback(app::CommandHandler * co { // Desired cooling setpoint is enforcable // Set the new cooling and heating setpoints - if (OccupiedCoolingSetpoint::Set(aEndpointId, CoolingSetpoint) == imcode::Success) + if (OccupiedCoolingSetpoint::Set(aEndpointId, CoolingSetpoint) == Status::Success) { - if (OccupiedHeatingSetpoint::Set(aEndpointId, HeatingSetpoint) == imcode::Success) - status = imcode::Success; + if (OccupiedHeatingSetpoint::Set(aEndpointId, HeatingSetpoint) == Status::Success) + status = Status::Success; } else ChipLogError(Zcl, "Error: SetOccupiedCoolingSetpoint failed!"); @@ -1842,7 +1000,7 @@ bool emberAfThermostatClusterSetpointRaiseLowerCallback(app::CommandHandler * co else { ChipLogError(Zcl, "Error: Could Not adjust cooling setpoint to maintain dead band!"); - status = imcode::InvalidCommand; + status = Status::InvalidCommand; } } else @@ -1860,11 +1018,11 @@ bool emberAfThermostatClusterSetpointRaiseLowerCallback(app::CommandHandler * co ChipLogError(Zcl, "Error: GetOccupiedHeatingSetpoint failed!"); } else - status = imcode::InvalidCommand; + status = Status::InvalidCommand; break; default: - status = imcode::InvalidCommand; + status = Status::InvalidCommand; break; } @@ -1877,14 +1035,3 @@ void MatterThermostatPluginServerInitCallback() Server::GetInstance().GetFabricTable().AddFabricDelegate(&gThermostatAttrAccess); AttributeAccessInterfaceRegistry::Instance().Register(&gThermostatAttrAccess); } - -void MatterThermostatClusterServerShutdownCallback(EndpointId endpoint) -{ - ChipLogProgress(Zcl, "Shutting down thermostat server cluster on endpoint %d", endpoint); - Delegate * delegate = GetDelegate(endpoint); - - if (delegate != nullptr) - { - resetAtomicWrite(delegate, endpoint); - } -} diff --git a/src/app/clusters/thermostat-server/thermostat-server.h b/src/app/clusters/thermostat-server/thermostat-server.h index ddede8a9bb..cc941cfa76 100644 --- a/src/app/clusters/thermostat-server/thermostat-server.h +++ b/src/app/clusters/thermostat-server/thermostat-server.h @@ -26,6 +26,7 @@ #include "thermostat-delegate.h" +#include #include #include @@ -34,25 +35,62 @@ namespace app { namespace Clusters { namespace Thermostat { +enum class AtomicWriteState +{ + Closed = 0, + Open, +}; + static constexpr size_t kThermostatEndpointCount = MATTER_DM_THERMOSTAT_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; -enum AtomicWriteState -{ - kAtomicWriteState_Closed = 0, - kAtomicWriteState_Open, -}; /** * @brief Thermostat Attribute Access Interface. */ class ThermostatAttrAccess : public chip::app::AttributeAccessInterface, public chip::FabricTable::Delegate { + public: ThermostatAttrAccess() : AttributeAccessInterface(Optional::Missing(), Thermostat::Id) {} CHIP_ERROR Read(const ConcreteReadAttributePath & aPath, AttributeValueEncoder & aEncoder) override; CHIP_ERROR Write(const ConcreteDataAttributePath & aPath, chip::app::AttributeValueDecoder & aDecoder) override; +private: + /** + * @brief Set the Active Preset to a given preset handle, or null + * + * @param endpoint The endpoint + * @param presetHandle The handle of the preset to set active, or null to clear the active preset + * @return Success if the active preset was updated, an error code if not + */ + Protocols::InteractionModel::Status SetActivePreset(EndpointId endpoint, DataModel::Nullable presetHandle); + + /** + * @brief Apply a preset to the pending lists of presets during an atomic write + * + * @param delegate The current ThermostatDelegate + * @param preset The preset to append + * @return CHIP_NO_ERROR if successful, an error code if not + */ + CHIP_ERROR AppendPendingPreset(Thermostat::Delegate * delegate, const Structs::PresetStruct::Type & preset); + + /** + * @brief Verifies if the pending presets for a given endpoint are valid + * + * @param endpoint The endpoint + * @return Success if the list of pending presets is valid, an error code if not + */ + Protocols::InteractionModel::Status PrecommitPresets(EndpointId endpoint); + + /** + * @brief Callback for when the server is removed from a given fabric; all associated atomic writes are reset + * + * @param fabricTable The fabric table + * @param fabricIndex The fabric index + */ + void OnFabricRemoved(const FabricTable & fabricTable, FabricIndex fabricIndex) override; + /** * @brief Gets the scoped node id of the originator that sent the last successful * AtomicRequest of type BeginWrite for the given endpoint. @@ -61,7 +99,7 @@ class ThermostatAttrAccess : public chip::app::AttributeAccessInterface, public * * @return the scoped node id for the given endpoint if set. Otherwise returns ScopedNodeId(). */ - ScopedNodeId GetAtomicWriteScopedNodeId(EndpointId endpoint); + ScopedNodeId GetAtomicWriteOriginatorScopedNodeId(EndpointId endpoint); /** * @brief Sets the atomic write state for the given endpoint and originatorNodeId @@ -69,46 +107,119 @@ class ThermostatAttrAccess : public chip::app::AttributeAccessInterface, public * @param[in] endpoint The endpoint. * @param[in] originatorNodeId The originator scoped node id. * @param[in] state Whether or not an atomic write is open or closed. + * @param attributeStatuses The set of attribute status structs the atomic write should be associated with + * @return true if it was able to update the atomic write state + * @return false if it was unable to update the atomic write state */ - void SetAtomicWrite(EndpointId endpoint, ScopedNodeId originatorNodeId, AtomicWriteState state); + bool + SetAtomicWrite(EndpointId endpoint, ScopedNodeId originatorNodeId, AtomicWriteState state, + Platform::ScopedMemoryBufferWithSize & attributeStatuses); /** - * @brief Gets whether an atomic write is in progress for the given endpoint + * @brief Sets the atomic write state for the given endpoint and originatorNodeId * - * @param[in] endpoint The endpoint. + */ + /** + * @brief Resets the atomic write for a given endpoint * - * @return Whether an atomic write is in progress for the given endpoint + * @param endpoint The endpoint */ - bool InAtomicWrite(EndpointId endpoint); + void ResetAtomicWrite(EndpointId endpoint); /** - * @brief Gets whether an atomic write is in progress for the given endpoint + * @brief Checks if a given endpoint has an atomic write open, optionally filtered by an attribute ID * - * @param[in] subjectDescriptor The subject descriptor. - * @param[in] endpoint The endpoint. + * @param endpoint The endpoint + * @param attributeId The optional attribute ID to filter on + * @return true if the endpoint has an open atomic write + * @return false if the endpoint does not have an open atomic write + */ + bool InAtomicWrite(EndpointId endpoint, Optional attributeId = NullOptional); + + /** + * @brief Checks if a given endpoint has an atomic write open for a given subject descriptor, optionally filtered by an + * attribute ID * - * @return Whether an atomic write is in progress for the given endpoint + * @param endpoint The endpoint + * @param subjectDescriptor The subject descriptor for the client making a read or write request + * @param attributeId The optional attribute ID to filter on + * @return true if the endpoint has an open atomic write + * @return false if the endpoint does not have an open atomic write */ - bool InAtomicWrite(const Access::SubjectDescriptor & subjectDescriptor, EndpointId endpoint); + bool InAtomicWrite(EndpointId endpoint, const Access::SubjectDescriptor & subjectDescriptor, + Optional attributeId = NullOptional); /** - * @brief Gets whether an atomic write is in progress for the given endpoint + * @brief Checks if a given endpoint has an atomic write open for a given command invocation, optionally filtered by an + * attribute ID * - * @param[in] commandObj The command handler. - * @param[in] endpoint The endpoint. + * @param endpoint The endpoint + * @param commandObj The CommandHandler for the invoked command + * @param attributeId The optional attribute ID to filter on + * @return true if the endpoint has an open atomic write + * @return false if the endpoint does not have an open atomic write + */ + bool InAtomicWrite(EndpointId endpoint, CommandHandler * commandObj, Optional attributeId = NullOptional); + + /** + * @brief Checks if a given endpoint has an atomic write open for a given command invocation and a list of attributes * - * @return Whether an atomic write is in progress for the given endpoint + * @param endpoint The endpoint + * @param commandObj The CommandHandler for the invoked command + * @param attributeStatuses The list of attribute statuses whose attributeIds must match the open atomic write + * @return true if the endpoint has an open atomic write + * @return false if the endpoint does not have an open atomic write */ - bool InAtomicWrite(CommandHandler * commandObj, EndpointId endpoint); + bool + InAtomicWrite(EndpointId endpoint, CommandHandler * commandObj, + Platform::ScopedMemoryBufferWithSize & attributeStatuses); -private: - CHIP_ERROR AppendPendingPreset(Thermostat::Delegate * delegate, const Structs::PresetStruct::Type & preset); + /** + * @brief Handles an AtomicRequest of type BeginWrite + * + * @param commandObj The AtomicRequest command handler + * @param commandPath The path for the Atomic Request command + * @param commandData The payload data for the Atomic Request + */ + void BeginAtomicWrite(CommandHandler * commandObj, const ConcreteCommandPath & commandPath, + const Commands::AtomicRequest::DecodableType & commandData); - void OnFabricRemoved(const FabricTable & fabricTable, FabricIndex fabricIndex) override; + /** + * @brief Handles an AtomicRequest of type CommitWrite + * + * @param commandObj The AtomicRequest command handler + * @param commandPath The path for the Atomic Request command + * @param commandData The payload data for the Atomic Request + */ + void CommitAtomicWrite(CommandHandler * commandObj, const ConcreteCommandPath & commandPath, + const Commands::AtomicRequest::DecodableType & commandData); + + /** + * @brief Handles an AtomicRequest of type RollbackWrite + * + * @param commandObj The AtomicRequest command handler + * @param commandPath The path for the Atomic Request command + * @param commandData The payload data for the Atomic Request + */ + void RollbackAtomicWrite(CommandHandler * commandObj, const ConcreteCommandPath & commandPath, + const Commands::AtomicRequest::DecodableType & commandData); + + friend void TimerExpiredCallback(System::Layer * systemLayer, void * callbackContext); + + friend void MatterThermostatClusterServerShutdownCallback(EndpointId endpoint); + + friend bool emberAfThermostatClusterSetActivePresetRequestCallback( + CommandHandler * commandObj, const ConcreteCommandPath & commandPath, + const Clusters::Thermostat::Commands::SetActivePresetRequest::DecodableType & commandData); + + friend bool + emberAfThermostatClusterAtomicRequestCallback(CommandHandler * commandObj, const ConcreteCommandPath & commandPath, + const Clusters::Thermostat::Commands::AtomicRequest::DecodableType & commandData); struct AtomicWriteSession { - AtomicWriteState state = kAtomicWriteState_Closed; + AtomicWriteState state = AtomicWriteState::Closed; + Platform::ScopedMemoryBufferWithSize attributeIds; ScopedNodeId nodeId; EndpointId endpointId = kInvalidEndpointId; }; @@ -124,6 +235,8 @@ class ThermostatAttrAccess : public chip::app::AttributeAccessInterface, public */ void SetDefaultDelegate(EndpointId endpoint, Delegate * delegate); +Delegate * GetDelegate(EndpointId endpoint); + } // namespace Thermostat } // namespace Clusters } // namespace app diff --git a/src/python_testing/TC_TSTAT_4_2.py b/src/python_testing/TC_TSTAT_4_2.py index 5c289ced50..563d6f3f2e 100644 --- a/src/python_testing/TC_TSTAT_4_2.py +++ b/src/python_testing/TC_TSTAT_4_2.py @@ -61,15 +61,30 @@ class TC_TSTAT_4_2(MatterBaseTest): def check_atomic_response(self, response: object, expected_status: Status = Status.Success, expected_overall_status: Status = Status.Success, - expected_preset_status: Status = Status.Success): + expected_preset_status: Status = Status.Success, + expected_schedules_status: Status = None, + expected_timeout: int = None): asserts.assert_equal(expected_status, Status.Success, "We expected we had a valid response") asserts.assert_equal(response.statusCode, expected_overall_status, "Response should have the right overall status") found_preset_status = False + found_schedules_status = False for attrStatus in response.attributeStatus: if attrStatus.attributeID == cluster.Attributes.Presets.attribute_id: asserts.assert_equal(attrStatus.statusCode, expected_preset_status, "Preset attribute should have the right status") found_preset_status = True + if attrStatus.attributeID == cluster.Attributes.Schedules.attribute_id: + asserts.assert_equal(attrStatus.statusCode, expected_schedules_status, + "Schedules attribute should have the right status") + found_schedules_status = True + if expected_timeout is not None: + asserts.assert_equal(response.timeout, expected_timeout, + "Timeout should have the right value") + asserts.assert_true(found_preset_status, "Preset attribute should have a status") + if expected_schedules_status is not None: + asserts.assert_true(found_schedules_status, "Schedules attribute should have a status") + asserts.assert_equal(attrStatus.statusCode, expected_schedules_status, + "Schedules attribute should have the right status") asserts.assert_true(found_preset_status, "Preset attribute should have a status") async def write_presets(self, @@ -87,17 +102,21 @@ async def write_presets(self, async def send_atomic_request_begin_command(self, dev_ctrl: ChipDeviceCtrl = None, endpoint: int = None, + timeout: int = 1800, expected_status: Status = Status.Success, expected_overall_status: Status = Status.Success, - expected_preset_status: Status = Status.Success): + expected_preset_status: Status = Status.Success, + expected_schedules_status: Status = None, + expected_timeout: int = None): try: response = await self.send_single_cmd(cmd=cluster.Commands.AtomicRequest(requestType=Globals.Enums.AtomicRequestTypeEnum.kBeginWrite, attributeRequests=[ cluster.Attributes.Presets.attribute_id], - timeout=1800), + timeout=timeout), dev_ctrl=dev_ctrl, endpoint=endpoint) - self.check_atomic_response(response, expected_status, expected_overall_status, expected_preset_status) + self.check_atomic_response(response, expected_status, expected_overall_status, + expected_preset_status, expected_schedules_status, expected_timeout) except InteractionModelError as e: asserts.assert_equal(e.status, expected_status, "Unexpected error returned") @@ -107,13 +126,15 @@ async def send_atomic_request_commit_command(self, endpoint: int = None, expected_status: Status = Status.Success, expected_overall_status: Status = Status.Success, - expected_preset_status: Status = Status.Success): + expected_preset_status: Status = Status.Success, + expected_schedules_status: Status = None): try: response = await self.send_single_cmd(cmd=cluster.Commands.AtomicRequest(requestType=Globals.Enums.AtomicRequestTypeEnum.kCommitWrite, - attributeRequests=[cluster.Attributes.Presets.attribute_id, cluster.Attributes.Schedules.attribute_id]), + attributeRequests=[cluster.Attributes.Presets.attribute_id]), dev_ctrl=dev_ctrl, endpoint=endpoint) - self.check_atomic_response(response, expected_status, expected_overall_status, expected_preset_status) + self.check_atomic_response(response, expected_status, expected_overall_status, + expected_preset_status, expected_schedules_status) except InteractionModelError as e: asserts.assert_equal(e.status, expected_status, "Unexpected error returned") @@ -122,13 +143,16 @@ async def send_atomic_request_rollback_command(self, endpoint: int = None, expected_status: Status = Status.Success, expected_overall_status: Status = Status.Success, - expected_preset_status: Status = Status.Success): + expected_preset_status: Status = Status.Success, + expected_schedules_status: Status = None): try: response = await self.send_single_cmd(cmd=cluster.Commands.AtomicRequest(requestType=Globals.Enums.AtomicRequestTypeEnum.kRollbackWrite, - attributeRequests=[cluster.Attributes.Presets.attribute_id, cluster.Attributes.Schedules.attribute_id]), + attributeRequests=[cluster.Attributes.Presets.attribute_id]), dev_ctrl=dev_ctrl, endpoint=endpoint) - self.check_atomic_response(response, expected_status, expected_overall_status, expected_preset_status) + self.check_atomic_response(response, expected_status, expected_overall_status, + expected_preset_status, expected_schedules_status) + except InteractionModelError as e: asserts.assert_equal(e.status, expected_status, "Unexpected error returned") @@ -219,7 +243,6 @@ async def test_TC_TSTAT_4_2(self): await self.write_presets(endpoint=endpoint, presets=new_presets, expected_status=Status.InvalidInState) self.step("3") - if self.pics_guard(self.check_pics("TSTAT.S.F08") and self.check_pics("TSTAT.S.A0050") and self.check_pics("TSTAT.S.Cfe.Rsp")): await self.send_atomic_request_begin_command() @@ -260,7 +283,7 @@ async def test_TC_TSTAT_4_2(self): if self.pics_guard(self.check_pics("TSTAT.S.F08") and self.check_pics("TSTAT.S.A0050") and self.check_pics("TSTAT.S.Cfe.Rsp")): # Send the AtomicRequest begin command - await self.send_atomic_request_begin_command() + await self.send_atomic_request_begin_command(timeout=5000, expected_timeout=3000) # Write to the presets attribute after removing a built in preset from the list. Remove the first entry. test_presets = new_presets_with_handle.copy() @@ -406,10 +429,7 @@ async def test_TC_TSTAT_4_2(self): self.step("14") if self.pics_guard(self.check_pics("TSTAT.S.F08") and self.check_pics("TSTAT.S.A0050") and self.check_pics("TSTAT.S.Cfe.Rsp")): - - # Send the AtomicRequest begin command await self.send_atomic_request_begin_command() - # Send the AtomicRequest begin command from separate controller, which should receive busy status = await self.send_atomic_request_begin_command(dev_ctrl=secondary_controller, expected_overall_status=Status.Failure, expected_preset_status=Status.Busy) From fe34e8198d8b27058b7d446516f5737e190d7326 Mon Sep 17 00:00:00 2001 From: Wang Qixiang <43193572+wqx6@users.noreply.github.com> Date: Fri, 23 Aug 2024 23:17:10 +0800 Subject: [PATCH 157/165] esp32: fix compiling when enabling ble commissioner (#35085) * esp32: fix compiling when enabling ble commissioner * Restyled by clang-format --------- Co-authored-by: Restyled.io --- src/platform/ESP32/nimble/BLEManagerImpl.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/platform/ESP32/nimble/BLEManagerImpl.cpp b/src/platform/ESP32/nimble/BLEManagerImpl.cpp index 4f6ab4f73f..d4d90f4536 100644 --- a/src/platform/ESP32/nimble/BLEManagerImpl.cpp +++ b/src/platform/ESP32/nimble/BLEManagerImpl.cpp @@ -659,7 +659,7 @@ CHIP_ERROR BLEManagerImpl::SendWriteRequest(BLE_CONNECTION_OBJECT conId, const C if (pBuf->DataLength() > UINT16_MAX) { ChipLogError(Ble, "Buffer data Length is too long"); - return false; + return CHIP_ERROR_INVALID_ARGUMENT; } rc = ble_gattc_write_flat(conId, chr->chr.val_handle, pBuf->Start(), static_cast(pBuf->DataLength()), OnWriteComplete, this); @@ -1746,12 +1746,12 @@ void BLEManagerImpl::DriveBLEState(intptr_t arg) #ifdef CONFIG_ENABLE_ESP32_BLE_CONTROLLER CHIP_ERROR BLEManagerImpl::HandleRXNotify(struct ble_gap_event * ble_event) { - size_t dataLen = OS_MBUF_PKTLEN(ble_event->notify_rx.om); + uint16_t dataLen = OS_MBUF_PKTLEN(ble_event->notify_rx.om); System::PacketBufferHandle buf = System::PacketBufferHandle::New(dataLen, 0); VerifyOrReturnError(!buf.IsNull(), CHIP_ERROR_NO_MEMORY); - VerifyOrExit(buf->AvailableDataLength() >= data_len, err = CHIP_ERROR_BUFFER_TOO_SMALL); - ble_hs_mbuf_to_flat(ble_event->notify_rx.om, buf->Start(), data_len, NULL); - buf->SetDataLength(data_len); + VerifyOrReturnError(buf->AvailableDataLength() >= dataLen, CHIP_ERROR_BUFFER_TOO_SMALL); + ble_hs_mbuf_to_flat(ble_event->notify_rx.om, buf->Start(), dataLen, NULL); + buf->SetDataLength(dataLen); ChipLogDetail(DeviceLayer, "Indication received, conn = %d", ble_event->notify_rx.conn_handle); From 9520bef5d88e4ec9f208390182dce8d1b3f8a664 Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Fri, 23 Aug 2024 12:06:22 -0400 Subject: [PATCH 158/165] Remove writeAttributeWithEndpointID implementation from MTRDevice. (#35170) This is implemented (differently) by the different subclasses. Once this implementation is removed, removeExpectedValueForAttributePath becomes unused and can be removed. Also removes the unused setExpectedValues declaration in MTRDevice_Internal.h and the implementations of it. --- src/darwin/Framework/CHIP/MTRDevice.mm | 136 ++---------------- .../Framework/CHIP/MTRDevice_Concrete.mm | 5 - .../Framework/CHIP/MTRDevice_Internal.h | 4 - 3 files changed, 9 insertions(+), 136 deletions(-) diff --git a/src/darwin/Framework/CHIP/MTRDevice.mm b/src/darwin/Framework/CHIP/MTRDevice.mm index 3f2acce5f5..f913f29388 100644 --- a/src/darwin/Framework/CHIP/MTRDevice.mm +++ b/src/darwin/Framework/CHIP/MTRDevice.mm @@ -1831,11 +1831,12 @@ static BOOL AttributeHasChangesOmittedQuality(MTRAttributePath * attributePath) attributeID:(NSNumber *)attributeID params:(MTRReadParams * _Nullable)params { -#define ErrorStr "MTRDevice readAttributeWithEndpointID:clusterID:attributeID:params: must be handled by subclasses" - MTR_LOG_ERROR(ErrorStr); +#define MTRDeviceErrorStr "MTRDevice readAttributeWithEndpointID:clusterID:attributeID:params: must be handled by subclasses" + MTR_LOG_ERROR(MTRDeviceErrorStr); #ifdef DEBUG - NSAssert(NO, @ErrorStr); + NSAssert(NO, @MTRDeviceErrorStr); #endif // DEBUG +#undef MTRDeviceErrorStr return nil; } @@ -1846,120 +1847,12 @@ - (void)writeAttributeWithEndpointID:(NSNumber *)endpointID expectedValueInterval:(NSNumber *)expectedValueInterval timedWriteTimeout:(NSNumber * _Nullable)timeout { - if (timeout) { - timeout = MTRClampedNumber(timeout, @(1), @(UINT16_MAX)); - } - expectedValueInterval = MTRClampedNumber(expectedValueInterval, @(1), @(UINT32_MAX)); - MTRAttributePath * attributePath = [MTRAttributePath attributePathWithEndpointID:endpointID - clusterID:clusterID - - attributeID:attributeID]; - - __block BOOL useValueAsExpectedValue = YES; +#define MTRDeviceErrorStr "MTRDevice writeAttributeWithEndpointID:clusterID:attributeID:value:expectedValueInterval:timedWriteTimeout: must be handled by subclasses" + MTR_LOG_ERROR(MTRDeviceErrorStr); #ifdef DEBUG - os_unfair_lock_lock(&self->_lock); - [self _callFirstDelegateSynchronouslyWithBlock:^(id delegate) { - if ([delegate respondsToSelector:@selector(unitTestShouldSkipExpectedValuesForWrite:)]) { - useValueAsExpectedValue = ![delegate unitTestShouldSkipExpectedValuesForWrite:self]; - } - }]; - os_unfair_lock_unlock(&self->_lock); -#endif - - uint64_t expectedValueID = 0; - if (useValueAsExpectedValue) { - // Commit change into expected value cache - NSDictionary * newExpectedValueDictionary = @{ MTRAttributePathKey : attributePath, MTRDataKey : value }; - [self setExpectedValues:@[ newExpectedValueDictionary ] - expectedValueInterval:expectedValueInterval - expectedValueID:&expectedValueID]; - } - - MTRAsyncWorkItem * workItem = [[MTRAsyncWorkItem alloc] initWithQueue:self.queue]; - uint64_t workItemID = workItem.uniqueID; // capture only the ID, not the work item - NSNumber * nodeID = _nodeID; - - // Write request data is an array of items (for now always length 1). Each - // item is an array containing: - // - // [ attribute path, value, timedWriteTimeout, expectedValueID ] - // - // where expectedValueID is stored as NSNumber and NSNull represents nil timeouts - auto * writeData = @[ attributePath, [value copy], timeout ?: [NSNull null], @(expectedValueID) ]; - - NSMutableArray * writeRequests = [NSMutableArray arrayWithObject:writeData]; - - [workItem setBatchingID:MTRDeviceWorkItemBatchingWriteID data:writeRequests handler:^(id opaqueDataCurrent, id opaqueDataNext) { - mtr_hide(self); // don't capture self accidentally - NSMutableArray * writeRequestsCurrent = opaqueDataCurrent; - NSMutableArray * writeRequestsNext = opaqueDataNext; - - if (writeRequestsCurrent.count != 1) { - // Very unexpected! - MTR_LOG_ERROR("Batching write attribute work item [%llu]: Unexpected write request count %lu", workItemID, static_cast(writeRequestsCurrent.count)); - return MTRNotBatched; - } - - MTRBatchingOutcome outcome = MTRNotBatched; - while (writeRequestsNext.count) { - // If paths don't match, we cannot replace the earlier write - // with the later one. - if (![writeRequestsNext[0][MTRDeviceWriteRequestFieldPathIndex] - isEqual:writeRequestsCurrent[0][MTRDeviceWriteRequestFieldPathIndex]]) { - MTR_LOG("Batching write attribute work item [%llu]: cannot replace with next work item due to path mismatch", workItemID); - return outcome; - } - - // Replace our one request with the first one from the next item. - auto writeItem = writeRequestsNext.firstObject; - [writeRequestsNext removeObjectAtIndex:0]; - [writeRequestsCurrent replaceObjectAtIndex:0 withObject:writeItem]; - MTR_LOG("Batching write attribute work item [%llu]: replaced with new write value %@ [0x%016llX]", - workItemID, writeItem, nodeID.unsignedLongLongValue); - outcome = MTRBatchedPartially; - } - NSCAssert(writeRequestsNext.count == 0, @"should have batched everything or returned early"); - return MTRBatchedFully; - }]; - // The write operation will install a duplicate check handler, to return NO for "isDuplicate". Since a write operation may - // change values, only read requests after this should be considered for duplicate requests. - [workItem setDuplicateTypeID:MTRDeviceWorkItemDuplicateReadTypeID handler:^(id opaqueItemData, BOOL * isDuplicate, BOOL * stop) { - *isDuplicate = NO; - *stop = YES; - }]; - [workItem setReadyHandler:^(MTRDevice * self, NSInteger retryCount, MTRAsyncWorkCompletionBlock completion) { - MTRBaseDevice * baseDevice = [self newBaseDevice]; - // Make sure to use writeRequests here, because that's what our batching - // handler will modify as needed. - NSCAssert(writeRequests.count == 1, @"Incorrect number of write requests: %lu", static_cast(writeRequests.count)); - - auto * request = writeRequests[0]; - MTRAttributePath * path = request[MTRDeviceWriteRequestFieldPathIndex]; - - id timedWriteTimeout = request[MTRDeviceWriteRequestFieldTimeoutIndex]; - if (timedWriteTimeout == [NSNull null]) { - timedWriteTimeout = nil; - } - - [baseDevice - writeAttributeWithEndpointID:path.endpoint - clusterID:path.cluster - attributeID:path.attribute - value:request[MTRDeviceWriteRequestFieldValueIndex] - timedWriteTimeout:timedWriteTimeout - queue:self.queue - completion:^(NSArray *> * _Nullable values, NSError * _Nullable error) { - if (error) { - MTR_LOG_ERROR("Write attribute work item [%llu] failed: %@", workItemID, error); - if (useValueAsExpectedValue) { - NSNumber * expectedValueID = request[MTRDeviceWriteRequestFieldExpectedValueIDIndex]; - [self removeExpectedValueForAttributePath:attributePath expectedValueID:expectedValueID.unsignedLongLongValue]; - } - } - completion(MTRAsyncWorkComplete); - }]; - }]; - [_asyncWorkQueue enqueueWorkItem:workItem descriptionWithFormat:@"write %@ 0x%llx 0x%llx", endpointID, clusterID.unsignedLongLongValue, attributeID.unsignedLongLongValue]; + NSAssert(NO, @MTRDeviceErrorStr); +#endif // DEBUG +#undef MTRDeviceErrorStr } - (void)invokeCommandWithEndpointID:(NSNumber *)endpointID @@ -2796,11 +2689,6 @@ - (NSArray *)_getAttributesToReportWithNewExpectedValues:(NSArray *> *)values expectedValueInterval:(NSNumber *)expectedValueInterval -{ - [self setExpectedValues:values expectedValueInterval:expectedValueInterval expectedValueID:nil]; -} - // expectedValueID is an out-argument that returns an identifier to be used when removing expected values - (void)setExpectedValues:(NSArray *> *)values expectedValueInterval:(NSNumber *)expectedValueInterval @@ -2833,12 +2721,6 @@ - (void)removeExpectedValuesForAttributePaths:(NSArray *)att } } -- (void)removeExpectedValueForAttributePath:(MTRAttributePath *)attributePath expectedValueID:(uint64_t)expectedValueID -{ - std::lock_guard lock(_lock); - [self _removeExpectedValueForAttributePath:attributePath expectedValueID:expectedValueID]; -} - - (void)_removeExpectedValueForAttributePath:(MTRAttributePath *)attributePath expectedValueID:(uint64_t)expectedValueID { os_unfair_lock_assert_owner(&self->_lock); diff --git a/src/darwin/Framework/CHIP/MTRDevice_Concrete.mm b/src/darwin/Framework/CHIP/MTRDevice_Concrete.mm index 12614ea409..b7e7bf7802 100644 --- a/src/darwin/Framework/CHIP/MTRDevice_Concrete.mm +++ b/src/darwin/Framework/CHIP/MTRDevice_Concrete.mm @@ -3644,11 +3644,6 @@ - (NSArray *)_getAttributesToReportWithNewExpectedValues:(NSArray *> *)values expectedValueInterval:(NSNumber *)expectedValueInterval -{ - [self setExpectedValues:values expectedValueInterval:expectedValueInterval expectedValueID:nil]; -} - // expectedValueID is an out-argument that returns an identifier to be used when removing expected values - (void)setExpectedValues:(NSArray *> *)values expectedValueInterval:(NSNumber *)expectedValueInterval diff --git a/src/darwin/Framework/CHIP/MTRDevice_Internal.h b/src/darwin/Framework/CHIP/MTRDevice_Internal.h index b6a59ac932..dae183eec2 100644 --- a/src/darwin/Framework/CHIP/MTRDevice_Internal.h +++ b/src/darwin/Framework/CHIP/MTRDevice_Internal.h @@ -125,10 +125,6 @@ MTR_DIRECT_MEMBERS - (instancetype)initForSubclassesWithNodeID:(NSNumber *)nodeID controller:(MTRDeviceController *)controller; - (instancetype)initWithNodeID:(NSNumber *)nodeID controller:(MTRDeviceController *)controller; -// Called from MTRClusters for writes and commands -- (void)setExpectedValues:(NSArray *> *)values - expectedValueInterval:(NSNumber *)expectedValueIntervalMs; - // called by controller to clean up and shutdown - (void)invalidate; From c1b3304fa69f356f21b8803c572c670c0ad1be17 Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Fri, 23 Aug 2024 13:16:06 -0400 Subject: [PATCH 159/165] Address followup issues for preset/atomic-write implementation. (#35175) * Puts some file-local functions in an anonymous namespace. * Fixes the "is this attribute supported?" check to correctly check for global attributes that are not in Ember metadata. * Moves the comment explaining why it's OK to skip the spec-required ACL check to the place where that check is being skipped. * Removes a non-spec-compliant "error if the timeout is 0" bit. Fixes https://github.com/project-chip/connectedhomeip/issues/35168 --- src/app/GlobalAttributes.h | 13 ++++++++ .../thermostat-server-atomic.cpp | 31 ++++++++++++------- 2 files changed, 33 insertions(+), 11 deletions(-) diff --git a/src/app/GlobalAttributes.h b/src/app/GlobalAttributes.h index 5096792309..461294267f 100644 --- a/src/app/GlobalAttributes.h +++ b/src/app/GlobalAttributes.h @@ -40,5 +40,18 @@ constexpr AttributeId GlobalAttributesNotInMetadata[] = { static_assert(ArrayIsSorted(GlobalAttributesNotInMetadata), "Array of global attribute ids must be sorted"); +inline bool IsSupportedGlobalAttributeNotInMetadata(AttributeId attributeId) +{ + for (auto & attr : GlobalAttributesNotInMetadata) + { + if (attr == attributeId) + { + return true; + } + } + + return false; +} + } // namespace app } // namespace chip diff --git a/src/app/clusters/thermostat-server/thermostat-server-atomic.cpp b/src/app/clusters/thermostat-server/thermostat-server-atomic.cpp index 2a6e52e504..19a6ffa338 100644 --- a/src/app/clusters/thermostat-server/thermostat-server-atomic.cpp +++ b/src/app/clusters/thermostat-server/thermostat-server-atomic.cpp @@ -17,6 +17,7 @@ #include "thermostat-server.h" +#include #include using namespace chip; @@ -47,6 +48,8 @@ void TimerExpiredCallback(System::Layer * systemLayer, void * callbackContext) gThermostatAttrAccess.ResetAtomicWrite(endpoint); } +namespace { + /** * @brief Schedules a timer for the given timeout in milliseconds. * @@ -185,15 +188,25 @@ Status BuildAttributeStatuses(const EndpointId endpoint, const DataModel::Decoda const EmberAfAttributeMetadata * metadata = emberAfLocateAttributeMetadata(endpoint, Thermostat::Id, attributeStatus.attributeID); - if (metadata == nullptr) + if (metadata != nullptr) + { + // This is definitely an attribute we know about. + continue; + } + + if (IsSupportedGlobalAttributeNotInMetadata(attributeStatus.attributeID)) { - // This is not a valid attribute on the Thermostat cluster on the supplied endpoint - return Status::InvalidCommand; + continue; } + + // This is not a valid attribute on the Thermostat cluster on the supplied endpoint + return Status::InvalidCommand; } return Status::Success; } +} // anonymous namespace + bool ThermostatAttrAccess::InAtomicWrite(EndpointId endpoint, Optional attributeId) { @@ -422,6 +435,10 @@ void ThermostatAttrAccess::BeginAtomicWrite(CommandHandler * commandObj, const C status = Status::Success; for (size_t i = 0; i < attributeStatuses.AllocatedSize(); ++i) { + // If we've gotten this far, then the client has manage permission to call AtomicRequest, + // which is also the privilege necessary to write to the atomic attributes, so no need to do + // the "If the client does not have sufficient privilege to write to the attribute" check + // from the spec. auto & attributeStatus = attributeStatuses[i]; auto statusCode = Status::Success; switch (attributeStatus.attributeID) @@ -442,11 +459,6 @@ void ThermostatAttrAccess::BeginAtomicWrite(CommandHandler * commandObj, const C } auto timeout = std::min(System::Clock::Milliseconds16(commandData.timeout.Value()), maximumTimeout); - if (timeout.count() == 0) - { - commandObj->AddStatus(commandPath, Status::InvalidInState); - return; - } if (status == Status::Success) { @@ -605,9 +617,6 @@ bool emberAfThermostatClusterAtomicRequestCallback(CommandHandler * commandObj, { auto & requestType = commandData.requestType; - // If we've gotten this far, then the client has manage permission to call AtomicRequest, which is also the - // privilege necessary to write to the atomic attributes, so no need to check - switch (requestType) { case Globals::AtomicRequestTypeEnum::kBeginWrite: From b3507cebe7defed94c3394b8bf3d574115279531 Mon Sep 17 00:00:00 2001 From: Anush Nadathur Date: Fri, 23 Aug 2024 12:28:24 -0700 Subject: [PATCH 160/165] [Darwin] Enable taking assertion on MTRDeviceController (#35148) * [Darwin] Enable taking assertion on MTRDeviceController - Added ability to take assertion on MTRDeviceController to keep it running until all assertions are removed - A request to shutdown will take place only if there are no assertions are present * Fixed format string * Account for existing controller that is asserted in factory when creating a new one * Simplified to use lock for assertion tracking * Fixed build error * Removed unneeded includes * Fixed bugs with wrong match logic * resytle fixes * Restyle fixes * Apply suggestions from code review Co-authored-by: Boris Zbarsky * Fixed build failure from review suggestions and added comment per review feedback --------- Co-authored-by: Boris Zbarsky --- .../Framework/CHIP/MTRDeviceController.mm | 94 +++++++++++++++++++ .../CHIP/MTRDeviceControllerFactory.mm | 19 ++++ .../CHIP/MTRDeviceControllerStartupParams.mm | 23 +++++ ...TRDeviceControllerStartupParams_Internal.h | 4 + .../CHIP/MTRDeviceController_Internal.h | 40 ++++++++ 5 files changed, 180 insertions(+) diff --git a/src/darwin/Framework/CHIP/MTRDeviceController.mm b/src/darwin/Framework/CHIP/MTRDeviceController.mm index 11fd481b48..4630ff7fe0 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController.mm +++ b/src/darwin/Framework/CHIP/MTRDeviceController.mm @@ -46,6 +46,7 @@ #import "MTRSetupPayload.h" #import "MTRTimeUtils.h" #import "MTRUnfairLock.h" +#import "MTRUtilities.h" #import "NSDataSpanConversion.h" #import "NSStringSpanConversion.h" #import @@ -129,6 +130,11 @@ @implementation MTRDeviceController { std::atomic> _storedCompressedFabricID; MTRP256KeypairBridge _signingKeypairBridge; MTRP256KeypairBridge _operationalKeypairBridge; + + // Counters to track assertion status and access controlled by the _assertionLock + NSUInteger _keepRunningAssertionCounter; + BOOL _shutdownPending; + os_unfair_lock _assertionLock; } - (os_unfair_lock_t)deviceMapLock @@ -142,6 +148,11 @@ - (instancetype)initForSubclasses // nothing, as superclass of MTRDeviceController is NSObject } _underlyingDeviceMapLock = OS_UNFAIR_LOCK_INIT; + + // Setup assertion variables + _keepRunningAssertionCounter = 0; + _shutdownPending = NO; + _assertionLock = OS_UNFAIR_LOCK_INIT; return self; } @@ -178,6 +189,12 @@ - (instancetype)initWithFactory:(MTRDeviceControllerFactory *)factory // Make sure our storage is all set up to work as early as possible, // before we start doing anything else with the controller. _uniqueIdentifier = uniqueIdentifier; + + // Setup assertion variables + _keepRunningAssertionCounter = 0; + _shutdownPending = NO; + _assertionLock = OS_UNFAIR_LOCK_INIT; + if (storageDelegate != nil) { if (storageDelegateQueue == nil) { MTR_LOG_ERROR("storageDelegate provided without storageDelegateQueue"); @@ -295,6 +312,9 @@ - (instancetype)initWithFactory:(MTRDeviceControllerFactory *)factory _storedFabricIndex = chip::kUndefinedFabricIndex; _storedCompressedFabricID = std::nullopt; + self.nodeID = nil; + self.fabricID = nil; + self.rootPublicKey = nil; _storageBehaviorConfiguration = storageBehaviorConfiguration; } @@ -311,8 +331,69 @@ - (BOOL)isRunning return _cppCommissioner != nullptr; } +- (BOOL)matchesPendingShutdownWithParams:(MTRDeviceControllerParameters *)parameters +{ + if (!parameters.operationalCertificate || !parameters.rootCertificate) { + return FALSE; + } + NSNumber * nodeID = [MTRDeviceControllerParameters nodeIDFromNOC:parameters.operationalCertificate]; + NSNumber * fabricID = [MTRDeviceControllerParameters fabricIDFromNOC:parameters.operationalCertificate]; + NSData * publicKey = [MTRDeviceControllerParameters publicKeyFromCertificate:parameters.rootCertificate]; + + std::lock_guard lock(_assertionLock); + + // If any of the local above are nil, the return will be false since MTREqualObjects handles them correctly + return _keepRunningAssertionCounter > 0 && _shutdownPending && MTREqualObjects(nodeID, self.nodeID) && MTREqualObjects(fabricID, self.fabricID) && MTREqualObjects(publicKey, self.rootPublicKey); +} + +- (void)addRunAssertion +{ + std::lock_guard lock(_assertionLock); + + // Only take an assertion if running + if ([self isRunning]) { + ++_keepRunningAssertionCounter; + MTR_LOG("%@ Adding keep running assertion, total %lu", self, static_cast(_keepRunningAssertionCounter)); + } +} + +- (void)removeRunAssertion; +{ + std::lock_guard lock(_assertionLock); + + if (_keepRunningAssertionCounter > 0) { + --_keepRunningAssertionCounter; + MTR_LOG("%@ Removing keep running assertion, total %lu", self, static_cast(_keepRunningAssertionCounter)); + + if ([self isRunning] && _keepRunningAssertionCounter == 0 && _shutdownPending) { + MTR_LOG("%@ All assertions removed and shutdown is pending, shutting down", self); + [self finalShutdown]; + } + } +} + +- (void)clearPendingShutdown +{ + std::lock_guard lock(_assertionLock); + _shutdownPending = NO; +} + - (void)shutdown { + std::lock_guard lock(_assertionLock); + + if (_keepRunningAssertionCounter > 0) { + MTR_LOG("%@ Pending shutdown since %lu assertions are present", self, static_cast(_keepRunningAssertionCounter)); + _shutdownPending = YES; + return; + } + [self finalShutdown]; +} + +- (void)finalShutdown +{ + os_unfair_lock_assert_owner(&_assertionLock); + MTR_LOG("%@ shutdown called", self); if (_cppCommissioner == nullptr) { // Already shut down. @@ -369,11 +450,16 @@ - (void)shutDownCppController // shuts down. _storedFabricIndex = chip::kUndefinedFabricIndex; _storedCompressedFabricID = std::nullopt; + self.nodeID = nil; + self.fabricID = nil; + self.rootPublicKey = nil; + delete commissionerToShutDown; if (_operationalCredentialsDelegate != nil) { _operationalCredentialsDelegate->SetDeviceCommissioner(nullptr); } } + _shutdownPending = NO; } - (void)deinitFromFactory @@ -609,6 +695,14 @@ - (BOOL)startup:(MTRDeviceControllerStartupParamsInternal *)startupParams self->_storedFabricIndex = fabricIdx; self->_storedCompressedFabricID = _cppCommissioner->GetCompressedFabricId(); + + chip::Crypto::P256PublicKey rootPublicKey; + if (_cppCommissioner->GetRootPublicKey(rootPublicKey) == CHIP_NO_ERROR) { + self.rootPublicKey = [NSData dataWithBytes:rootPublicKey.Bytes() length:rootPublicKey.Length()]; + self.nodeID = @(_cppCommissioner->GetNodeId()); + self.fabricID = @(_cppCommissioner->GetFabricId()); + } + commissionerInitialized = YES; MTR_LOG("%@ startup succeeded for nodeID 0x%016llX", self, self->_cppCommissioner->GetNodeId()); diff --git a/src/darwin/Framework/CHIP/MTRDeviceControllerFactory.mm b/src/darwin/Framework/CHIP/MTRDeviceControllerFactory.mm index 5b089b3920..bd0b90450b 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceControllerFactory.mm +++ b/src/darwin/Framework/CHIP/MTRDeviceControllerFactory.mm @@ -1133,12 +1133,31 @@ - (void)operationalInstanceAdded:(chip::PeerId &)operationalID } } +- (nullable MTRDeviceController *)_findControllerWithPendingShutdownMatchingParams:(MTRDeviceControllerParameters *)parameters +{ + std::lock_guard lock(_controllersLock); + for (MTRDeviceController * controller in _controllers) { + if ([controller matchesPendingShutdownWithParams:parameters]) { + MTR_LOG("%@ Found existing controller %@ that is pending shutdown and matching parameters, re-using it", self, controller); + [controller clearPendingShutdown]; + return controller; + } + } + return nil; +} + - (nullable MTRDeviceController *)initializeController:(MTRDeviceController *)controller withParameters:(MTRDeviceControllerParameters *)parameters error:(NSError * __autoreleasing *)error { [self _assertCurrentQueueIsNotMatterQueue]; + // If there is a controller already running with matching parameters that is conceptually shut down from the API consumer's viewpoint, re-use it. + MTRDeviceController * existingController = [self _findControllerWithPendingShutdownMatchingParams:parameters]; + if (existingController) { + return existingController; + } + return [self _startDeviceController:controller startupParams:parameters fabricChecker:^MTRDeviceControllerStartupParamsInternal *( diff --git a/src/darwin/Framework/CHIP/MTRDeviceControllerStartupParams.mm b/src/darwin/Framework/CHIP/MTRDeviceControllerStartupParams.mm index c5923ad4e5..5850a8c4ef 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceControllerStartupParams.mm +++ b/src/darwin/Framework/CHIP/MTRDeviceControllerStartupParams.mm @@ -306,6 +306,29 @@ - (void)setOTAProviderDelegate:(id)otaProviderDelegate q _otaProviderDelegateQueue = queue; } ++ (nullable NSNumber *)nodeIDFromNOC:(MTRCertificateDERBytes)noc +{ + NSNumber * nodeID = nil; + ExtractNodeIDFromNOC(noc, &nodeID); + return nodeID; +} + ++ (nullable NSNumber *)fabricIDFromNOC:(MTRCertificateDERBytes)noc +{ + NSNumber * fabricID = nil; + ExtractFabricIDFromNOC(noc, &fabricID); + return fabricID; +} + ++ (nullable NSData *)publicKeyFromCertificate:(MTRCertificateDERBytes)certificate +{ + Crypto::P256PublicKey pubKey; + if (ExtractPubkeyFromX509Cert(AsByteSpan(certificate), pubKey) != CHIP_NO_ERROR) { + return nil; + } + return [NSData dataWithBytes:pubKey.Bytes() length:pubKey.Length()]; +} + @end @implementation MTRDeviceControllerExternalCertificateParameters diff --git a/src/darwin/Framework/CHIP/MTRDeviceControllerStartupParams_Internal.h b/src/darwin/Framework/CHIP/MTRDeviceControllerStartupParams_Internal.h index 6b8c762633..0b4065f491 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceControllerStartupParams_Internal.h +++ b/src/darwin/Framework/CHIP/MTRDeviceControllerStartupParams_Internal.h @@ -85,6 +85,10 @@ NS_ASSUME_NONNULL_BEGIN @property (nonatomic, strong, readonly, nullable) id otaProviderDelegate; @property (nonatomic, strong, readonly, nullable) dispatch_queue_t otaProviderDelegateQueue; ++ (nullable NSNumber *)nodeIDFromNOC:(MTRCertificateDERBytes)noc; ++ (nullable NSNumber *)fabricIDFromNOC:(MTRCertificateDERBytes)noc; ++ (nullable NSData *)publicKeyFromCertificate:(MTRCertificateDERBytes)certificate; + @end @interface MTRDeviceControllerStartupParamsInternal : MTRDeviceControllerStartupParams diff --git a/src/darwin/Framework/CHIP/MTRDeviceController_Internal.h b/src/darwin/Framework/CHIP/MTRDeviceController_Internal.h index 54d5cfd8d3..e625d13a80 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController_Internal.h +++ b/src/darwin/Framework/CHIP/MTRDeviceController_Internal.h @@ -45,6 +45,7 @@ #import #import +@class MTRDeviceControllerParameters; @class MTRDeviceControllerStartupParamsInternal; @class MTRDeviceControllerFactory; @class MTRDevice; @@ -117,6 +118,21 @@ NS_ASSUME_NONNULL_BEGIN */ @property (nonatomic, readonly) MTRAsyncWorkQueue * concurrentSubscriptionPool; +/** + * Fabric ID tied to controller + */ +@property (nonatomic, retain, nullable) NSNumber * fabricID; + +/** + * Node ID tied to controller + */ +@property (nonatomic, retain, nullable) NSNumber * nodeID; + +/** + * Root Public Key tied to controller + */ +@property (nonatomic, retain, nullable) NSData * rootPublicKey; + /** * Init a newly created controller. * @@ -289,6 +305,30 @@ NS_ASSUME_NONNULL_BEGIN */ - (void)directlyGetSessionForNode:(chip::NodeId)nodeID completion:(MTRInternalDeviceConnectionCallback)completion; +/** + * Takes an assertion to keep the controller running. If `-[MTRDeviceController shutdown]` is called while an assertion + * is held, the shutdown will be honored only after all assertions are released. Invoking this method multiple times increases + * the number of assertions and needs to be matched with equal amount of '-[MTRDeviceController removeRunAssertion]` to release + * the assertion. + */ +- (void)addRunAssertion; + +/** + * Removes an assertion to allow the controller to shutdown once all assertions have been released. + * Invoking this method once all assertions have been released in a noop. + */ +- (void)removeRunAssertion; + +/** + * This method returns TRUE if this controller matches the fabric reference and node ID as listed in the parameters. + */ +- (BOOL)matchesPendingShutdownWithParams:(MTRDeviceControllerParameters *)parameters; + +/** + * Clear any pending shutdown request. + */ +- (void)clearPendingShutdown; + @end /** From 0b5af2a0bcdbc1c0f96b239b631a8eb3148fce12 Mon Sep 17 00:00:00 2001 From: Junior Martinez <67972863+jmartinez-silabs@users.noreply.github.com> Date: Fri, 23 Aug 2024 16:31:26 -0400 Subject: [PATCH 161/165] Cleanup/updates tied with latest sdk update (#35140) --- examples/platform/silabs/FreeRTOSConfig.h | 2 +- src/platform/silabs/ConfigurationManagerImpl.cpp | 2 +- .../silabs/efr32/Efr32PsaOpaqueKeypair.cpp | 15 +++++---------- .../silabs/efr32/OTAImageProcessorImpl.cpp | 2 +- .../silabs/multi-ota/OTACustomProcessor.cpp | 2 +- .../silabs/multi-ota/OTAFirmwareProcessor.cpp | 2 +- .../multi-ota/OTAMultiImageProcessorImpl.cpp | 2 +- .../silabs/platformAbstraction/GsdkSpam.cpp | 16 +++++++++++++++- src/test_driver/efr32/include/FreeRTOSConfig.h | 2 +- 9 files changed, 27 insertions(+), 18 deletions(-) diff --git a/examples/platform/silabs/FreeRTOSConfig.h b/examples/platform/silabs/FreeRTOSConfig.h index b27c775d9b..1c2db9621f 100644 --- a/examples/platform/silabs/FreeRTOSConfig.h +++ b/examples/platform/silabs/FreeRTOSConfig.h @@ -118,8 +118,8 @@ extern uint32_t SystemCoreClock; #include "RTE_Components.h" #include CMSIS_device_header -#include "em_assert.h" #include "em_device.h" +#include "sl_assert.h" #endif #if defined(SL_COMPONENT_CATALOG_PRESENT) diff --git a/src/platform/silabs/ConfigurationManagerImpl.cpp b/src/platform/silabs/ConfigurationManagerImpl.cpp index 5a511038c7..122799952a 100644 --- a/src/platform/silabs/ConfigurationManagerImpl.cpp +++ b/src/platform/silabs/ConfigurationManagerImpl.cpp @@ -121,7 +121,7 @@ CHIP_ERROR ConfigurationManagerImpl::GetBootReason(uint32_t & bootReason) matterBootCause = BootReasonType::kPowerOnReboot; } else if (rebootCause & EMU_RSTCAUSE_AVDDBOD || rebootCause & EMU_RSTCAUSE_DVDDBOD || rebootCause & EMU_RSTCAUSE_DECBOD || - rebootCause & EMU_RSTCAUSE_VREGIN || rebootCause & EMU_RSTCAUSE_IOVDD0BOD || rebootCause & EMU_RSTCAUSE_DVDDLEBOD) + rebootCause & EMU_RSTCAUSE_IOVDD0BOD || rebootCause & EMU_RSTCAUSE_DVDDLEBOD) { matterBootCause = BootReasonType::kBrownOutReset; } diff --git a/src/platform/silabs/efr32/Efr32PsaOpaqueKeypair.cpp b/src/platform/silabs/efr32/Efr32PsaOpaqueKeypair.cpp index 7a74c13759..542142cd1a 100644 --- a/src/platform/silabs/efr32/Efr32PsaOpaqueKeypair.cpp +++ b/src/platform/silabs/efr32/Efr32PsaOpaqueKeypair.cpp @@ -18,6 +18,7 @@ #include "Efr32OpaqueKeypair.h" #include "em_device.h" #include +#include #include #include @@ -47,14 +48,6 @@ namespace Internal { static_assert((kEFR32OpaqueKeyIdPersistentMax - kEFR32OpaqueKeyIdPersistentMin) < PSA_KEY_ID_FOR_MATTER_SIZE, "Not enough PSA range to store all allowed opaque key IDs"); -#if defined(SEMAILBOX_PRESENT) && (_SILICON_LABS_SECURITY_FEATURE == _SILICON_LABS_SECURITY_FEATURE_VAULT) -#define PSA_CRYPTO_LOCATION_FOR_DEVICE PSA_KEY_LOCATION_SL_SE_OPAQUE -#elif defined(CRYPTOACC_PRESENT) && defined(SEPUF_PRESENT) && defined(SL_TRUSTZONE_NONSECURE) -#define PSA_CRYPTO_LOCATION_FOR_DEVICE PSA_KEY_LOCATION_SL_CRYPTOACC_OPAQUE -#else -#define PSA_CRYPTO_LOCATION_FOR_DEVICE PSA_KEY_LOCATION_LOCAL_STORAGE -#endif - static void _log_PSA_error(psa_status_t status) { if (status != PSA_SUCCESS) @@ -190,7 +183,8 @@ CHIP_ERROR EFR32OpaqueKeypair::Create(EFR32OpaqueKeyId opaque_id, EFR32OpaqueKey if (opaque_id == kEFR32OpaqueKeyIdVolatile) { psa_set_key_lifetime( - &attr, PSA_KEY_LIFETIME_FROM_PERSISTENCE_AND_LOCATION(PSA_KEY_LIFETIME_VOLATILE, PSA_CRYPTO_LOCATION_FOR_DEVICE)); + &attr, + PSA_KEY_LIFETIME_FROM_PERSISTENCE_AND_LOCATION(PSA_KEY_LIFETIME_VOLATILE, sl_psa_get_most_secure_key_location())); } else { @@ -210,7 +204,8 @@ CHIP_ERROR EFR32OpaqueKeypair::Create(EFR32OpaqueKeyId opaque_id, EFR32OpaqueKey psa_set_key_id(&attr, key_id); psa_set_key_lifetime( - &attr, PSA_KEY_LIFETIME_FROM_PERSISTENCE_AND_LOCATION(PSA_KEY_LIFETIME_PERSISTENT, PSA_CRYPTO_LOCATION_FOR_DEVICE)); + &attr, + PSA_KEY_LIFETIME_FROM_PERSISTENCE_AND_LOCATION(PSA_KEY_LIFETIME_PERSISTENT, sl_psa_get_most_secure_key_location())); } switch (usage) diff --git a/src/platform/silabs/efr32/OTAImageProcessorImpl.cpp b/src/platform/silabs/efr32/OTAImageProcessorImpl.cpp index 598ee5a209..846d4f720a 100644 --- a/src/platform/silabs/efr32/OTAImageProcessorImpl.cpp +++ b/src/platform/silabs/efr32/OTAImageProcessorImpl.cpp @@ -22,7 +22,7 @@ extern "C" { #include "btl_interface.h" -#include "em_bus.h" // For CORE_CRITICAL_SECTION +#include "sl_core.h" #if SL_WIFI #include "spi_multiplex.h" #endif // SL_WIFI diff --git a/src/platform/silabs/multi-ota/OTACustomProcessor.cpp b/src/platform/silabs/multi-ota/OTACustomProcessor.cpp index 85ceb7d44d..ef761d003e 100644 --- a/src/platform/silabs/multi-ota/OTACustomProcessor.cpp +++ b/src/platform/silabs/multi-ota/OTACustomProcessor.cpp @@ -24,7 +24,7 @@ extern "C" { #include "btl_interface.h" -#include "em_bus.h" // For CORE_CRITICAL_SECTION +#include "sl_core.h" #if SL_WIFI #include "spi_multiplex.h" #endif // SL_WIFI diff --git a/src/platform/silabs/multi-ota/OTAFirmwareProcessor.cpp b/src/platform/silabs/multi-ota/OTAFirmwareProcessor.cpp index 3fc66e5391..d8545d01f4 100644 --- a/src/platform/silabs/multi-ota/OTAFirmwareProcessor.cpp +++ b/src/platform/silabs/multi-ota/OTAFirmwareProcessor.cpp @@ -24,7 +24,7 @@ extern "C" { #include "btl_interface.h" -#include "em_bus.h" // For CORE_CRITICAL_SECTION +#include "sl_core.h" #if SL_WIFI #include "spi_multiplex.h" #endif // SL_WIFI diff --git a/src/platform/silabs/multi-ota/OTAMultiImageProcessorImpl.cpp b/src/platform/silabs/multi-ota/OTAMultiImageProcessorImpl.cpp index 9dfb42fc87..a95cb4e1ad 100644 --- a/src/platform/silabs/multi-ota/OTAMultiImageProcessorImpl.cpp +++ b/src/platform/silabs/multi-ota/OTAMultiImageProcessorImpl.cpp @@ -32,7 +32,7 @@ static chip::OTAMultiImageProcessorImpl gImageProcessor; extern "C" { #include "btl_interface.h" -#include "em_bus.h" // For CORE_CRITICAL_SECTION +#include "sl_core.h" #if SL_WIFI #include "spi_multiplex.h" #endif // SL_WIFI diff --git a/src/platform/silabs/platformAbstraction/GsdkSpam.cpp b/src/platform/silabs/platformAbstraction/GsdkSpam.cpp index 5140033058..eb8704ecfc 100644 --- a/src/platform/silabs/platformAbstraction/GsdkSpam.cpp +++ b/src/platform/silabs/platformAbstraction/GsdkSpam.cpp @@ -17,7 +17,11 @@ #include +#if defined(_SILICON_LABS_32B_SERIES_2) #include "em_rmu.h" +#else +#include "sl_hal_emu.h" +#endif #include "sl_system_kernel.h" #ifdef ENABLE_WSTK_LEDS @@ -71,9 +75,19 @@ SilabsPlatform::SilabsButtonCb SilabsPlatform::mButtonCallback = nullptr; CHIP_ERROR SilabsPlatform::Init(void) { +#ifdef _SILICON_LABS_32B_SERIES_2 + // Read the cause of last reset. mRebootCause = RMU_ResetCauseGet(); - // Clear register so it does accumualate the causes of each reset + + // Clear the register, as the causes cumulate over resets. RMU_ResetCauseClear(); +#else + // Read the cause of last reset. + mRebootCause = sl_hal_emu_get_reset_cause(); + + // Clear the register, as the causes cumulate over resets. + sl_hal_emu_clear_reset_cause(); +#endif // _SILICON_LABS_32B_SERIES_2 #if SILABS_LOG_OUT_UART && defined(SL_CATALOG_CLI_PRESENT) sl_iostream_set_default(sl_iostream_stdio_handle); diff --git a/src/test_driver/efr32/include/FreeRTOSConfig.h b/src/test_driver/efr32/include/FreeRTOSConfig.h index 7a02673c27..5cd17b4a72 100644 --- a/src/test_driver/efr32/include/FreeRTOSConfig.h +++ b/src/test_driver/efr32/include/FreeRTOSConfig.h @@ -108,8 +108,8 @@ extern "C" { #include "RTE_Components.h" #include CMSIS_device_header -#include "em_assert.h" #include "em_device.h" +#include "sl_assert.h" #if defined(SL_COMPONENT_CATALOG_PRESENT) #include "sl_component_catalog.h" From f01ec93099f1d3f9c542ff50d2ff1c3cbdb52271 Mon Sep 17 00:00:00 2001 From: chirag-silabs <100861685+chirag-silabs@users.noreply.github.com> Date: Sat, 24 Aug 2024 02:02:50 +0530 Subject: [PATCH 162/165] [Silabs] Adding the gn build header for the lwip IPv4 and RS9116 (#35142) * adding the gn build header for the lwip and rs9116 * Restyled by clang-format --------- Co-authored-by: Restyled.io --- .../platform/silabs/efr32/rs911x/rsi_wlan_config.h | 4 ++++ src/lwip/silabs/lwipopts-rs911x.h | 10 ++++++++++ src/lwip/silabs/lwipopts-wf200.h | 10 ++++++++++ 3 files changed, 24 insertions(+) diff --git a/examples/platform/silabs/efr32/rs911x/rsi_wlan_config.h b/examples/platform/silabs/efr32/rs911x/rsi_wlan_config.h index 96bd71bb80..b851cd7958 100644 --- a/examples/platform/silabs/efr32/rs911x/rsi_wlan_config.h +++ b/examples/platform/silabs/efr32/rs911x/rsi_wlan_config.h @@ -20,6 +20,10 @@ #include "rsi_wlan_defines.h" +#if (SL_MATTER_GN_BUILD == 0) +#include "sl_matter_wifi_config.h" +#endif // SL_MATTER_GN_BUILD + //! Enable feature #define RSI_ENABLE 1 //! Disable feature diff --git a/src/lwip/silabs/lwipopts-rs911x.h b/src/lwip/silabs/lwipopts-rs911x.h index 4f8075461b..c563a706ac 100644 --- a/src/lwip/silabs/lwipopts-rs911x.h +++ b/src/lwip/silabs/lwipopts-rs911x.h @@ -32,6 +32,10 @@ #include +#if (SL_MATTER_GN_BUILD == 0) +#include "sl_matter_wifi_config.h" +#endif // SL_MATTER_GN_BUILD + #define NO_SYS 0 #define MEM_ALIGNMENT (4) #define MEMP_NUM_TCP_SEG (TCP_SND_QUEUELEN + 1) @@ -90,6 +94,12 @@ #define MEMP_NUM_NETCONN (0) +#if CHIP_DEVICE_CONFIG_ENABLE_IPV4 +#define LWIP_IPV4 1 +#else +#define LWIP_IPV4 0 +#endif // CHIP_DEVICE_CONFIG_ENABLE_IPV4 + #ifndef LWIP_ARP #define LWIP_ARP (LWIP_IPV4) #endif /* LWIP_ARP */ diff --git a/src/lwip/silabs/lwipopts-wf200.h b/src/lwip/silabs/lwipopts-wf200.h index cc9b45b144..9ea7e4f6bb 100644 --- a/src/lwip/silabs/lwipopts-wf200.h +++ b/src/lwip/silabs/lwipopts-wf200.h @@ -32,6 +32,10 @@ #include +#if (SL_MATTER_GN_BUILD == 0) +#include "sl_matter_wifi_config.h" +#endif // SL_MATTER_GN_BUILD + #define NO_SYS 0 #define MEM_ALIGNMENT (4) #define MEMP_NUM_TCP_SEG (TCP_SND_QUEUELEN + 1) @@ -91,6 +95,12 @@ #define MEMP_NUM_NETCONN (0) +#if CHIP_DEVICE_CONFIG_ENABLE_IPV4 +#define LWIP_IPV4 1 +#else +#define LWIP_IPV4 0 +#endif // CHIP_DEVICE_CONFIG_ENABLE_IPV4 + #ifndef LWIP_ARP #define LWIP_ARP (LWIP_IPV4) #endif /* LWIP_ARP */ From 26e59b68b795ff36f1e8a14dd602c46d1e442c57 Mon Sep 17 00:00:00 2001 From: chirag-silabs <100861685+chirag-silabs@users.noreply.github.com> Date: Sat, 24 Aug 2024 02:17:24 +0530 Subject: [PATCH 163/165] [Silabs] [WiFi] Fixing the retry logic for the WiFi Devices (#34225) * Modifying the retry logic for the wifi devices * Baseapplication.cpp modification of the delegate fix * Restyled by clang-format * removing the soc and sleepy condition * Restyled by clang-format * Restyled by gn * moving the variable to efr32_sdk.gni to make it available everywhere * correcting the path of the 917 ncp file * fixing the build for the 917 ncp * addressing the review comments * fixing the build and replacing the define * removing the unused else case * Update third_party/silabs/efr32_sdk.gni Co-authored-by: mkardous-silabs <84793247+mkardous-silabs@users.noreply.github.com> * addressing the review comments * Restyled by whitespace * Restyled by clang-format * fixing the build * fixing the efr32 build --------- Co-authored-by: Restyled.io Co-authored-by: mkardous-silabs <84793247+mkardous-silabs@users.noreply.github.com> --- examples/platform/silabs/BaseApplication.cpp | 3 + examples/platform/silabs/BaseApplication.h | 5 +- examples/platform/silabs/SiWx917/BUILD.gn | 4 +- .../silabs/SiWx917/SiWx917/sl_wifi_if.cpp | 22 +- examples/platform/silabs/efr32/BUILD.gn | 2 - .../platform/silabs/efr32/rs911x/rs9117.gni | 2 +- .../platform/silabs/efr32/rs911x/rs911x.gni | 2 +- .../platform/silabs/efr32/rs911x/rsi_if.c | 103 +++----- .../platform/silabs/efr32/wf200/host_if.cpp | 28 +-- .../platform/silabs/efr32/wf200/wf200.gni | 2 +- examples/platform/silabs/wfx_rsi.h | 1 - .../platform/silabs}/wifi/wfx_notify.cpp | 130 +++++------ .../silabs/SiWx917/wifi/wfx_host_events.h | 8 +- .../silabs/efr32/wifi/wfx_host_events.h | 13 +- src/platform/silabs/efr32/wifi/wfx_notify.cpp | 220 ------------------ third_party/silabs/efr32_sdk.gni | 2 + 16 files changed, 131 insertions(+), 416 deletions(-) rename {src/platform/silabs/SiWx917 => examples/platform/silabs}/wifi/wfx_notify.cpp (64%) delete mode 100644 src/platform/silabs/efr32/wifi/wfx_notify.cpp diff --git a/examples/platform/silabs/BaseApplication.cpp b/examples/platform/silabs/BaseApplication.cpp index 99123c5bf7..8cf5b3891d 100644 --- a/examples/platform/silabs/BaseApplication.cpp +++ b/examples/platform/silabs/BaseApplication.cpp @@ -190,6 +190,9 @@ void BaseApplicationDelegate::OnCommissioningWindowClosed() #endif // CHIP_CONFIG_ENABLE_ICD_SERVER && SLI_SI917 if (BaseApplication::GetProvisionStatus()) { + // After the device is provisioned and the commissioning passed + // resetting the isCommissioningStarted to false + isComissioningStarted = false; #ifdef DISPLAY_ENABLED #ifdef QR_CODE_ENABLED SilabsLCD::Screen_e screen; diff --git a/examples/platform/silabs/BaseApplication.h b/examples/platform/silabs/BaseApplication.h index 9052e9355a..5d757b8ca4 100644 --- a/examples/platform/silabs/BaseApplication.h +++ b/examples/platform/silabs/BaseApplication.h @@ -65,9 +65,12 @@ class BaseApplicationDelegate : public AppDelegate, public chip::FabricTable::Delegate { +public: + bool isCommissioningInProgress() { return isComissioningStarted; } + private: // AppDelegate - bool isComissioningStarted; + bool isComissioningStarted = false; void OnCommissioningSessionStarted() override; void OnCommissioningSessionStopped() override; void OnCommissioningWindowClosed() override; diff --git a/examples/platform/silabs/SiWx917/BUILD.gn b/examples/platform/silabs/SiWx917/BUILD.gn index 80d247b56c..2780e2ecbc 100644 --- a/examples/platform/silabs/SiWx917/BUILD.gn +++ b/examples/platform/silabs/SiWx917/BUILD.gn @@ -50,8 +50,6 @@ declare_args() { # Sanity check assert(chip_enable_wifi) - -silabs_common_plat_dir = "${chip_root}/examples/platform/silabs" silabs_plat_si91x_wifi_dir = "${chip_root}/src/platform/silabs/SiWx917/wifi" import("${silabs_common_plat_dir}/args.gni") @@ -193,10 +191,10 @@ 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_plat_si91x_wifi_dir}/dhcp_client.cpp", "${silabs_plat_si91x_wifi_dir}/ethernetif.cpp", "${silabs_plat_si91x_wifi_dir}/lwip_netif.cpp", - "${silabs_plat_si91x_wifi_dir}/wfx_notify.cpp", "SiWx917/sl_wifi_if.cpp", "SiWx917/wfx_rsi_host.cpp", ] diff --git a/examples/platform/silabs/SiWx917/SiWx917/sl_wifi_if.cpp b/examples/platform/silabs/SiWx917/SiWx917/sl_wifi_if.cpp index 03b51540cf..92d5ca4808 100644 --- a/examples/platform/silabs/SiWx917/SiWx917/sl_wifi_if.cpp +++ b/examples/platform/silabs/SiWx917/SiWx917/sl_wifi_if.cpp @@ -101,11 +101,6 @@ bool hasNotifiedIPV4 = false; #endif /* CHIP_DEVICE_CONFIG_ENABLE_IPV4 */ bool hasNotifiedWifiConnectivity = false; -/* Declare a flag to differentiate between after boot-up first IP connection or reconnection */ -bool is_wifi_disconnection_event = false; - -/* Declare a variable to hold connection time intervals */ -uint32_t retryInterval = WLAN_MIN_RETRY_TIMER_MS; volatile bool scan_results_complete = false; volatile bool bg_scan_results_complete = false; extern osSemaphoreId_t sl_rs_ble_init_sem; @@ -247,12 +242,7 @@ sl_status_t join_callback_handler(sl_wifi_event_t event, char * result, uint32_t 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_interval_handler(is_wifi_disconnection_event, wfx_rsi.join_retries++); - if (is_wifi_disconnection_event || wfx_rsi.join_retries <= WFX_RSI_CONFIG_MAX_JOIN) - { - WfxEvent.eventType = WFX_EVT_STA_START_JOIN; - WfxPostEvent(&WfxEvent); - } + wfx_retry_connection(++wfx_rsi.join_retries); return SL_STATUS_FAIL; } /* @@ -264,10 +254,7 @@ sl_status_t join_callback_handler(sl_wifi_event_t event, char * result, uint32_t WfxEvent.eventType = WFX_EVT_STA_CONN; WfxPostEvent(&WfxEvent); wfx_rsi.join_retries = 0; - retryInterval = WLAN_MIN_RETRY_TIMER_MS; - // Once the join passes setting the disconnection event to true to differentiate between the first connection and reconnection - is_wifi_disconnection_event = true; - callback_status = SL_STATUS_OK; + callback_status = SL_STATUS_OK; return SL_STATUS_OK; } @@ -693,12 +680,11 @@ static sl_status_t wfx_rsi_do_join(void) // 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((is_wifi_disconnection_event || wfx_rsi.join_retries <= MAX_JOIN_RETRIES_COUNT), 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_interval_handler(is_wifi_disconnection_event, wfx_rsi.join_retries); - wfx_rsi.join_retries++; + wfx_retry_connection(++wfx_rsi.join_retries); event.eventType = WFX_EVT_STA_START_JOIN; WfxPostEvent(&event); return status; diff --git a/examples/platform/silabs/efr32/BUILD.gn b/examples/platform/silabs/efr32/BUILD.gn index 22b7458588..3691091a0b 100644 --- a/examples/platform/silabs/efr32/BUILD.gn +++ b/examples/platform/silabs/efr32/BUILD.gn @@ -48,8 +48,6 @@ declare_args() { sl_test_event_trigger_enable_key = "00112233445566778899AABBCCDDEEFF" } -silabs_common_plat_dir = "${chip_root}/examples/platform/silabs" - import("${silabs_common_plat_dir}/args.gni") # Sanity check diff --git a/examples/platform/silabs/efr32/rs911x/rs9117.gni b/examples/platform/silabs/efr32/rs911x/rs9117.gni index c068e7aa3e..356b72f55f 100644 --- a/examples/platform/silabs/efr32/rs911x/rs9117.gni +++ b/examples/platform/silabs/efr32/rs911x/rs9117.gni @@ -8,7 +8,7 @@ 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_plat_efr32_wifi_dir}/wfx_notify.cpp", + "${silabs_common_plat_dir}/wifi/wfx_notify.cpp", ] rs9117_inc_plat = [ diff --git a/examples/platform/silabs/efr32/rs911x/rs911x.gni b/examples/platform/silabs/efr32/rs911x/rs911x.gni index ebf7c546f6..54507de66e 100644 --- a/examples/platform/silabs/efr32/rs911x/rs911x.gni +++ b/examples/platform/silabs/efr32/rs911x/rs911x.gni @@ -9,7 +9,7 @@ rs911x_src_plat = [ "${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_plat_efr32_wifi_dir}/wfx_notify.cpp", + "${silabs_common_plat_dir}/wifi/wfx_notify.cpp", ] # diff --git a/examples/platform/silabs/efr32/rs911x/rsi_if.c b/examples/platform/silabs/efr32/rs911x/rsi_if.c index e4d6f51bf0..f012128538 100644 --- a/examples/platform/silabs/efr32/rs911x/rsi_if.c +++ b/examples/platform/silabs/efr32/rs911x/rsi_if.c @@ -70,12 +70,6 @@ bool hasNotifiedIPV4 = false; #endif /* CHIP_DEVICE_CONFIG_ENABLE_IPV4 */ bool hasNotifiedWifiConnectivity = false; -/* Declare a flag to differentiate between after boot-up first IP connection or reconnection */ -bool is_wifi_disconnection_event = false; - -/* Declare a variable to hold connection time intervals */ -uint32_t retryInterval = WLAN_MIN_RETRY_TIMER_MS; - #if (RSI_BLE_ENABLE) extern rsi_semaphore_handle_t sl_rs_ble_init_sem; #endif @@ -279,13 +273,8 @@ static void wfx_rsi_join_cb(uint16_t status, const uint8_t * buf, const uint16_t /* * We should enable retry.. (Need config variable for this) */ - SILABS_LOG("%s: failed. retry: %d", __func__, wfx_rsi.join_retries); - wfx_retry_interval_handler(is_wifi_disconnection_event, wfx_rsi.join_retries++); - if (is_wifi_disconnection_event || wfx_rsi.join_retries <= WFX_RSI_CONFIG_MAX_JOIN) - { - WfxEvent.eventType = WFX_EVT_STA_START_JOIN; - WfxPostEvent(&WfxEvent); - } + SILABS_LOG("wfx_rsi_join_cb: failed. retry: %d", wfx_rsi.join_retries); + wfx_retry_connection(++wfx_rsi.join_retries); } else { @@ -293,11 +282,10 @@ static void wfx_rsi_join_cb(uint16_t status, const uint8_t * buf, const uint16_t * Join was complete - Do the DHCP */ memset(&temp_reset, 0, sizeof(wfx_wifi_scan_ext_t)); - SILABS_LOG("%s: join completed.", __func__); + SILABS_LOG("wfx_rsi_join_cb: join completed."); WfxEvent.eventType = WFX_EVT_STA_CONN; WfxPostEvent(&WfxEvent); wfx_rsi.join_retries = 0; - retryInterval = WLAN_MIN_RETRY_TIMER_MS; } } @@ -313,12 +301,11 @@ 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) { - SILABS_LOG("%s: error: failed status: %02x", __func__, status); + SILABS_LOG("wfx_rsi_join_fail_cb: error: failed status: %02x", status); WfxEvent_t WfxEvent; wfx_rsi.join_retries += 1; wfx_rsi.dev_state &= ~(WFX_RSI_ST_STA_CONNECTING | WFX_RSI_ST_STA_CONNECTED); - is_wifi_disconnection_event = true; - WfxEvent.eventType = WFX_EVT_STA_START_JOIN; + WfxEvent.eventType = WFX_EVT_STA_START_JOIN; WfxPostEvent(&WfxEvent); } /************************************************************************************* @@ -354,23 +341,23 @@ static int32_t wfx_rsi_init(void) uint8_t buf[RSI_RESPONSE_HOLD_BUFF_SIZE]; extern void rsi_hal_board_init(void); - SILABS_LOG("%s: starting(HEAP_SZ = %d)", __func__, SL_HEAP_SIZE); + SILABS_LOG("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)) { - SILABS_LOG("%s: error: RSI Driver initialization failed with status: %02x", __func__, status); + SILABS_LOG("wfx_rsi_init: error: RSI Driver initialization failed with status: %02x", status); return status; } - SILABS_LOG("%s: rsi_device_init", __func__); + SILABS_LOG("wfx_rsi_init: rsi_device_init", __func__); /* ! Redpine module intialisation */ if ((status = rsi_device_init(LOAD_NWP_FW)) != RSI_SUCCESS) { - SILABS_LOG("%s: error: rsi_device_init failed with status: %02x", __func__, status); + SILABS_LOG("wfx_rsi_init: error: rsi_device_init failed with status: %02x", status); return status; } - SILABS_LOG("%s: start wireless drv task", __func__); + SILABS_LOG("wfx_rsi_init: start wireless drv task", __func__); /* * Create the driver task */ @@ -378,7 +365,7 @@ static int32_t wfx_rsi_init(void) WLAN_TASK_PRIORITY, driverRsiTaskStack, &driverRsiTaskBuffer); if (NULL == wfx_rsi.drv_task) { - SILABS_LOG("%s: error: rsi_wireless_driver_task failed", __func__); + SILABS_LOG("wfx_rsi_init: error: rsi_wireless_driver_task failed", __func__); return RSI_ERROR_INVALID_PARAM; } @@ -389,40 +376,40 @@ static int32_t wfx_rsi_init(void) if ((status = rsi_wireless_init(OPER_MODE_0, COEX_MODE_0)) != RSI_SUCCESS) { #endif - SILABS_LOG("%s: error: Initialize WiSeConnect failed with status: %02x", __func__, status); + SILABS_LOG("wfx_rsi_init: error: Initialize WiSeConnect failed with status: %02x", status); return status; } - SILABS_LOG("%s: get FW version..", __func__); + SILABS_LOG("wfx_rsi_init: get FW version..", __func__); /* * Get the MAC and other info to let the user know about it. */ if (rsi_wlan_get(RSI_FW_VERSION, buf, sizeof(buf)) != RSI_SUCCESS) { - SILABS_LOG("%s: error: rsi_wlan_get(RSI_FW_VERSION) failed with status: %02x", __func__, status); + SILABS_LOG("wfx_rsi_init: error: rsi_wlan_get(RSI_FW_VERSION) failed with status: %02x", status); return status; } buf[sizeof(buf) - 1] = 0; - SILABS_LOG("%s: RSI firmware version: %s", __func__, buf); + SILABS_LOG("wfx_rsi_init: RSI firmware version: %s", buf); //! Send feature frame if ((status = rsi_send_feature_frame()) != RSI_SUCCESS) { - SILABS_LOG("%s: error: rsi_send_feature_frame failed with status: %02x", __func__, status); + SILABS_LOG("wfx_rsi_init: error: rsi_send_feature_frame failed with status: %02x", status); return status; } - SILABS_LOG("%s: sent rsi_send_feature_frame", __func__); + SILABS_LOG("wfx_rsi_init: sent rsi_send_feature_frame", __func__); /* initializes wlan radio parameters and WLAN supplicant parameters. */ (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) { - SILABS_LOG("%s: error: rsi_wlan_get failed with status: %02x", __func__, status); + SILABS_LOG("wfx_rsi_init: error: rsi_wlan_get failed with status: %02x", status); return status; } - SILABS_LOG("%s: WLAN: MAC %02x:%02x:%02x %02x:%02x:%02x", __func__, wfx_rsi.sta_mac.octet[0], wfx_rsi.sta_mac.octet[1], + SILABS_LOG("wfx_rsi_init: WLAN: 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 @@ -445,12 +432,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) { - SILABS_LOG("%s: RSI callback register join failed with status: %02x", __func__, status); + SILABS_LOG("wfx_rsi_init: RSI callback register join failed with status: %02x", status); return status; } if ((status = rsi_wlan_register_callbacks(RSI_WLAN_DATA_RECEIVE_NOTIFY_CB, wfx_rsi_wlan_pkt_cb)) != RSI_SUCCESS) { - SILABS_LOG("%s: RSI callback register data-notify failed with status: %02x", __func__, status); + SILABS_LOG("wfx_rsi_init: RSI callback register data-notify failed with status: %02x", status); return status; } @@ -459,7 +446,7 @@ static int32_t wfx_rsi_init(void) #endif wfx_rsi.dev_state |= WFX_RSI_ST_DEV_READY; - SILABS_LOG("%s: RSI: OK", __func__); + SILABS_LOG("wfx_rsi_init: RSI: OK", __func__); return RSI_SUCCESS; } @@ -488,7 +475,7 @@ static void wfx_rsi_save_ap_info() // translation #else /* !WIFI_ENABLE_SECURITY_WPA3_TRANSITION */ wfx_rsi.sec.security = WFX_SEC_WPA2; #endif /* WIFI_ENABLE_SECURITY_WPA3_TRANSITION */ - SILABS_LOG("%s: warn: failed with status: %02x", __func__, status); + SILABS_LOG("wfx_rsi_save_ap_info: warn: failed with status: %02x", status); return; } wfx_rsi.sec.security = WFX_SEC_UNSPECIFIED; @@ -524,7 +511,8 @@ static void wfx_rsi_save_ap_info() // translation break; } - SILABS_LOG("%s: WLAN: connecting to %s, sec=%d, status=%02x", __func__, &wfx_rsi.sec.ssid[0], wfx_rsi.sec.security, status); + SILABS_LOG("wfx_rsi_save_ap_info: WLAN: connecting to %s, sec=%d, status=%02x", &wfx_rsi.sec.ssid[0], wfx_rsi.sec.security, + status); } /******************************************************************************************** @@ -541,7 +529,7 @@ static void wfx_rsi_do_join(void) if (wfx_rsi.dev_state & (WFX_RSI_ST_STA_CONNECTING | WFX_RSI_ST_STA_CONNECTED)) { - SILABS_LOG("%s: not joining - already in progress", __func__); + SILABS_LOG("wfx_rsi_do_join: not joining - already in progress"); } else { @@ -564,11 +552,11 @@ static void wfx_rsi_do_join(void) connect_security_mode = RSI_OPEN; break; default: - SILABS_LOG("%s: error: unknown security type.", __func__); + SILABS_LOG("wfx_rsi_do_join: error: unknown security type."); return; } - SILABS_LOG("%s: WLAN: connecting to %s, sec=%d", __func__, &wfx_rsi.sec.ssid[0], wfx_rsi.sec.security); + SILABS_LOG("wfx_rsi_do_join: WLAN: connecting to %s, sec=%d", &wfx_rsi.sec.ssid[0], wfx_rsi.sec.security); /* * Join the network @@ -580,33 +568,18 @@ static void wfx_rsi_do_join(void) if ((status = rsi_wlan_register_callbacks(RSI_JOIN_FAIL_CB, wfx_rsi_join_fail_cb)) != RSI_SUCCESS) { - SILABS_LOG("%s: RSI callback register join failed with status: %02x", __func__, status); + SILABS_LOG("wfx_rsi_do_join: RSI callback register join failed with status: %02x", status); } /* Try to connect Wifi with given Credentials * untill there is a success or maximum number of tries allowed */ - while (is_wifi_disconnection_event || wfx_rsi.join_retries <= WFX_RSI_CONFIG_MAX_JOIN) + 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) { - /* Call rsi connect call with given ssid and password - * And check there is a success - */ - 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; - SILABS_LOG("%s: rsi_wlan_connect_async failed with status: %02x on try %d", __func__, status, wfx_rsi.join_retries); - - wfx_retry_interval_handler(is_wifi_disconnection_event, wfx_rsi.join_retries); - wfx_rsi.join_retries++; - } - else - { - SILABS_LOG("%s: starting JOIN to %s after %d tries\n", __func__, (char *) &wfx_rsi.sec.ssid[0], - wfx_rsi.join_retries); - break; // exit while loop - } + wfx_rsi.dev_state &= ~WFX_RSI_ST_STA_CONNECTING; + SILABS_LOG("wfx_rsi_do_join: rsi_wlan_connect_async failed with status: %02x on try %d", status, wfx_rsi.join_retries); + wfx_retry_connection(++wfx_rsi.join_retries); } } } @@ -701,7 +674,7 @@ void ProcessEvent(WfxEvent_t inEvent) switch (inEvent.eventType) { case WFX_EVT_STA_CONN: - SILABS_LOG("%s: starting LwIP STA", __func__); + SILABS_LOG("Starting LwIP STA"); wfx_rsi.dev_state |= WFX_RSI_ST_STA_CONNECTED; ResetDHCPNotificationFlags(); wfx_lwip_set_sta_link_up(); @@ -715,7 +688,7 @@ void ProcessEvent(WfxEvent_t inEvent) // 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); - SILABS_LOG("%s: disconnect notify", __func__); + SILABS_LOG("Disconnect notify"); /* TODO: Implement disconnect notify */ ResetDHCPNotificationFlags(); wfx_lwip_set_sta_link_down(); // Internally dhcpclient_poll(netif) -> @@ -813,7 +786,7 @@ void wfx_rsi_task(void * arg) uint32_t rsi_status = wfx_rsi_init(); if (rsi_status != RSI_SUCCESS) { - SILABS_LOG("%s: error: wfx_rsi_init with status: %02x", __func__, rsi_status); + SILABS_LOG("wfx_rsi_task: error: wfx_rsi_init with status: %02x", rsi_status); return; } WfxEvent_t wfxEvent; @@ -853,7 +826,7 @@ void wfx_dhcp_got_ipv4(uint32_t ip) 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; - SILABS_LOG("%s: DHCP OK: IP=%d.%d.%d.%d", __func__, wfx_rsi.ip4_addr[0], wfx_rsi.ip4_addr[1], wfx_rsi.ip4_addr[2], + SILABS_LOG("wfx_dhcp_got_ipv4: 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; diff --git a/examples/platform/silabs/efr32/wf200/host_if.cpp b/examples/platform/silabs/efr32/wf200/host_if.cpp index ac3ad07773..44e65e2728 100644 --- a/examples/platform/silabs/efr32/wf200/host_if.cpp +++ b/examples/platform/silabs/efr32/wf200/host_if.cpp @@ -99,12 +99,6 @@ bool hasNotifiedWifiConnectivity = false; static uint8_t retryJoin = 0; bool retryInProgress = false; -/* Declare a flag to differentiate between after boot-up first IP connection or reconnection */ -bool is_wifi_disconnection_event = false; - -/* Declare a variable to hold connection time intervals */ -uint32_t retryInterval = WLAN_MIN_RETRY_TIMER_MS; - #ifdef SL_WFX_CONFIG_SCAN static struct scan_result_holder { @@ -401,14 +395,14 @@ static void sl_wfx_connect_callback(sl_wfx_connect_ind_body_t connect_indication } } - if ((status != WFM_STATUS_SUCCESS) && (!is_wifi_disconnection_event ? (retryJoin < MAX_JOIN_RETRIES_COUNT) : true)) + if (status != WFM_STATUS_SUCCESS) { retryJoin += 1; retryInProgress = false; SILABS_LOG("WFX Retry to connect to network count: %d", retryJoin); sl_wfx_context->state = static_cast(static_cast(sl_wfx_context->state) & ~static_cast(SL_WFX_STARTED)); - xEventGroupSetBits(sl_wfx_event_group, SL_WFX_RETRY_CONNECT); + wfx_retry_connection(retryJoin); } } @@ -424,9 +418,8 @@ static void sl_wfx_disconnect_callback(uint8_t * mac, uint16_t reason) SILABS_LOG("WFX Disconnected %d\r\n", reason); sl_wfx_context->state = static_cast(static_cast(sl_wfx_context->state) & ~static_cast(SL_WFX_STA_INTERFACE_CONNECTED)); - retryInProgress = false; - is_wifi_disconnection_event = true; - xEventGroupSetBits(sl_wfx_event_group, SL_WFX_RETRY_CONNECT); + retryInProgress = false; + wfx_retry_connection(retryJoin); } #ifdef SL_WFX_CONFIG_SOFTAP @@ -541,13 +534,8 @@ static void wfx_events_task(void * p_arg) pdTRUE, pdFALSE, pdMS_TO_TICKS(250)); /* 250 msec delay converted to ticks */ if (flags & SL_WFX_RETRY_CONNECT) { - if (!retryInProgress) - { - retryInProgress = true; - wfx_retry_interval_handler(is_wifi_disconnection_event, retryJoin); - SILABS_LOG("WFX sending the connect command"); - wfx_connect_to_ap(); - } + SILABS_LOG("WFX sending the connect command"); + wfx_connect_to_ap(); } if (wifi_extra & WE_ST_STA_CONN) @@ -599,8 +587,7 @@ static void wfx_events_task(void * p_arg) hasNotifiedWifiConnectivity = false; SILABS_LOG("WIFI: Connected to AP"); wifi_extra |= WE_ST_STA_CONN; - retryJoin = 0; - retryInterval = WLAN_MIN_RETRY_TIMER_MS; + retryJoin = 0; wfx_lwip_set_sta_link_up(); #if CHIP_CONFIG_ENABLE_ICD_SERVER if (!(wfx_get_wifi_state() & SL_WFX_AP_INTERFACE_UP)) @@ -750,6 +737,7 @@ static void wfx_wifi_hw_start(void) /* Initialize the LwIP stack */ SILABS_LOG("WF200:Start LWIP"); wfx_lwip_start(); + wfx_started_notify(); wifiContext.state = SL_WFX_STARTED; /* Really this is a bit mask */ SILABS_LOG("WF200:ready.."); } diff --git a/examples/platform/silabs/efr32/wf200/wf200.gni b/examples/platform/silabs/efr32/wf200/wf200.gni index 7e3b4ae6f1..307b681537 100644 --- a/examples/platform/silabs/efr32/wf200/wf200.gni +++ b/examples/platform/silabs/efr32/wf200/wf200.gni @@ -4,7 +4,7 @@ import("${efr32_sdk_build_root}/efr32_sdk.gni") wf200_plat_incs = [ "${examples_plat_dir}/wf200" ] wf200_plat_src = [ - "${silabs_plat_efr32_wifi_dir}/wfx_notify.cpp", + "${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", diff --git a/examples/platform/silabs/wfx_rsi.h b/examples/platform/silabs/wfx_rsi.h index c559e1e761..502dd1a96e 100644 --- a/examples/platform/silabs/wfx_rsi.h +++ b/examples/platform/silabs/wfx_rsi.h @@ -31,7 +31,6 @@ #define WFX_RSI_WLAN_TASK_SZ (1024 + 512 + 256) /* Stack for the WLAN task */ #define WFX_RSI_TASK_SZ (1024 + 1024) /* Stack for the WFX/RSI task */ #define WFX_RSI_BUF_SZ (1024 * 10) /* May need tweak */ -#define WFX_RSI_CONFIG_MAX_JOIN (5) /* Max join retries */ // TODO: Default values are usually in minutes, but this is in ms. Confirm if this is correct #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 */ diff --git a/src/platform/silabs/SiWx917/wifi/wfx_notify.cpp b/examples/platform/silabs/wifi/wfx_notify.cpp similarity index 64% rename from src/platform/silabs/SiWx917/wifi/wfx_notify.cpp rename to examples/platform/silabs/wifi/wfx_notify.cpp index ded8e8389d..a37b102c33 100644 --- a/src/platform/silabs/SiWx917/wifi/wfx_notify.cpp +++ b/examples/platform/silabs/wifi/wfx_notify.cpp @@ -15,6 +15,9 @@ * limitations under the License. */ +#include "AppConfig.h" +#include "BaseApplication.h" +#include #include #include #include @@ -29,32 +32,33 @@ #include "wfx_rsi.h" #endif -#if SL_ICD_ENABLED -#ifdef __cplusplus -extern "C" { -#endif - -#ifdef __cplusplus -} -#endif -#endif // SL_ICD_ENABLED - #include -// #include -#include -#include using namespace ::chip; using namespace ::chip::DeviceLayer; -#include - -extern uint32_t retryInterval; +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 wfx_started_notify() * @brief @@ -67,6 +71,10 @@ void wfx_started_notify() 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; @@ -90,13 +98,7 @@ void wfx_connected_notify(int32_t status, sl_wfx_mac_address_t * ap) { sl_wfx_connect_ind_t evt; - if (status != SUCCESS_STATUS) - { - ChipLogProgress(DeviceLayer, "%s: error: failed status: %ld.", __func__, status); - return; - } - - ChipLogProgress(DeviceLayer, "%s: connected.", __func__); + VerifyOrReturn(status != SUCCESS_STATUS); memset(&evt, 0, sizeof(evt)); evt.header.id = SL_WFX_CONNECT_IND_ID; @@ -143,16 +145,6 @@ void wfx_ipv6_notify(int got_ip) 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); - - /* So the other threads can run and have the connectivity OK */ - if (got_ip) - { - /* Should remember this */ - vTaskDelay(1); - chip::DeviceLayer::PlatformMgr().LockChipStack(); - chip::app::DnssdServer::Instance().StartServer(/*Dnssd::CommissioningMode::kEnabledBasic*/); - chip::DeviceLayer::PlatformMgr().UnlockChipStack(); - } } /************************************************************************************** @@ -170,67 +162,67 @@ void wfx_ip_changed_notify(int got_ip) 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); - - /* So the other threads can run and have the connectivity OK */ - if (got_ip) - { - /* Should remember this */ - vTaskDelay(1); - chip::DeviceLayer::PlatformMgr().LockChipStack(); - chip::app::DnssdServer::Instance().StartServer(/*Dnssd::CommissioningMode::kEnabledBasic*/); - chip::DeviceLayer::PlatformMgr().UnlockChipStack(); - } } /************************************************************************************** - * @fn void wfx_retry_interval_handler(bool is_wifi_disconnection_event, uint16_t retryJoin) + * @fn void wfx_retry_connection(uint16_t retryAttempt) * @brief - * Based on condition will delay for a certain period of time. - * @param[in] is_wifi_disconnection_event, retryJoin + * 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_interval_handler(bool is_wifi_disconnection_event, uint16_t retryJoin) +void wfx_retry_connection(uint16_t retryAttempt) { - if (!is_wifi_disconnection_event) + // During commissioning, we retry to join the network MAX_JOIN_RETRIES_COUNT + if (BaseApplication::sAppDelegate.isCommissioningInProgress()) { - /* After the reboot or a commissioning time device failed to connect with AP. - * Device will retry to connect with AP upto WFX_RSI_CONFIG_MAX_JOIN retries. - */ - if (retryJoin < MAX_JOIN_RETRIES_COUNT) + if (retryAttempt < MAX_JOIN_RETRIES_COUNT) { - ChipLogProgress(DeviceLayer, "wfx_retry_interval_handler : Next attempt after %d Seconds", - CONVERT_MS_TO_SEC(WLAN_RETRY_TIMER_MS)); -#if SL_ICD_ENABLED - // TODO: cleanup the retry logic MATTER-1921 - if (!chip::Server::GetInstance().GetCommissioningWindowManager().IsCommissioningWindowOpen()) + ChipLogProgress(DeviceLayer, "wfx_retry_connection : Next attempt after %d Seconds", kWlanRetryIntervalInSec); + if (osTimerStart(sRetryTimer, pdMS_TO_TICKS(CONVERT_SEC_TO_MS(kWlanRetryIntervalInSec))) != osOK) { - wfx_rsi_power_save(RSI_SLEEP_MODE_8, STANDBY_POWER_SAVE_WITH_RAM_RETENTION); + 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; } -#endif // SL_ICD_ENABLED - vTaskDelay(pdMS_TO_TICKS(WLAN_RETRY_TIMER_MS)); } else { - ChipLogProgress(DeviceLayer, "Connect failed after max %d tries", retryJoin); + ChipLogProgress(DeviceLayer, "Connect failed after max %d tries", retryAttempt); } } else { - /* After disconnection + /* 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 > WLAN_MAX_RETRY_TIMER_MS) + if (retryInterval > kWlanMaxRetryIntervalsInSec) + { + retryInterval = kWlanMaxRetryIntervalsInSec; + } + if (osTimerStart(sRetryTimer, pdMS_TO_TICKS(CONVERT_SEC_TO_MS(retryInterval))) != osOK) { - retryInterval = WLAN_MAX_RETRY_TIMER_MS; + 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; } - ChipLogProgress(DeviceLayer, "wfx_retry_interval_handler : Next attempt after %ld Seconds", - CONVERT_MS_TO_SEC(retryInterval)); -#if SL_ICD_ENABLED +#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 // SL_ICD_ENABLED - vTaskDelay(pdMS_TO_TICKS(retryInterval)); +#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/SiWx917/wifi/wfx_host_events.h b/src/platform/silabs/SiWx917/wifi/wfx_host_events.h index beee667f58..319a1c508e 100644 --- a/src/platform/silabs/SiWx917/wifi/wfx_host_events.h +++ b/src/platform/silabs/SiWx917/wifi/wfx_host_events.h @@ -60,11 +60,7 @@ #define BLE_DRIVER_TASK_PRIORITY (2) #define MAX_JOIN_RETRIES_COUNT (5) -// WLAN retry time intervals in milli seconds -#define WLAN_MAX_RETRY_TIMER_MS 30000 -#define WLAN_MIN_RETRY_TIMER_MS 1000 -#define WLAN_RETRY_TIMER_MS 5000 -#define CONVERT_MS_TO_SEC(TimeInMS) (TimeInMS / 1000) +#define CONVERT_SEC_TO_MS(TimeInS) (TimeInS * 1000) // WLAN related Macros #define ETH_FRAME (0) @@ -255,7 +251,7 @@ void sl_button_on_change(uint8_t btn, uint8_t btnAction); #endif /* SL_ICD_ENABLED */ void wfx_ipv6_notify(int got_ip); -void wfx_retry_interval_handler(bool is_wifi_disconnection_event, uint16_t retryJoin); +void wfx_retry_connection(uint16_t retryAttempt); #ifdef __cplusplus } diff --git a/src/platform/silabs/efr32/wifi/wfx_host_events.h b/src/platform/silabs/efr32/wifi/wfx_host_events.h index 24e5b6ea70..51f96d7b9d 100644 --- a/src/platform/silabs/efr32/wifi/wfx_host_events.h +++ b/src/platform/silabs/efr32/wifi/wfx_host_events.h @@ -139,12 +139,10 @@ typedef struct __attribute__((__packed__)) sl_wfx_mib_req_s #define WLAN_TASK_PRIORITY 1 #define WLAN_DRIVER_TASK_PRIORITY 1 #define BLE_DRIVER_TASK_PRIORITY 1 -#define MAX_JOIN_RETRIES_COUNT 5 #else /* WF200 */ #define WLAN_TASK_STACK_SIZE 1024 #define WLAN_TASK_PRIORITY 1 -#define MAX_JOIN_RETRIES_COUNT 5 #endif // RS911X_WIFI // MAX SSID LENGTH excluding NULL character @@ -152,11 +150,10 @@ typedef struct __attribute__((__packed__)) sl_wfx_mib_req_s // MAX PASSKEY LENGTH including NULL character #define WFX_MAX_PASSKEY_LENGTH (64) -// WLAN retry time intervals in milli seconds -#define WLAN_MAX_RETRY_TIMER_MS 30000 -#define WLAN_MIN_RETRY_TIMER_MS 1000 -#define WLAN_RETRY_TIMER_MS 5000 -#define CONVERT_MS_TO_SEC(TimeInMS) (TimeInMS / 1000) +#define CONVERT_SEC_TO_MS(TimeInS) (TimeInS * 1000) + +// WLAN MAX retry +#define MAX_JOIN_RETRIES_COUNT 5 // WLAN related Macros #define ETH_FRAME 0 @@ -388,7 +385,7 @@ void sl_wfx_host_gpio_init(void); sl_status_t sl_wfx_host_process_event(sl_wfx_generic_message_t * event_payload); #endif -void wfx_retry_interval_handler(bool is_wifi_disconnection_event, uint16_t retryJoin); +void wfx_retry_connection(uint16_t retryAttempt); #ifdef __cplusplus } diff --git a/src/platform/silabs/efr32/wifi/wfx_notify.cpp b/src/platform/silabs/efr32/wifi/wfx_notify.cpp deleted file mode 100644 index fd183100e7..0000000000 --- a/src/platform/silabs/efr32/wifi/wfx_notify.cpp +++ /dev/null @@ -1,220 +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 "em_bus.h" -#include "em_cmu.h" -#include "em_gpio.h" -#include "em_ldma.h" -#include "em_usart.h" -#include "gpiointerrupt.h" - -#include "FreeRTOS.h" -#include "event_groups.h" -#include "task.h" - -#include "wfx_host_events.h" - -#ifdef RS911X_WIFI -#include "wfx_rsi.h" -#endif - -#include -#include -#include -#include - -using namespace ::chip; -using namespace ::chip::DeviceLayer; - -extern uint32_t retryInterval; - -/* - * Notifications to the upper-layer - * All done in the context of the RSI/WiFi task (rsi_if.c) - */ - -/*********************************************************************************** - * @fn wfx_started_notify() - * @brief - * Wifi device started notification - * @param[in]: None - * @return None - *************************************************************************************/ -void wfx_started_notify() -{ - sl_wfx_startup_ind_t evt; - sl_wfx_mac_address_t mac; - - 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; - - if (status != SUCCESS_STATUS) - { - ChipLogProgress(DeviceLayer, "%s: error: failed status: %ld.", __func__, status); - return; - } - - ChipLogProgress(DeviceLayer, "%s: connected.", __func__); - - 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); - - /* So the other threads can run and have the connectivity OK */ - if (got_ip) - { - /* Should remember this */ - vTaskDelay(1); - chip::DeviceLayer::PlatformMgr().LockChipStack(); - chip::app::DnssdServer::Instance().StartServer(/*Dnssd::CommissioningMode::kEnabledBasic*/); - chip::DeviceLayer::PlatformMgr().UnlockChipStack(); - } -} - -/************************************************************************************** - * @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); - - /* So the other threads can run and have the connectivity OK */ - if (got_ip) - { - /* Should remember this */ - vTaskDelay(1); - chip::DeviceLayer::PlatformMgr().LockChipStack(); - chip::app::DnssdServer::Instance().StartServer(/*Dnssd::CommissioningMode::kEnabledBasic*/); - chip::DeviceLayer::PlatformMgr().UnlockChipStack(); - } -} - -/************************************************************************************** - * @fn void wfx_retry_interval_handler(bool is_wifi_disconnection_event, uint16_t retryJoin) - * @brief - * Based on condition will delay for a certain period of time. - * @param[in] is_wifi_disconnection_event, retryJoin - * @return None - ********************************************************************************************/ -void wfx_retry_interval_handler(bool is_wifi_disconnection_event, uint16_t retryJoin) -{ - if (!is_wifi_disconnection_event) - { - /* After the reboot or a commissioning time device failed to connect with AP. - * Device will retry to connect with AP upto WFX_RSI_CONFIG_MAX_JOIN retries. - */ - if (retryJoin < MAX_JOIN_RETRIES_COUNT) - { - ChipLogProgress(DeviceLayer, "%s: Next attempt after %d Seconds", __func__, CONVERT_MS_TO_SEC(WLAN_RETRY_TIMER_MS)); - vTaskDelay(pdMS_TO_TICKS(WLAN_RETRY_TIMER_MS)); - } - else - { - ChipLogProgress(DeviceLayer, "Connect failed after max %d tries", retryJoin); - } - } - else - { - /* After disconnection - * 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 > WLAN_MAX_RETRY_TIMER_MS) - { - retryInterval = WLAN_MAX_RETRY_TIMER_MS; - } - ChipLogProgress(DeviceLayer, "%s: Next attempt after %ld Seconds", __func__, CONVERT_MS_TO_SEC(retryInterval)); - vTaskDelay(pdMS_TO_TICKS(retryInterval)); - retryInterval += retryInterval; - } -} diff --git a/third_party/silabs/efr32_sdk.gni b/third_party/silabs/efr32_sdk.gni index 617dfd10fa..ce7b09e3e0 100644 --- a/third_party/silabs/efr32_sdk.gni +++ b/third_party/silabs/efr32_sdk.gni @@ -89,6 +89,8 @@ declare_args() { examples_plat_dir = "${chip_root}/examples/platform/silabs/efr32" silabs_plat_efr32_wifi_dir = "${chip_root}/src/platform/silabs/efr32/wifi" +silabs_common_plat_dir = "${chip_root}/examples/platform/silabs" + is_series_2 = silabs_family == "mgm24" || silabs_family == "efr32mg24" || silabs_family == "efr32mg26" From be0009e75879cb61e57ad09e7d2e67677d52f679 Mon Sep 17 00:00:00 2001 From: waqar rashid <6962179+wickywaka@users.noreply.github.com> Date: Sat, 24 Aug 2024 01:33:21 +0200 Subject: [PATCH 164/165] Fixed missing trailing zero in example documentation (#35149) Co-authored-by: Boris Zbarsky --- docs/getting_started/first_example.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/getting_started/first_example.md b/docs/getting_started/first_example.md index 4aba0d4e48..fefa1916c2 100644 --- a/docs/getting_started/first_example.md +++ b/docs/getting_started/first_example.md @@ -92,7 +92,7 @@ codes, discriminator and passcode from the logs. Open a new terminal to use chip tool. Commission the device using: -`./out/linux-x64-chip-tool/chip-tool pairing code 0x12344321 MT:-24J0AFN00KA0648G0` +`./out/linux-x64-chip-tool/chip-tool pairing code 0x12344321 MT:-24J0AFN00KA0648G00` NOTE: pairing is the old name for commissioning. 0x12344321 is the node ID you want to assign to the node. 0x12344321 is the default for testing. From a93f4b6a98535cd03905a06032ad362f20c48faf Mon Sep 17 00:00:00 2001 From: chirag-silabs <100861685+chirag-silabs@users.noreply.github.com> Date: Sat, 24 Aug 2024 06:45:25 +0530 Subject: [PATCH 165/165] [Silabs] Fixing the build for the custom boards on NCP (#35055) * fixing the build for the custom boards on ncp * Restyled by clang-format * applying the restyler * addressing the review comments and adding sl_custom_board.h file * adding the warning message for 917 NCP * Restyled by whitespace * Restyled by clang-format * Apply suggestions from code review Co-authored-by: Yufeng Wang * Restyled by clang-format --------- Co-authored-by: Restyled.io Co-authored-by: Junior Martinez <67972863+jmartinez-silabs@users.noreply.github.com> Co-authored-by: Yufeng Wang --- .../silabs/efr32/rs911x/hal/efx32_ncp_host.c | 3 + .../silabs/efr32/rs911x/hal/efx_spi.c | 19 ++--- .../rs911x/hal/rsi_board_configuration.h | 3 +- .../efr32/rs911x/hal/sl_board_configuration.h | 3 +- .../efr32/rs911x/hal/sl_si91x_ncp_utility.c | 4 +- .../platform/silabs/efr32/sl_custom_board.h | 71 +++++++++++++++++++ .../platform/silabs/efr32/wf200/efr_spi.c | 5 -- .../silabs/efr32/wf200/sl_wfx_board.h | 3 +- 8 files changed, 88 insertions(+), 23 deletions(-) create mode 100644 examples/platform/silabs/efr32/sl_custom_board.h diff --git a/examples/platform/silabs/efr32/rs911x/hal/efx32_ncp_host.c b/examples/platform/silabs/efr32/rs911x/hal/efx32_ncp_host.c index fded8defa3..0a2fad7d0d 100644 --- a/examples/platform/silabs/efr32/rs911x/hal/efx32_ncp_host.c +++ b/examples/platform/silabs/efr32/rs911x/hal/efx32_ncp_host.c @@ -36,7 +36,10 @@ #include "sl_power_manager.h" #endif +#ifdef SL_BOARD_NAME #include "sl_board_control.h" +#endif // SL_BOARD_NAME + #include "sl_si91x_ncp_utility.h" #include "spi_multiplex.h" diff --git a/examples/platform/silabs/efr32/rs911x/hal/efx_spi.c b/examples/platform/silabs/efr32/rs911x/hal/efx_spi.c index 6c03b6f1f4..1f10640e04 100644 --- a/examples/platform/silabs/efr32/rs911x/hal/efx_spi.c +++ b/examples/platform/silabs/efr32/rs911x/hal/efx_spi.c @@ -35,7 +35,6 @@ #include "em_gpio.h" #include "em_ldma.h" #include "gpiointerrupt.h" -#include "sl_board_control.h" #include "sl_device_init_clocks.h" #include "sl_device_init_hfxo.h" #include "sl_spidrv_instances.h" @@ -47,6 +46,10 @@ #include "wfx_host_events.h" #include "wfx_rsi.h" +#ifdef SL_BOARD_NAME +#include "sl_board_control.h" +#endif // SL_BOARD_NAME + #if defined(SL_CATALOG_POWER_MANAGER_PRESENT) #include "sl_power_manager.h" #endif @@ -65,18 +68,12 @@ #include "sl_mx25_flash_shutdown_usart_config.h" #endif // SL_MX25CTRL_MUX -#if defined(EFR32MG24) #include "em_eusart.h" #include "sl_spidrv_eusart_exp_config.h" #include "spi_multiplex.h" -#else -#error "Unknown platform" -#endif -#if defined(EFR32MG24) #define SL_SPIDRV_HANDLE sl_spidrv_eusart_exp_handle #define SL_SPIDRV_EXP_BITRATE_MULTIPLEXED SL_SPIDRV_EUSART_EXP_BITRATE -#endif #define CONCAT(A, B) (A##B) #define SPI_CLOCK(N) CONCAT(cmuClock_USART, N) @@ -113,10 +110,8 @@ void sl_wfx_host_gpio_init(void) // Enable GPIO clock. CMU_ClockEnable(cmuClock_GPIO, true); -#if defined(EFR32MG24) // Set CS pin to high/inactive GPIO_PinModeSet(SL_SPIDRV_EUSART_EXP_CS_PORT, SL_SPIDRV_EUSART_EXP_CS_PIN, gpioModePushPull, PINOUT_SET); -#endif // EFR32MG24 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); @@ -195,9 +190,7 @@ sl_status_t sl_wfx_host_spi_cs_assert(void) if (!spi_enabled) // Reduce sl_spidrv_init_instances { sl_spidrv_init_instances(); -#if defined(EFR32MG24) GPIO_PinOutClear(SL_SPIDRV_EUSART_EXP_CS_PORT, SL_SPIDRV_EUSART_EXP_CS_PIN); -#endif // EFR32MG24 spi_enabled = true; } return SL_STATUS_OK; @@ -211,11 +204,9 @@ sl_status_t sl_wfx_host_spi_cs_deassert(void) status = SPIDRV_DeInit(SL_SPIDRV_HANDLE); if (SL_STATUS_OK == status) { -#if defined(EFR32MG24) 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; -#endif // EFR32MG24 - spi_enabled = false; + spi_enabled = false; } } #if SL_SPICTRL_MUX diff --git a/examples/platform/silabs/efr32/rs911x/hal/rsi_board_configuration.h b/examples/platform/silabs/efr32/rs911x/hal/rsi_board_configuration.h index 4d8d9da1dd..ed04acf5b3 100644 --- a/examples/platform/silabs/efr32/rs911x/hal/rsi_board_configuration.h +++ b/examples/platform/silabs/efr32/rs911x/hal/rsi_board_configuration.h @@ -35,7 +35,8 @@ typedef struct #elif defined(EFR32MG24_BRD4187C) || defined(BRD4187C) #include "brd4187c.h" #else -#error "Need SPI Pins" +#include "sl_custom_board.h" +#warning "Modify sl_custom_board.h configuration file to match your hardware SPIDRV USART peripheral" #endif /* EFR32MG24_BRD4186C */ #endif /* _RSI_BOARD_CONFIGURATION_H_ */ diff --git a/examples/platform/silabs/efr32/rs911x/hal/sl_board_configuration.h b/examples/platform/silabs/efr32/rs911x/hal/sl_board_configuration.h index c1dceab06d..317bdc5bd2 100644 --- a/examples/platform/silabs/efr32/rs911x/hal/sl_board_configuration.h +++ b/examples/platform/silabs/efr32/rs911x/hal/sl_board_configuration.h @@ -36,7 +36,8 @@ typedef struct #elif defined(EFR32MG24_BRD4187C) || defined(BRD4187C) #include "brd4187c.h" #else -#error "Need SPI Pins" +#include "sl_custom_board.h" +#warning "Modify sl_custom_board.h configuration file to match your hardware SPIDRV USART peripheral" #endif #if EXP_BOARD #define RESET_PIN PIN(A, 6) 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 4b876883c1..b16bbdc475 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 @@ -36,7 +36,9 @@ #include "spidrv.h" #include "task.h" +#ifdef SL_BOARD_NAME #include "sl_board_control.h" +#endif // SL_BOARD_NAME #include "sl_device_init_clocks.h" #include "sl_device_init_hfxo.h" @@ -242,4 +244,4 @@ sl_status_t sl_wfx_host_spiflash_cs_deassert(void) GPIO_PinOutSet(SL_MX25_FLASH_SHUTDOWN_CS_PORT, SL_MX25_FLASH_SHUTDOWN_CS_PIN); return SL_STATUS_OK; } -#endif // SL_MX25CTRL_MUX \ No newline at end of file +#endif // SL_MX25CTRL_MUX diff --git a/examples/platform/silabs/efr32/sl_custom_board.h b/examples/platform/silabs/efr32/sl_custom_board.h new file mode 100644 index 0000000000..420b715de9 --- /dev/null +++ b/examples/platform/silabs/efr32/sl_custom_board.h @@ -0,0 +1,71 @@ +/* + * This file is used to set the pins for the SPI for Custom boards + * The SPI pins are defined in the file + * + * !!!! MODIFY THIS FILE TO THE CORRECT PINS !!!! + */ + +#ifndef _CUSTOM_BOARD_H_ +#define _CUSTOM_BOARD_H_ + +#define WAKE_INDICATOR_PIN PIN(D, 2) +#ifdef RS911X_WIFI +// SPI ports and pins +#define EUS1MOSI_PORT gpioPortC +#define EUS1MOSI_PIN 1 +#define EUS1MISO_PORT gpioPortC +#define EUS1MISO_PIN 2 +#define EUS1SCLK_PORT gpioPortC +#define EUS1SCLK_PIN 3 +#define EUS1CS_PORT gpioPortC +#define EUS1CS_PIN 0 + +#define MY_USART EUSART1 +#define MY_USART_CLOCK cmuClock_EUSART1 +#define MY_USART_TX_SIGNAL dmadrvPeripheralSignal_EUSART1_TXBL +#define MY_USART_RX_SIGNAL dmadrvPeripheralSignal_EUSART1_RXDATAV + +#define WFX_RESET_PIN PIN(A, 6) +#define WFX_INTERRUPT_PIN PIN(A, 7) +#ifdef EXP_BOARD +#define WFX_SLEEP_CONFIRM_PIN PIN(D, 2) /* Expansion header pin7 */ +#else +#define WFX_SLEEP_CONFIRM_PIN PIN(A, 5) +#endif /* EXP_BOARD */ +#define SL_WFX_HOST_PINOUT_SPI_IRQ 5 + +#else /* WF200 */ + +#define PIN_OUT_SET 1 +#define PIN_OUT_CLEAR 0 + +#define MY_USART USART0 +#define MY_USART_CLOCK cmuClock_USART0 +#define MY_USART_TX_SIGNAL dmadrvPeripheralSignal_USART0_TXBL +#define MY_USART_RX_SIGNAL dmadrvPeripheralSignal_USART0_RXDATAV + +#define SL_WFX_HOST_PINOUT_RESET_PORT gpioPortA +#define SL_WFX_HOST_PINOUT_RESET_PIN 5 +#define SL_WFX_HOST_PINOUT_SPI_WIRQ_PORT gpioPortA /* SPI IRQ port */ +#define SL_WFX_HOST_PINOUT_SPI_WIRQ_PIN 8 /* SPI IRQ pin */ +#define SL_WFX_HOST_PINOUT_WUP_PORT gpioPortB +#define SL_WFX_HOST_PINOUT_WUP_PIN 5 + +#define SL_WFX_HOST_PINOUT_SPI_TX_PORT gpioPortC +#define SL_WFX_HOST_PINOUT_SPI_TX_PIN 1 +#define SL_WFX_HOST_PINOUT_SPI_TX_LOC 1 + +#define SL_WFX_HOST_PINOUT_SPI_RX_PORT gpioPortC +#define SL_WFX_HOST_PINOUT_SPI_RX_PIN 2 +#define SL_WFX_HOST_PINOUT_SPI_RX_LOC 1 + +#define SL_WFX_HOST_PINOUT_SPI_CLK_PORT gpioPortC +#define SL_WFX_HOST_PINOUT_SPI_CLK_PIN 3 +#define SL_WFX_HOST_PINOUT_SPI_CLK_LOC 1 + +#define SL_WFX_HOST_PINOUT_SPI_CS_PORT gpioPortC +#define SL_WFX_HOST_PINOUT_SPI_CS_PIN 0 +#define SL_WFX_HOST_PINOUT_SPI_CS_LOC 1 + +#endif /* WF200/9116 */ +#endif /* _CUSTOM_BOARD_H_ */ diff --git a/examples/platform/silabs/efr32/wf200/efr_spi.c b/examples/platform/silabs/efr32/wf200/efr_spi.c index 122652e96d..3ef34c928e 100644 --- a/examples/platform/silabs/efr32/wf200/efr_spi.c +++ b/examples/platform/silabs/efr32/wf200/efr_spi.c @@ -98,11 +98,9 @@ sl_status_t sl_wfx_host_init_bus(void) * EUSARTROUTE register to do this. */ -#if defined(EFR32MG24) GPIO->USARTROUTE[0].ROUTEEN = GPIO_USART_ROUTEEN_RXPEN | // MISO GPIO_USART_ROUTEEN_TXPEN | // MOSI GPIO_USART_ROUTEEN_CLKPEN; -#endif spi_sem = xSemaphoreCreateBinaryStatic(&xEfrSpiSemaBuffer); xSemaphoreGive(spi_sem); @@ -338,11 +336,8 @@ void sl_wfx_host_gpio_init(void) { // Enable GPIO clock. CMU_ClockEnable(cmuClock_GPIO, true); - -#if defined(EFR32MG24) // configure WF200 CS pin. GPIO_PinModeSet(SL_SPIDRV_EXP_CS_PORT, SL_SPIDRV_EXP_CS_PIN, gpioModePushPull, 1); -#endif // Configure WF200 reset pin. GPIO_PinModeSet(SL_WFX_HOST_PINOUT_RESET_PORT, SL_WFX_HOST_PINOUT_RESET_PIN, gpioModePushPull, 0); // Configure WF200 WUP pin. diff --git a/examples/platform/silabs/efr32/wf200/sl_wfx_board.h b/examples/platform/silabs/efr32/wf200/sl_wfx_board.h index 3cbed666d6..35ce2f633d 100644 --- a/examples/platform/silabs/efr32/wf200/sl_wfx_board.h +++ b/examples/platform/silabs/efr32/wf200/sl_wfx_board.h @@ -25,6 +25,7 @@ #elif defined(EFR32MG24_BRD4187C) || defined(BRD4187C) || defined(EFR32MG24_BRD4187A) || defined(BRD4187A) #include "brd4187c.h" #else -#error "Need SPI Pins" +#include "sl_custom_board.h" +#warning "Modify sl_custom_board.h configuration file to match your hardware SPIDRV USART peripheral" #endif #endif /* _SL_WFX_BOARD_H_ */