From 536a0d9b0f738ed79a939c638ef1bbfae3e7cf59 Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Tue, 7 Mar 2023 23:36:46 -0500 Subject: [PATCH 1/9] Correctly return RESOURCE_EXHAUSTED when too many bindings are written. (#25549) Fixes https://github.com/project-chip/connectedhomeip/issues/25538 --- src/app/clusters/bindings/bindings.cpp | 35 ++++-- src/app/clusters/bindings/bindings.h | 2 +- src/app/tests/suites/TestBinding.yaml | 21 ++++ .../chip-tool/zap-generated/test/Commands.h | 108 +++++++++++++++++- .../zap-generated/test/Commands.h | 103 ++++++++++++++++- 5 files changed, 255 insertions(+), 14 deletions(-) diff --git a/src/app/clusters/bindings/bindings.cpp b/src/app/clusters/bindings/bindings.cpp index 0b48cee6f6c4a4..22c4fba0be6920 100644 --- a/src/app/clusters/bindings/bindings.cpp +++ b/src/app/clusters/bindings/bindings.cpp @@ -30,6 +30,8 @@ #include #include #include +#include + using namespace chip; using namespace chip::app; using namespace chip::app::Clusters; @@ -117,7 +119,7 @@ CHIP_ERROR CheckValidBindingList(const EndpointId localEndpoint, const Decodable return CHIP_NO_ERROR; } -void CreateBindingEntry(const TargetStructType & entry, EndpointId localEndpoint) +CHIP_ERROR CreateBindingEntry(const TargetStructType & entry, EndpointId localEndpoint) { EmberBindingTableEntry bindingEntry; @@ -131,7 +133,7 @@ void CreateBindingEntry(const TargetStructType & entry, EndpointId localEndpoint entry.cluster); } - AddBindingEntry(bindingEntry); + return AddBindingEntry(bindingEntry); } CHIP_ERROR BindingTableAccess::Read(const ConcreteReadAttributePath & path, AttributeValueEncoder & encoder) @@ -225,10 +227,11 @@ CHIP_ERROR BindingTableAccess::WriteBindingTable(const ConcreteDataAttributePath } // Add new entries - auto iter = newBindingList.begin(); - while (iter.Next()) + auto iter = newBindingList.begin(); + CHIP_ERROR err = CHIP_NO_ERROR; + while (iter.Next() && err == CHIP_NO_ERROR) { - CreateBindingEntry(iter.GetValue(), path.mEndpointId); + err = CreateBindingEntry(iter.GetValue(), path.mEndpointId); } // If this was not caused by a list operation, OnListWriteEnd is not going to be triggered @@ -238,7 +241,7 @@ CHIP_ERROR BindingTableAccess::WriteBindingTable(const ConcreteDataAttributePath // Notify binding table has changed LogErrorOnFailure(NotifyBindingsChanged()); } - return CHIP_NO_ERROR; + return err; } if (path.mListOp == ConcreteDataAttributePath::ListOperation::AppendItem) { @@ -248,8 +251,7 @@ CHIP_ERROR BindingTableAccess::WriteBindingTable(const ConcreteDataAttributePath { return CHIP_IM_GLOBAL_STATUS(ConstraintError); } - CreateBindingEntry(target, path.mEndpointId); - return CHIP_NO_ERROR; + return CreateBindingEntry(target, path.mEndpointId); } return CHIP_IM_GLOBAL_STATUS(UnsupportedWrite); } @@ -269,11 +271,22 @@ void MatterBindingPluginServerInitCallback() registerAttributeAccessOverride(&gAttrAccess); } -void AddBindingEntry(const EmberBindingTableEntry & entry) +CHIP_ERROR AddBindingEntry(const EmberBindingTableEntry & entry) { + CHIP_ERROR err = BindingTable::GetInstance().Add(entry); + if (err == CHIP_ERROR_NO_MEMORY) + { + return CHIP_IM_GLOBAL_STATUS(ResourceExhausted); + } + + if (err != CHIP_NO_ERROR) + { + return err; + } + if (entry.type == EMBER_UNICAST_BINDING) { - CHIP_ERROR err = BindingManager::GetInstance().UnicastBindingCreated(entry.fabricIndex, entry.nodeId); + err = BindingManager::GetInstance().UnicastBindingCreated(entry.fabricIndex, entry.nodeId); if (err != CHIP_NO_ERROR) { // Unicast connection failure can happen if peer is offline. We'll retry connection on-demand. @@ -283,5 +296,5 @@ void AddBindingEntry(const EmberBindingTableEntry & entry) } } - BindingTable::GetInstance().Add(entry); + return CHIP_NO_ERROR; } diff --git a/src/app/clusters/bindings/bindings.h b/src/app/clusters/bindings/bindings.h index 3d6d773cdbcd8c..b77f7e99b2cedf 100644 --- a/src/app/clusters/bindings/bindings.h +++ b/src/app/clusters/bindings/bindings.h @@ -28,4 +28,4 @@ * * @param entry binding to add */ -void AddBindingEntry(const EmberBindingTableEntry & entry); +CHIP_ERROR AddBindingEntry(const EmberBindingTableEntry & entry); diff --git a/src/app/tests/suites/TestBinding.yaml b/src/app/tests/suites/TestBinding.yaml index 6ca70ad3d9c330..15f25cbb5f2365 100644 --- a/src/app/tests/suites/TestBinding.yaml +++ b/src/app/tests/suites/TestBinding.yaml @@ -104,3 +104,24 @@ tests: { FabricIndex: 1, Node: 1, Endpoint: 1, Cluster: 6 }, { FabricIndex: 1, Node: 2, Endpoint: 1 }, ] + + - label: "Write over-long binding table on endpoint 1" + command: "writeAttribute" + attribute: "Binding" + arguments: + value: + [ + { FabricIndex: 0, Node: 1, Endpoint: 1, Cluster: 6 }, + { FabricIndex: 0, Node: 2, Endpoint: 2, Cluster: 6 }, + { FabricIndex: 0, Node: 3, Endpoint: 3, Cluster: 6 }, + { FabricIndex: 0, Node: 4, Endpoint: 4, Cluster: 6 }, + { FabricIndex: 0, Node: 5, Endpoint: 5, Cluster: 6 }, + { FabricIndex: 0, Node: 6, Endpoint: 6, Cluster: 6 }, + { FabricIndex: 0, Node: 7, Endpoint: 7, Cluster: 6 }, + { FabricIndex: 0, Node: 8, Endpoint: 8, Cluster: 6 }, + { FabricIndex: 0, Node: 9, Endpoint: 9, Cluster: 6 }, + { FabricIndex: 0, Node: 10, Endpoint: 10, Cluster: 6 }, + { FabricIndex: 0, Node: 11, Endpoint: 11, Cluster: 6 }, + ] + response: + error: RESOURCE_EXHAUSTED diff --git a/zzz_generated/chip-tool/zap-generated/test/Commands.h b/zzz_generated/chip-tool/zap-generated/test/Commands.h index dd43f9aaafa5fe..c8b5d75ba7ac0e 100644 --- a/zzz_generated/chip-tool/zap-generated/test/Commands.h +++ b/zzz_generated/chip-tool/zap-generated/test/Commands.h @@ -70473,7 +70473,7 @@ class TestSystemCommandsSuite : public TestCommand class TestBindingSuite : public TestCommand { public: - TestBindingSuite(CredentialIssuerCommands * credsIssuerConfig) : TestCommand("TestBinding", 9, credsIssuerConfig) + TestBindingSuite(CredentialIssuerCommands * credsIssuerConfig) : TestCommand("TestBinding", 10, credsIssuerConfig) { AddArgument("nodeId", 0, UINT64_MAX, &mNodeId); AddArgument("cluster", &mCluster); @@ -70608,6 +70608,9 @@ class TestBindingSuite : public TestCommand } } break; + case 9: + VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), EMBER_ZCL_STATUS_RESOURCE_EXHAUSTED)); + break; default: LogErrorOnFailure(ContinueOnChipMainThread(CHIP_ERROR_INVALID_ARGUMENT)); } @@ -70740,6 +70743,109 @@ class TestBindingSuite : public TestCommand return ReadAttribute(kIdentityAlpha, GetEndpoint(1), Binding::Id, Binding::Attributes::Binding::Id, true, chip::NullOptional); } + case 9: { + LogStep(9, "Write over-long binding table on endpoint 1"); + ListFreer listFreer; + chip::app::DataModel::List value; + + { + auto * listHolder_0 = new ListHolder(11); + listFreer.add(listHolder_0); + + listHolder_0->mList[0].node.Emplace(); + listHolder_0->mList[0].node.Value() = 1ULL; + listHolder_0->mList[0].endpoint.Emplace(); + listHolder_0->mList[0].endpoint.Value() = 1U; + listHolder_0->mList[0].cluster.Emplace(); + listHolder_0->mList[0].cluster.Value() = 6UL; + listHolder_0->mList[0].fabricIndex = 0U; + + listHolder_0->mList[1].node.Emplace(); + listHolder_0->mList[1].node.Value() = 2ULL; + listHolder_0->mList[1].endpoint.Emplace(); + listHolder_0->mList[1].endpoint.Value() = 2U; + listHolder_0->mList[1].cluster.Emplace(); + listHolder_0->mList[1].cluster.Value() = 6UL; + listHolder_0->mList[1].fabricIndex = 0U; + + listHolder_0->mList[2].node.Emplace(); + listHolder_0->mList[2].node.Value() = 3ULL; + listHolder_0->mList[2].endpoint.Emplace(); + listHolder_0->mList[2].endpoint.Value() = 3U; + listHolder_0->mList[2].cluster.Emplace(); + listHolder_0->mList[2].cluster.Value() = 6UL; + listHolder_0->mList[2].fabricIndex = 0U; + + listHolder_0->mList[3].node.Emplace(); + listHolder_0->mList[3].node.Value() = 4ULL; + listHolder_0->mList[3].endpoint.Emplace(); + listHolder_0->mList[3].endpoint.Value() = 4U; + listHolder_0->mList[3].cluster.Emplace(); + listHolder_0->mList[3].cluster.Value() = 6UL; + listHolder_0->mList[3].fabricIndex = 0U; + + listHolder_0->mList[4].node.Emplace(); + listHolder_0->mList[4].node.Value() = 5ULL; + listHolder_0->mList[4].endpoint.Emplace(); + listHolder_0->mList[4].endpoint.Value() = 5U; + listHolder_0->mList[4].cluster.Emplace(); + listHolder_0->mList[4].cluster.Value() = 6UL; + listHolder_0->mList[4].fabricIndex = 0U; + + listHolder_0->mList[5].node.Emplace(); + listHolder_0->mList[5].node.Value() = 6ULL; + listHolder_0->mList[5].endpoint.Emplace(); + listHolder_0->mList[5].endpoint.Value() = 6U; + listHolder_0->mList[5].cluster.Emplace(); + listHolder_0->mList[5].cluster.Value() = 6UL; + listHolder_0->mList[5].fabricIndex = 0U; + + listHolder_0->mList[6].node.Emplace(); + listHolder_0->mList[6].node.Value() = 7ULL; + listHolder_0->mList[6].endpoint.Emplace(); + listHolder_0->mList[6].endpoint.Value() = 7U; + listHolder_0->mList[6].cluster.Emplace(); + listHolder_0->mList[6].cluster.Value() = 6UL; + listHolder_0->mList[6].fabricIndex = 0U; + + listHolder_0->mList[7].node.Emplace(); + listHolder_0->mList[7].node.Value() = 8ULL; + listHolder_0->mList[7].endpoint.Emplace(); + listHolder_0->mList[7].endpoint.Value() = 8U; + listHolder_0->mList[7].cluster.Emplace(); + listHolder_0->mList[7].cluster.Value() = 6UL; + listHolder_0->mList[7].fabricIndex = 0U; + + listHolder_0->mList[8].node.Emplace(); + listHolder_0->mList[8].node.Value() = 9ULL; + listHolder_0->mList[8].endpoint.Emplace(); + listHolder_0->mList[8].endpoint.Value() = 9U; + listHolder_0->mList[8].cluster.Emplace(); + listHolder_0->mList[8].cluster.Value() = 6UL; + listHolder_0->mList[8].fabricIndex = 0U; + + listHolder_0->mList[9].node.Emplace(); + listHolder_0->mList[9].node.Value() = 10ULL; + listHolder_0->mList[9].endpoint.Emplace(); + listHolder_0->mList[9].endpoint.Value() = 10U; + listHolder_0->mList[9].cluster.Emplace(); + listHolder_0->mList[9].cluster.Value() = 6UL; + listHolder_0->mList[9].fabricIndex = 0U; + + listHolder_0->mList[10].node.Emplace(); + listHolder_0->mList[10].node.Value() = 11ULL; + listHolder_0->mList[10].endpoint.Emplace(); + listHolder_0->mList[10].endpoint.Value() = 11U; + listHolder_0->mList[10].cluster.Emplace(); + listHolder_0->mList[10].cluster.Value() = 6UL; + listHolder_0->mList[10].fabricIndex = 0U; + + value = + chip::app::DataModel::List(listHolder_0->mList, 11); + } + return WriteAttribute(kIdentityAlpha, GetEndpoint(1), Binding::Id, Binding::Attributes::Binding::Id, value, + chip::NullOptional, chip::NullOptional); + } } return CHIP_NO_ERROR; } diff --git a/zzz_generated/darwin-framework-tool/zap-generated/test/Commands.h b/zzz_generated/darwin-framework-tool/zap-generated/test/Commands.h index 211cf0f0c7a45b..36318231e2cb0d 100644 --- a/zzz_generated/darwin-framework-tool/zap-generated/test/Commands.h +++ b/zzz_generated/darwin-framework-tool/zap-generated/test/Commands.h @@ -102449,6 +102449,10 @@ class TestBinding : public TestCommandBridge { ChipLogProgress(chipTool, " ***** Test Step 8 : Verify endpoint 1 not changed\n"); err = TestVerifyEndpoint1NotChanged_8(); break; + case 9: + ChipLogProgress(chipTool, " ***** Test Step 9 : Write over-long binding table on endpoint 1\n"); + err = TestWriteOverLongBindingTableOnEndpoint1_9(); + break; } if (CHIP_NO_ERROR != err) { @@ -102487,6 +102491,9 @@ class TestBinding : public TestCommandBridge { case 8: VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); break; + case 9: + VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), EMBER_ZCL_STATUS_RESOURCE_EXHAUSTED)); + break; } // Go on to the next test. @@ -102500,7 +102507,7 @@ class TestBinding : public TestCommandBridge { private: std::atomic_uint16_t mTestIndex; - const uint16_t mTestCount = 9; + const uint16_t mTestCount = 10; chip::Optional mNodeId; chip::Optional mCluster; @@ -102790,6 +102797,100 @@ class TestBinding : public TestCommandBridge { return CHIP_NO_ERROR; } + + CHIP_ERROR TestWriteOverLongBindingTableOnEndpoint1_9() + { + + MTRBaseDevice * device = GetDevice("alpha"); + __auto_type * cluster = [[MTRBaseClusterBinding alloc] initWithDevice:device endpointID:@(1) queue:mCallbackQueue]; + VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); + + id bindingArgument; + { + NSMutableArray * temp_0 = [[NSMutableArray alloc] init]; + temp_0[0] = [[MTRBindingClusterTargetStruct alloc] init]; + ((MTRBindingClusterTargetStruct *) temp_0[0]).node = [NSNumber numberWithUnsignedLongLong:1ULL]; + ((MTRBindingClusterTargetStruct *) temp_0[0]).endpoint = [NSNumber numberWithUnsignedShort:1U]; + ((MTRBindingClusterTargetStruct *) temp_0[0]).cluster = [NSNumber numberWithUnsignedInt:6UL]; + ((MTRBindingClusterTargetStruct *) temp_0[0]).fabricIndex = [NSNumber numberWithUnsignedChar:0U]; + + temp_0[1] = [[MTRBindingClusterTargetStruct alloc] init]; + ((MTRBindingClusterTargetStruct *) temp_0[1]).node = [NSNumber numberWithUnsignedLongLong:2ULL]; + ((MTRBindingClusterTargetStruct *) temp_0[1]).endpoint = [NSNumber numberWithUnsignedShort:2U]; + ((MTRBindingClusterTargetStruct *) temp_0[1]).cluster = [NSNumber numberWithUnsignedInt:6UL]; + ((MTRBindingClusterTargetStruct *) temp_0[1]).fabricIndex = [NSNumber numberWithUnsignedChar:0U]; + + temp_0[2] = [[MTRBindingClusterTargetStruct alloc] init]; + ((MTRBindingClusterTargetStruct *) temp_0[2]).node = [NSNumber numberWithUnsignedLongLong:3ULL]; + ((MTRBindingClusterTargetStruct *) temp_0[2]).endpoint = [NSNumber numberWithUnsignedShort:3U]; + ((MTRBindingClusterTargetStruct *) temp_0[2]).cluster = [NSNumber numberWithUnsignedInt:6UL]; + ((MTRBindingClusterTargetStruct *) temp_0[2]).fabricIndex = [NSNumber numberWithUnsignedChar:0U]; + + temp_0[3] = [[MTRBindingClusterTargetStruct alloc] init]; + ((MTRBindingClusterTargetStruct *) temp_0[3]).node = [NSNumber numberWithUnsignedLongLong:4ULL]; + ((MTRBindingClusterTargetStruct *) temp_0[3]).endpoint = [NSNumber numberWithUnsignedShort:4U]; + ((MTRBindingClusterTargetStruct *) temp_0[3]).cluster = [NSNumber numberWithUnsignedInt:6UL]; + ((MTRBindingClusterTargetStruct *) temp_0[3]).fabricIndex = [NSNumber numberWithUnsignedChar:0U]; + + temp_0[4] = [[MTRBindingClusterTargetStruct alloc] init]; + ((MTRBindingClusterTargetStruct *) temp_0[4]).node = [NSNumber numberWithUnsignedLongLong:5ULL]; + ((MTRBindingClusterTargetStruct *) temp_0[4]).endpoint = [NSNumber numberWithUnsignedShort:5U]; + ((MTRBindingClusterTargetStruct *) temp_0[4]).cluster = [NSNumber numberWithUnsignedInt:6UL]; + ((MTRBindingClusterTargetStruct *) temp_0[4]).fabricIndex = [NSNumber numberWithUnsignedChar:0U]; + + temp_0[5] = [[MTRBindingClusterTargetStruct alloc] init]; + ((MTRBindingClusterTargetStruct *) temp_0[5]).node = [NSNumber numberWithUnsignedLongLong:6ULL]; + ((MTRBindingClusterTargetStruct *) temp_0[5]).endpoint = [NSNumber numberWithUnsignedShort:6U]; + ((MTRBindingClusterTargetStruct *) temp_0[5]).cluster = [NSNumber numberWithUnsignedInt:6UL]; + ((MTRBindingClusterTargetStruct *) temp_0[5]).fabricIndex = [NSNumber numberWithUnsignedChar:0U]; + + temp_0[6] = [[MTRBindingClusterTargetStruct alloc] init]; + ((MTRBindingClusterTargetStruct *) temp_0[6]).node = [NSNumber numberWithUnsignedLongLong:7ULL]; + ((MTRBindingClusterTargetStruct *) temp_0[6]).endpoint = [NSNumber numberWithUnsignedShort:7U]; + ((MTRBindingClusterTargetStruct *) temp_0[6]).cluster = [NSNumber numberWithUnsignedInt:6UL]; + ((MTRBindingClusterTargetStruct *) temp_0[6]).fabricIndex = [NSNumber numberWithUnsignedChar:0U]; + + temp_0[7] = [[MTRBindingClusterTargetStruct alloc] init]; + ((MTRBindingClusterTargetStruct *) temp_0[7]).node = [NSNumber numberWithUnsignedLongLong:8ULL]; + ((MTRBindingClusterTargetStruct *) temp_0[7]).endpoint = [NSNumber numberWithUnsignedShort:8U]; + ((MTRBindingClusterTargetStruct *) temp_0[7]).cluster = [NSNumber numberWithUnsignedInt:6UL]; + ((MTRBindingClusterTargetStruct *) temp_0[7]).fabricIndex = [NSNumber numberWithUnsignedChar:0U]; + + temp_0[8] = [[MTRBindingClusterTargetStruct alloc] init]; + ((MTRBindingClusterTargetStruct *) temp_0[8]).node = [NSNumber numberWithUnsignedLongLong:9ULL]; + ((MTRBindingClusterTargetStruct *) temp_0[8]).endpoint = [NSNumber numberWithUnsignedShort:9U]; + ((MTRBindingClusterTargetStruct *) temp_0[8]).cluster = [NSNumber numberWithUnsignedInt:6UL]; + ((MTRBindingClusterTargetStruct *) temp_0[8]).fabricIndex = [NSNumber numberWithUnsignedChar:0U]; + + temp_0[9] = [[MTRBindingClusterTargetStruct alloc] init]; + ((MTRBindingClusterTargetStruct *) temp_0[9]).node = [NSNumber numberWithUnsignedLongLong:10ULL]; + ((MTRBindingClusterTargetStruct *) temp_0[9]).endpoint = [NSNumber numberWithUnsignedShort:10U]; + ((MTRBindingClusterTargetStruct *) temp_0[9]).cluster = [NSNumber numberWithUnsignedInt:6UL]; + ((MTRBindingClusterTargetStruct *) temp_0[9]).fabricIndex = [NSNumber numberWithUnsignedChar:0U]; + + temp_0[10] = [[MTRBindingClusterTargetStruct alloc] init]; + ((MTRBindingClusterTargetStruct *) temp_0[10]).node = [NSNumber numberWithUnsignedLongLong:11ULL]; + ((MTRBindingClusterTargetStruct *) temp_0[10]).endpoint = [NSNumber numberWithUnsignedShort:11U]; + ((MTRBindingClusterTargetStruct *) temp_0[10]).cluster = [NSNumber numberWithUnsignedInt:6UL]; + ((MTRBindingClusterTargetStruct *) temp_0[10]).fabricIndex = [NSNumber numberWithUnsignedChar:0U]; + + bindingArgument = temp_0; + } + [cluster + writeAttributeBindingWithValue:bindingArgument + completion:^(NSError * _Nullable err) { + NSLog(@"Write over-long binding table on endpoint 1 Error: %@", err); + + VerifyOrReturn(CheckValue("status", + err ? ([err.domain isEqualToString:MTRInteractionErrorDomain] ? err.code + : EMBER_ZCL_STATUS_FAILURE) + : 0, + EMBER_ZCL_STATUS_RESOURCE_EXHAUSTED)); + NextTest(); + }]; + + return CHIP_NO_ERROR; + } }; class TestUserLabelCluster : public TestCommandBridge { From e49795958861ff5b0f81c8990bc1383de374f80b Mon Sep 17 00:00:00 2001 From: Michael Spang Date: Wed, 8 Mar 2023 08:48:37 -0500 Subject: [PATCH 2/9] Fix the EFR32 version stamping (#25548) There are build rules to set CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING to a custom string, but the #define is not actually set in the context where it is used (GenericConfigurationManagerImpl). Fix this by exporting it from //third_party/silabs:efr32_sdk --- third_party/silabs/BUILD.gn | 1 + 1 file changed, 1 insertion(+) diff --git a/third_party/silabs/BUILD.gn b/third_party/silabs/BUILD.gn index e78442dd164945..0ced1ac6826680 100644 --- a/third_party/silabs/BUILD.gn +++ b/third_party/silabs/BUILD.gn @@ -45,6 +45,7 @@ config("silabs_config") { group("efr32_sdk") { public_deps = [ efr32_sdk_target ] + public_configs = [ ":silabs_config" ] } # Openthread GSDK libraries configurations From 0d62a7e4863036eeecf89aabdcfce77eef147202 Mon Sep 17 00:00:00 2001 From: Junior Martinez <67972863+jmartinez-silabs@users.noreply.github.com> Date: Wed, 8 Mar 2023 09:02:23 -0500 Subject: [PATCH 3/9] [Silabs] Fix a few issues preventing siwx917 platform builds. (#25557) * Fix a few issues preventing siwx917 builds. efr32 KeyValueStoreManagerImpl.cpp and MigrationManager implementation could and should be share for the siwx917 platform so move it and renable the class and namespace of the migration manager * Restyled by clang-format --------- Co-authored-by: Restyled.io --- .../SiWx917/include/CHIPProjectConfig.h | 11 - .../platform/silabs/SiWx917/SiWx917/rsi_if.c | 1 + .../{efr32 => }/KeyValueStoreManagerImpl.cpp | 2 +- .../silabs/{efr32 => }/MigrationManager.cpp | 10 +- .../silabs/{efr32 => }/MigrationManager.h | 14 +- src/platform/silabs/SiWx917/BUILD.gn | 4 +- .../SiWx917/KeyValueStoreManagerImpl.cpp | 213 ------------------ src/platform/silabs/efr32/BUILD.gn | 4 +- 8 files changed, 19 insertions(+), 240 deletions(-) rename src/platform/silabs/{efr32 => }/KeyValueStoreManagerImpl.cpp (99%) rename src/platform/silabs/{efr32 => }/MigrationManager.cpp (92%) rename src/platform/silabs/{efr32 => }/MigrationManager.h (80%) delete mode 100644 src/platform/silabs/SiWx917/KeyValueStoreManagerImpl.cpp diff --git a/examples/lighting-app/silabs/SiWx917/include/CHIPProjectConfig.h b/examples/lighting-app/silabs/SiWx917/include/CHIPProjectConfig.h index ff01045a6c6707..751ebfcff265f2 100644 --- a/examples/lighting-app/silabs/SiWx917/include/CHIPProjectConfig.h +++ b/examples/lighting-app/silabs/SiWx917/include/CHIPProjectConfig.h @@ -69,17 +69,6 @@ */ #define CHIP_DEVICE_CONFIG_DEVICE_HARDWARE_VERSION 1 -/** - * CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING - * - * A string identifying the software version running on the device. - * CHIP service currently expects the software version to be in the format - * {MAJOR_VERSION}.0d{MINOR_VERSION} - */ -#ifndef CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING -#define CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING "0.1ALPHA" -#endif - /** * CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION * diff --git a/examples/platform/silabs/SiWx917/SiWx917/rsi_if.c b/examples/platform/silabs/SiWx917/SiWx917/rsi_if.c index 4197532369b0ee..d2e3a5124695dc 100644 --- a/examples/platform/silabs/SiWx917/SiWx917/rsi_if.c +++ b/examples/platform/silabs/SiWx917/SiWx917/rsi_if.c @@ -422,6 +422,7 @@ static void wfx_rsi_save_ap_info() static void wfx_rsi_do_join(void) { int32_t status; + rsi_security_mode_t connect_security_mode; if (wfx_rsi.dev_state & (WFX_RSI_ST_STA_CONNECTING | WFX_RSI_ST_STA_CONNECTED)) { diff --git a/src/platform/silabs/efr32/KeyValueStoreManagerImpl.cpp b/src/platform/silabs/KeyValueStoreManagerImpl.cpp similarity index 99% rename from src/platform/silabs/efr32/KeyValueStoreManagerImpl.cpp rename to src/platform/silabs/KeyValueStoreManagerImpl.cpp index dc5b3267564e1b..ffff7b945186bb 100644 --- a/src/platform/silabs/efr32/KeyValueStoreManagerImpl.cpp +++ b/src/platform/silabs/KeyValueStoreManagerImpl.cpp @@ -49,7 +49,7 @@ CHIP_ERROR KeyValueStoreManagerImpl::Init(void) err = SilabsConfig::Init(); SuccessOrExit(err); - EFR32::EFR32Migration::GetMigrationManager().applyMigrations(); + Silabs::MigrationManager::GetMigrationInstance().applyMigrations(); memset(mKvsKeyMap, 0, sizeof(mKvsKeyMap)); size_t outLen; diff --git a/src/platform/silabs/efr32/MigrationManager.cpp b/src/platform/silabs/MigrationManager.cpp similarity index 92% rename from src/platform/silabs/efr32/MigrationManager.cpp rename to src/platform/silabs/MigrationManager.cpp index abd0bcbc834adf..037f9f7f292079 100644 --- a/src/platform/silabs/efr32/MigrationManager.cpp +++ b/src/platform/silabs/MigrationManager.cpp @@ -26,7 +26,7 @@ using namespace ::chip::DeviceLayer::PersistedStorage; namespace chip { namespace DeviceLayer { -namespace EFR32 { +namespace Silabs { namespace { typedef void (*func_ptr)(); @@ -45,7 +45,7 @@ static migrationData_t migrationTable[] = { } // namespace -void EFR32Migration::applyMigrations() +void MigrationManager::applyMigrations() { uint32_t lastMigationGroupDone = 0; SilabsConfig::ReadConfigValue(SilabsConfig::kConfigKey_MigrationCounter, lastMigationGroupDone); @@ -62,12 +62,12 @@ void EFR32Migration::applyMigrations() SilabsConfig::WriteConfigValue(SilabsConfig::kConfigKey_MigrationCounter, completedMigrationGroup); } -EFR32Migration & EFR32Migration::GetMigrationManager() +MigrationManager & MigrationManager::GetMigrationInstance() { - static EFR32Migration sMigrationManager; + static MigrationManager sMigrationManager; return sMigrationManager; } -} // namespace EFR32 +} // namespace Silabs } // namespace DeviceLayer } // namespace chip diff --git a/src/platform/silabs/efr32/MigrationManager.h b/src/platform/silabs/MigrationManager.h similarity index 80% rename from src/platform/silabs/efr32/MigrationManager.h rename to src/platform/silabs/MigrationManager.h index 59ea29d0769152..2d560c4fa194df 100644 --- a/src/platform/silabs/efr32/MigrationManager.h +++ b/src/platform/silabs/MigrationManager.h @@ -20,25 +20,25 @@ namespace chip { namespace DeviceLayer { -namespace EFR32 { +namespace Silabs { -class EFR32Migration +class MigrationManager { friend class KeyValueStoreManagerImpl; public: /** - * The EFR32 migration manager is implemented as a singleton + * The Silabs migration manager is implemented as a singleton * User should get the object from this getter. */ - static EFR32Migration & GetMigrationManager(); + static MigrationManager & GetMigrationInstance(); static void applyMigrations(); private: - EFR32Migration(){}; - ~EFR32Migration(){}; + MigrationManager(){}; + ~MigrationManager(){}; }; -} // namespace EFR32 +} // namespace Silabs } // namespace DeviceLayer } // namespace chip diff --git a/src/platform/silabs/SiWx917/BUILD.gn b/src/platform/silabs/SiWx917/BUILD.gn index d53d04894869ce..e79810a4029093 100644 --- a/src/platform/silabs/SiWx917/BUILD.gn +++ b/src/platform/silabs/SiWx917/BUILD.gn @@ -43,8 +43,11 @@ static_library("SiWx917") { "${silabs_platform_dir}/DiagnosticDataProviderImpl.cpp", "${silabs_platform_dir}/DiagnosticDataProviderImpl.h", "${silabs_platform_dir}/InetPlatformConfig.h", + "${silabs_platform_dir}/KeyValueStoreManagerImpl.cpp", "${silabs_platform_dir}/KeyValueStoreManagerImpl.h", "${silabs_platform_dir}/Logging.cpp", + "${silabs_platform_dir}/MigrationManager.cpp", + "${silabs_platform_dir}/MigrationManager.h", "${silabs_platform_dir}/PlatformManagerImpl.h", "${silabs_platform_dir}/SilabsConfig.cpp", "${silabs_platform_dir}/SilabsConfig.h", @@ -53,7 +56,6 @@ static_library("SiWx917") { "../../SingletonConfigurationManager.cpp", "BLEManagerImpl.cpp", "ConfigurationManagerImpl.cpp", - "KeyValueStoreManagerImpl.cpp", "PlatformManagerImpl.cpp", "bluetooth/rsi_ble_config.h", "bluetooth/wfx_sl_ble_init.c", diff --git a/src/platform/silabs/SiWx917/KeyValueStoreManagerImpl.cpp b/src/platform/silabs/SiWx917/KeyValueStoreManagerImpl.cpp deleted file mode 100644 index 9bca8221fcb229..00000000000000 --- a/src/platform/silabs/SiWx917/KeyValueStoreManagerImpl.cpp +++ /dev/null @@ -1,213 +0,0 @@ -/* - * - * Copyright (c) 2021-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 - * Platform-specific key value storage implementation for SILABS - */ - -#include -#include -#include -#include -#include -#include -#include - -using namespace ::chip; -using namespace ::chip::DeviceLayer::Internal; - -#define CONVERT_KEYMAP_INDEX_TO_NVM3KEY(index) (SilabsConfig::kConfigKey_KvsFirstKeySlot + index) -#define CONVERT_NVM3KEY_TO_KEYMAP_INDEX(nvm3Key) (nvm3Key - SilabsConfig::kConfigKey_KvsFirstKeySlot) - -namespace chip { -namespace DeviceLayer { -namespace PersistedStorage { - -KeyValueStoreManagerImpl KeyValueStoreManagerImpl::sInstance; -char mKvsStoredKeyString[KeyValueStoreManagerImpl::kMaxEntries][PersistentStorageDelegate::kKeyLengthMax + 1]; - -CHIP_ERROR KeyValueStoreManagerImpl::Init(void) -{ - CHIP_ERROR err; - err = SilabsConfig::Init(); - SuccessOrExit(err); - - memset(mKvsStoredKeyString, 0, sizeof(mKvsStoredKeyString)); - size_t outLen; - err = SilabsConfig::ReadConfigValueBin(SilabsConfig::kConfigKey_KvsStringKeyMap, - reinterpret_cast(mKvsStoredKeyString), sizeof(mKvsStoredKeyString), outLen); - - if (err == CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND) // Initial boot - { - err = CHIP_NO_ERROR; - } - -exit: - return err; -} - -bool KeyValueStoreManagerImpl::IsValidKvsNvm3Key(uint32_t nvm3Key) const -{ - return ((SilabsConfig::kConfigKey_KvsFirstKeySlot <= nvm3Key) && (nvm3Key <= SilabsConfig::kConfigKey_KvsLastKeySlot)); -} - -CHIP_ERROR KeyValueStoreManagerImpl::MapKvsKeyToNvm3(const char * key, uint32_t & nvm3Key, bool isSlotNeeded) const -{ - CHIP_ERROR err; - uint8_t firstEmptyKeySlot = kMaxEntries; - for (uint8_t keyIndex = 0; keyIndex < kMaxEntries; keyIndex++) - { - if (strcmp(key, mKvsStoredKeyString[keyIndex]) == 0) - { - nvm3Key = CONVERT_KEYMAP_INDEX_TO_NVM3KEY(keyIndex); - VerifyOrDie(IsValidKvsNvm3Key(nvm3Key) == true); - return CHIP_NO_ERROR; - } - - if (isSlotNeeded && (firstEmptyKeySlot == kMaxEntries) && (mKvsStoredKeyString[keyIndex][0] == 0)) - { - firstEmptyKeySlot = keyIndex; - } - } - - if (isSlotNeeded) - { - if (firstEmptyKeySlot != kMaxEntries) - { - nvm3Key = CONVERT_KEYMAP_INDEX_TO_NVM3KEY(firstEmptyKeySlot); - VerifyOrDie(IsValidKvsNvm3Key(nvm3Key) == true); - err = CHIP_NO_ERROR; - } - else - { - err = CHIP_ERROR_PERSISTED_STORAGE_FAILED; - } - } - else - { - err = CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND; - } - return err; -} - -void KeyValueStoreManagerImpl::ForceKeyMapSave() -{ - OnScheduledKeyMapSave(nullptr, nullptr); -} - -void KeyValueStoreManagerImpl::OnScheduledKeyMapSave(System::Layer * systemLayer, void * appState) -{ - SilabsConfig::WriteConfigValueBin(SilabsConfig::kConfigKey_KvsStringKeyMap, - reinterpret_cast(mKvsStoredKeyString), sizeof(mKvsStoredKeyString)); -} - -void KeyValueStoreManagerImpl::ScheduleKeyMapSave(void) -{ - /* - During commissioning, the key map will be modified multiples times subsequently. - Commit the key map in nvm once it as stabilized. - */ - SystemLayer().StartTimer( - std::chrono::duration_cast(System::Clock::Seconds32(SILABS_KVS_SAVE_DELAY_SECONDS)), - KeyValueStoreManagerImpl::OnScheduledKeyMapSave, NULL); -} - -CHIP_ERROR KeyValueStoreManagerImpl::_Get(const char * key, void * value, size_t value_size, size_t * read_bytes_size, - size_t offset_bytes) const -{ - VerifyOrReturnError(key != nullptr, CHIP_ERROR_INVALID_ARGUMENT); - - uint32_t nvm3Key; - CHIP_ERROR err = MapKvsKeyToNvm3(key, nvm3Key); - VerifyOrReturnError(err == CHIP_NO_ERROR, err); - - size_t outLen; - err = SilabsConfig::ReadConfigValueBin(nvm3Key, reinterpret_cast(value), value_size, outLen, offset_bytes); - if (read_bytes_size) - { - *read_bytes_size = outLen; - } - - if (err == CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND) - { - return CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND; - } - - return err; -} - -CHIP_ERROR KeyValueStoreManagerImpl::_Put(const char * key, const void * value, size_t value_size) -{ - VerifyOrReturnError(key != nullptr, CHIP_ERROR_INVALID_ARGUMENT); - - uint32_t nvm3Key; - CHIP_ERROR err = MapKvsKeyToNvm3(key, nvm3Key, /* isSlotNeeded */ true); - VerifyOrReturnError(err == CHIP_NO_ERROR, err); - - err = SilabsConfig::WriteConfigValueBin(nvm3Key, reinterpret_cast(value), value_size); - if (err == CHIP_NO_ERROR) - { - uint32_t keyIndex = nvm3Key - SilabsConfig::kConfigKey_KvsFirstKeySlot; - Platform::CopyString(mKvsStoredKeyString[keyIndex], key); - ScheduleKeyMapSave(); - } - - return err; -} - -CHIP_ERROR KeyValueStoreManagerImpl::_Delete(const char * key) -{ - VerifyOrReturnError(key != nullptr, CHIP_ERROR_INVALID_ARGUMENT); - - uint32_t nvm3Key; - CHIP_ERROR err = MapKvsKeyToNvm3(key, nvm3Key); - VerifyOrReturnError(err == CHIP_NO_ERROR, err); - - err = SilabsConfig::ClearConfigValue(nvm3Key); - if (err == CHIP_NO_ERROR) - { - uint32_t keyIndex = CONVERT_NVM3KEY_TO_KEYMAP_INDEX(nvm3Key); - memset(mKvsStoredKeyString[keyIndex], 0, sizeof(mKvsStoredKeyString[keyIndex])); - ScheduleKeyMapSave(); - } - - return err; -} - -CHIP_ERROR KeyValueStoreManagerImpl::ErasePartition(void) -{ - // Iterate over all the Matter Kvs nvm3 records and delete each one... - CHIP_ERROR err = CHIP_NO_ERROR; - for (uint32_t nvm3Key = SilabsConfig::kMinConfigKey_MatterKvs; nvm3Key < SilabsConfig::kMaxConfigKey_MatterKvs; nvm3Key++) - { - err = SilabsConfig::ClearConfigValue(nvm3Key); - - if (err != CHIP_NO_ERROR) - { - break; - } - } - - memset(mKvsStoredKeyString, 0, sizeof(mKvsStoredKeyString)); - return err; -} - -} // namespace PersistedStorage -} // namespace DeviceLayer -} // namespace chip diff --git a/src/platform/silabs/efr32/BUILD.gn b/src/platform/silabs/efr32/BUILD.gn index f294a8d2d10846..f5f0108ed778e2 100644 --- a/src/platform/silabs/efr32/BUILD.gn +++ b/src/platform/silabs/efr32/BUILD.gn @@ -57,8 +57,10 @@ static_library("efr32") { "${silabs_platform_dir}/DiagnosticDataProviderImpl.cpp", "${silabs_platform_dir}/DiagnosticDataProviderImpl.h", "${silabs_platform_dir}/InetPlatformConfig.h", + "${silabs_platform_dir}/KeyValueStoreManagerImpl.cpp", "${silabs_platform_dir}/KeyValueStoreManagerImpl.h", "${silabs_platform_dir}/Logging.cpp", + "${silabs_platform_dir}/MigrationManager.cpp", "${silabs_platform_dir}/PlatformManagerImpl.h", "${silabs_platform_dir}/SilabsConfig.cpp", "${silabs_platform_dir}/SilabsConfig.h", @@ -66,8 +68,6 @@ static_library("efr32") { "../../FreeRTOS/SystemTimeSupport.cpp", "../../SingletonConfigurationManager.cpp", "ConfigurationManagerImpl.cpp", - "KeyValueStoreManagerImpl.cpp", - "MigrationManager.cpp", "PlatformManagerImpl.cpp", ] From 208635584788869e7324334a90fa8bd58fe45251 Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Wed, 8 Mar 2023 09:04:49 -0500 Subject: [PATCH 4/9] Switch to using WiFiVersionEnum instead of raw integers. (#25547) Fixes https://github.com/project-chip/connectedhomeip/issues/24948 --- .../wifi-network-diagnostics-server.cpp | 6 ++-- src/include/platform/DiagnosticDataProvider.h | 4 +-- .../Ameba/DiagnosticDataProviderImpl.cpp | 5 ++-- .../Ameba/DiagnosticDataProviderImpl.h | 2 +- .../Beken/DiagnosticDataProviderImpl.cpp | 5 ++-- .../Beken/DiagnosticDataProviderImpl.h | 2 +- .../ESP32/DiagnosticDataProviderImpl.cpp | 28 ++++++++++++------- .../ESP32/DiagnosticDataProviderImpl.h | 2 +- .../PSOC6/DiagnosticDataProviderImpl.cpp | 16 +++++------ .../PSOC6/DiagnosticDataProviderImpl.h | 2 +- .../Linux/ConnectivityManagerImpl.cpp | 4 +-- src/platform/Linux/ConnectivityManagerImpl.h | 2 +- .../Linux/DiagnosticDataProviderImpl.cpp | 2 +- .../Linux/DiagnosticDataProviderImpl.h | 2 +- .../BL602/DiagnosticDataProviderImpl.cpp | 6 ++-- .../BL602/DiagnosticDataProviderImpl.h | 2 +- .../DiagnosticDataProviderImplNrf.cpp | 2 +- .../DiagnosticDataProviderImplNrf.h | 2 +- src/platform/nrfconnect/wifi/WiFiManager.cpp | 14 +++++----- src/platform/nrfconnect/wifi/WiFiManager.h | 2 +- .../nxp/mw320/ConnectivityManagerImpl.cpp | 10 +++---- .../nxp/mw320/ConnectivityManagerImpl.h | 2 +- .../nxp/mw320/DiagnosticDataProviderImpl.cpp | 2 +- .../nxp/mw320/DiagnosticDataProviderImpl.h | 2 +- .../silabs/DiagnosticDataProviderImpl.cpp | 4 +-- .../silabs/DiagnosticDataProviderImpl.h | 2 +- .../webos/ConnectivityManagerImpl.cpp | 7 +++-- src/platform/webos/ConnectivityManagerImpl.h | 2 +- .../webos/DiagnosticDataProviderImpl.cpp | 2 +- .../webos/DiagnosticDataProviderImpl.h | 2 +- 30 files changed, 78 insertions(+), 67 deletions(-) diff --git a/src/app/clusters/wifi-network-diagnostics-server/wifi-network-diagnostics-server.cpp b/src/app/clusters/wifi-network-diagnostics-server/wifi-network-diagnostics-server.cpp index dc6e751b0d5f4b..d3e6a86fdd281d 100644 --- a/src/app/clusters/wifi-network-diagnostics-server/wifi-network-diagnostics-server.cpp +++ b/src/app/clusters/wifi-network-diagnostics-server/wifi-network-diagnostics-server.cpp @@ -119,12 +119,12 @@ CHIP_ERROR WiFiDiagosticsAttrAccess::ReadSecurityType(AttributeValueEncoder & aE CHIP_ERROR WiFiDiagosticsAttrAccess::ReadWiFiVersion(AttributeValueEncoder & aEncoder) { Attributes::WiFiVersion::TypeInfo::Type version; - uint8_t value = 0; + WiFiVersionEnum value = WiFiVersionEnum::kUnknownEnumValue; if (DeviceLayer::GetDiagnosticDataProvider().GetWiFiVersion(value) == CHIP_NO_ERROR) { - version.SetNonNull(static_cast(value)); - ChipLogProgress(Zcl, "The current 802.11 standard version in use by the Node: %d", value); + version.SetNonNull(value); + ChipLogProgress(Zcl, "The current 802.11 standard version in use by the Node: %d", to_underlying(value)); } else { diff --git a/src/include/platform/DiagnosticDataProvider.h b/src/include/platform/DiagnosticDataProvider.h index 27a92eeeeb339f..5098c5a167e8f4 100644 --- a/src/include/platform/DiagnosticDataProvider.h +++ b/src/include/platform/DiagnosticDataProvider.h @@ -158,7 +158,7 @@ class DiagnosticDataProvider */ virtual CHIP_ERROR GetWiFiBssId(ByteSpan & value); virtual CHIP_ERROR GetWiFiSecurityType(app::Clusters::WiFiNetworkDiagnostics::SecurityTypeEnum & securityType); - virtual CHIP_ERROR GetWiFiVersion(uint8_t & wiFiVersion); + virtual CHIP_ERROR GetWiFiVersion(app::Clusters::WiFiNetworkDiagnostics::WiFiVersionEnum & wiFiVersion); virtual CHIP_ERROR GetWiFiChannelNumber(uint16_t & channelNumber); virtual CHIP_ERROR GetWiFiRssi(int8_t & rssi); virtual CHIP_ERROR GetWiFiBeaconLostCount(uint32_t & beaconLostCount); @@ -339,7 +339,7 @@ DiagnosticDataProvider::GetWiFiSecurityType(app::Clusters::WiFiNetworkDiagnostic return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; } -inline CHIP_ERROR DiagnosticDataProvider::GetWiFiVersion(uint8_t & wiFiVersion) +inline CHIP_ERROR DiagnosticDataProvider::GetWiFiVersion(app::Clusters::WiFiNetworkDiagnostics::WiFiVersionEnum & wiFiVersion) { return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; } diff --git a/src/platform/Ameba/DiagnosticDataProviderImpl.cpp b/src/platform/Ameba/DiagnosticDataProviderImpl.cpp index 5a272040fac48a..c869aee8d09f2d 100644 --- a/src/platform/Ameba/DiagnosticDataProviderImpl.cpp +++ b/src/platform/Ameba/DiagnosticDataProviderImpl.cpp @@ -270,10 +270,11 @@ CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiBssId(ByteSpan & BssId) return CHIP_NO_ERROR; } -CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiVersion(uint8_t & wifiVersion) +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiVersion(app::Clusters::WiFiNetworkDiagnostics::WiFiVersionEnum & wifiVersion) { // Support 802.11a/n Wi-Fi in AmebaD chipset - wifiVersion = to_underlying(app::Clusters::WiFiNetworkDiagnostics::WiFiVersionEnum::kN); + // TODO: https://github.com/project-chip/connectedhomeip/issues/25542 + wifiVersion = app::Clusters::WiFiNetworkDiagnostics::WiFiVersionEnum::kN; return CHIP_NO_ERROR; } diff --git a/src/platform/Ameba/DiagnosticDataProviderImpl.h b/src/platform/Ameba/DiagnosticDataProviderImpl.h index 83484c1dfd5419..e4fedb659c9912 100644 --- a/src/platform/Ameba/DiagnosticDataProviderImpl.h +++ b/src/platform/Ameba/DiagnosticDataProviderImpl.h @@ -56,7 +56,7 @@ class DiagnosticDataProviderImpl : public DiagnosticDataProvider #if CHIP_DEVICE_CONFIG_ENABLE_WIFI CHIP_ERROR GetWiFiBssId(ByteSpan & BssId) override; CHIP_ERROR GetWiFiSecurityType(app::Clusters::WiFiNetworkDiagnostics::SecurityTypeEnum & securityType) override; - CHIP_ERROR GetWiFiVersion(uint8_t & wifiVersion) override; + CHIP_ERROR GetWiFiVersion(app::Clusters::WiFiNetworkDiagnostics::WiFiVersionEnum & wifiVersion) override; CHIP_ERROR GetWiFiChannelNumber(uint16_t & channelNumber) override; CHIP_ERROR GetWiFiRssi(int8_t & rssi) override; CHIP_ERROR GetWiFiBeaconLostCount(uint32_t & beaconLostCount) override; diff --git a/src/platform/Beken/DiagnosticDataProviderImpl.cpp b/src/platform/Beken/DiagnosticDataProviderImpl.cpp index f8cb5c584800e8..2c08da4cbcd081 100644 --- a/src/platform/Beken/DiagnosticDataProviderImpl.cpp +++ b/src/platform/Beken/DiagnosticDataProviderImpl.cpp @@ -170,10 +170,11 @@ CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiBssId(ByteSpan & BssId) return CHIP_NO_ERROR; } -CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiVersion(uint8_t & wifiVersion) +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiVersion(app::Clusters::WiFiNetworkDiagnostics::WiFiVersionEnum & wifiVersion) { // Support 802.11a/n Wi-Fi in Beken chipset - wiFiVersion = to_underlying(app::Clusters::WiFiNetworkDiagnostics::WiFiVersionEnum::kN); + // TODO: https://github.com/project-chip/connectedhomeip/issues/25543 + wiFiVersion = app::Clusters::WiFiNetworkDiagnostics::WiFiVersionEnum::kN; return CHIP_NO_ERROR; } diff --git a/src/platform/Beken/DiagnosticDataProviderImpl.h b/src/platform/Beken/DiagnosticDataProviderImpl.h index ecae313ea1643e..5e47df4e04a8f0 100644 --- a/src/platform/Beken/DiagnosticDataProviderImpl.h +++ b/src/platform/Beken/DiagnosticDataProviderImpl.h @@ -52,7 +52,7 @@ class DiagnosticDataProviderImpl : public DiagnosticDataProvider #if CHIP_DEVICE_CONFIG_ENABLE_WIFI CHIP_ERROR GetWiFiBssId(ByteSpan & BssId) override; CHIP_ERROR GetWiFiSecurityType(app::Clusters::WiFiNetworkDiagnostics::SecurityTypeEnum & securityType) override; - CHIP_ERROR GetWiFiVersion(uint8_t & wifiVersion) override; + CHIP_ERROR GetWiFiVersion(app::Clusters::WiFiNetworkDiagnostics::WiFiVersionEnum & wifiVersion) override; CHIP_ERROR GetWiFiChannelNumber(uint16_t & channelNumber) override; CHIP_ERROR GetWiFiRssi(int8_t & rssi) override; CHIP_ERROR GetWiFiBeaconLostCount(uint32_t & beaconLostCount) override; diff --git a/src/platform/ESP32/DiagnosticDataProviderImpl.cpp b/src/platform/ESP32/DiagnosticDataProviderImpl.cpp index 4ac4bebca424ec..f811170d335894 100644 --- a/src/platform/ESP32/DiagnosticDataProviderImpl.cpp +++ b/src/platform/ESP32/DiagnosticDataProviderImpl.cpp @@ -82,16 +82,19 @@ app::Clusters::WiFiNetworkDiagnostics::SecurityTypeEnum MapAuthModeToSecurityTyp } } -uint8_t GetWiFiVersionFromAPRecord(wifi_ap_record_t ap_info) +app::Clusters::WiFiNetworkDiagnostics::WiFiVersionEnum GetWiFiVersionFromAPRecord(wifi_ap_record_t ap_info) { + using app::Clusters::WiFiNetworkDiagnostics::WiFiVersionEnum; if (ap_info.phy_11n) - return 3; + return WiFiVersionEnum::kN; else if (ap_info.phy_11g) - return 2; + return WiFiVersionEnum::kG; else if (ap_info.phy_11b) - return 1; + return WiFiVersionEnum::kB; else - return 0; + // TODO: This is keeping the old behavior, it doesn't look right. + // https://github.com/project-chip/connectedhomeip/issues/25544 + return WiFiVersionEnum::kA; } #endif // CHIP_DEVICE_CONFIG_ENABLE_WIFI @@ -305,17 +308,18 @@ CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiSecurityType(app::Clusters::WiFiNe return CHIP_NO_ERROR; } -CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiVersion(uint8_t & wifiVersion) +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiVersion(app::Clusters::WiFiNetworkDiagnostics::WiFiVersionEnum & wifiVersion) { - wifiVersion = 0; wifi_ap_record_t ap_info; esp_err_t err; err = esp_wifi_sta_get_ap_info(&ap_info); if (err == ESP_OK) { wifiVersion = GetWiFiVersionFromAPRecord(ap_info); + return CHIP_NO_ERROR; } - return CHIP_NO_ERROR; + + return ESP32Utils::MapError(err); } CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiChannelNumber(uint16_t & channelNumber) @@ -328,8 +332,10 @@ CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiChannelNumber(uint16_t & channelNu if (err == ESP_OK) { channelNumber = ap_info.primary; + return CHIP_NO_ERROR; } - return CHIP_NO_ERROR; + + return ESP32Utils::MapError(err); } CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiRssi(int8_t & rssi) @@ -343,8 +349,10 @@ CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiRssi(int8_t & rssi) if (err == ESP_OK) { rssi = ap_info.rssi; + return CHIP_NO_ERROR; } - return CHIP_NO_ERROR; + + return ESP32Utils::MapError(err); } CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiBeaconLostCount(uint32_t & beaconLostCount) diff --git a/src/platform/ESP32/DiagnosticDataProviderImpl.h b/src/platform/ESP32/DiagnosticDataProviderImpl.h index ff8f252a6844f1..d272386ad3ffe5 100644 --- a/src/platform/ESP32/DiagnosticDataProviderImpl.h +++ b/src/platform/ESP32/DiagnosticDataProviderImpl.h @@ -54,7 +54,7 @@ class DiagnosticDataProviderImpl : public DiagnosticDataProvider #if CHIP_DEVICE_CONFIG_ENABLE_WIFI CHIP_ERROR GetWiFiBssId(ByteSpan & BssId) override; CHIP_ERROR GetWiFiSecurityType(app::Clusters::WiFiNetworkDiagnostics::SecurityTypeEnum & securityType) override; - CHIP_ERROR GetWiFiVersion(uint8_t & wifiVersion) override; + CHIP_ERROR GetWiFiVersion(app::Clusters::WiFiNetworkDiagnostics::WiFiVersionEnum & wifiVersion) override; CHIP_ERROR GetWiFiChannelNumber(uint16_t & channelNumber) override; CHIP_ERROR GetWiFiRssi(int8_t & rssi) override; CHIP_ERROR GetWiFiBeaconLostCount(uint32_t & beaconLostCount) override; diff --git a/src/platform/Infineon/PSOC6/DiagnosticDataProviderImpl.cpp b/src/platform/Infineon/PSOC6/DiagnosticDataProviderImpl.cpp index 19bb5154ceed3c..076238a2f52899 100644 --- a/src/platform/Infineon/PSOC6/DiagnosticDataProviderImpl.cpp +++ b/src/platform/Infineon/PSOC6/DiagnosticDataProviderImpl.cpp @@ -245,9 +245,10 @@ CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiSecurityType(app::Clusters::WiFiNe return err; } -CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiVersion(uint8_t & wiFiVersion) +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiVersion(app::Clusters::WiFiNetworkDiagnostics::WiFiVersionEnum & wiFiVersion) { - CHIP_ERROR err = CHIP_NO_ERROR; + using app::Clusters::WiFiNetworkDiagnostics::WiFiVersionEnum; + wl_bss_info_t bss_info; whd_security_t security; cy_rslt_t result = CY_RSLT_SUCCESS; @@ -256,27 +257,26 @@ CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiVersion(uint8_t & wiFiVersion) if (result != CY_RSLT_SUCCESS) { ChipLogError(DeviceLayer, "whd_wifi_get_ap_info failed: %d", (int) result); - SuccessOrExit(CHIP_ERROR_INTERNAL); + return CHIP_ERROR_INTERNAL; } /* VHT Capable */ if (bss_info.vht_cap) { - wiFiVersion = to_underlying(app::Clusters::WiFiNetworkDiagnostics::WiFiVersionEnum::kAc); + wiFiVersion = WiFiVersionEnum::kAc; } /* HT Capable */ else if (bss_info.n_cap) { - wiFiVersion = to_underlying(app::Clusters::WiFiNetworkDiagnostics::WiFiVersionEnum::kN); + wiFiVersion = WiFiVersionEnum::kN; } /* 11g Capable */ else { - wiFiVersion = to_underlying(app::Clusters::WiFiNetworkDiagnostics::WiFiVersionEnum::kG); + wiFiVersion = WiFiVersionEnum::kG; } -exit: - return err; + return CHIP_NO_ERROR; } CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiChannelNumber(uint16_t & channelNumber) diff --git a/src/platform/Infineon/PSOC6/DiagnosticDataProviderImpl.h b/src/platform/Infineon/PSOC6/DiagnosticDataProviderImpl.h index 80470d7996c22b..49756749c398da 100644 --- a/src/platform/Infineon/PSOC6/DiagnosticDataProviderImpl.h +++ b/src/platform/Infineon/PSOC6/DiagnosticDataProviderImpl.h @@ -77,7 +77,7 @@ class DiagnosticDataProviderImpl : public DiagnosticDataProvider CHIP_ERROR GetWiFiBssId(ByteSpan & BssId) override; CHIP_ERROR GetWiFiSecurityType(app::Clusters::WiFiNetworkDiagnostics::SecurityTypeEnum & securityType) override; - CHIP_ERROR GetWiFiVersion(uint8_t & wifiVersion) override; + CHIP_ERROR GetWiFiVersion(app::Clusters::WiFiNetworkDiagnostics::WiFiVersionEnum & wifiVersion) override; CHIP_ERROR GetWiFiChannelNumber(uint16_t & channelNumber) override; CHIP_ERROR GetWiFiRssi(int8_t & rssi) override; CHIP_ERROR GetWiFiBeaconRxCount(uint32_t & beaconRxCount) override; diff --git a/src/platform/Linux/ConnectivityManagerImpl.cpp b/src/platform/Linux/ConnectivityManagerImpl.cpp index f3d3d2b138bd54..c04adfaf105780 100644 --- a/src/platform/Linux/ConnectivityManagerImpl.cpp +++ b/src/platform/Linux/ConnectivityManagerImpl.cpp @@ -1239,10 +1239,10 @@ CHIP_ERROR ConnectivityManagerImpl::GetWiFiSecurityType(SecurityTypeEnum & secur return CHIP_NO_ERROR; } -CHIP_ERROR ConnectivityManagerImpl::GetWiFiVersion(uint8_t & wiFiVersion) +CHIP_ERROR ConnectivityManagerImpl::GetWiFiVersion(WiFiVersionEnum & wiFiVersion) { // We don't have direct API to get the WiFi version yet, return 802.11n on Linux simulation. - wiFiVersion = to_underlying(WiFiVersionEnum::kN); + wiFiVersion = WiFiVersionEnum::kN; return CHIP_NO_ERROR; } diff --git a/src/platform/Linux/ConnectivityManagerImpl.h b/src/platform/Linux/ConnectivityManagerImpl.h index 1ddb171d405a3c..e3fac9628a2238 100644 --- a/src/platform/Linux/ConnectivityManagerImpl.h +++ b/src/platform/Linux/ConnectivityManagerImpl.h @@ -137,7 +137,7 @@ class ConnectivityManagerImpl final : public ConnectivityManager, int32_t GetDisconnectReason(); CHIP_ERROR GetWiFiBssId(ByteSpan & value); CHIP_ERROR GetWiFiSecurityType(app::Clusters::WiFiNetworkDiagnostics::SecurityTypeEnum & securityType); - CHIP_ERROR GetWiFiVersion(uint8_t & wiFiVersion); + CHIP_ERROR GetWiFiVersion(app::Clusters::WiFiNetworkDiagnostics::WiFiVersionEnum & wiFiVersion); CHIP_ERROR GetConfiguredNetwork(NetworkCommissioning::Network & network); CHIP_ERROR StartWiFiScan(ByteSpan ssid, NetworkCommissioning::WiFiDriver::ScanCallback * callback); #endif diff --git a/src/platform/Linux/DiagnosticDataProviderImpl.cpp b/src/platform/Linux/DiagnosticDataProviderImpl.cpp index 2444b359cd83e3..08a42a599da0f2 100644 --- a/src/platform/Linux/DiagnosticDataProviderImpl.cpp +++ b/src/platform/Linux/DiagnosticDataProviderImpl.cpp @@ -813,7 +813,7 @@ CHIP_ERROR DiagnosticDataProviderImpl::ResetWiFiNetworkDiagnosticsCounts() #endif // CHIP_DEVICE_CONFIG_ENABLE_WIFI #if CHIP_DEVICE_CONFIG_ENABLE_WPA -CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiVersion(uint8_t & wiFiVersion) +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiVersion(app::Clusters::WiFiNetworkDiagnostics::WiFiVersionEnum & wiFiVersion) { return ConnectivityMgrImpl().GetWiFiVersion(wiFiVersion); } diff --git a/src/platform/Linux/DiagnosticDataProviderImpl.h b/src/platform/Linux/DiagnosticDataProviderImpl.h index 7dab9dafa68d84..f1320595624335 100644 --- a/src/platform/Linux/DiagnosticDataProviderImpl.h +++ b/src/platform/Linux/DiagnosticDataProviderImpl.h @@ -83,7 +83,7 @@ class DiagnosticDataProviderImpl : public DiagnosticDataProvider #endif #if CHIP_DEVICE_CONFIG_ENABLE_WPA - CHIP_ERROR GetWiFiVersion(uint8_t & wiFiVersion) override; + CHIP_ERROR GetWiFiVersion(app::Clusters::WiFiNetworkDiagnostics::WiFiVersionEnum & wiFiVersion) override; CHIP_ERROR GetWiFiBssId(ByteSpan & value) override; CHIP_ERROR GetWiFiSecurityType(app::Clusters::WiFiNetworkDiagnostics::SecurityTypeEnum & securityType) override; #endif diff --git a/src/platform/bouffalolab/BL602/DiagnosticDataProviderImpl.cpp b/src/platform/bouffalolab/BL602/DiagnosticDataProviderImpl.cpp index 9b40585f108c4c..7c1d8fe9c28ff6 100644 --- a/src/platform/bouffalolab/BL602/DiagnosticDataProviderImpl.cpp +++ b/src/platform/bouffalolab/BL602/DiagnosticDataProviderImpl.cpp @@ -257,9 +257,11 @@ CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiSecurityType(app::Clusters::WiFiNe return CHIP_NO_ERROR; } -CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiVersion(uint8_t & wifiVersion) +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiVersion(app::Clusters::WiFiNetworkDiagnostics::WiFiVersionEnum & wifiVersion) { - wifiVersion = 0; + // TODO: Keeping existing behavior, but this looks broken. + // https://github.com/project-chip/connectedhomeip/issues/25546 + wifiVersion = app::Clusters::WiFiNetworkDiagnostics::WiFiVersionEnum::kA; return CHIP_NO_ERROR; } diff --git a/src/platform/bouffalolab/BL602/DiagnosticDataProviderImpl.h b/src/platform/bouffalolab/BL602/DiagnosticDataProviderImpl.h index 357e3dbb9a3ef4..47aabacb85b9ff 100644 --- a/src/platform/bouffalolab/BL602/DiagnosticDataProviderImpl.h +++ b/src/platform/bouffalolab/BL602/DiagnosticDataProviderImpl.h @@ -52,7 +52,7 @@ class DiagnosticDataProviderImpl : public DiagnosticDataProvider void ReleaseNetworkInterfaces(NetworkInterface * netifp) override; CHIP_ERROR GetWiFiBssId(ByteSpan & BssId) override; CHIP_ERROR GetWiFiSecurityType(app::Clusters::WiFiNetworkDiagnostics::SecurityTypeEnum & securityType) override; - CHIP_ERROR GetWiFiVersion(uint8_t & wifiVersion) override; + CHIP_ERROR GetWiFiVersion(app::Clusters::WiFiNetworkDiagnostics::WiFiVersionEnum & wifiVersion) override; CHIP_ERROR GetWiFiChannelNumber(uint16_t & channelNumber) override; CHIP_ERROR GetWiFiRssi(int8_t & rssi) override; CHIP_ERROR GetWiFiBeaconLostCount(uint32_t & beaconLostCount) override; diff --git a/src/platform/nrfconnect/DiagnosticDataProviderImplNrf.cpp b/src/platform/nrfconnect/DiagnosticDataProviderImplNrf.cpp index 8a058207581143..9190e451b680e4 100644 --- a/src/platform/nrfconnect/DiagnosticDataProviderImplNrf.cpp +++ b/src/platform/nrfconnect/DiagnosticDataProviderImplNrf.cpp @@ -61,7 +61,7 @@ DiagnosticDataProviderImplNrf::GetWiFiSecurityType(app::Clusters::WiFiNetworkDia return err; } -CHIP_ERROR DiagnosticDataProviderImplNrf::GetWiFiVersion(uint8_t & wiFiVersion) +CHIP_ERROR DiagnosticDataProviderImplNrf::GetWiFiVersion(app::Clusters::WiFiNetworkDiagnostics::WiFiVersionEnum & wiFiVersion) { WiFiManager::WiFiInfo info; CHIP_ERROR err = WiFiManager::Instance().GetWiFiInfo(info); diff --git a/src/platform/nrfconnect/DiagnosticDataProviderImplNrf.h b/src/platform/nrfconnect/DiagnosticDataProviderImplNrf.h index 1f6307726fc0ba..b3bc549c4aa0bb 100644 --- a/src/platform/nrfconnect/DiagnosticDataProviderImplNrf.h +++ b/src/platform/nrfconnect/DiagnosticDataProviderImplNrf.h @@ -34,7 +34,7 @@ class DiagnosticDataProviderImplNrf : public DiagnosticDataProviderImpl #ifdef CONFIG_WIFI_NRF700X CHIP_ERROR GetWiFiBssId(ByteSpan & value) override; CHIP_ERROR GetWiFiSecurityType(app::Clusters::WiFiNetworkDiagnostics::SecurityTypeEnum & securityType) override; - CHIP_ERROR GetWiFiVersion(uint8_t & wiFiVersion) override; + CHIP_ERROR GetWiFiVersion(app::Clusters::WiFiNetworkDiagnostics::WiFiVersionEnum & wiFiVersion) override; CHIP_ERROR GetWiFiChannelNumber(uint16_t & channelNumber) override; CHIP_ERROR GetWiFiRssi(int8_t & rssi) override; CHIP_ERROR GetWiFiBeaconLostCount(uint32_t & beaconLostCount) override; diff --git a/src/platform/nrfconnect/wifi/WiFiManager.cpp b/src/platform/nrfconnect/wifi/WiFiManager.cpp index 272dca72b20bb9..f8a8f63fdd166f 100644 --- a/src/platform/nrfconnect/wifi/WiFiManager.cpp +++ b/src/platform/nrfconnect/wifi/WiFiManager.cpp @@ -75,30 +75,30 @@ NetworkCommissioning::WiFiScanResponse ToScanResponse(const wifi_scan_result * r // Matter expectations towards Wi-Fi version codes are unaligned with // what wpa_supplicant provides. This function maps supplicant codes -// to the ones defined in the Matter spec (11.14.3.2. WiFiVersion enum) -uint8_t MapToMatterWiFiVersionCode(wifi_link_mode wifiVersion) +// to the ones defined in the Matter spec (11.14.5.2. WiFiVersionEnum) +app::Clusters::WiFiNetworkDiagnostics::WiFiVersionEnum MapToMatterWiFiVersionCode(wifi_link_mode wifiVersion) { using app::Clusters::WiFiNetworkDiagnostics::WiFiVersionEnum; if (wifiVersion < WIFI_1 || wifiVersion > WIFI_6E) { ChipLogError(DeviceLayer, "Unsupported Wi-Fi version detected"); - return static_cast(WiFiVersionEnum::kA); // let's return 'a' by default + return WiFiVersionEnum::kA; // let's return 'a' by default } switch (wifiVersion) { case WIFI_1: - return static_cast(WiFiVersionEnum::kB); + return WiFiVersionEnum::kB; case WIFI_2: - return static_cast(WiFiVersionEnum::kA); + return WiFiVersionEnum::kA; case WIFI_6E: - return static_cast(WiFiVersionEnum::kAx); // treat as 802.11ax + return WiFiVersionEnum::kAx; // treat as 802.11ax default: break; } - return (static_cast(wifiVersion) - 1); + return static_cast(wifiVersion - 1); } // Matter expectations towards Wi-Fi security type codes are unaligned with diff --git a/src/platform/nrfconnect/wifi/WiFiManager.h b/src/platform/nrfconnect/wifi/WiFiManager.h index beed57575f3283..2e1b86e94b0a8e 100644 --- a/src/platform/nrfconnect/wifi/WiFiManager.h +++ b/src/platform/nrfconnect/wifi/WiFiManager.h @@ -129,7 +129,7 @@ class WiFiManager { ByteSpan mBssId{}; app::Clusters::WiFiNetworkDiagnostics::SecurityTypeEnum mSecurityType{}; - uint8_t mWiFiVersion{}; + app::Clusters::WiFiNetworkDiagnostics::WiFiVersionEnum mWiFiVersion{}; uint16_t mChannel{}; int8_t mRssi{}; uint8_t mSsid[DeviceLayer::Internal::kMaxWiFiSSIDLength]; diff --git a/src/platform/nxp/mw320/ConnectivityManagerImpl.cpp b/src/platform/nxp/mw320/ConnectivityManagerImpl.cpp index c5aa4adf1f9b69..bb8d3a39a7fa0c 100644 --- a/src/platform/nxp/mw320/ConnectivityManagerImpl.cpp +++ b/src/platform/nxp/mw320/ConnectivityManagerImpl.cpp @@ -209,10 +209,8 @@ CHIP_ERROR ConnectivityManagerImpl::GetWiFiBssId(ByteSpan & value) return CHIP_NO_ERROR; } -CHIP_ERROR ConnectivityManagerImpl::GetWiFiSecurityType(app::Clusters::WiFiNetworkDiagnostics::SecurityTypeEnum & securityType) +CHIP_ERROR ConnectivityManagerImpl::GetWiFiSecurityType(SecurityTypeEnum & securityType) { - using app::Clusters::WiFiNetworkDiagnostics::SecurityTypeEnum; - int ret = wlan_get_current_network(&sta_network); if (ret != WM_SUCCESS) { @@ -244,10 +242,10 @@ CHIP_ERROR ConnectivityManagerImpl::GetWiFiSecurityType(app::Clusters::WiFiNetwo return CHIP_NO_ERROR; } -CHIP_ERROR ConnectivityManagerImpl::GetWiFiVersion(uint8_t & wiFiVersion) +CHIP_ERROR ConnectivityManagerImpl::GetWiFiVersion(WiFiVersionEnum & wiFiVersion) { - wiFiVersion = to_underlying(WiFiVersionEnum::kN); - ChipLogProgress(DeviceLayer, "GetWiFiVersion: %u", wiFiVersion); + wiFiVersion = WiFiVersionEnum::kN; + ChipLogProgress(DeviceLayer, "GetWiFiVersion: %u", to_underlying(wiFiVersion)); return CHIP_NO_ERROR; } diff --git a/src/platform/nxp/mw320/ConnectivityManagerImpl.h b/src/platform/nxp/mw320/ConnectivityManagerImpl.h index 83360590706920..23677c82afd8de 100644 --- a/src/platform/nxp/mw320/ConnectivityManagerImpl.h +++ b/src/platform/nxp/mw320/ConnectivityManagerImpl.h @@ -86,7 +86,7 @@ class ConnectivityManagerImpl final : public ConnectivityManager, void StartWiFiManagement(); CHIP_ERROR GetWiFiBssId(ByteSpan & value); CHIP_ERROR GetWiFiSecurityType(app::Clusters::WiFiNetworkDiagnostics::SecurityTypeEnum & securityType); - CHIP_ERROR GetWiFiVersion(uint8_t & wiFiVersion); + CHIP_ERROR GetWiFiVersion(app::Clusters::WiFiNetworkDiagnostics::WiFiVersionEnum & wiFiVersion); #endif CHIP_ERROR GetConfiguredNetwork(NetworkCommissioning::Network & network); CHIP_ERROR StartWiFiScan(ByteSpan ssid, NetworkCommissioning::WiFiDriver::ScanCallback * callback); diff --git a/src/platform/nxp/mw320/DiagnosticDataProviderImpl.cpp b/src/platform/nxp/mw320/DiagnosticDataProviderImpl.cpp index 4c6e7df903c8d6..07fff9135836a6 100644 --- a/src/platform/nxp/mw320/DiagnosticDataProviderImpl.cpp +++ b/src/platform/nxp/mw320/DiagnosticDataProviderImpl.cpp @@ -289,7 +289,7 @@ CHIP_ERROR DiagnosticDataProviderImpl::ResetWiFiNetworkDiagnosticsCounts() return CHIP_NO_ERROR; } -CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiVersion(uint8_t & wiFiVersion) +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiVersion(app::Clusters::WiFiNetworkDiagnostics::WiFiVersionEnum & wiFiVersion) { return ConnectivityMgrImpl().GetWiFiVersion(wiFiVersion); } diff --git a/src/platform/nxp/mw320/DiagnosticDataProviderImpl.h b/src/platform/nxp/mw320/DiagnosticDataProviderImpl.h index 1314aaa5a64883..72501a4d944de5 100644 --- a/src/platform/nxp/mw320/DiagnosticDataProviderImpl.h +++ b/src/platform/nxp/mw320/DiagnosticDataProviderImpl.h @@ -69,7 +69,7 @@ class DiagnosticDataProviderImpl : public DiagnosticDataProvider CHIP_ERROR GetWiFiOverrunCount(uint64_t & overrunCount) override; CHIP_ERROR ResetWiFiNetworkDiagnosticsCounts() override; - CHIP_ERROR GetWiFiVersion(uint8_t & wiFiVersion) override; + CHIP_ERROR GetWiFiVersion(app::Clusters::WiFiNetworkDiagnostics::WiFiVersionEnum & wiFiVersion) override; CHIP_ERROR GetWiFiBssId(ByteSpan & value) override; CHIP_ERROR GetWiFiSecurityType(app::Clusters::WiFiNetworkDiagnostics::SecurityTypeEnum & securityType) override; }; diff --git a/src/platform/silabs/DiagnosticDataProviderImpl.cpp b/src/platform/silabs/DiagnosticDataProviderImpl.cpp index 64451504c038f2..9662668c39c16d 100644 --- a/src/platform/silabs/DiagnosticDataProviderImpl.cpp +++ b/src/platform/silabs/DiagnosticDataProviderImpl.cpp @@ -376,9 +376,9 @@ CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiSecurityType(app::Clusters::WiFiNe return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; } -CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiVersion(uint8_t & wifiVersion) +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiVersion(app::Clusters::WiFiNetworkDiagnostics::WiFiVersionEnum & wifiVersion) { - wifiVersion = to_underlying(app::Clusters::WiFiNetworkDiagnostics::WiFiVersionEnum::kN); + wifiVersion = app::Clusters::WiFiNetworkDiagnostics::WiFiVersionEnum::kN; return CHIP_NO_ERROR; } diff --git a/src/platform/silabs/DiagnosticDataProviderImpl.h b/src/platform/silabs/DiagnosticDataProviderImpl.h index bbaa8bff7dd26d..7d62cc8f84adc4 100644 --- a/src/platform/silabs/DiagnosticDataProviderImpl.h +++ b/src/platform/silabs/DiagnosticDataProviderImpl.h @@ -59,7 +59,7 @@ class DiagnosticDataProviderImpl : public DiagnosticDataProvider #if SL_WIFI CHIP_ERROR GetWiFiBssId(ByteSpan & BssId) override; CHIP_ERROR GetWiFiSecurityType(app::Clusters::WiFiNetworkDiagnostics::SecurityTypeEnum & securityType) override; - CHIP_ERROR GetWiFiVersion(uint8_t & wifiVersion) override; + CHIP_ERROR GetWiFiVersion(app::Clusters::WiFiNetworkDiagnostics::WiFiVersionEnum & wifiVersion) override; CHIP_ERROR GetWiFiChannelNumber(uint16_t & channelNumber) override; CHIP_ERROR GetWiFiRssi(int8_t & rssi) override; CHIP_ERROR GetWiFiBeaconLostCount(uint32_t & beaconLostCount) override; diff --git a/src/platform/webos/ConnectivityManagerImpl.cpp b/src/platform/webos/ConnectivityManagerImpl.cpp index 32870b75c180aa..6cbefb8751eeae 100644 --- a/src/platform/webos/ConnectivityManagerImpl.cpp +++ b/src/platform/webos/ConnectivityManagerImpl.cpp @@ -1150,7 +1150,7 @@ CHIP_ERROR ConnectivityManagerImpl::GetWiFiBssId(ByteSpan & value) return err; } -CHIP_ERROR ConnectivityManagerImpl::GetWiFiSecurityType(app::Clusters::WiFiNetworkDiagnostics::SecurityTypeEnum & securityType) +CHIP_ERROR ConnectivityManagerImpl::GetWiFiSecurityType(SecurityTypeEnum & securityType) { const gchar * mode = nullptr; @@ -1201,10 +1201,11 @@ CHIP_ERROR ConnectivityManagerImpl::GetWiFiSecurityType(app::Clusters::WiFiNetwo return CHIP_NO_ERROR; } -CHIP_ERROR ConnectivityManagerImpl::GetWiFiVersion(uint8_t & wiFiVersion) +CHIP_ERROR ConnectivityManagerImpl::GetWiFiVersion(WiFiVersionEnum & wiFiVersion) { // We don't have direct API to get the WiFi version yet, return 802.11n on Linux simulation. - wiFiVersion = to_underlying(WiFiVersionEnum::kN); + // TODO: This is not "Linux simulation". + wiFiVersion = WiFiVersionEnum::kN; return CHIP_NO_ERROR; } diff --git a/src/platform/webos/ConnectivityManagerImpl.h b/src/platform/webos/ConnectivityManagerImpl.h index 2d3b08c647282e..6d23f83d8683f0 100644 --- a/src/platform/webos/ConnectivityManagerImpl.h +++ b/src/platform/webos/ConnectivityManagerImpl.h @@ -137,7 +137,7 @@ class ConnectivityManagerImpl final : public ConnectivityManager, int32_t GetDisconnectReason(); CHIP_ERROR GetWiFiBssId(ByteSpan & value); CHIP_ERROR GetWiFiSecurityType(app::Clusters::WiFiNetworkDiagnostics::SecurityTypeEnum & securityType); - CHIP_ERROR GetWiFiVersion(uint8_t & wiFiVersion); + CHIP_ERROR GetWiFiVersion(app::Clusters::WiFiNetworkDiagnostics::WiFiVersionEnum & wiFiVersion); CHIP_ERROR GetConfiguredNetwork(NetworkCommissioning::Network & network); CHIP_ERROR StartWiFiScan(ByteSpan ssid, NetworkCommissioning::WiFiDriver::ScanCallback * callback); #endif diff --git a/src/platform/webos/DiagnosticDataProviderImpl.cpp b/src/platform/webos/DiagnosticDataProviderImpl.cpp index 22790a4705849c..dc4e534f40e18c 100644 --- a/src/platform/webos/DiagnosticDataProviderImpl.cpp +++ b/src/platform/webos/DiagnosticDataProviderImpl.cpp @@ -782,7 +782,7 @@ CHIP_ERROR DiagnosticDataProviderImpl::ResetWiFiNetworkDiagnosticsCounts() #endif // CHIP_DEVICE_CONFIG_ENABLE_WIFI #if CHIP_DEVICE_CONFIG_ENABLE_WPA -CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiVersion(uint8_t & wiFiVersion) +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiVersion(app::Clusters::WiFiNetworkDiagnostics::WiFiVersionEnum & wiFiVersion) { return ConnectivityMgrImpl().GetWiFiVersion(wiFiVersion); } diff --git a/src/platform/webos/DiagnosticDataProviderImpl.h b/src/platform/webos/DiagnosticDataProviderImpl.h index ba933b8743dfbf..87a7eb6f9c1982 100644 --- a/src/platform/webos/DiagnosticDataProviderImpl.h +++ b/src/platform/webos/DiagnosticDataProviderImpl.h @@ -81,7 +81,7 @@ class DiagnosticDataProviderImpl : public DiagnosticDataProvider #endif #if CHIP_DEVICE_CONFIG_ENABLE_WPA - CHIP_ERROR GetWiFiVersion(uint8_t & wiFiVersion) override; + CHIP_ERROR GetWiFiVersion(app::Clusters::WiFiNetworkDiagnostics::WiFiVersionEnum & wiFiVersion) override; CHIP_ERROR GetWiFiBssId(ByteSpan & value) override; CHIP_ERROR GetWiFiSecurityType(app::Clusters::WiFiNetworkDiagnostics::SecurityTypeEnum & securityType) override; #endif From 8a126951deec6d3832f4108af59cb162aa68c72e Mon Sep 17 00:00:00 2001 From: Vivien Nicolas Date: Wed, 8 Mar 2023 16:24:00 +0100 Subject: [PATCH 5/9] Use assertChipStackLockedByCurrentThread when accessing statics in src/system/SystemStats.cpp (#25485) * Use assertChipStackLockedByCurrentThread when accessing statics in src/system/SystemStats.cpp * Update src/platform/Darwin/BleConnectionDelegateImpl.mm such that it does not creates a PacketBufferHandle from the ble work queue but from the chip work queue --- src/lib/core/tests/BUILD.gn | 1 + .../Darwin/BleConnectionDelegateImpl.mm | 29 ++++++++----------- src/setup_payload/tests/BUILD.gn | 1 + src/system/SystemStats.cpp | 9 ++++++ 4 files changed, 23 insertions(+), 17 deletions(-) diff --git a/src/lib/core/tests/BUILD.gn b/src/lib/core/tests/BUILD.gn index 295f7a337d09dd..ec83bc715411c1 100644 --- a/src/lib/core/tests/BUILD.gn +++ b/src/lib/core/tests/BUILD.gn @@ -37,6 +37,7 @@ chip_test_suite("tests") { public_deps = [ "${chip_root}/src/lib/core", "${chip_root}/src/lib/support:testing", + "${chip_root}/src/platform", "${nlunit_test_root}:nlunit-test", ] } diff --git a/src/platform/Darwin/BleConnectionDelegateImpl.mm b/src/platform/Darwin/BleConnectionDelegateImpl.mm index 67ab838c4af525..d69623006d84ab 100644 --- a/src/platform/Darwin/BleConnectionDelegateImpl.mm +++ b/src/platform/Darwin/BleConnectionDelegateImpl.mm @@ -376,24 +376,19 @@ - (void)peripheral:(CBPeripheral *)peripheral chip::Ble::ChipBleUUID charId; [BleConnection fillServiceWithCharacteristicUuids:characteristic svcId:&svcId charId:&charId]; - // build a inet buffer from the rxEv and send to blelayer. - __block chip::System::PacketBufferHandle msgBuf - = chip::System::PacketBufferHandle::NewWithData(characteristic.value.bytes, characteristic.value.length); - - if (!msgBuf.IsNull()) { - dispatch_async(_chipWorkQueue, ^{ - if (!_mBleLayer->HandleIndicationReceived((__bridge void *) peripheral, &svcId, &charId, std::move(msgBuf))) { - // since this error comes from device manager core - // we assume it would do the right thing, like closing the connection - ChipLogError(Ble, "Failed at handling incoming BLE data"); - } - }); - } else { - ChipLogError(Ble, "Failed at allocating buffer for incoming BLE data"); - dispatch_async(_chipWorkQueue, ^{ + dispatch_async(_chipWorkQueue, ^{ + // build a inet buffer from the rxEv and send to blelayer. + auto msgBuf = chip::System::PacketBufferHandle::NewWithData(characteristic.value.bytes, characteristic.value.length); + + if (msgBuf.IsNull()) { + ChipLogError(Ble, "Failed at allocating buffer for incoming BLE data"); _mBleLayer->HandleConnectionError((__bridge void *) peripheral, CHIP_ERROR_NO_MEMORY); - }); - } + } else if (!_mBleLayer->HandleIndicationReceived((__bridge void *) peripheral, &svcId, &charId, std::move(msgBuf))) { + // since this error comes from device manager core + // we assume it would do the right thing, like closing the connection + ChipLogError(Ble, "Failed at handling incoming BLE data"); + } + }); } else { ChipLogError( Ble, "BLE:Error receiving indication of Characteristics on the device: [%s]", [error.localizedDescription UTF8String]); diff --git a/src/setup_payload/tests/BUILD.gn b/src/setup_payload/tests/BUILD.gn index 2d76bb4cfa5680..1b39f08f0eca25 100644 --- a/src/setup_payload/tests/BUILD.gn +++ b/src/setup_payload/tests/BUILD.gn @@ -34,6 +34,7 @@ chip_test_suite("tests") { public_deps = [ "${chip_root}/src/lib/support:testing", + "${chip_root}/src/platform", "${chip_root}/src/setup_payload", "${nlunit_test_root}:nlunit-test", ] diff --git a/src/system/SystemStats.cpp b/src/system/SystemStats.cpp index bf3473fd62c924..244a2517b31c78 100644 --- a/src/system/SystemStats.cpp +++ b/src/system/SystemStats.cpp @@ -29,6 +29,7 @@ #include #include +#include #include @@ -59,21 +60,29 @@ count_t sHighWatermarks[kNumEntries]; const Label * GetStrings() { + assertChipStackLockedByCurrentThread(); + return sStatsStrings; } count_t * GetResourcesInUse() { + assertChipStackLockedByCurrentThread(); + return sResourcesInUse; } count_t * GetHighWatermarks() { + assertChipStackLockedByCurrentThread(); + return sHighWatermarks; } void UpdateSnapshot(Snapshot & aSnapshot) { + assertChipStackLockedByCurrentThread(); + memcpy(&aSnapshot.mResourcesInUse, &sResourcesInUse, sizeof(aSnapshot.mResourcesInUse)); memcpy(&aSnapshot.mHighWatermarks, &sHighWatermarks, sizeof(aSnapshot.mHighWatermarks)); From b78dadbe01dda67f02053fc49be8b4b1ea1433d8 Mon Sep 17 00:00:00 2001 From: Andrei Litvin Date: Wed, 8 Mar 2023 11:47:24 -0500 Subject: [PATCH 6/9] Add M5Stack specific builds for esp32 light (#25550) * Enable builds for m5stack for more apps as m5stack and devkitc are the same MCU except screen support -i.e. defaults should work * start adding some compile options for ESP32 display ... still made a TODO for actual integration * Enable m5stack in Kconfig * Things compile now * Restyle * Remove demo items * Add more config variables to get displays working * Cleanup unused widgets, add callbacks for the wifi one * Make wifi green * Cleanup device with display: no more virtual devices * Restyle * Remove unnedded log * Remove unused variable * Remove useless commment in QRCodeScreen.h * Remove one more useless coment * Update examples/lighting-app/esp32/main/Button.cpp Co-authored-by: Cliff Chung <116232729+cliffamzn@users.noreply.github.com> * Update examples/lighting-app/esp32/main/DeviceWithDisplay.cpp Co-authored-by: Cliff Chung <116232729+cliffamzn@users.noreply.github.com> * Update examples/lighting-app/esp32/main/Globals.cpp Co-authored-by: Cliff Chung <116232729+cliffamzn@users.noreply.github.com> * Update examples/lighting-app/esp32/main/StatusScreen.cpp Co-authored-by: Cliff Chung <116232729+cliffamzn@users.noreply.github.com> * Update copyright dates and remove a bunch of @file comments * Move ifdefs around * Remove useless button.h comments * Move ifdefs a bit - HAVE_DISPLAY is a result of a header --------- Co-authored-by: Andrei Litvin Co-authored-by: Cliff Chung <116232729+cliffamzn@users.noreply.github.com> --- examples/common/screen-framework/Display.cpp | 12 +- examples/lighting-app/esp32/CMakeLists.txt | 8 +- examples/lighting-app/esp32/main/AppTask.cpp | 62 ++++- examples/lighting-app/esp32/main/Button.cpp | 93 ++++++-- .../lighting-app/esp32/main/CMakeLists.txt | 6 +- .../esp32/main/DeviceCallbacks.cpp | 21 +- .../esp32/main/DeviceWithDisplay.cpp | 224 ++++++++++++++++++ .../esp32/main/DeviceWithDisplay.h | 52 ++++ examples/lighting-app/esp32/main/Globals.cpp | 21 ++ .../lighting-app/esp32/main/Kconfig.projbuild | 24 +- .../lighting-app/esp32/main/LEDWidget.cpp | 21 +- .../lighting-app/esp32/main/QRCodeScreen.cpp | 100 ++++++++ .../lighting-app/esp32/main/StatusScreen.cpp | 189 +++++++++++++++ .../lighting-app/esp32/main/WiFiWidget.cpp | 66 ++++++ .../esp32/main/include/AppEvent.h | 3 +- .../lighting-app/esp32/main/include/AppTask.h | 6 +- .../lighting-app/esp32/main/include/Button.h | 32 ++- .../esp32/main/include/DeviceCallbacks.h | 17 +- .../lighting-app/esp32/main/include/Globals.h | 23 ++ .../esp32/main/include/LEDWidget.h | 11 +- .../esp32/main/include/QRCodeScreen.h | 42 ++++ .../esp32/main/include/StatusScreen.h | 38 +++ .../esp32/main/include/WiFiWidget.h | 36 +++ examples/lighting-app/esp32/main/main.cpp | 6 +- .../esp32/sdkconfig_m5stack.defaults | 64 +++++ scripts/build/builders/esp32.py | 3 +- 26 files changed, 1099 insertions(+), 81 deletions(-) create mode 100644 examples/lighting-app/esp32/main/DeviceWithDisplay.cpp create mode 100644 examples/lighting-app/esp32/main/DeviceWithDisplay.h create mode 100644 examples/lighting-app/esp32/main/Globals.cpp create mode 100644 examples/lighting-app/esp32/main/QRCodeScreen.cpp create mode 100644 examples/lighting-app/esp32/main/StatusScreen.cpp create mode 100644 examples/lighting-app/esp32/main/WiFiWidget.cpp create mode 100644 examples/lighting-app/esp32/main/include/Globals.h create mode 100644 examples/lighting-app/esp32/main/include/QRCodeScreen.h create mode 100644 examples/lighting-app/esp32/main/include/StatusScreen.h create mode 100644 examples/lighting-app/esp32/main/include/WiFiWidget.h create mode 100644 examples/lighting-app/esp32/sdkconfig_m5stack.defaults diff --git a/examples/common/screen-framework/Display.cpp b/examples/common/screen-framework/Display.cpp index bd6e363b33c9ac..71e41f10aaa36e 100644 --- a/examples/common/screen-framework/Display.cpp +++ b/examples/common/screen-framework/Display.cpp @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2020-2023 Project CHIP Authors * Copyright (c) 2018 Nest Labs, Inc. * All rights reserved. * @@ -16,14 +16,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -/** - * @file Display.cpp - * - * This file implements helper APIs for the M5Stack's display - * - */ - #include #include "driver/ledc.h" @@ -54,7 +46,7 @@ // The M5Stack's backlight is on Channel 7 #define BACKLIGHT_CHANNEL LEDC_CHANNEL_7 -extern const char * TAG; +static const char * TAG = "Display"; uint16_t DisplayHeight = 0; uint16_t DisplayWidth = 0; diff --git a/examples/lighting-app/esp32/CMakeLists.txt b/examples/lighting-app/esp32/CMakeLists.txt index 92f2a10fec2f0b..3b61c69d0e05bd 100644 --- a/examples/lighting-app/esp32/CMakeLists.txt +++ b/examples/lighting-app/esp32/CMakeLists.txt @@ -1,5 +1,5 @@ # -# Copyright (c) 2021 Project CHIP Authors +# Copyright (c) 2021-2023 Project CHIP Authors # All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -29,6 +29,12 @@ set(EXTRA_COMPONENT_DIRS "${CMAKE_CURRENT_LIST_DIR}/third_party/connectedhomeip/examples/common/QRCode" ) +if(${IDF_TARGET} STREQUAL "esp32") + list(APPEND EXTRA_COMPONENT_DIRS "${CMAKE_CURRENT_LIST_DIR}/third_party/connectedhomeip/examples/common/m5stack-tft/repo/components/tft" + "${CMAKE_CURRENT_LIST_DIR}/third_party/connectedhomeip/examples/common/m5stack-tft/repo/components/spidriver" + "${CMAKE_CURRENT_LIST_DIR}/third_party/connectedhomeip/examples/common/screen-framework") +endif() + project(chip-lighting-app) # C++17 is required for RPC build. diff --git a/examples/lighting-app/esp32/main/AppTask.cpp b/examples/lighting-app/esp32/main/AppTask.cpp index 91f91340e37bca..6369cf91089670 100644 --- a/examples/lighting-app/esp32/main/AppTask.cpp +++ b/examples/lighting-app/esp32/main/AppTask.cpp @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2022 Project CHIP Authors + * Copyright (c) 2022-2023 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -20,6 +20,8 @@ #include "esp_log.h" #include "freertos/FreeRTOS.h" +#include "DeviceWithDisplay.h" + #include #define APP_TASK_NAME "APP" @@ -36,7 +38,6 @@ using namespace ::chip::DeviceLayer; static const char * TAG = "app-task"; LEDWidget AppLED; -Button AppButton; namespace { constexpr EndpointId kLightEndpointId = 1; @@ -61,14 +62,59 @@ CHIP_ERROR AppTask::StartAppTask() return (xReturned == pdPASS) ? CHIP_NO_ERROR : APP_ERROR_CREATE_TASK_FAILED; } +void AppTask::ButtonEventHandler(const uint8_t buttonHandle, uint8_t btnAction) +{ + if (btnAction != APP_BUTTON_PRESSED) + { + return; + } + + AppEvent button_event = {}; + button_event.Type = AppEvent::kEventType_Button; + +#if CONFIG_HAVE_DISPLAY + button_event.ButtonEvent.PinNo = buttonHandle; + button_event.ButtonEvent.Action = btnAction; + button_event.mHandler = ButtonPressedAction; +#else + button_event.mHandler = AppTask::LightingActionEventHandler; +#endif + + sAppTask.PostEvent(&button_event); +} + +#if CONFIG_DEVICE_TYPE_M5STACK +void AppTask::ButtonPressedAction(AppEvent * aEvent) +{ + uint32_t io_num = aEvent->ButtonEvent.PinNo; + int level = gpio_get_level((gpio_num_t) io_num); + if (level == 0) + { + bool woken = WakeDisplay(); + if (woken) + { + return; + } + // Button 1 is connected to the pin 39 + // Button 2 is connected to the pin 38 + // Button 3 is connected to the pin 37 + // So we use 40 - io_num to map the pin number to button number + ScreenManager::ButtonPressed(40 - io_num); + } +} +#endif + CHIP_ERROR AppTask::Init() { CHIP_ERROR err = CHIP_NO_ERROR; AppLED.Init(); - AppButton.Init(); - AppButton.SetButtonPressCallback(ButtonPressCallback); +#if CONFIG_HAVE_DISPLAY + InitDeviceDisplay(); + + AppLED.SetVLED(ScreenManager::AddVLED(TFT_YELLOW)); +#endif return err; } @@ -139,14 +185,6 @@ void AppTask::LightingActionEventHandler(AppEvent * aEvent) chip::DeviceLayer::PlatformMgr().UnlockChipStack(); } -void AppTask::ButtonPressCallback() -{ - AppEvent button_event; - button_event.Type = AppEvent::kEventType_Button; - button_event.mHandler = AppTask::LightingActionEventHandler; - sAppTask.PostEvent(&button_event); -} - void AppTask::UpdateClusterState() { ESP_LOGI(TAG, "Writing to OnOff cluster"); diff --git a/examples/lighting-app/esp32/main/Button.cpp b/examples/lighting-app/esp32/main/Button.cpp index aadae002bc2d08..ea4959ff6188cb 100644 --- a/examples/lighting-app/esp32/main/Button.cpp +++ b/examples/lighting-app/esp32/main/Button.cpp @@ -1,6 +1,7 @@ /* * - * Copyright (c) 2022 Project CHIP Authors + * Copyright (c) 2022-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. @@ -14,53 +15,95 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#include "driver/gpio.h" +#include "esp_check.h" +#include "esp_log.h" +#include "esp_system.h" +#include "AppTask.h" #include "Button.h" -#include "esp_attr.h" +#include "Globals.h" +#include "ScreenManager.h" +#include +#include +#include -#define GPIO_INPUT_IO_0 9 -#define GPIO_INPUT_PIN_SEL (1ULL << GPIO_INPUT_IO_0) -#define ESP_INTR_FLAG_DEFAULT 0 +static const char * TAG = "Button.cpp"; -static const char * TAG = "Button"; +extern Button gButtons[BUTTON_NUMBER]; -static Button::ButtonPressCallback button_press_handler = nullptr; +Button::Button() {} -static void IRAM_ATTR gpio_isr_handler(void * arg) +Button::Button(gpio_num_t gpioNum) { - if (button_press_handler != nullptr) + mGPIONum = gpioNum; +} + +int32_t Find_Button_Via_Pin(gpio_num_t gpioNum) +{ + for (int i = 0; i < BUTTON_NUMBER; i++) { - button_press_handler(); + if (gButtons[i].GetGPIONum() == gpioNum) + { + return i; + } } + return -1; } -void Button::Init() +void IRAM_ATTR button_isr_handler(void * arg) { - /* Initialize button interrupt*/ - // zero-initialize the config structure. + uint32_t gpio_num = (uint32_t) arg; + int32_t idx = Find_Button_Via_Pin((gpio_num_t) gpio_num); + if (idx == -1) + { + return; + } + BaseType_t taskWoken = pdFALSE; + xTimerStartFromISR(gButtons[idx].mbuttonTimer, + &taskWoken); // If the timer had already been started ,restart it will reset its expiry time +} + +esp_err_t Button::Init() +{ + return Init(mGPIONum); +} + +esp_err_t Button::Init(gpio_num_t gpioNum) +{ + esp_err_t ret = ESP_OK; + + mGPIONum = gpioNum; + // zero-initialize the config structure. gpio_config_t io_conf = {}; - // interrupt of rising edge + // interrupt of falling edge io_conf.intr_type = GPIO_INTR_NEGEDGE; // bit mask of the pins, use GPIO4/5 here - io_conf.pin_bit_mask = GPIO_INPUT_PIN_SEL; + io_conf.pin_bit_mask = 1ULL << gpioNum; // set as input mode io_conf.mode = GPIO_MODE_INPUT; // enable pull-up mode io_conf.pull_up_en = GPIO_PULLUP_ENABLE; + gpio_config(&io_conf); - // install gpio isr service - gpio_install_isr_service(ESP_INTR_FLAG_DEFAULT); // hook isr handler for specific gpio pin - gpio_isr_handler_add(static_cast(GPIO_INPUT_IO_0), gpio_isr_handler, (void *) GPIO_INPUT_IO_0); + ret = gpio_isr_handler_add(gpioNum, button_isr_handler, (void *) gpioNum); + ESP_RETURN_ON_ERROR(ret, TAG, "gpio_isr_handler_add failed: %s", esp_err_to_name(ret)); - ESP_LOGI(TAG, "Button initialized.."); -} + mbuttonTimer = xTimerCreate("BtnTmr", // Just a text name, not used by the RTOS kernel + pdMS_TO_TICKS(50), // timer period + false, // no timer reload (==one-shot) + (void *) (int) gpioNum, // init timer id = gpioNum index + TimerCallback // timer callback handler (all buttons use + // the same timer cn function) + ); -void Button::SetButtonPressCallback(ButtonPressCallback button_callback) + return ESP_OK; +} +void Button::TimerCallback(TimerHandle_t xTimer) { - if (button_callback != nullptr) - { - button_press_handler = button_callback; - } + // Get the button index of the expired timer and call button event Handler. + uint32_t gpio_num = (uint32_t) pvTimerGetTimerID(xTimer); + GetAppTask().ButtonEventHandler(gpio_num, APP_BUTTON_PRESSED); } diff --git a/examples/lighting-app/esp32/main/CMakeLists.txt b/examples/lighting-app/esp32/main/CMakeLists.txt index 450a47f7db3fee..fcedfb4774637e 100644 --- a/examples/lighting-app/esp32/main/CMakeLists.txt +++ b/examples/lighting-app/esp32/main/CMakeLists.txt @@ -1,5 +1,5 @@ # -# Copyright (c) 2021 Project CHIP Authors +# Copyright (c) 2021-2023 Project CHIP Authors # All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -85,6 +85,10 @@ set(SRC_DIRS_LIST "${SRC_DIRS_LIST}" ) endif (CONFIG_ENABLE_PW_RPC) +if ("${CONFIG_DEVICE_TYPE_M5STACK}" STREQUAL "y") + list(APPEND PRIV_REQUIRES_LIST tft screen-framework) +endif() + idf_component_register(PRIV_INCLUDE_DIRS ${PRIV_INCLUDE_DIRS_LIST} SRC_DIRS ${SRC_DIRS_LIST} PRIV_REQUIRES ${PRIV_REQUIRES_LIST}) diff --git a/examples/lighting-app/esp32/main/DeviceCallbacks.cpp b/examples/lighting-app/esp32/main/DeviceCallbacks.cpp index 46983fdf441cd4..dcaaa187186b9e 100644 --- a/examples/lighting-app/esp32/main/DeviceCallbacks.cpp +++ b/examples/lighting-app/esp32/main/DeviceCallbacks.cpp @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2021-2023 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,17 +15,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -/** - * @file DeviceCallbacks.cpp - * - * Implements all the callbacks to the application from the CHIP Stack - * - **/ - #include "AppTask.h" #include "DeviceCallbacks.h" +#include "Globals.h" #include "LEDWidget.h" #include @@ -147,3 +140,13 @@ void emberAfOnOffClusterInitCallback(EndpointId endpoint) ESP_LOGI(TAG, "emberAfOnOffClusterInitCallback"); GetAppTask().UpdateClusterState(); } + +void AppDeviceCallbacksDelegate::OnIPv4ConnectivityEstablished() +{ + wifiLED.Set(true); +} + +void AppDeviceCallbacksDelegate::OnIPv4ConnectivityLost() +{ + wifiLED.Set(false); +} diff --git a/examples/lighting-app/esp32/main/DeviceWithDisplay.cpp b/examples/lighting-app/esp32/main/DeviceWithDisplay.cpp new file mode 100644 index 00000000000000..bbca9845d0662d --- /dev/null +++ b/examples/lighting-app/esp32/main/DeviceWithDisplay.cpp @@ -0,0 +1,224 @@ +/* + * + * 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 "DeviceWithDisplay.h" + +#if CONFIG_HAVE_DISPLAY + +#include "Globals.h" +#include +#include +#include + +using namespace ::chip; +using namespace ::chip::Credentials; +using namespace ::chip::DeviceManager; +using namespace ::chip::DeviceLayer; + +static const char * TAG = "DeviceWithDisplay"; + +#if CONFIG_DEVICE_TYPE_M5STACK + +Button gButtons[BUTTON_NUMBER] = { Button(BUTTON_1_GPIO_NUM), Button(BUTTON_2_GPIO_NUM), Button(BUTTON_3_GPIO_NUM) }; + +class ActionListModel : public ListScreen::Model +{ + int GetItemCount() override { return static_cast(mActions.size()); } + std::string GetItemText(int i) override { return mActions[i].title.c_str(); } + void ItemAction(int i) override + { + ESP_LOGI(TAG, "generic action %d", i); + mActions[i].action(); + } + +protected: + void AddAction(const char * name, std::function action) { mActions.push_back(Action(name, action)); } + +private: + struct Action + { + std::string title; + std::function action; + + Action(const char * t, std::function a) : title(t), action(a) {} + }; + + std::vector mActions; +}; + +class MdnsDebugListModel : public ActionListModel +{ +public: + std::string GetTitle() override { return "mDNS Debug"; } + + MdnsDebugListModel() { AddAction("(Re-)Init", std::bind(&MdnsDebugListModel::DoReinit, this)); } + +private: + void DoReinit() + { + CHIP_ERROR err = Dnssd::ServiceAdvertiser::Instance().Init(DeviceLayer::UDPEndPointManager()); + if (err != CHIP_NO_ERROR) + { + ESP_LOGE(TAG, "Error initializing: %s", err.AsString()); + } + } +}; + +class TouchesMatterStackModel : public ListScreen::Model +{ + // We could override Action() and then hope focusIndex has not changed by + // the time our queued task runs, but it's cleaner to just capture its value + // now. + struct QueuedAction + { + QueuedAction(TouchesMatterStackModel * selfArg, int iArg) : self(selfArg), i(iArg) {} + TouchesMatterStackModel * self; + int i; + }; + + void ItemAction(int i) final + { + auto * action = chip::Platform::New(this, i); + chip::DeviceLayer::PlatformMgr().ScheduleWork(QueuedActionHandler, reinterpret_cast(action)); + } + + static void QueuedActionHandler(intptr_t closure) + { + auto * queuedAction = reinterpret_cast(closure); + queuedAction->self->DoAction(queuedAction->i); + chip::Platform::Delete(queuedAction); + } + + virtual void DoAction(int i) = 0; +}; + +class SetupListModel : public TouchesMatterStackModel +{ +public: + SetupListModel() + { + std::string resetWiFi = "Reset WiFi"; + std::string resetToFactory = "Reset to factory"; + std::string forceWiFiCommissioningBasic = "Force WiFi commissioning (basic)"; + options.emplace_back(resetWiFi); + options.emplace_back(resetToFactory); + options.emplace_back(forceWiFiCommissioningBasic); + } + virtual std::string GetTitle() { return "Setup"; } + virtual int GetItemCount() { return options.size(); } + virtual std::string GetItemText(int i) { return options.at(i); } + void DoAction(int i) override + { + ESP_LOGI(TAG, "Opening options %d: %s", i, GetItemText(i).c_str()); + if (i == 0) + { + ConnectivityMgr().ClearWiFiStationProvision(); + chip::Server::GetInstance().GetFabricTable().DeleteAllFabrics(); + chip::Server::GetInstance().GetCommissioningWindowManager().OpenBasicCommissioningWindow(); + } + else if (i == 1) + { + chip::Server::GetInstance().ScheduleFactoryReset(); + } + else if (i == 2) + { + chip::Server::GetInstance().GetFabricTable().DeleteAllFabrics(); + auto & commissionMgr = chip::Server::GetInstance().GetCommissioningWindowManager(); + commissionMgr.OpenBasicCommissioningWindow(commissionMgr.MaxCommissioningTimeout(), + CommissioningWindowAdvertisement::kDnssdOnly); + } + } + +private: + std::vector options; +}; + +esp_err_t InitM5Stack(std::string qrCodeText) +{ + esp_err_t err; + // Initialize the buttons. + err = gpio_install_isr_service(0); + ESP_RETURN_ON_ERROR(err, TAG, "Button preInit failed: %s", esp_err_to_name(err)); + for (int i = 0; i < BUTTON_NUMBER; ++i) + { + err = gButtons[i].Init(); + ESP_RETURN_ON_ERROR(err, TAG, "Button.Init() failed: %s", esp_err_to_name(err)); + } + // Push a rudimentary user interface. + ScreenManager::PushScreen(chip::Platform::New( + (chip::Platform::New()) + ->Title("CHIP") + ->Action([](int i) { ESP_LOGI(TAG, "action on item %d", i); }) + ->Item("mDNS Debug", + []() { + ESP_LOGI(TAG, "Opening MDNS debug"); + ScreenManager::PushScreen(chip::Platform::New(chip::Platform::New())); + }) + ->Item("QR Code", + [=]() { + ESP_LOGI(TAG, "Opening QR code screen"); + PrintOnboardingCodes(chip::RendezvousInformationFlags(CONFIG_RENDEZVOUS_MODE)); + ScreenManager::PushScreen(chip::Platform::New(qrCodeText)); + }) + ->Item("Setup", + [=]() { + ESP_LOGI(TAG, "Opening Setup list"); + ScreenManager::PushScreen(chip::Platform::New(chip::Platform::New())); + }) + ->Item("Status", [=]() { + ESP_LOGI(TAG, "Opening Status screen"); + ScreenManager::PushScreen(chip::Platform::New()); + }))); + return ESP_OK; +} +#endif + +void InitDeviceDisplay() +{ + // Create buffer for QR code that can fit max size and null terminator. + char qrCodeBuffer[chip::QRCodeBasicSetupPayloadGenerator::kMaxQRCodeBase38RepresentationLength + 1]; + chip::MutableCharSpan qrCodeText(qrCodeBuffer); + + // Get QR Code and emulate its content using NFC tag + GetQRCode(qrCodeText, chip::RendezvousInformationFlags(CONFIG_RENDEZVOUS_MODE)); + + // Initialize the display device. + esp_err_t err = InitDisplay(); + if (err != ESP_OK) + { + ESP_LOGE(TAG, "InitDisplay() failed: %s", esp_err_to_name(err)); + return; + } + + // Initialize the screen manager + ScreenManager::Init(); + wifiLED.SetVLED(ScreenManager::AddVLED(TFT_GREEN)); + +#if CONFIG_DEVICE_TYPE_M5STACK + + InitM5Stack(qrCodeText.data()); + +#elif CONFIG_DEVICE_TYPE_ESP32_WROVER_KIT + + // Display the QR Code + QRCodeScreen qrCodeScreen(qrCodeText.data()); + qrCodeScreen.Display(); + +#endif +} +#endif diff --git a/examples/lighting-app/esp32/main/DeviceWithDisplay.h b/examples/lighting-app/esp32/main/DeviceWithDisplay.h new file mode 100644 index 00000000000000..82feb8dbf841b6 --- /dev/null +++ b/examples/lighting-app/esp32/main/DeviceWithDisplay.h @@ -0,0 +1,52 @@ +/* + * + * 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 "Button.h" +#include "DeviceCallbacks.h" +#include "Display.h" +#include "ListScreen.h" +#include "QRCodeScreen.h" +#include "ScreenManager.h" +#include "StatusScreen.h" +#include "esp_check.h" +#include "esp_log.h" +#include "esp_system.h" +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include +#include + +#if CONFIG_HAVE_DISPLAY + +#include +#include +#include +#include + +#if CONFIG_DEVICE_TYPE_M5STACK +#define BUTTON_1_GPIO_NUM ((gpio_num_t) 39) // Left button on M5Stack +#define BUTTON_2_GPIO_NUM ((gpio_num_t) 38) // Middle button on M5Stack +#define BUTTON_3_GPIO_NUM ((gpio_num_t) 37) // Right button on M5Stack + +esp_err_t InitM5Stack(std::string qrCodeText); +#endif + +void InitDeviceDisplay(); +#endif diff --git a/examples/lighting-app/esp32/main/Globals.cpp b/examples/lighting-app/esp32/main/Globals.cpp new file mode 100644 index 00000000000000..4c0f82bf564efc --- /dev/null +++ b/examples/lighting-app/esp32/main/Globals.cpp @@ -0,0 +1,21 @@ +/* + * + * 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 "Globals.h" + +WiFiWidget wifiLED; diff --git a/examples/lighting-app/esp32/main/Kconfig.projbuild b/examples/lighting-app/esp32/main/Kconfig.projbuild index b41b4ef0e4fb81..5f3c88166c6dda 100644 --- a/examples/lighting-app/esp32/main/Kconfig.projbuild +++ b/examples/lighting-app/esp32/main/Kconfig.projbuild @@ -1,5 +1,5 @@ # -# Copyright (c) 2021 Project CHIP Authors +# Copyright (c) 2021-2023 Project CHIP Authors # All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -38,6 +38,9 @@ menu "Demo" config DEVICE_TYPE_ESP32_WROVER_KIT bool "ESP32-WROVER-KIT_V4.1" depends on IDF_TARGET_ESP32 + config DEVICE_TYPE_M5STACK + bool "M5Stack" + depends on IDF_TARGET_ESP32 config DEVICE_TYPE_ESP32_C3_DEVKITM bool "ESP32C3-DevKitM" depends on IDF_TARGET_ESP32C3 @@ -82,6 +85,7 @@ menu "Demo" default 26 if DEVICE_TYPE_ESP32_WROVER_KIT default 8 if DEVICE_TYPE_ESP32_C3_DEVKITM || DEVICE_TYPE_ESP32H2_DEVKITC || DEVICE_TYPE_ESP32_C2_DEVKITM default 48 if DEVICE_TYPE_ESP32_S3_DEVKITM + default 5 if DEVICE_TYPE_M5STACK default 5 help GPIO number (IOxx) to blink on and off or the RMT signal for the addressable LED. @@ -102,6 +106,17 @@ menu "Demo" bool "Ethernet" endchoice + # NOTE: This config is not displayed as a input in the Kconfig menu, as its value is + # entirely derived from the Device Type choice. However the CONFIG_EXAMPLE_DISPLAY_TYPE + # define that is produced is needed to configure the TFT library correctly. + config TFT_PREDEFINED_DISPLAY_TYPE + int + range 0 5 + default 0 if DEVICE_TYPE_ESP32_DEVKITC + default 0 if DEVICE_TYPE_ESP32_C3_DEVKITM || DEVICE_TYPE_ESP32_C2_DEVKITM + default 3 if DEVICE_TYPE_M5STACK + default 4 if DEVICE_TYPE_ESP32_WROVER_KIT + config RENDEZVOUS_MODE int range 0 8 @@ -110,6 +125,13 @@ menu "Demo" default 4 if RENDEZVOUS_MODE_THREAD default 8 if RENDEZVOUS_MODE_ETHERNET + config DISPLAY_AUTO_OFF + bool "Automatically turn off the M5Stack's Display after a few seconds" + default "y" + depends on DEVICE_TYPE_M5STACK + help + To reduce wear and heat the M5Stack's Display is automatically switched off after a few seconds + endmenu menu "PW RPC Debug channel" diff --git a/examples/lighting-app/esp32/main/LEDWidget.cpp b/examples/lighting-app/esp32/main/LEDWidget.cpp index 6e65bec7c0c1e5..246b0cec8d2b2d 100644 --- a/examples/lighting-app/esp32/main/LEDWidget.cpp +++ b/examples/lighting-app/esp32/main/LEDWidget.cpp @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2021-2023 Project CHIP Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,6 +17,7 @@ #include "LEDWidget.h" #include "ColorFormat.h" +#include "ScreenManager.h" #include "led_strip.h" static const char * TAG = "LEDWidget"; @@ -126,11 +127,27 @@ void LEDWidget::DoSet(void) mStrip->refresh(mStrip, 100); } #else - ESP_LOGI(TAG, "DoSet to GPIO number %d", mGPIONum); if (mGPIONum < GPIO_NUM_MAX) { ledc_set_duty(LEDC_LOW_SPEED_MODE, LEDC_CHANNEL_0, brightness); ledc_update_duty(LEDC_LOW_SPEED_MODE, LEDC_CHANNEL_0); } #endif // CONFIG_LED_TYPE_RMT +#if CONFIG_HAVE_DISPLAY + if (mVirtualLEDIndex != -1) + { + ScreenManager::SetVLED(mVirtualLEDIndex, mState); + } +#endif // CONFIG_HAVE_DISPLAY +} + +#if CONFIG_DEVICE_TYPE_M5STACK +void LEDWidget::SetVLED(int id1) +{ + mVirtualLEDIndex = id1; + if (mVirtualLEDIndex != -1) + { + ScreenManager::SetVLED(mVirtualLEDIndex, mState); + } } +#endif diff --git a/examples/lighting-app/esp32/main/QRCodeScreen.cpp b/examples/lighting-app/esp32/main/QRCodeScreen.cpp new file mode 100644 index 00000000000000..d4113c4d0889b9 --- /dev/null +++ b/examples/lighting-app/esp32/main/QRCodeScreen.cpp @@ -0,0 +1,100 @@ +/* + * + * Copyright (c) 2020-2023 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. + */ + +/** + * @file QRCodeScreen.cpp + * + * Screen which displays a QR code. + * + */ + +#include "QRCodeScreen.h" + +#if CONFIG_HAVE_DISPLAY + +// TODO organize includes below + +#include "esp_log.h" +#include "esp_system.h" +#include "esp_wifi.h" +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" + +#include "qrcodegen.h" + +#include +#include +#include + +namespace { + +constexpr int kVersion = 4; +constexpr int kModuleSize = 4; +constexpr int kBorderSize = 1; + +color_t qrCodeColor = TFT_LIGHTGREY; + +}; // namespace + +QRCodeScreen::QRCodeScreen(std::string text, std::string title) : title(title) +{ + constexpr int qrCodeSize = qrcodegen_BUFFER_LEN_FOR_VERSION(kVersion); + + // TODO check text length against max size permitted, or maybe adjust version used accordingly + + std::vector temp(qrCodeSize); + qrCode.resize(qrCodeSize); + + if (!qrcodegen_encodeText(text.c_str(), temp.data(), qrCode.data(), qrcodegen_Ecc_LOW, kVersion, kVersion, qrcodegen_Mask_AUTO, + true)) + { + ESP_LOGE("QRCodeScreen", "qrcodegen_encodeText() failed"); + qrCode.clear(); + } +} + +void QRCodeScreen::Display() +{ + if (qrCode.empty()) + { + return; + } + + const uint8_t * data = qrCode.data(); + const int size = qrcodegen_getSize(data); + const int displaySize = (2 * kBorderSize + size) * kModuleSize; + const int displayX = (DisplayWidth - displaySize) / 2; + const int displayY = ScreenTitleSafeTop + ((DisplayHeight - ScreenTitleSafeTop - ScreenTitleSafeBottom) - displaySize) / 2; + + TFT_fillRect(displayX, displayY, displaySize, displaySize, qrCodeColor); + + for (int y = 0; y < size; ++y) + { + for (int x = 0; x < size; ++x) + { + if (qrcodegen_getModule(data, x, y)) + { + TFT_fillRect(displayX + (kBorderSize + x) * kModuleSize, displayY + (kBorderSize + y) * kModuleSize, kModuleSize, + kModuleSize, TFT_BLACK); + } + } + } +} + +#endif // CONFIG_HAVE_DISPLAY diff --git a/examples/lighting-app/esp32/main/StatusScreen.cpp b/examples/lighting-app/esp32/main/StatusScreen.cpp new file mode 100644 index 00000000000000..698a12d835ce06 --- /dev/null +++ b/examples/lighting-app/esp32/main/StatusScreen.cpp @@ -0,0 +1,189 @@ +/* + * + * 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. + */ + +/** + * @file StatusScreen.cpp + * + * Screen which displays device state and status: + * - Fabric Index : none | # + * - Fabric ID : none | # + * - Node ID : none | # + * - UDP Port : # + * - IPv4 : none | addr + * - IPv6 LL : none | addr + * - IPv6 ULA : none | addr + */ + +#include "StatusScreen.h" + +#if CONFIG_HAVE_DISPLAY + +#include "esp_log.h" +#include "esp_system.h" +#include "esp_wifi.h" +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" + +#include +#include + +#include +#include + +#define MAX_LENGTH_SMALL_FONT 30 + +using namespace chip; + +class StatusListModel : public ListScreen::Model +{ +public: + enum + { + kStatusItemFabricIndex, + kStatusItemFabricId, + kStatusItemNodeId, + kStatusItemPort, + kStatusItemIp4, + kStatusItemIp6LinkLocal, + kStatusItemIp6Ula, + }; + + StatusListModel() + { + options.emplace_back("FabricIndex : none"); + options.emplace_back("FabricID : none"); + options.emplace_back("NodeID : none"); + options.emplace_back("UDP port : " + std::to_string(CHIP_PORT)); + options.emplace_back("IPv4 : none"); + options.emplace_back("IPv6 LL : none"); + options.emplace_back("IPv6 ULA : none"); + } + + virtual std::string GetTitle() { return "Status"; } + + virtual int GetItemCount() { return options.size(); } + virtual std::string GetItemText(int i) + { + std::string itemString = options.at(i); + switch (i) + { + case kStatusItemFabricIndex: { + for (const auto & fb : Server::GetInstance().GetFabricTable()) + { + FabricIndex fabricIndex = fb.GetFabricIndex(); + itemString = "FabricIdx : " + std::to_string(fabricIndex); + break; // Only print first fabric for now + } + break; + } + + case kStatusItemFabricId: { + for (const auto & fb : Server::GetInstance().GetFabricTable()) + { + FabricId fabricId = fb.GetFabricId(); + itemString = "FabricID : " + std::to_string(fabricId); + break; // Only print first fabric for now + } + break; + } + + case kStatusItemNodeId: { + for (const auto & fb : Server::GetInstance().GetFabricTable()) + { + NodeId nodeId = fb.GetNodeId(); + itemString = "NodeID : " + std::to_string(nodeId); + break; // Only print first fabric for now + } + break; + } + + case kStatusItemIp4: { + chip::Inet::IPAddress addr; + for (chip::Inet::InterfaceAddressIterator it; it.HasCurrent(); it.Next()) + { + if ((it.GetAddress(addr) == CHIP_NO_ERROR) && addr.IsIPv4()) + { + char buf[Inet::IPAddress::kMaxStringLength]; + addr.ToString(buf); + itemString = std::string(buf); + break; // Only print first IPv4 address for now + } + } + break; + } + + case kStatusItemIp6LinkLocal: { + chip::Inet::IPAddress addr; + for (chip::Inet::InterfaceAddressIterator it; it.HasCurrent(); it.Next()) + { + if ((it.GetAddress(addr) == CHIP_NO_ERROR) && addr.IsIPv6LinkLocal()) + { + char buf[Inet::IPAddress::kMaxStringLength]; + addr.ToString(buf); + itemString = std::string(buf); + if (itemString.length() < MAX_LENGTH_SMALL_FONT) + { + TFT_setFont(SMALL_FONT, nullptr); + } + else + { + TFT_setFont(DEF_SMALL_FONT, nullptr); + } + break; // Only print first IPv6 LL for now + } + } + break; + } + + case kStatusItemIp6Ula: { + chip::Inet::IPAddress addr; + for (chip::Inet::InterfaceAddressIterator it; it.HasCurrent(); it.Next()) + { + if ((it.GetAddress(addr) == CHIP_NO_ERROR) && addr.IsIPv6ULA()) + { + char buf[Inet::IPAddress::kMaxStringLength]; + addr.ToString(buf); + itemString = std::string(buf); + if (itemString.length() < MAX_LENGTH_SMALL_FONT) + { + TFT_setFont(SMALL_FONT, nullptr); + } + else + { + TFT_setFont(DEF_SMALL_FONT, nullptr); + } + break; // Only print first IPv6 ULA for now + } + } + break; + } + } + ESP_LOGI("M5 UI", "Display status %d: %s", i, itemString.c_str()); + + return itemString; + } + + virtual void ItemAction(int i) {} + +private: + std::vector options; +}; + +StatusScreen::StatusScreen() : ListScreen(chip::Platform::New()) {} + +#endif // CONFIG_HAVE_DISPLAY diff --git a/examples/lighting-app/esp32/main/WiFiWidget.cpp b/examples/lighting-app/esp32/main/WiFiWidget.cpp new file mode 100644 index 00000000000000..4062cc68e237c7 --- /dev/null +++ b/examples/lighting-app/esp32/main/WiFiWidget.cpp @@ -0,0 +1,66 @@ +/* + * + * Copyright (c) 2020-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. + */ + +/** + * @file WiFiWidget.cpp + * + * Implements a WiFi Widget controller that display the state of bluetooth + * connection on display. + */ + +#include "ScreenManager.h" + +#include "WiFiWidget.h" + +#include "esp_log.h" +#include "esp_system.h" + +void WiFiWidget::Init() +{ +#if CONFIG_HAVE_DISPLAY + mVLED = -1; +#endif // CONFIG_HAVE_DISPLAY + + mState = false; +} + +void WiFiWidget::Set(bool state) +{ + bool stateChange = (mState != state); + mState = state; + if (stateChange) + { +#if CONFIG_HAVE_DISPLAY + if (mVLED != -1) + { + ScreenManager::SetVLED(mVLED, mState); + } +#endif // CONFIG_HAVE_DISPLAY + } +} + +#if CONFIG_HAVE_DISPLAY +void WiFiWidget::SetVLED(int id) +{ + mVLED = id; + if (mVLED != -1) + { + ScreenManager::SetVLED(mVLED, mState); + } +} +#endif // CONFIG_HAVE_DISPLAY diff --git a/examples/lighting-app/esp32/main/include/AppEvent.h b/examples/lighting-app/esp32/main/include/AppEvent.h index 65ebd7aedc8157..079109e6fac770 100644 --- a/examples/lighting-app/esp32/main/include/AppEvent.h +++ b/examples/lighting-app/esp32/main/include/AppEvent.h @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2022 Project CHIP Authors + * Copyright (c) 2022-2023 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -38,6 +38,7 @@ struct AppEvent struct { uint8_t Action; + uint8_t PinNo; } ButtonEvent; struct { diff --git a/examples/lighting-app/esp32/main/include/AppTask.h b/examples/lighting-app/esp32/main/include/AppTask.h index 9271ebd3499b44..a7ba9387395316 100644 --- a/examples/lighting-app/esp32/main/include/AppTask.h +++ b/examples/lighting-app/esp32/main/include/AppTask.h @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2022 Project CHIP Authors + * Copyright (c) 2022-2023 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -57,7 +57,9 @@ class AppTask static void SwitchActionEventHandler(AppEvent * aEvent); static void LightingActionEventHandler(AppEvent * aEvent); - static void ButtonPressCallback(); +#if CONFIG_DEVICE_TYPE_M5STACK + static void ButtonPressedAction(AppEvent * aEvent); +#endif static AppTask sAppTask; }; diff --git a/examples/lighting-app/esp32/main/include/Button.h b/examples/lighting-app/esp32/main/include/Button.h index 17a08d7c1a9496..1251633630e7b5 100644 --- a/examples/lighting-app/esp32/main/include/Button.h +++ b/examples/lighting-app/esp32/main/include/Button.h @@ -1,6 +1,7 @@ /* * - * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2022-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. @@ -14,17 +15,38 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - #pragma once #include "driver/gpio.h" #include "esp_log.h" +#include "esp_system.h" +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "freertos/timers.h" +#define APP_BUTTON_PRESSED 0 +#define APP_BUTTON_RELEASED 1 +#define BUTTON_NUMBER 3 class Button { public: - typedef void (*ButtonPressCallback)(void); + Button(); + Button(gpio_num_t gpioNum); + + esp_err_t Init(); + esp_err_t Init(gpio_num_t gpioNum); + + inline gpio_num_t GetGPIONum(); + static void TimerCallback(TimerHandle_t xTimer); - void Init(void); - void SetButtonPressCallback(ButtonPressCallback button_callback); + friend void IRAM_ATTR button_isr_handler(void * arg); + +private: + gpio_num_t mGPIONum; + TimerHandle_t mbuttonTimer; // FreeRTOS timers used for debouncing buttons }; + +inline gpio_num_t Button::GetGPIONum() +{ + return mGPIONum; +} diff --git a/examples/lighting-app/esp32/main/include/DeviceCallbacks.h b/examples/lighting-app/esp32/main/include/DeviceCallbacks.h index 05933202b8c22a..e45a3b21f712bf 100644 --- a/examples/lighting-app/esp32/main/include/DeviceCallbacks.h +++ b/examples/lighting-app/esp32/main/include/DeviceCallbacks.h @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2021-2023 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,14 +15,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -/** - * @file DeviceCallbacks.h - * - * Implementations for the DeviceManager callbacks for this application - * - **/ - #pragma once #include @@ -44,3 +36,10 @@ class AppDeviceCallbacks : public CommonDeviceCallbacks void OnColorControlAttributeChangeCallback(chip::EndpointId endpointId, chip::AttributeId attributeId, uint8_t * value); #endif }; + +class AppDeviceCallbacksDelegate : public DeviceCallbacksDelegate +{ +public: + void OnIPv4ConnectivityEstablished() override; + void OnIPv4ConnectivityLost() override; +}; diff --git a/examples/lighting-app/esp32/main/include/Globals.h b/examples/lighting-app/esp32/main/include/Globals.h new file mode 100644 index 00000000000000..c26aa66edc7f7d --- /dev/null +++ b/examples/lighting-app/esp32/main/include/Globals.h @@ -0,0 +1,23 @@ +/* + * + * Copyright (c) 2020-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 "WiFiWidget.h" + +extern WiFiWidget wifiLED; diff --git a/examples/lighting-app/esp32/main/include/LEDWidget.h b/examples/lighting-app/esp32/main/include/LEDWidget.h index c390d63ac1024f..a230ae3451353e 100644 --- a/examples/lighting-app/esp32/main/include/LEDWidget.h +++ b/examples/lighting-app/esp32/main/include/LEDWidget.h @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2021-2023 Project CHIP Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,6 +43,11 @@ class LEDWidget uint8_t GetLevel(void); bool IsTurnedOn(void); +#if CONFIG_DEVICE_TYPE_M5STACK + // binds this LED to a virtual LED on a screen + void SetVLED(int id1); +#endif + private: bool mState; uint8_t mBrightness; @@ -55,5 +60,9 @@ class LEDWidget gpio_num_t mGPIONum; #endif +#if CONFIG_DEVICE_TYPE_M5STACK + int mVirtualLEDIndex = -1; +#endif + void DoSet(void); }; diff --git a/examples/lighting-app/esp32/main/include/QRCodeScreen.h b/examples/lighting-app/esp32/main/include/QRCodeScreen.h new file mode 100644 index 00000000000000..f82ad33d8e35b2 --- /dev/null +++ b/examples/lighting-app/esp32/main/include/QRCodeScreen.h @@ -0,0 +1,42 @@ +/* + * + * Copyright (c) 2020-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 "Screen.h" +#include "ScreenManager.h" + +#if CONFIG_HAVE_DISPLAY + +#include +#include + +class QRCodeScreen : public Screen +{ + std::vector qrCode; + std::string title; + +public: + QRCodeScreen(std::string text, std::string title = "QR Code"); + + virtual std::string GetTitle() { return title; } + + virtual void Display(); +}; + +#endif // CONFIG_HAVE_DISPLAY diff --git a/examples/lighting-app/esp32/main/include/StatusScreen.h b/examples/lighting-app/esp32/main/include/StatusScreen.h new file mode 100644 index 00000000000000..3aa537ebf0b9ba --- /dev/null +++ b/examples/lighting-app/esp32/main/include/StatusScreen.h @@ -0,0 +1,38 @@ +/* + * + * Copyright (c) 2022-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 "ListScreen.h" +#include "ScreenManager.h" + +#if CONFIG_HAVE_DISPLAY + +#include +#include + +class StatusScreen : public ListScreen +{ + +public: + StatusScreen(); + + virtual ~StatusScreen() {} +}; + +#endif // CONFIG_HAVE_DISPLAY diff --git a/examples/lighting-app/esp32/main/include/WiFiWidget.h b/examples/lighting-app/esp32/main/include/WiFiWidget.h new file mode 100644 index 00000000000000..cbc128c5ddfca9 --- /dev/null +++ b/examples/lighting-app/esp32/main/include/WiFiWidget.h @@ -0,0 +1,36 @@ +/* + * + * Copyright (c) 2020-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 "Display.h" + +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" + +class WiFiWidget +{ +public: + void Init(); + void Set(bool state); + void SetVLED(int id); + +private: + int mVLED; + bool mState; +}; diff --git a/examples/lighting-app/esp32/main/main.cpp b/examples/lighting-app/esp32/main/main.cpp index 7e872e8f78b0f9..0d0244b7e00059 100644 --- a/examples/lighting-app/esp32/main/main.cpp +++ b/examples/lighting-app/esp32/main/main.cpp @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2021-2023 Project CHIP Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,6 +46,8 @@ #include "Rpc.h" #endif +#include "DeviceWithDisplay.h" + #if CONFIG_ENABLE_ESP32_DEVICE_INFO_PROVIDER #include #else @@ -60,6 +62,7 @@ using namespace ::chip::DeviceLayer; static const char * TAG = "light-app"; static AppDeviceCallbacks EchoCallbacks; +static AppDeviceCallbacksDelegate sAppDeviceCallbacksDelegate; namespace { #if CONFIG_ENABLE_ESP32_FACTORY_DATA_PROVIDER @@ -78,6 +81,7 @@ static void InitServer(intptr_t context) // Print QR Code URL PrintOnboardingCodes(chip::RendezvousInformationFlags(CONFIG_RENDEZVOUS_MODE)); + DeviceCallbacksDelegate::Instance().SetAppDelegate(&sAppDeviceCallbacksDelegate); Esp32AppServer::Init(); // Init ZCL Data Model and CHIP App Server AND Initialize device attestation config } diff --git a/examples/lighting-app/esp32/sdkconfig_m5stack.defaults b/examples/lighting-app/esp32/sdkconfig_m5stack.defaults new file mode 100644 index 00000000000000..3f70ee3bfe1c46 --- /dev/null +++ b/examples/lighting-app/esp32/sdkconfig_m5stack.defaults @@ -0,0 +1,64 @@ +# +# 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. +# +# Description: +# Some useful defaults for the demo app configuration. +# +CONFIG_IDF_TARGET="esp32" +CONFIG_IDF_TARGET_ESP32=y +CONFIG_DEVICE_TYPE_M5STACK=y + +# Default to 921600 baud when flashing and monitoring device +CONFIG_ESPTOOLPY_BAUD_921600B=y +CONFIG_ESPTOOLPY_BAUD=921600 +CONFIG_ESPTOOLPY_COMPRESSED=y +CONFIG_ESPTOOLPY_MONITOR_BAUD_115200B=y +CONFIG_ESPTOOLPY_MONITOR_BAUD=115200 + +#enable BT +CONFIG_BT_ENABLED=y +CONFIG_BT_NIMBLE_ENABLED=y + +#disable BT connection reattempt +CONFIG_BT_NIMBLE_ENABLE_CONN_REATTEMPT=n + +#enable lwip ipv6 autoconfig +CONFIG_LWIP_IPV6_AUTOCONFIG=y + +#enable debug shell +CONFIG_ENABLE_CHIP_SHELL=y + +# Use a custom partition table +CONFIG_PARTITION_TABLE_CUSTOM=y +CONFIG_PARTITION_TABLE_FILENAME="partitions.csv" + +#enable lwIP route hooks +CONFIG_LWIP_HOOK_IP6_ROUTE_DEFAULT=y +CONFIG_LWIP_HOOK_ND6_GET_GW_DEFAULT=y + +# Main task needs a bit more stack than the default +# default is 3584, bump this up to 5k. +CONFIG_ESP_MAIN_TASK_STACK_SIZE=5120 + +# Serial Flasher config +CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y +CONFIG_ESPTOOLPY_FLASHSIZE="4MB" + +# Disable softap support by default +CONFIG_ESP_WIFI_SOFTAP_SUPPORT=n +# This example uses the older version of RMT driver to work with both +# idf-v4.4.3 and idf-v5.0, so supressing the warnings by setting below option +CONFIG_RMT_SUPPRESS_DEPRECATE_WARN=y diff --git a/scripts/build/builders/esp32.py b/scripts/build/builders/esp32.py index f9b50927dd41ab..9c7f62915686d2 100644 --- a/scripts/build/builders/esp32.py +++ b/scripts/build/builders/esp32.py @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Project CHIP Authors +# Copyright (c) 2021-2023 Project CHIP Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -126,6 +126,7 @@ def DefaultsFileName(board: Esp32Board, app: Esp32App, enable_rpcs: bool): specific_apps = { Esp32App.ALL_CLUSTERS, Esp32App.ALL_CLUSTERS_MINIMAL, + Esp32App.LIGHT, Esp32App.OTA_REQUESTOR, } if app in specific_apps: From 498f2389e2f12bd7c2daf7fcbba641b09080429e Mon Sep 17 00:00:00 2001 From: Wang Qixiang <43193572+wqx6@users.noreply.github.com> Date: Thu, 9 Mar 2023 01:12:12 +0800 Subject: [PATCH 7/9] ESP: Add support on all-clusters-app and lighting-app for ESP32-C6 (#25564) --- config/esp32/components/chip/CMakeLists.txt | 14 ++-- docs/guides/esp32/setup_idf_chip.md | 10 +++ .../all-clusters-app/esp32/CMakeLists.txt | 2 + .../esp32/main/CMakeLists.txt | 14 ++-- .../esp32/main/Kconfig.projbuild | 14 ++-- .../all-clusters-app/esp32/main/LEDWidget.cpp | 10 +-- .../esp32/main/include/LEDWidget.h | 4 +- .../esp32/sdkconfig.defaults.esp32c6 | 64 +++++++++++++++++++ examples/lighting-app/esp32/CMakeLists.txt | 2 + .../esp32/sdkconfig.defaults.esp32c6 | 64 +++++++++++++++++++ src/platform/ESP32/ConnectivityManagerImpl.h | 2 +- .../ESP32/ConnectivityManagerImpl_WiFi.cpp | 7 +- 12 files changed, 180 insertions(+), 27 deletions(-) create mode 100644 examples/all-clusters-app/esp32/sdkconfig.defaults.esp32c6 create mode 100644 examples/lighting-app/esp32/sdkconfig.defaults.esp32c6 diff --git a/config/esp32/components/chip/CMakeLists.txt b/config/esp32/components/chip/CMakeLists.txt index 2b983e36a0761f..a878b95ee3f5b8 100644 --- a/config/esp32/components/chip/CMakeLists.txt +++ b/config/esp32/components/chip/CMakeLists.txt @@ -137,7 +137,9 @@ if (CONFIG_ENABLE_CHIP_SHELL) chip_gn_arg_append("chip_build_libshell" "true") endif() -if (CONFIG_IDF_TARGET_ESP32H2) +if (CONFIG_ENABLE_WIFI_STATION OR CONFIG_ENABLE_WIFI_AP) + chip_gn_arg_append("chip_enable_wifi" "true") +else() chip_gn_arg_append("chip_enable_wifi" "false") endif() @@ -286,20 +288,22 @@ target_include_directories(${COMPONENT_LIB} INTERFACE idf_component_get_property(esp32_mbedtls_lib esp32_mbedtls COMPONENT_LIB) if(CONFIG_BT_ENABLED) + idf_component_get_property(bt_lib bt COMPONENT_LIB) if("${CONFIG_IDF_TARGET}" STREQUAL "esp32h2") - idf_component_get_property(bt_lib bt COMPONENT_LIB) idf_component_get_property(bt_dir bt COMPONENT_DIR) list(APPEND chip_libraries $) if(CONFIG_IDF_TARGET_ESP32H2_BETA_VERSION_2) list(APPEND chip_libraries ${bt_dir}/controller/lib_esp32h2/esp32h2-bt-lib/beta2/libble_app.a) endif() elseif("${CONFIG_IDF_TARGET}" STREQUAL "esp32c2") - idf_component_get_property(bt_lib bt COMPONENT_LIB) idf_component_get_property(bt_dir bt COMPONENT_DIR) list(APPEND chip_libraries $) list(APPEND chip_libraries ${bt_dir}/controller/lib_esp32c2/esp32c2-bt-lib/libble_app.a) + elseif("${CONFIG_IDF_TARGET}" STREQUAL "esp32c6") + idf_component_get_property(bt_dir bt COMPONENT_DIR) + list(APPEND chip_libraries $) + list(APPEND chip_libraries ${bt_dir}/controller/lib_esp32c6/esp32c6-bt-lib/libble_app.a) else() - idf_component_get_property(bt_lib bt COMPONENT_LIB) list(APPEND chip_libraries $ -lbtdm_app) endif() endif() @@ -314,7 +318,7 @@ if(CONFIG_OPENTHREAD_ENABLED) list(APPEND chip_libraries $) endif() -if((NOT CONFIG_USE_MINIMAL_MDNS) AND (NOT CONFIG_IDF_TARGET_ESP32H2)) +if((NOT CONFIG_USE_MINIMAL_MDNS) AND (CONFIG_ENABLE_WIFI_STATION OR CONFIG_ENABLE_WIFI_AP)) idf_build_get_property(build_components BUILD_COMPONENTS) # For IDF v5.x, the mdns component was moved to idf_managed_components. # We should use 'espressif__mdns' for 'idf_component_get_property'. diff --git a/docs/guides/esp32/setup_idf_chip.md b/docs/guides/esp32/setup_idf_chip.md index fa888fe0423a56..63303c79a5dfca 100644 --- a/docs/guides/esp32/setup_idf_chip.md +++ b/docs/guides/esp32/setup_idf_chip.md @@ -50,6 +50,16 @@ step. $ ./install.sh ``` +- For ESP32C6, please use commit + [afbdb0f3e](https://github.com/espressif/esp-idf/tree/afbdb0f3e). + + ``` + $ cd esp-idf + $ git checkout afbdb0f3e + $ git submodule update --init + $ ./install.sh + ``` + ## Setup Matter environment ### Install Prerequisites diff --git a/examples/all-clusters-app/esp32/CMakeLists.txt b/examples/all-clusters-app/esp32/CMakeLists.txt index e1eb655da1c9e9..dc92f0c65b2e19 100644 --- a/examples/all-clusters-app/esp32/CMakeLists.txt +++ b/examples/all-clusters-app/esp32/CMakeLists.txt @@ -47,6 +47,8 @@ idf_build_set_property(COMPILE_OPTIONS "-Wno-format-nonliteral;-Wno-format-secur # See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=80635 idf_build_set_property(COMPILE_OPTIONS "-Wno-error=maybe-uninitialized" APPEND) +idf_build_set_property(COMPILE_OPTIONS "-Wno-error=array-bounds" APPEND) + flashing_script() if (CONFIG_ENABLE_PW_RPC) diff --git a/examples/all-clusters-app/esp32/main/CMakeLists.txt b/examples/all-clusters-app/esp32/main/CMakeLists.txt index f09f3369862640..02d6693e20fecf 100644 --- a/examples/all-clusters-app/esp32/main/CMakeLists.txt +++ b/examples/all-clusters-app/esp32/main/CMakeLists.txt @@ -21,7 +21,7 @@ set(PRIV_INCLUDE_DIRS_LIST "${CMAKE_CURRENT_LIST_DIR}/include" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/providers" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/platform/esp32" - "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/third_party/nlfaultinjection/repo/include" + "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/third_party/nlfaultinjection/repo/include" ) set(SRC_DIRS_LIST "${CMAKE_CURRENT_LIST_DIR}" @@ -40,9 +40,9 @@ set(SRC_DIRS_LIST "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/test-cluster-server" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/descriptor" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/fault-injection-server" - "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/fan-control-server" + "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/fan-control-server" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/fixed-label-server" - "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/user-label-server" + "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/user-label-server" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/on-off-server" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/level-control" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/identify-server" @@ -67,7 +67,7 @@ set(SRC_DIRS_LIST "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/target-navigator-server" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/thermostat-server" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/thermostat-user-interface-configuration-server" - "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/thread-network-diagnostics-server" + "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/thread-network-diagnostics-server" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/channel-server" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/scenes" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/software-diagnostics-server" @@ -83,8 +83,8 @@ set(SRC_DIRS_LIST "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/ethernet-network-diagnostics-server" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/localization-configuration-server" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/time-format-localization-server" - "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/wifi-network-diagnostics-server" - "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/wake-on-lan-server" + "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/wifi-network-diagnostics-server" + "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/wake-on-lan-server" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/pump-configuration-and-control-server" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/power-source-configuration-server" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/power-source-server" @@ -108,7 +108,7 @@ set(SRC_DIRS_LIST "${SRC_DIRS_LIST}" ) endif (CONFIG_ENABLE_PW_RPC) -if(("${CONFIG_DEVICE_TYPE_ESP32_DEVKITC}" STREQUAL "y") OR ("${CONFIG_DEVICE_TYPE_ESP32_C3_DEVKITM}" STREQUAL "y") OR ("${CONFIG_DEVICE_TYPE_ESP32_C2_DEVKITM}" STREQUAL "y")) +if(("${CONFIG_DEVICE_TYPE_ESP32_DEVKITC}" STREQUAL "y") OR ("${CONFIG_DEVICE_TYPE_ESP32_C3_DEVKITM}" STREQUAL "y") OR ("${CONFIG_DEVICE_TYPE_ESP32_C2_DEVKITM}" STREQUAL "y") OR ("${CONFIG_DEVICE_TYPE_ESP32_C6_DEVKITC}" STREQUAL "y")) list(APPEND PRIV_INCLUDE_DIRS_LIST "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/common/screen-framework/include") set(PRIV_REQUIRES_LIST chip QRCode bt) diff --git a/examples/all-clusters-app/esp32/main/Kconfig.projbuild b/examples/all-clusters-app/esp32/main/Kconfig.projbuild index 4f9e071eb8a5dd..8ed41e03971ef3 100644 --- a/examples/all-clusters-app/esp32/main/Kconfig.projbuild +++ b/examples/all-clusters-app/esp32/main/Kconfig.projbuild @@ -25,6 +25,7 @@ menu "Demo" default DEVICE_TYPE_ESP32_DEVKITC if IDF_TARGET_ESP32 default DEVICE_TYPE_ESP32_C3_DEVKITM if IDF_TARGET_ESP32C3 default DEVICE_TYPE_ESP32_C2_DEVKITM if IDF_TARGET_ESP32C2 + default DEVICE_TYPE_ESP32_C6_DEVKITC if IDF_TARGET_ESP32C6 help Specifies the type of ESP32 device. @@ -50,6 +51,9 @@ menu "Demo" config DEVICE_TYPE_ESP32_C2_DEVKITM bool "ESP32C2-DevKitM" depends on IDF_TARGET_ESP32C2 + config DEVICE_TYPE_ESP32_C6_DEVKITC + bool "ESP32C6-DevKitC" + depends on IDF_TARGET_ESP32C6 endchoice choice @@ -81,7 +85,7 @@ menu "Demo" int range 0 5 default 0 if DEVICE_TYPE_ESP32_DEVKITC - default 0 if DEVICE_TYPE_ESP32_C3_DEVKITM || DEVICE_TYPE_ESP32_C2_DEVKITM + default 0 if DEVICE_TYPE_ESP32_C3_DEVKITM || DEVICE_TYPE_ESP32_C2_DEVKITM || DEVICE_TYPE_ESP32_C6_DEVKITC default 3 if DEVICE_TYPE_M5STACK default 4 if DEVICE_TYPE_ESP32_WROVER_KIT @@ -102,12 +106,12 @@ menu "Demo" To reduce wear and heat the M5Stack's Display is automatically switched off after a few seconds config STATUS_LED_GPIO_NUM - int + int range 0 40 - default 2 if DEVICE_TYPE_ESP32_DEVKITC #Use LED1 (blue LED) as status LED on DevKitC + default 2 if DEVICE_TYPE_ESP32_DEVKITC #Use LED1 (blue LED) as status LED on DevKitC default 2 if DEVICE_TYPE_ESP32_ETHERNET_KIT - default 8 if DEVICE_TYPE_ESP32_C3_DEVKITM || DEVICE_TYPE_ESP32_C2_DEVKITM - default 26 if DEVICE_TYPE_ESP32_WROVER_KIT + default 8 if DEVICE_TYPE_ESP32_C3_DEVKITM || DEVICE_TYPE_ESP32_C2_DEVKITM || DEVICE_TYPE_ESP32_C6_DEVKITC + default 26 if DEVICE_TYPE_ESP32_WROVER_KIT default 40 if DEVICE_TYPE_M5STACK help Each board has a status led, define its pin number. diff --git a/examples/all-clusters-app/esp32/main/LEDWidget.cpp b/examples/all-clusters-app/esp32/main/LEDWidget.cpp index 13dcdc4893c2cf..4a95c13b09a46e 100644 --- a/examples/all-clusters-app/esp32/main/LEDWidget.cpp +++ b/examples/all-clusters-app/esp32/main/LEDWidget.cpp @@ -30,7 +30,7 @@ #include "esp_log.h" #include "esp_system.h" #include "esp_timer.h" -#if CONFIG_DEVICE_TYPE_ESP32_C3_DEVKITM +#if CONFIG_DEVICE_TYPE_ESP32_C3_DEVKITM || CONFIG_DEVICE_TYPE_ESP32_C6_DEVKITC #include "driver/rmt.h" #include "led_strip.h" #define RMT_TX_DEFAULT_GPIO GPIO_NUM_8 @@ -51,7 +51,7 @@ void LEDWidget::Init(gpio_num_t gpioNum) mState = false; mError = false; errorTimer = NULL; -#if CONFIG_DEVICE_TYPE_ESP32_C3_DEVKITM +#if CONFIG_DEVICE_TYPE_ESP32_C3_DEVKITM || CONFIG_DEVICE_TYPE_ESP32_C6_DEVKITC if (gpioNum == RMT_TX_DEFAULT_GPIO) { rmt_config_t config = RMT_DEFAULT_CONFIG_TX(RMT_TX_DEFAULT_GPIO, RMT_TX_DEFAULT_CHANNEL); @@ -98,7 +98,7 @@ void LEDWidget::Set(bool state) void LEDWidget::SetBrightness(uint8_t brightness) { -#if CONFIG_DEVICE_TYPE_ESP32_C3_DEVKITM +#if CONFIG_DEVICE_TYPE_ESP32_C3_DEVKITM || CONFIG_DEVICE_TYPE_ESP32_C6_DEVKITC if (strip) { uint8_t red, green, blue; @@ -186,7 +186,7 @@ void LEDWidget::DoSet(bool state) { bool stateChange = (mState != state); mState = state; -#if CONFIG_DEVICE_TYPE_ESP32_C3_DEVKITM +#if CONFIG_DEVICE_TYPE_ESP32_C3_DEVKITM || CONFIG_DEVICE_TYPE_ESP32_C6_DEVKITC if (strip) { uint8_t red, green, blue; @@ -229,7 +229,7 @@ void LEDWidget::SetVLED(int id1, int id2) } #endif -#if CONFIG_DEVICE_TYPE_ESP32_C3_DEVKITM +#if CONFIG_DEVICE_TYPE_ESP32_C3_DEVKITM || CONFIG_DEVICE_TYPE_ESP32_C6_DEVKITC void LEDWidget::SetColor(uint8_t Hue, uint8_t Saturation) { uint8_t red, green, blue; diff --git a/examples/all-clusters-app/esp32/main/include/LEDWidget.h b/examples/all-clusters-app/esp32/main/include/LEDWidget.h index 8ce4323329854d..195e44196e2fa7 100644 --- a/examples/all-clusters-app/esp32/main/include/LEDWidget.h +++ b/examples/all-clusters-app/esp32/main/include/LEDWidget.h @@ -47,7 +47,7 @@ class LEDWidget void BlinkOnError(); void Animate(); -#if CONFIG_DEVICE_TYPE_ESP32_C3_DEVKITM +#if CONFIG_DEVICE_TYPE_ESP32_C3_DEVKITM || CONFIG_DEVICE_TYPE_ESP32_C6_DEVKITC void SetColor(uint8_t Hue, uint8_t Saturation); void HSB2rgb(uint16_t Hue, uint8_t Saturation, uint8_t brightness, uint8_t & red, uint8_t & green, uint8_t & blue); @@ -61,7 +61,7 @@ class LEDWidget uint32_t mBlinkOnTimeMS; uint32_t mBlinkOffTimeMS; uint8_t mDefaultOnBrightness; -#if CONFIG_DEVICE_TYPE_ESP32_C3_DEVKITM +#if CONFIG_DEVICE_TYPE_ESP32_C3_DEVKITM || CONFIG_DEVICE_TYPE_ESP32_C6_DEVKITC uint16_t mHue; // mHue [0, 360] uint8_t mSaturation; // mSaturation [0, 100] #endif diff --git a/examples/all-clusters-app/esp32/sdkconfig.defaults.esp32c6 b/examples/all-clusters-app/esp32/sdkconfig.defaults.esp32c6 new file mode 100644 index 00000000000000..7ef46707ea5c95 --- /dev/null +++ b/examples/all-clusters-app/esp32/sdkconfig.defaults.esp32c6 @@ -0,0 +1,64 @@ +CONFIG_IDF_TARGET="esp32c6" + +# Default to 921600 baud when flashing and monitoring device +CONFIG_ESPTOOLPY_BAUD_921600B=y +CONFIG_ESPTOOLPY_BAUD=921600 +CONFIG_ESPTOOLPY_COMPRESSED=y +CONFIG_ESPTOOLPY_FLASHMODE_QIO=y +CONFIG_ESPTOOLPY_FLASHFREQ_40M=y +CONFIG_ESPTOOLPY_FLASHFREQ="40m" +CONFIG_ESPTOOLPY_MONITOR_BAUD_115200B=y +CONFIG_ESPTOOLPY_MONITOR_BAUD=115200 + +# libsodium +CONFIG_LIBSODIUM_USE_MBEDTLS_SHA=y + + +# NIMBLE +CONFIG_BT_ENABLED=y +CONFIG_BT_NIMBLE_ENABLED=y +CONFIG_BT_NIMBLE_EXT_ADV=n +CONFIG_BT_NIMBLE_HCI_EVT_BUF_SIZE=70 +CONFIG_USE_BLE_ONLY_FOR_COMMISSIONING=n + +# Disable OpenThread +CONFIG_OPENTHREAD_ENABLED=n + +# Disable lwip ipv6 autoconfig +CONFIG_LWIP_IPV6_AUTOCONFIG=n + +# Use a custom partition table +CONFIG_PARTITION_TABLE_CUSTOM=y +CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv" + +# LwIP config for OpenThread +CONFIG_LWIP_IPV6_NUM_ADDRESSES=8 +CONFIG_LWIP_MULTICAST_PING=y + +# mbedTLS +CONFIG_MBEDTLS_HARDWARE_AES=n +CONFIG_MBEDTLS_HARDWARE_MPI=n +CONFIG_MBEDTLS_HARDWARE_SHA=n +CONFIG_MBEDTLS_HARDWARE_ECC=y +CONFIG_MBEDTLS_CMAC_C=y +CONFIG_MBEDTLS_KEY_EXCHANGE_ECJPAKE=y +CONFIG_MBEDTLS_ECJPAKE_C=y + +# MDNS platform +CONFIG_USE_MINIMAL_MDNS=y +CONFIG_ENABLE_EXTENDED_DISCOVERY=y + +# FreeRTOS should use legacy API +CONFIG_FREERTOS_ENABLE_BACKWARD_COMPATIBILITY=y + +# Wi-Fi Settings +CONFIG_ENABLE_WIFI_STATION=y +CONFIG_ENABLE_WIFI_AP=n +# Enable this to avoid implicit declaration of function 'esp_send_assoc_resp' +CONFIG_ESP_WIFI_SOFTAP_SUPPORT=y + +# Enable OTA Requestor +CONFIG_ENABLE_OTA_REQUESTOR=y + +# Enable chip shell +CONFIG_ENABLE_CHIP_SHELL=y diff --git a/examples/lighting-app/esp32/CMakeLists.txt b/examples/lighting-app/esp32/CMakeLists.txt index 3b61c69d0e05bd..e9a5418e8dda46 100644 --- a/examples/lighting-app/esp32/CMakeLists.txt +++ b/examples/lighting-app/esp32/CMakeLists.txt @@ -52,6 +52,8 @@ idf_build_set_property(COMPILE_OPTIONS "-Wno-error=maybe-uninitialized" APPEND) #For the H2, -Werror=uninitialized will cause an error in "src/lib/support/LambdaBridge.h" idf_build_set_property(COMPILE_OPTIONS "-Wno-error=uninitialized" APPEND) +#For ESP32-C6, -Werror=array-bounds will cause an error in 'third_party/nlfaultinjection/repo/src/nlfaultinjection.cpp' +idf_build_set_property(COMPILE_OPTIONS "-Wno-error=array-bounds" APPEND) flashing_script() diff --git a/examples/lighting-app/esp32/sdkconfig.defaults.esp32c6 b/examples/lighting-app/esp32/sdkconfig.defaults.esp32c6 new file mode 100644 index 00000000000000..7ef46707ea5c95 --- /dev/null +++ b/examples/lighting-app/esp32/sdkconfig.defaults.esp32c6 @@ -0,0 +1,64 @@ +CONFIG_IDF_TARGET="esp32c6" + +# Default to 921600 baud when flashing and monitoring device +CONFIG_ESPTOOLPY_BAUD_921600B=y +CONFIG_ESPTOOLPY_BAUD=921600 +CONFIG_ESPTOOLPY_COMPRESSED=y +CONFIG_ESPTOOLPY_FLASHMODE_QIO=y +CONFIG_ESPTOOLPY_FLASHFREQ_40M=y +CONFIG_ESPTOOLPY_FLASHFREQ="40m" +CONFIG_ESPTOOLPY_MONITOR_BAUD_115200B=y +CONFIG_ESPTOOLPY_MONITOR_BAUD=115200 + +# libsodium +CONFIG_LIBSODIUM_USE_MBEDTLS_SHA=y + + +# NIMBLE +CONFIG_BT_ENABLED=y +CONFIG_BT_NIMBLE_ENABLED=y +CONFIG_BT_NIMBLE_EXT_ADV=n +CONFIG_BT_NIMBLE_HCI_EVT_BUF_SIZE=70 +CONFIG_USE_BLE_ONLY_FOR_COMMISSIONING=n + +# Disable OpenThread +CONFIG_OPENTHREAD_ENABLED=n + +# Disable lwip ipv6 autoconfig +CONFIG_LWIP_IPV6_AUTOCONFIG=n + +# Use a custom partition table +CONFIG_PARTITION_TABLE_CUSTOM=y +CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv" + +# LwIP config for OpenThread +CONFIG_LWIP_IPV6_NUM_ADDRESSES=8 +CONFIG_LWIP_MULTICAST_PING=y + +# mbedTLS +CONFIG_MBEDTLS_HARDWARE_AES=n +CONFIG_MBEDTLS_HARDWARE_MPI=n +CONFIG_MBEDTLS_HARDWARE_SHA=n +CONFIG_MBEDTLS_HARDWARE_ECC=y +CONFIG_MBEDTLS_CMAC_C=y +CONFIG_MBEDTLS_KEY_EXCHANGE_ECJPAKE=y +CONFIG_MBEDTLS_ECJPAKE_C=y + +# MDNS platform +CONFIG_USE_MINIMAL_MDNS=y +CONFIG_ENABLE_EXTENDED_DISCOVERY=y + +# FreeRTOS should use legacy API +CONFIG_FREERTOS_ENABLE_BACKWARD_COMPATIBILITY=y + +# Wi-Fi Settings +CONFIG_ENABLE_WIFI_STATION=y +CONFIG_ENABLE_WIFI_AP=n +# Enable this to avoid implicit declaration of function 'esp_send_assoc_resp' +CONFIG_ESP_WIFI_SOFTAP_SUPPORT=y + +# Enable OTA Requestor +CONFIG_ENABLE_OTA_REQUESTOR=y + +# Enable chip shell +CONFIG_ENABLE_CHIP_SHELL=y diff --git a/src/platform/ESP32/ConnectivityManagerImpl.h b/src/platform/ESP32/ConnectivityManagerImpl.h index 3065180a372d94..35658206b76c02 100644 --- a/src/platform/ESP32/ConnectivityManagerImpl.h +++ b/src/platform/ESP32/ConnectivityManagerImpl.h @@ -161,7 +161,7 @@ class ConnectivityManagerImpl final : public ConnectivityManager, void UpdateInternetConnectivityState(void); void OnStationIPv4AddressAvailable(const ip_event_got_ip_t & got_ip); void OnStationIPv4AddressLost(void); - void OnIPv6AddressAvailable(const ip_event_got_ip6_t & got_ip); + void OnStationIPv6AddressAvailable(const ip_event_got_ip6_t & got_ip); #endif // CHIP_DEVICE_CONFIG_ENABLE_WIFI // ===== Members for internal use by the following friends. diff --git a/src/platform/ESP32/ConnectivityManagerImpl_WiFi.cpp b/src/platform/ESP32/ConnectivityManagerImpl_WiFi.cpp index f426c5a56cbd69..4c962d24a5e5b0 100644 --- a/src/platform/ESP32/ConnectivityManagerImpl_WiFi.cpp +++ b/src/platform/ESP32/ConnectivityManagerImpl_WiFi.cpp @@ -520,7 +520,10 @@ void ConnectivityManagerImpl::OnWiFiPlatformEvent(const ChipDeviceEvent * event) break; case IP_EVENT_GOT_IP6: ChipLogProgress(DeviceLayer, "IP_EVENT_GOT_IP6"); - OnIPv6AddressAvailable(event->Platform.ESPSystemEvent.Data.IpGotIp6); + if (strcmp(esp_netif_get_ifkey(event->Platform.ESPSystemEvent.Data.IpGotIp6.esp_netif), "WIFI_STA_DEF") == 0) + { + OnStationIPv6AddressAvailable(event->Platform.ESPSystemEvent.Data.IpGotIp6); + } break; default: break; @@ -1080,7 +1083,7 @@ void ConnectivityManagerImpl::OnStationIPv4AddressLost(void) PlatformMgr().PostEventOrDie(&event); } -void ConnectivityManagerImpl::OnIPv6AddressAvailable(const ip_event_got_ip6_t & got_ip) +void ConnectivityManagerImpl::OnStationIPv6AddressAvailable(const ip_event_got_ip6_t & got_ip) { #if CHIP_PROGRESS_LOGGING { From de5cf941b99101195cecb41415c9de23fb3553e1 Mon Sep 17 00:00:00 2001 From: Shubham Patil Date: Wed, 8 Mar 2023 22:42:28 +0530 Subject: [PATCH 8/9] [ESP32] Fix the wifi version returning WiFiVersionEnum::kA in case of error (#25565) --- .../ESP32/DiagnosticDataProviderImpl.cpp | 22 ++++++++----------- 1 file changed, 9 insertions(+), 13 deletions(-) diff --git a/src/platform/ESP32/DiagnosticDataProviderImpl.cpp b/src/platform/ESP32/DiagnosticDataProviderImpl.cpp index f811170d335894..11c7c27ec5b76f 100644 --- a/src/platform/ESP32/DiagnosticDataProviderImpl.cpp +++ b/src/platform/ESP32/DiagnosticDataProviderImpl.cpp @@ -92,9 +92,7 @@ app::Clusters::WiFiNetworkDiagnostics::WiFiVersionEnum GetWiFiVersionFromAPRecor else if (ap_info.phy_11b) return WiFiVersionEnum::kB; else - // TODO: This is keeping the old behavior, it doesn't look right. - // https://github.com/project-chip/connectedhomeip/issues/25544 - return WiFiVersionEnum::kA; + return WiFiVersionEnum::kUnknownEnumValue; } #endif // CHIP_DEVICE_CONFIG_ENABLE_WIFI @@ -237,7 +235,7 @@ CHIP_ERROR DiagnosticDataProviderImpl::GetNetworkInterfaces(NetworkInterface ** { memcpy(ifp->Ipv4AddressesBuffer[0], &(ipv4_info.ip.addr), kMaxIPv4AddrSize); ifp->Ipv4AddressSpans[0] = ByteSpan(ifp->Ipv4AddressesBuffer[0], kMaxIPv4AddrSize); - ifp->IPv4Addresses = chip::app::DataModel::List(ifp->Ipv4AddressSpans, 1); + ifp->IPv4Addresses = app::DataModel::List(ifp->Ipv4AddressSpans, 1); } static_assert(kMaxIPv6AddrCount <= UINT8_MAX, "Count might not fit in ipv6_addr_count"); @@ -256,7 +254,7 @@ CHIP_ERROR DiagnosticDataProviderImpl::GetNetworkInterfaces(NetworkInterface ** memcpy(ifp->Ipv6AddressesBuffer[idx], ip6_addr[idx].addr, kMaxIPv6AddrSize); ifp->Ipv6AddressSpans[idx] = ByteSpan(ifp->Ipv6AddressesBuffer[idx], kMaxIPv6AddrSize); } - ifp->IPv6Addresses = chip::app::DataModel::List(ifp->Ipv6AddressSpans, ipv6_addr_count); + ifp->IPv6Addresses = app::DataModel::List(ifp->Ipv6AddressSpans, ipv6_addr_count); ifp->Next = head; head = ifp; @@ -311,15 +309,13 @@ CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiSecurityType(app::Clusters::WiFiNe CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiVersion(app::Clusters::WiFiNetworkDiagnostics::WiFiVersionEnum & wifiVersion) { wifi_ap_record_t ap_info; - esp_err_t err; - err = esp_wifi_sta_get_ap_info(&ap_info); - if (err == ESP_OK) - { - wifiVersion = GetWiFiVersionFromAPRecord(ap_info); - return CHIP_NO_ERROR; - } + esp_err_t err = esp_wifi_sta_get_ap_info(&ap_info); + VerifyOrReturnError(err == ESP_OK, ESP32Utils::MapError(err)); - return ESP32Utils::MapError(err); + wifiVersion = GetWiFiVersionFromAPRecord(ap_info); + VerifyOrReturnError(wifiVersion != app::Clusters::WiFiNetworkDiagnostics::WiFiVersionEnum::kUnknownEnumValue, + CHIP_ERROR_INTERNAL); + return CHIP_NO_ERROR; } CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiChannelNumber(uint16_t & channelNumber) From 43d45ef58acb86acb17f040aa672a9c9abecfbe2 Mon Sep 17 00:00:00 2001 From: Praveen Chandran Date: Wed, 8 Mar 2023 09:19:45 -0800 Subject: [PATCH 9/9] [infineon PSoC6] Fix for Doorlock credentials update (#25558) --- .../infineon/psoc6/include/LockManager.h | 13 ++-- .../lock-app/infineon/psoc6/src/AppTask.cpp | 6 +- .../infineon/psoc6/src/LockManager.cpp | 76 +++++++++---------- 3 files changed, 46 insertions(+), 49 deletions(-) diff --git a/examples/lock-app/infineon/psoc6/include/LockManager.h b/examples/lock-app/infineon/psoc6/include/LockManager.h index ab3eb96c0a92c6..d08cab2cc104b3 100644 --- a/examples/lock-app/infineon/psoc6/include/LockManager.h +++ b/examples/lock-app/infineon/psoc6/include/LockManager.h @@ -56,10 +56,8 @@ static constexpr uint8_t kMaxCredentialsPerUser = 10; static constexpr uint8_t kMaxWeekdaySchedulesPerUser = 10; static constexpr uint8_t kMaxYeardaySchedulesPerUser = 10; static constexpr uint8_t kMaxHolidaySchedules = 10; -static constexpr uint8_t kMaxCredentialSize = 8; - -// Indices received for user/credential/schedules are 1-indexed -static constexpr uint8_t kStartIndexValue = 1; +static constexpr uint8_t kMaxCredentialSize = 20; +static constexpr uint8_t kNumCredentialTypes = 6; static constexpr uint8_t kMaxCredentials = kMaxUsers * kMaxCredentialsPerUser; } // namespace ResourceRanges @@ -178,6 +176,7 @@ class LockManager uint32_t localEndTime, OperatingModeEnum operatingMode); bool IsValidUserIndex(uint16_t userIndex); + bool IsValidCredentialType(CredentialTypeEnum type); bool IsValidCredentialIndex(uint16_t credentialIndex, CredentialTypeEnum type); bool IsValidWeekdayScheduleIndex(uint8_t scheduleIndex); bool IsValidYeardayScheduleIndex(uint8_t scheduleIndex); @@ -205,14 +204,14 @@ class LockManager static void ActuatorMovementTimerEventHandler(AppEvent * aEvent); EmberAfPluginDoorLockUserInfo mLockUsers[kMaxUsers]; - EmberAfPluginDoorLockCredentialInfo mLockCredentials[kMaxCredentials]; + EmberAfPluginDoorLockCredentialInfo mLockCredentials[kNumCredentialTypes][kMaxCredentials]; WeekDaysScheduleInfo mWeekdaySchedule[kMaxUsers][kMaxWeekdaySchedulesPerUser]; YearDayScheduleInfo mYeardaySchedule[kMaxUsers][kMaxYeardaySchedulesPerUser]; HolidayScheduleInfo mHolidaySchedule[kMaxHolidaySchedules]; char mUserNames[ArraySize(mLockUsers)][DOOR_LOCK_MAX_USER_NAME_SIZE]; - uint8_t mCredentialData[kMaxCredentials][kMaxCredentialSize]; - CredentialStruct mCredentials[kMaxUsers][kMaxCredentialsPerUser]; + uint8_t mCredentialData[kNumCredentialTypes][kMaxCredentials][kMaxCredentialSize]; + CredentialStruct mCredentials[kMaxUsers][kMaxCredentials]; static LockManager sLock; P6DoorLock::LockInitParams::LockParam LockParams; diff --git a/examples/lock-app/infineon/psoc6/src/AppTask.cpp b/examples/lock-app/infineon/psoc6/src/AppTask.cpp index 1a695da5dc8511..b5bd7a4edf2dcf 100644 --- a/examples/lock-app/infineon/psoc6/src/AppTask.cpp +++ b/examples/lock-app/infineon/psoc6/src/AppTask.cpp @@ -283,7 +283,8 @@ void AppTask::lockMgr_Init() } ConfigurationMgr().LogDeviceConfig(); - + // Users and credentials should be checked once from flash on boot + LockMgr().ReadConfigValues(); // Print setup info PrintOnboardingCodes(chip::RendezvousInformationFlag(chip::RendezvousInformationFlag::kBLE)); } @@ -323,9 +324,6 @@ void AppTask::AppTaskMain(void * pvParameter) sAppTask.Init(); P6_LOG("App Task started"); - // Users and credentials should be checked once from flash on boot - LockMgr().ReadConfigValues(); - while (true) { BaseType_t eventReceived = xQueueReceive(sAppEventQueue, &event, portMAX_DELAY); diff --git a/examples/lock-app/infineon/psoc6/src/LockManager.cpp b/examples/lock-app/infineon/psoc6/src/LockManager.cpp index 06de91f664a827..764ee16ee61c56 100644 --- a/examples/lock-app/infineon/psoc6/src/LockManager.cpp +++ b/examples/lock-app/infineon/psoc6/src/LockManager.cpp @@ -118,6 +118,11 @@ bool LockManager::IsValidCredentialIndex(uint16_t credentialIndex, CredentialTyp return (credentialIndex < kMaxCredentialsPerUser); } +bool LockManager::IsValidCredentialType(CredentialTypeEnum type) +{ + return (to_underlying(type) < kNumCredentialTypes); +} + bool LockManager::IsValidWeekdayScheduleIndex(uint8_t scheduleIndex) { return (scheduleIndex < kMaxWeekdaySchedulesPerUser); @@ -140,7 +145,7 @@ bool LockManager::ReadConfigValues() sizeof(EmberAfPluginDoorLockUserInfo) * ArraySize(mLockUsers), outLen); P6Config::ReadConfigValueBin(P6Config::kConfigKey_Credential, reinterpret_cast(&mLockCredentials), - sizeof(EmberAfPluginDoorLockCredentialInfo) * ArraySize(mLockCredentials), outLen); + sizeof(EmberAfPluginDoorLockCredentialInfo) * kMaxCredentials * kNumCredentialTypes, outLen); P6Config::ReadConfigValueBin(P6Config::kConfigKey_LockUserName, reinterpret_cast(mUserNames), sizeof(mUserNames), outLen); @@ -149,8 +154,7 @@ bool LockManager::ReadConfigValues() sizeof(mCredentialData), outLen); P6Config::ReadConfigValueBin(P6Config::kConfigKey_UserCredentials, reinterpret_cast(mCredentials), - sizeof(CredentialStruct) * LockParams.numberOfUsers * LockParams.numberOfCredentialsPerUser, - outLen); + sizeof(CredentialStruct) * LockParams.numberOfUsers * kMaxCredentials, outLen); P6Config::ReadConfigValueBin(P6Config::kConfigKey_WeekDaySchedules, reinterpret_cast(mWeekdaySchedule), sizeof(EmberAfPluginDoorLockWeekDaySchedule) * LockParams.numberOfWeekdaySchedulesPerUser * @@ -384,11 +388,6 @@ bool LockManager::SetUser(chip::EndpointId endpointId, uint16_t userIndex, chip: for (size_t i = 0; i < totalCredentials; ++i) { mCredentials[userIndex][i] = credentials[i]; - // TODO: Why are we modifying the passed-in credentials? - // https://github.com/project-chip/connectedhomeip/issues/25081 - // For now, preserve pre-existing behavior, which set credentialType to 1. - mCredentials[userIndex][i].credentialType = CredentialTypeEnum::kPin; - mCredentials[userIndex][i].credentialIndex = i + 1; } userInStorage.credentials = chip::Span(mCredentials[userIndex], totalCredentials); @@ -398,7 +397,7 @@ bool LockManager::SetUser(chip::EndpointId endpointId, uint16_t userIndex, chip: sizeof(EmberAfPluginDoorLockUserInfo) * LockParams.numberOfUsers); P6Config::WriteConfigValueBin(P6Config::kConfigKey_UserCredentials, reinterpret_cast(mCredentials), - sizeof(CredentialStruct) * LockParams.numberOfUsers * LockParams.numberOfCredentialsPerUser); + sizeof(CredentialStruct) * LockParams.numberOfUsers * kMaxCredentials); P6Config::WriteConfigValueBin(P6Config::kConfigKey_LockUserName, reinterpret_cast(mUserNames), sizeof(mUserNames)); @@ -411,25 +410,21 @@ bool LockManager::SetUser(chip::EndpointId endpointId, uint16_t userIndex, chip: bool LockManager::GetCredential(chip::EndpointId endpointId, uint16_t credentialIndex, CredentialTypeEnum credentialType, EmberAfPluginDoorLockCredentialInfo & credential) { - - VerifyOrReturnValue(credentialIndex > 0, false); // indices are one-indexed - - credentialIndex--; - - VerifyOrReturnValue(IsValidCredentialIndex(credentialIndex, credentialType), false); + VerifyOrReturnValue(IsValidCredentialType(credentialType), false); + if (CredentialTypeEnum::kProgrammingPIN == credentialType) + { + VerifyOrReturnValue(IsValidCredentialIndex(credentialIndex, credentialType), + false); // programming pin index is only index allowed to contain 0 + } + else + { + VerifyOrReturnValue(IsValidCredentialIndex(--credentialIndex, credentialType), false); // otherwise, indices are one-indexed + } ChipLogProgress(Zcl, "Lock App: LockManager::GetCredential [credentialType=%u], credentialIndex=%d", to_underlying(credentialType), credentialIndex); - if (credentialType == CredentialTypeEnum::kProgrammingPIN) - { - ChipLogError(Zcl, "Programming user not supported [credentialType=%u], credentialIndex=%d", to_underlying(credentialType), - credentialIndex); - - return true; - } - - const auto & credentialInStorage = mLockCredentials[credentialIndex]; + const auto & credentialInStorage = mLockCredentials[to_underlying(credentialType)][credentialIndex]; credential.status = credentialInStorage.status; ChipLogDetail(Zcl, "CredentialStatus: %d, CredentialIndex: %d ", (int) credential.status, credentialIndex); @@ -458,31 +453,36 @@ bool LockManager::SetCredential(chip::EndpointId endpointId, uint16_t credential chip::FabricIndex modifier, DlCredentialStatus credentialStatus, CredentialTypeEnum credentialType, const chip::ByteSpan & credentialData) { - - VerifyOrReturnValue(credentialIndex > 0, false); // indices are one-indexed - - credentialIndex--; - - VerifyOrReturnValue(IsValidCredentialIndex(credentialIndex, credentialType), false); + VerifyOrReturnValue(IsValidCredentialType(credentialType), false); + if (CredentialTypeEnum::kProgrammingPIN == credentialType) + { + VerifyOrReturnValue(IsValidCredentialIndex(credentialIndex, credentialType), + false); // programming pin index is only index allowed to contain 0 + } + else + { + VerifyOrReturnValue(IsValidCredentialIndex(--credentialIndex, credentialType), false); // otherwise, indices are one-indexed + } ChipLogProgress(Zcl, "Door Lock App: LockManager::SetCredential " "[credentialStatus=%u,credentialType=%u,credentialDataSize=%u,creator=%d,modifier=%d]", to_underlying(credentialStatus), to_underlying(credentialType), credentialData.size(), creator, modifier); - auto & credentialInStorage = mLockCredentials[credentialIndex]; + auto & credentialInStorage = mLockCredentials[to_underlying(credentialType)][credentialIndex]; credentialInStorage.status = credentialStatus; credentialInStorage.credentialType = credentialType; credentialInStorage.createdBy = creator; credentialInStorage.lastModifiedBy = modifier; - memcpy(mCredentialData[credentialIndex], credentialData.data(), credentialData.size()); - credentialInStorage.credentialData = chip::ByteSpan{ mCredentialData[credentialIndex], credentialData.size() }; + memcpy(mCredentialData[to_underlying(credentialType)][credentialIndex], credentialData.data(), credentialData.size()); + credentialInStorage.credentialData = + chip::ByteSpan{ mCredentialData[to_underlying(credentialType)][credentialIndex], credentialData.size() }; // Save credential information in NVM flash P6Config::WriteConfigValueBin(P6Config::kConfigKey_Credential, reinterpret_cast(&mLockCredentials), - sizeof(EmberAfPluginDoorLockCredentialInfo) * LockParams.numberOfCredentialsPerUser); + sizeof(EmberAfPluginDoorLockCredentialInfo) * kMaxCredentials * kNumCredentialTypes); P6Config::WriteConfigValueBin(P6Config::kConfigKey_CredentialData, reinterpret_cast(&mCredentialData), sizeof(mCredentialData)); @@ -686,15 +686,15 @@ bool LockManager::setLockState(chip::EndpointId endpointId, DlLockState lockStat } // Check the PIN code - for (uint8_t i = 0; i < kMaxCredentials; i++) + for (const auto & currentCredential : mLockCredentials[to_underlying(CredentialTypeEnum::kPin)]) { - if (mLockCredentials[i].credentialType != CredentialTypeEnum::kPin || - mLockCredentials[i].status == DlCredentialStatus::kAvailable) + + if (currentCredential.status == DlCredentialStatus::kAvailable) { continue; } - if (mLockCredentials[i].credentialData.data_equal(pin.Value())) + if (currentCredential.credentialData.data_equal(pin.Value())) { ChipLogDetail(Zcl, "Lock App: specified PIN code was found in the database, setting lock state to \"%s\" [endpointId=%d]",