From a42570bfc530d47aff5936e3321ab12d78284f87 Mon Sep 17 00:00:00 2001 From: Arkadiusz Bokowy Date: Tue, 4 Jun 2024 19:07:53 +0200 Subject: [PATCH 01/15] Setup bloat reports for Tizen CI builds (#33729) * Setup bloat reports for Tizen CI builds * Apply suggestions from code review Co-authored-by: Andrei Litvin * Configuration for Tizen --------- Co-authored-by: Andrei Litvin --- .github/workflows/examples-tizen.yaml | 23 +++++++++ scripts/tools/memory/platform/tizen.cfg | 67 +++++++++++++++++++++++++ 2 files changed, 90 insertions(+) create mode 100644 scripts/tools/memory/platform/tizen.cfg diff --git a/.github/workflows/examples-tizen.yaml b/.github/workflows/examples-tizen.yaml index 17cd275e0d5b52..295f6d158c87d9 100644 --- a/.github/workflows/examples-tizen.yaml +++ b/.github/workflows/examples-tizen.yaml @@ -50,6 +50,12 @@ jobs: with: platform: tizen + - name: Set up environment for size reports + uses: ./.github/actions/setup-size-reports + if: ${{ !env.ACT }} + with: + gh-context: ${{ toJson(github) }} + - name: Build Tizen examples run: | ./scripts/run_in_build_env.sh \ @@ -61,3 +67,20 @@ jobs: build \ --copy-artifacts-to out/artifacts \ " + + - name: Bloat report - chip-tool + run: | + .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py \ + tizen arm chip-tool-ubsan out/tizen-arm-chip-tool-ubsan/chip-tool \ + /tmp/bloat_reports/ + - name: Bloat report - all-clusters-app + run: | + .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py \ + tizen arm all-clusters-app out/tizen-arm-all-clusters/chip-all-clusters-app \ + /tmp/bloat_reports/ + + - name: Uploading Size Reports + uses: ./.github/actions/upload-size-reports + if: ${{ !env.ACT }} + with: + platform-name: Tizen diff --git a/scripts/tools/memory/platform/tizen.cfg b/scripts/tools/memory/platform/tizen.cfg new file mode 100644 index 00000000000000..294bf21386de3e --- /dev/null +++ b/scripts/tools/memory/platform/tizen.cfg @@ -0,0 +1,67 @@ +# Copyright (c) 2024 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Memory tools default configuation for Tizen. + +{ + 'section': { + # By default, only these sections will be included + # when operating by sections. + 'default': [ + '.text', '.data', '.data.rel.ro', '.bss', '.dynamic', '.got', + '.init', '.init_array', '.rodata' + ] + }, + 'region': { + # Regions are sets of sections that can be used for aggregate reports. + 'sections': { + 'FLASH': [ + ".dynstr", + ".dynsym", + ".eh_frame_hdr", + ".eh_frame", + ".fini", + ".gcc_except_table", + ".gnu.version_d", + ".gnu.version_r", + ".gnu.version", + ".hash", + ".init", + ".interp", + ".note.ABI-tag", + ".rodata1", + ".rodata", + ".strtab", + ".symtab", + ".text", + ], + 'RAM': [ + ".bss", + ".ctors", + ".data1", + ".data.rel.ro", + ".data", + ".dtors", + ".dynamic", + ".fini_array", + ".got.plt", + ".init_array", + ".jcr", + ".preinit_array", + ".tbss", + ".tdata", + ] + } + }, +} From d8e7e43fec024800a3441762f68123b369c85164 Mon Sep 17 00:00:00 2001 From: Song GUO Date: Tue, 4 Jun 2024 17:53:30 +0000 Subject: [PATCH 02/15] [python] Add ICD support to Python binding (#33533) * [icd] Add ICD support to python * [python] Add ICD support to Python binding * Update * update * update * Update * Use ScopedNodeId in ICD commissioning callbacks * update * fix --- .../commands/pairing/PairingCommand.cpp | 14 +- .../commands/pairing/PairingCommand.h | 4 +- .../commands/pairing/PairingCommand.cpp | 16 +- .../commands/pairing/PairingCommand.h | 4 +- src/controller/CHIPDeviceController.cpp | 10 +- src/controller/DevicePairingDelegate.h | 4 +- .../java/AndroidDeviceControllerWrapper.cpp | 12 +- .../java/AndroidDeviceControllerWrapper.h | 2 +- src/controller/python/BUILD.gn | 3 + .../ChipDeviceController-ScriptBinding.cpp | 88 +++++++++- ...Controller-ScriptDevicePairingDelegate.cpp | 40 +++++ ...ceController-ScriptDevicePairingDelegate.h | 8 +- src/controller/python/OpCredsBinding.cpp | 5 + src/controller/python/chip/ChipDeviceCtrl.py | 163 +++++++++++++++++- src/controller/python/chip/ChipReplStartup.py | 4 +- .../python/chip/icd/PyChipCheckInDelegate.cpp | 33 ++++ .../python/chip/icd/PyChipCheckInDelegate.h | 42 +++++ src/controller/python/chip/internal/types.py | 6 +- 18 files changed, 419 insertions(+), 39 deletions(-) create mode 100644 src/controller/python/chip/icd/PyChipCheckInDelegate.cpp create mode 100644 src/controller/python/chip/icd/PyChipCheckInDelegate.h diff --git a/examples/chip-tool/commands/pairing/PairingCommand.cpp b/examples/chip-tool/commands/pairing/PairingCommand.cpp index 5f6c179779f3c2..76c8ac8a58cc19 100644 --- a/examples/chip-tool/commands/pairing/PairingCommand.cpp +++ b/examples/chip-tool/commands/pairing/PairingCommand.cpp @@ -436,7 +436,7 @@ void PairingCommand::OnReadCommissioningInfo(const Controller::ReadCommissioning info.icd.idleModeDuration, info.icd.activeModeDuration, info.icd.activeModeThreshold); } -void PairingCommand::OnICDRegistrationComplete(NodeId nodeId, uint32_t icdCounter) +void PairingCommand::OnICDRegistrationComplete(ScopedNodeId nodeId, uint32_t icdCounter) { char icdSymmetricKeyHex[chip::Crypto::kAES_CCM128_Key_Length * 2 + 1]; @@ -444,7 +444,7 @@ void PairingCommand::OnICDRegistrationComplete(NodeId nodeId, uint32_t icdCounte sizeof(icdSymmetricKeyHex), chip::Encoding::HexFlags::kNullTerminate); app::ICDClientInfo clientInfo; - clientInfo.peer_node = ScopedNodeId(nodeId, CurrentCommissioner().GetFabricIndex()); + clientInfo.peer_node = nodeId; clientInfo.monitored_subject = mICDMonitoredSubject.Value(); clientInfo.start_icd_counter = icdCounter; @@ -457,7 +457,7 @@ void PairingCommand::OnICDRegistrationComplete(NodeId nodeId, uint32_t icdCounte if (err != CHIP_NO_ERROR) { CHIPCommand::sICDClientStorage.RemoveKey(clientInfo); - ChipLogError(chipTool, "Failed to persist symmetric key for " ChipLogFormatX64 ": %s", ChipLogValueX64(nodeId), + ChipLogError(chipTool, "Failed to persist symmetric key for " ChipLogFormatX64 ": %s", ChipLogValueX64(nodeId.GetNodeId()), err.AsString()); SetCommandExitStatus(err); return; @@ -465,18 +465,18 @@ void PairingCommand::OnICDRegistrationComplete(NodeId nodeId, uint32_t icdCounte mDeviceIsICD = true; - ChipLogProgress(chipTool, "Saved ICD Symmetric key for " ChipLogFormatX64, ChipLogValueX64(nodeId)); + ChipLogProgress(chipTool, "Saved ICD Symmetric key for " ChipLogFormatX64, ChipLogValueX64(nodeId.GetNodeId())); ChipLogProgress(chipTool, "ICD Registration Complete for device " ChipLogFormatX64 " / Check-In NodeID: " ChipLogFormatX64 " / Monitored Subject: " ChipLogFormatX64 " / Symmetric Key: %s / ICDCounter %u", - ChipLogValueX64(nodeId), ChipLogValueX64(mICDCheckInNodeId.Value()), + ChipLogValueX64(nodeId.GetNodeId()), ChipLogValueX64(mICDCheckInNodeId.Value()), ChipLogValueX64(mICDMonitoredSubject.Value()), icdSymmetricKeyHex, icdCounter); } -void PairingCommand::OnICDStayActiveComplete(NodeId deviceId, uint32_t promisedActiveDuration) +void PairingCommand::OnICDStayActiveComplete(ScopedNodeId deviceId, uint32_t promisedActiveDuration) { ChipLogProgress(chipTool, "ICD Stay Active Complete for device " ChipLogFormatX64 " / promisedActiveDuration: %u", - ChipLogValueX64(deviceId), promisedActiveDuration); + ChipLogValueX64(deviceId.GetNodeId()), promisedActiveDuration); } void PairingCommand::OnDiscoveredDevice(const chip::Dnssd::CommissionNodeData & nodeData) diff --git a/examples/chip-tool/commands/pairing/PairingCommand.h b/examples/chip-tool/commands/pairing/PairingCommand.h index 99b0fd0c91882e..aaa8dc714e1017 100644 --- a/examples/chip-tool/commands/pairing/PairingCommand.h +++ b/examples/chip-tool/commands/pairing/PairingCommand.h @@ -197,8 +197,8 @@ class PairingCommand : public CHIPCommand, void OnPairingDeleted(CHIP_ERROR error) override; void OnReadCommissioningInfo(const chip::Controller::ReadCommissioningInfo & info) override; void OnCommissioningComplete(NodeId deviceId, CHIP_ERROR error) override; - void OnICDRegistrationComplete(NodeId deviceId, uint32_t icdCounter) override; - void OnICDStayActiveComplete(NodeId deviceId, uint32_t promisedActiveDuration) override; + void OnICDRegistrationComplete(chip::ScopedNodeId deviceId, uint32_t icdCounter) override; + void OnICDStayActiveComplete(chip::ScopedNodeId deviceId, uint32_t promisedActiveDuration) override; /////////// DeviceDiscoveryDelegate Interface ///////// void OnDiscoveredDevice(const chip::Dnssd::CommissionNodeData & nodeData) override; diff --git a/examples/fabric-admin/commands/pairing/PairingCommand.cpp b/examples/fabric-admin/commands/pairing/PairingCommand.cpp index 379b56431379e4..92754c2adaa69a 100644 --- a/examples/fabric-admin/commands/pairing/PairingCommand.cpp +++ b/examples/fabric-admin/commands/pairing/PairingCommand.cpp @@ -436,7 +436,7 @@ void PairingCommand::OnReadCommissioningInfo(const Controller::ReadCommissioning info.icd.idleModeDuration, info.icd.activeModeDuration, info.icd.activeModeThreshold); } -void PairingCommand::OnICDRegistrationComplete(NodeId nodeId, uint32_t icdCounter) +void PairingCommand::OnICDRegistrationComplete(ScopedNodeId nodeId, uint32_t icdCounter) { char icdSymmetricKeyHex[chip::Crypto::kAES_CCM128_Key_Length * 2 + 1]; @@ -444,7 +444,7 @@ void PairingCommand::OnICDRegistrationComplete(NodeId nodeId, uint32_t icdCounte sizeof(icdSymmetricKeyHex), chip::Encoding::HexFlags::kNullTerminate); app::ICDClientInfo clientInfo; - clientInfo.peer_node = ScopedNodeId(nodeId, CurrentCommissioner().GetFabricIndex()); + clientInfo.peer_node = nodeId; clientInfo.monitored_subject = mICDMonitoredSubject.Value(); clientInfo.start_icd_counter = icdCounter; @@ -457,26 +457,26 @@ void PairingCommand::OnICDRegistrationComplete(NodeId nodeId, uint32_t icdCounte if (err != CHIP_NO_ERROR) { CHIPCommand::sICDClientStorage.RemoveKey(clientInfo); - ChipLogError(NotSpecified, "Failed to persist symmetric key for " ChipLogFormatX64 ": %s", ChipLogValueX64(nodeId), - err.AsString()); + ChipLogError(NotSpecified, "Failed to persist symmetric key for " ChipLogFormatX64 ": %s", + ChipLogValueX64(nodeId.GetNodeId()), err.AsString()); SetCommandExitStatus(err); return; } mDeviceIsICD = true; - ChipLogProgress(NotSpecified, "Saved ICD Symmetric key for " ChipLogFormatX64, ChipLogValueX64(nodeId)); + ChipLogProgress(NotSpecified, "Saved ICD Symmetric key for " ChipLogFormatX64, ChipLogValueX64(nodeId.GetNodeId())); ChipLogProgress(NotSpecified, "ICD Registration Complete for device " ChipLogFormatX64 " / Check-In NodeID: " ChipLogFormatX64 " / Monitored Subject: " ChipLogFormatX64 " / Symmetric Key: %s / ICDCounter %u", - ChipLogValueX64(nodeId), ChipLogValueX64(mICDCheckInNodeId.Value()), + ChipLogValueX64(nodeId.GetNodeId()), ChipLogValueX64(mICDCheckInNodeId.Value()), ChipLogValueX64(mICDMonitoredSubject.Value()), icdSymmetricKeyHex, icdCounter); } -void PairingCommand::OnICDStayActiveComplete(NodeId deviceId, uint32_t promisedActiveDuration) +void PairingCommand::OnICDStayActiveComplete(ScopedNodeId deviceId, uint32_t promisedActiveDuration) { ChipLogProgress(NotSpecified, "ICD Stay Active Complete for device " ChipLogFormatX64 " / promisedActiveDuration: %u", - ChipLogValueX64(deviceId), promisedActiveDuration); + ChipLogValueX64(deviceId.GetNodeId()), promisedActiveDuration); } void PairingCommand::OnDiscoveredDevice(const chip::Dnssd::CommissionNodeData & nodeData) diff --git a/examples/fabric-admin/commands/pairing/PairingCommand.h b/examples/fabric-admin/commands/pairing/PairingCommand.h index 8de34a0ba989ed..331d177448aed5 100644 --- a/examples/fabric-admin/commands/pairing/PairingCommand.h +++ b/examples/fabric-admin/commands/pairing/PairingCommand.h @@ -196,8 +196,8 @@ class PairingCommand : public CHIPCommand, void OnPairingDeleted(CHIP_ERROR error) override; void OnReadCommissioningInfo(const chip::Controller::ReadCommissioningInfo & info) override; void OnCommissioningComplete(NodeId deviceId, CHIP_ERROR error) override; - void OnICDRegistrationComplete(NodeId deviceId, uint32_t icdCounter) override; - void OnICDStayActiveComplete(NodeId deviceId, uint32_t promisedActiveDuration) override; + void OnICDRegistrationComplete(chip::ScopedNodeId deviceId, uint32_t icdCounter) override; + void OnICDStayActiveComplete(chip::ScopedNodeId deviceId, uint32_t promisedActiveDuration) override; /////////// DeviceDiscoveryDelegate Interface ///////// void OnDiscoveredDevice(const chip::Dnssd::CommissionNodeData & nodeData) override; diff --git a/src/controller/CHIPDeviceController.cpp b/src/controller/CHIPDeviceController.cpp index 1381ed3381a649..75c95ee20abc06 100644 --- a/src/controller/CHIPDeviceController.cpp +++ b/src/controller/CHIPDeviceController.cpp @@ -1326,8 +1326,8 @@ void DeviceCommissioner::OnICDManagementRegisterClientResponse( if (commissioner->mPairingDelegate != nullptr) { - commissioner->mPairingDelegate->OnICDRegistrationComplete(commissioner->mDeviceBeingCommissioned->GetDeviceId(), - data.ICDCounter); + commissioner->mPairingDelegate->OnICDRegistrationComplete( + ScopedNodeId(commissioner->mDeviceBeingCommissioned->GetDeviceId(), commissioner->GetFabricIndex()), data.ICDCounter); } exit: @@ -1346,8 +1346,10 @@ void DeviceCommissioner::OnICDManagementStayActiveResponse( if (commissioner->mPairingDelegate != nullptr) { - commissioner->mPairingDelegate->OnICDStayActiveComplete(commissioner->mDeviceBeingCommissioned->GetDeviceId(), - data.promisedActiveDuration); + commissioner->mPairingDelegate->OnICDStayActiveComplete( + + ScopedNodeId(commissioner->mDeviceBeingCommissioned->GetDeviceId(), commissioner->GetFabricIndex()), + data.promisedActiveDuration); } exit: diff --git a/src/controller/DevicePairingDelegate.h b/src/controller/DevicePairingDelegate.h index 558a6c16a6bc2e..849df45436d9e8 100644 --- a/src/controller/DevicePairingDelegate.h +++ b/src/controller/DevicePairingDelegate.h @@ -136,7 +136,7 @@ class DLL_EXPORT DevicePairingDelegate * @param[in] icdNodeId The node id of the ICD. * @param[in] icdCounter The ICD Counter received from the device. */ - virtual void OnICDRegistrationComplete(NodeId icdNodeId, uint32_t icdCounter) {} + virtual void OnICDRegistrationComplete(ScopedNodeId icdNodeId, uint32_t icdCounter) {} /** * @brief @@ -147,7 +147,7 @@ class DLL_EXPORT DevicePairingDelegate * @param[in] promisedActiveDurationMsec The actual duration that the ICD server can stay active * from the time it receives the StayActiveRequest command. */ - virtual void OnICDStayActiveComplete(NodeId icdNodeId, uint32_t promisedActiveDurationMsec) {} + virtual void OnICDStayActiveComplete(ScopedNodeId icdNodeId, uint32_t promisedActiveDurationMsec) {} }; } // namespace Controller diff --git a/src/controller/java/AndroidDeviceControllerWrapper.cpp b/src/controller/java/AndroidDeviceControllerWrapper.cpp index 526f6830844f13..87f53735bcf617 100644 --- a/src/controller/java/AndroidDeviceControllerWrapper.cpp +++ b/src/controller/java/AndroidDeviceControllerWrapper.cpp @@ -994,13 +994,13 @@ void AndroidDeviceControllerWrapper::OnICDRegistrationInfoRequired() env->CallVoidMethod(mJavaObjectRef.ObjectRef(), onICDRegistrationInfoRequiredMethod); } -void AndroidDeviceControllerWrapper::OnICDRegistrationComplete(chip::NodeId icdNodeId, uint32_t icdCounter) +void AndroidDeviceControllerWrapper::OnICDRegistrationComplete(chip::ScopedNodeId icdNodeId, uint32_t icdCounter) { chip::DeviceLayer::StackUnlock unlock; CHIP_ERROR err = CHIP_NO_ERROR; chip::app::ICDClientInfo clientInfo; - clientInfo.peer_node = ScopedNodeId(icdNodeId, Controller()->GetFabricIndex()); + clientInfo.peer_node = icdNodeId; clientInfo.monitored_subject = mAutoCommissioner.GetCommissioningParameters().GetICDMonitoredSubject().Value(); clientInfo.start_icd_counter = icdCounter; @@ -1014,13 +1014,13 @@ void AndroidDeviceControllerWrapper::OnICDRegistrationComplete(chip::NodeId icdN if (err == CHIP_NO_ERROR) { - ChipLogProgress(Controller, "Saved ICD Symmetric key for " ChipLogFormatX64, ChipLogValueX64(icdNodeId)); + ChipLogProgress(Controller, "Saved ICD Symmetric key for " ChipLogFormatX64, ChipLogValueX64(icdNodeId.GetNodeId())); } else { getICDClientStorage()->RemoveKey(clientInfo); - ChipLogError(Controller, "Failed to persist symmetric key for " ChipLogFormatX64 ": %s", ChipLogValueX64(icdNodeId), - err.AsString()); + ChipLogError(Controller, "Failed to persist symmetric key for " ChipLogFormatX64 ": %s", + ChipLogValueX64(icdNodeId.GetNodeId()), err.AsString()); } mDeviceIsICD = true; @@ -1055,7 +1055,7 @@ void AndroidDeviceControllerWrapper::OnICDRegistrationComplete(chip::NodeId icdN icdDeviceInfoObj = env->NewObject( icdDeviceInfoClass, icdDeviceInfoStructCtor, jSymmetricKey, static_cast(mUserActiveModeTriggerHint.Raw()), jUserActiveModeTriggerInstruction, static_cast(mIdleModeDuration), static_cast(mActiveModeDuration), - static_cast(mActiveModeThreshold), static_cast(icdNodeId), static_cast(icdCounter), + static_cast(mActiveModeThreshold), static_cast(icdNodeId.GetNodeId()), static_cast(icdCounter), static_cast(mAutoCommissioner.GetCommissioningParameters().GetICDMonitoredSubject().Value()), static_cast(Controller()->GetFabricId()), static_cast(Controller()->GetFabricIndex())); diff --git a/src/controller/java/AndroidDeviceControllerWrapper.h b/src/controller/java/AndroidDeviceControllerWrapper.h index 1d26d31d112774..02d50499bbbcda 100644 --- a/src/controller/java/AndroidDeviceControllerWrapper.h +++ b/src/controller/java/AndroidDeviceControllerWrapper.h @@ -118,7 +118,7 @@ class AndroidDeviceControllerWrapper : public chip::Controller::DevicePairingDel const chip::app::Clusters::NetworkCommissioning::Commands::ScanNetworksResponse::DecodableType & dataResponse) override; void OnScanNetworksFailure(CHIP_ERROR error) override; void OnICDRegistrationInfoRequired() override; - void OnICDRegistrationComplete(chip::NodeId icdNodeId, uint32_t icdCounter) override; + void OnICDRegistrationComplete(chip::ScopedNodeId icdNodeId, uint32_t icdCounter) override; // PersistentStorageDelegate implementation CHIP_ERROR SyncSetKeyValue(const char * key, const void * value, uint16_t size) override; diff --git a/src/controller/python/BUILD.gn b/src/controller/python/BUILD.gn index 4676f89b362970..9adda770125317 100644 --- a/src/controller/python/BUILD.gn +++ b/src/controller/python/BUILD.gn @@ -76,6 +76,8 @@ shared_library("ChipDeviceCtrl") { "chip/crypto/p256keypair.cpp", "chip/crypto/p256keypair.h", "chip/discovery/NodeResolution.cpp", + "chip/icd/PyChipCheckInDelegate.cpp", + "chip/icd/PyChipCheckInDelegate.h", "chip/interaction_model/Delegate.cpp", "chip/interaction_model/Delegate.h", "chip/internal/ChipThreadWork.cpp", @@ -121,6 +123,7 @@ shared_library("ChipDeviceCtrl") { public_deps = [ "${chip_root}/src/app", + "${chip_root}/src/app/icd/client:handler", "${chip_root}/src/app/server", "${chip_root}/src/credentials:default_attestation_verifier", "${chip_root}/src/lib", diff --git a/src/controller/python/ChipDeviceController-ScriptBinding.cpp b/src/controller/python/ChipDeviceController-ScriptBinding.cpp index 728fd5801f1cb1..821b2a34e03b60 100644 --- a/src/controller/python/ChipDeviceController-ScriptBinding.cpp +++ b/src/controller/python/ChipDeviceController-ScriptBinding.cpp @@ -42,6 +42,9 @@ #include #include +#include +#include +#include #include #include #include @@ -55,7 +58,9 @@ #include #include #include +#include #include +#include #include #include @@ -101,20 +106,24 @@ chip::Platform::ScopedMemoryBuffer sDefaultNTPBuf; app::Clusters::TimeSynchronization::Structs::DSTOffsetStruct::Type sDSTBuf; app::Clusters::TimeSynchronization::Structs::TimeZoneStruct::Type sTimeZoneBuf; chip::Platform::ScopedMemoryBuffer sTimeZoneNameBuf; -chip::Controller::CommissioningParameters sCommissioningParameters; - } // namespace +chip::Controller::CommissioningParameters sCommissioningParameters; +chip::app::DefaultICDClientStorage sICDClientStorage; chip::Controller::ScriptPairingDeviceDiscoveryDelegate sPairingDeviceDiscoveryDelegate; chip::Credentials::GroupDataProviderImpl sGroupDataProvider; chip::Credentials::PersistentStorageOpCertStore sPersistentStorageOpCertStore; chip::Crypto::RawKeySessionKeystore sSessionKeystore; +chip::app::CheckInHandler sCheckInHandler; + // NOTE: Remote device ID is in sync with the echo server device id // At some point, we may want to add an option to connect to a device without // knowing its id, because the ID can be learned on the first response that is received. +chip::Controller::PyChipCheckInDelegate sCheckInDelegate; chip::NodeId kDefaultLocalDeviceId = chip::kTestControllerNodeId; chip::NodeId kRemoteDeviceId = chip::kTestDeviceNodeId; +uint8_t sICDSymmetricKey[chip::Crypto::kAES_CCM128_Key_Length]; extern "C" { PyChipError pychip_DeviceController_StackInit(Controller::Python::StorageAdapter * storageAdapter, bool enableServerInteractions); @@ -126,6 +135,7 @@ PyChipError pychip_DeviceController_GetAddressAndPort(chip::Controller::DeviceCo char * outAddress, uint64_t maxAddressLen, uint16_t * outPort); PyChipError pychip_DeviceController_GetCompressedFabricId(chip::Controller::DeviceCommissioner * devCtrl, uint64_t * outFabricId); PyChipError pychip_DeviceController_GetFabricId(chip::Controller::DeviceCommissioner * devCtrl, uint64_t * outFabricId); +PyChipError pychip_DeviceController_GetFabricIndex(chip::Controller::DeviceCommissioner * devCtrl, uint8_t * outFabricIndex); PyChipError pychip_DeviceController_GetNodeId(chip::Controller::DeviceCommissioner * devCtrl, uint64_t * outNodeId); // Rendezvous @@ -144,6 +154,8 @@ PyChipError pychip_DeviceController_SetDSTOffset(int32_t offset, uint64_t validS PyChipError pychip_DeviceController_SetDefaultNtp(const char * defaultNTP); PyChipError pychip_DeviceController_SetTrustedTimeSource(chip::NodeId nodeId, chip::EndpointId endpoint); PyChipError pychip_DeviceController_SetCheckMatchingFabric(bool check); +struct IcdRegistrationParameters; +PyChipError pychip_DeviceController_SetIcdRegistrationParameters(bool enabled, const IcdRegistrationParameters * params); PyChipError pychip_DeviceController_ResetCommissioningParameters(); PyChipError pychip_DeviceController_CloseSession(chip::Controller::DeviceCommissioner * devCtrl, chip::NodeId nodeid); PyChipError pychip_DeviceController_EstablishPASESessionIP(chip::Controller::DeviceCommissioner * devCtrl, const char * peerAddrStr, @@ -235,6 +247,11 @@ void * pychip_Storage_InitializeStorageAdapter(chip::Controller::Python::PyObjec chip::Controller::Python::SetGetKeyValueCb getCb, chip::Controller::Python::SyncDeleteKeyValueCb deleteCb); void pychip_Storage_ShutdownAdapter(chip::Controller::Python::StorageAdapter * storageAdapter); + +// +// ICD +// +void pychip_CheckInDelegate_SetOnCheckInCompleteCallback(PyChipCheckInDelegate::OnCheckInCompleteCallback * callback); } void * pychip_Storage_InitializeStorageAdapter(chip::Controller::Python::PyObject * context, @@ -260,6 +277,8 @@ PyChipError pychip_DeviceController_StackInit(Controller::Python::StorageAdapter factoryParams.fabricIndependentStorage = storageAdapter; factoryParams.sessionKeystore = &sSessionKeystore; + sICDClientStorage.Init(storageAdapter, &sSessionKeystore); + sGroupDataProvider.SetStorageDelegate(storageAdapter); sGroupDataProvider.SetSessionKeystore(factoryParams.sessionKeystore); PyReturnErrorOnFailure(ToPyChipError(sGroupDataProvider.Init())); @@ -290,6 +309,11 @@ PyChipError pychip_DeviceController_StackInit(Controller::Python::StorageAdapter // DeviceControllerFactory::GetInstance().RetainSystemState(); + auto engine = chip::app::InteractionModelEngine::GetInstance(); + PyReturnErrorOnFailure(ToPyChipError(sCheckInDelegate.Init(&sICDClientStorage, engine))); + PyReturnErrorOnFailure(ToPyChipError(sCheckInHandler.Init( + DeviceControllerFactory::GetInstance().GetSystemState()->ExchangeMgr(), &sICDClientStorage, &sCheckInDelegate, engine))); + // // Finally, start up the main Matter thread. Any further interactions with the stack // will now need to happen on the Matter thread, OR protected with the stack lock. @@ -342,6 +366,12 @@ PyChipError pychip_DeviceController_GetFabricId(chip::Controller::DeviceCommissi return ToPyChipError(CHIP_NO_ERROR); } +PyChipError pychip_DeviceController_GetFabricIndex(chip::Controller::DeviceCommissioner * devCtrl, uint8_t * outFabricIndex) +{ + *outFabricIndex = devCtrl->GetFabricIndex(); + return ToPyChipError(CHIP_NO_ERROR); +} + PyChipError pychip_DeviceController_GetNodeId(chip::Controller::DeviceCommissioner * devCtrl, uint64_t * outNodeId) { *outNodeId = devCtrl->GetNodeId(); @@ -554,6 +584,55 @@ PyChipError pychip_DeviceController_SetCheckMatchingFabric(bool check) return ToPyChipError(CHIP_NO_ERROR); } +struct IcdRegistrationParameters +{ + uint8_t * symmetricKey; + size_t symmetricKeyLength; + uint64_t checkInNodeId; + uint64_t monitoredSubject; + uint32_t stayActiveMsec; +}; + +PyChipError pychip_DeviceController_SetIcdRegistrationParameters(bool enabled, const IcdRegistrationParameters * params) +{ + if (!enabled) + { + sCommissioningParameters.SetICDRegistrationStrategy(ICDRegistrationStrategy::kIgnore); + return ToPyChipError(CHIP_NO_ERROR); + } + + if (params == nullptr) + { + return ToPyChipError(CHIP_ERROR_INVALID_ARGUMENT); + } + + if (params->symmetricKey == nullptr || params->symmetricKeyLength != sizeof(sICDSymmetricKey)) + { + return ToPyChipError(CHIP_ERROR_INVALID_ARGUMENT); + } + + if (params->checkInNodeId == 0) + { + return ToPyChipError(CHIP_ERROR_INVALID_ARGUMENT); + } + if (params->monitoredSubject == 0) + { + return ToPyChipError(CHIP_ERROR_INVALID_ARGUMENT); + } + + memcpy(sICDSymmetricKey, params->symmetricKey, sizeof(sICDSymmetricKey)); + sCommissioningParameters.SetICDSymmetricKey(ByteSpan(sICDSymmetricKey)); + if (params->stayActiveMsec != 0) + { + sCommissioningParameters.SetICDStayActiveDurationMsec(params->stayActiveMsec); + } + sCommissioningParameters.SetICDCheckInNodeId(params->checkInNodeId); + sCommissioningParameters.SetICDMonitoredSubject(params->monitoredSubject); + sCommissioningParameters.SetICDRegistrationStrategy(ICDRegistrationStrategy::kBeforeComplete); + + return ToPyChipError(CHIP_NO_ERROR); +} + PyChipError pychip_DeviceController_ResetCommissioningParameters() { sCommissioningParameters = CommissioningParameters(); @@ -871,3 +950,8 @@ PyChipError pychip_DeviceController_PostTaskOnChipThread(ChipThreadTaskRunnerFun PlatformMgr().ScheduleWork(callback, reinterpret_cast(pythonContext)); return ToPyChipError(CHIP_NO_ERROR); } + +void pychip_CheckInDelegate_SetOnCheckInCompleteCallback(PyChipCheckInDelegate::OnCheckInCompleteCallback * callback) +{ + chip::MainLoopWork::ExecuteInMainLoop([callback]() { sCheckInDelegate.SetOnCheckInCompleteCallback(callback); }); +} diff --git a/src/controller/python/ChipDeviceController-ScriptDevicePairingDelegate.cpp b/src/controller/python/ChipDeviceController-ScriptDevicePairingDelegate.cpp index c1df8125793d02..c979e0d9cd77a3 100644 --- a/src/controller/python/ChipDeviceController-ScriptDevicePairingDelegate.cpp +++ b/src/controller/python/ChipDeviceController-ScriptDevicePairingDelegate.cpp @@ -19,12 +19,17 @@ #include "ChipDeviceController-ScriptDevicePairingDelegate.h" #include "lib/support/TypeTraits.h" +#include #include #include #include #include +extern chip::app::DefaultICDClientStorage sICDClientStorage; +extern chip::Controller::CommissioningParameters sCommissioningParameters; +extern uint8_t sICDSymmetricKey[chip::Crypto::kAES_CCM128_Key_Length]; + namespace chip { namespace Controller { @@ -180,5 +185,40 @@ ScriptDevicePairingDelegate::GetOpenWindowCallback(Controller::CommissioningWind return &mOpenWindowCallback; } +void ScriptDevicePairingDelegate::OnICDRegistrationComplete(ScopedNodeId nodeId, uint32_t icdCounter) +{ + app::ICDClientInfo clientInfo; + clientInfo.peer_node = nodeId; + clientInfo.monitored_subject = sCommissioningParameters.GetICDMonitoredSubject().Value(); + clientInfo.start_icd_counter = icdCounter; + + CHIP_ERROR err = sICDClientStorage.SetKey(clientInfo, ByteSpan(sICDSymmetricKey)); + if (err == CHIP_NO_ERROR) + { + err = sICDClientStorage.StoreEntry(clientInfo); + } + + if (err != CHIP_NO_ERROR) + { + sICDClientStorage.RemoveKey(clientInfo); + ChipLogError(Controller, "Failed to persist symmetric key for " ChipLogFormatX64 ": %s", + ChipLogValueX64(nodeId.GetNodeId()), err.AsString()); + return; + } + + ChipLogProgress(Controller, "Saved ICD Symmetric key for " ChipLogFormatX64, ChipLogValueX64(nodeId.GetNodeId())); + ChipLogProgress(Controller, + "ICD Registration Complete for device " ChipLogFormatX64 " / Check-In NodeID: " ChipLogFormatX64 + " / Monitored Subject: " ChipLogFormatX64 " / ICDCounter %u", + ChipLogValueX64(nodeId.GetNodeId()), ChipLogValueX64(sCommissioningParameters.GetICDCheckInNodeId().Value()), + ChipLogValueX64(clientInfo.monitored_subject), icdCounter); +} + +void ScriptDevicePairingDelegate::OnICDStayActiveComplete(ScopedNodeId deviceId, uint32_t promisedActiveDuration) +{ + ChipLogProgress(Controller, "ICD Stay Active Complete for device " ChipLogFormatX64 " / promisedActiveDuration: %u", + ChipLogValueX64(deviceId.GetNodeId()), promisedActiveDuration); +} + } // namespace Controller } // namespace chip diff --git a/src/controller/python/ChipDeviceController-ScriptDevicePairingDelegate.h b/src/controller/python/ChipDeviceController-ScriptDevicePairingDelegate.h index 2740b6eb85e983..d6665f8fb2baba 100644 --- a/src/controller/python/ChipDeviceController-ScriptDevicePairingDelegate.h +++ b/src/controller/python/ChipDeviceController-ScriptDevicePairingDelegate.h @@ -27,6 +27,7 @@ #include #include +#include #include namespace chip { @@ -68,11 +69,14 @@ class ScriptDevicePairingDelegate final : public Controller::DevicePairingDelega void OnCommissioningFailure(PeerId peerId, CHIP_ERROR error, CommissioningStage stageFailed, Optional additionalErrorInfo) override; void OnCommissioningStatusUpdate(PeerId peerId, CommissioningStage stageCompleted, CHIP_ERROR error) override; + void OnICDRegistrationComplete(ScopedNodeId deviceId, uint32_t icdCounter) override; + void OnICDStayActiveComplete(ScopedNodeId deviceId, uint32_t promisedActiveDuration) override; void OnFabricCheck(NodeId matchingNodeId) override; Callback::Callback * GetOpenWindowCallback(Controller::CommissioningWindowOpener * context); void OnOpenCommissioningWindow(NodeId deviceId, CHIP_ERROR status, SetupPayload payload); void SetExpectingPairingComplete(bool value) { expectingPairingComplete = value; } + void SetFabricIndex(FabricIndex fabricIndex) { mFabricIndex = fabricIndex; } private: DevicePairingDelegate_OnPairingCompleteFunct mOnPairingCompleteCallback = nullptr; @@ -84,7 +88,9 @@ class ScriptDevicePairingDelegate final : public Controller::DevicePairingDelega DevicePairingDelegate_OnFabricCheckFunct mOnFabricCheckCallback = nullptr; Callback::Callback mOpenWindowCallback; Controller::CommissioningWindowOpener * mWindowOpener = nullptr; - bool expectingPairingComplete = false; + + bool expectingPairingComplete = false; + FabricIndex mFabricIndex = 0; }; } // namespace Controller diff --git a/src/controller/python/OpCredsBinding.cpp b/src/controller/python/OpCredsBinding.cpp index 5fd4205d4c7ce7..427ee9be46ba3c 100644 --- a/src/controller/python/OpCredsBinding.cpp +++ b/src/controller/python/OpCredsBinding.cpp @@ -26,6 +26,7 @@ #include "controller/python/chip/crypto/p256keypair.h" #include "controller/python/chip/interaction_model/Delegate.h" +#include #include #include #include @@ -104,6 +105,7 @@ class OperationalCredentialsAdapter : public OperationalCredentialsDelegate extern chip::Credentials::GroupDataProviderImpl sGroupDataProvider; extern chip::Controller::ScriptDevicePairingDelegate sPairingDelegate; +extern chip::app::DefaultICDClientStorage sICDClientStorage; class TestCommissioner : public chip::Controller::AutoCommissioner { @@ -569,6 +571,9 @@ PyChipError pychip_OpCreds_AllocateController(OpCredsContext * context, chip::Co chip::Credentials::SetSingleIpkEpochKey(&sGroupDataProvider, devCtrl->GetFabricIndex(), defaultIpk, compressedFabricIdSpan); VerifyOrReturnError(err == CHIP_NO_ERROR, ToPyChipError(err)); + sICDClientStorage.UpdateFabricList(devCtrl->GetFabricIndex()); + pairingDelegate->SetFabricIndex(devCtrl->GetFabricIndex()); + *outDevCtrl = devCtrl.release(); *outPairingDelegate = pairingDelegate.release(); diff --git a/src/controller/python/chip/ChipDeviceCtrl.py b/src/controller/python/chip/ChipDeviceCtrl.py index 4fb8fb28bcaf90..2ba7c584db927b 100644 --- a/src/controller/python/chip/ChipDeviceCtrl.py +++ b/src/controller/python/chip/ChipDeviceCtrl.py @@ -35,11 +35,12 @@ import enum import json import logging +import secrets import threading import time import typing -from ctypes import (CDLL, CFUNCTYPE, POINTER, byref, c_bool, c_char, c_char_p, c_int, c_int32, c_size_t, c_uint8, c_uint16, - c_uint32, c_uint64, c_void_p, create_string_buffer, pointer, py_object, resize, string_at) +from ctypes import (CDLL, CFUNCTYPE, POINTER, Structure, byref, c_bool, c_char, c_char_p, c_int, c_int32, c_size_t, c_uint8, + c_uint16, c_uint32, c_uint64, c_void_p, create_string_buffer, pointer, py_object, resize, string_at) from dataclasses import dataclass import dacite @@ -98,6 +99,21 @@ class NOCChain: adminSubject: int +@dataclass +class ICDRegistrationParameters: + symmetricKey: typing.Optional[bytes] + checkInNodeId: typing.Optional[int] + monitoredSubject: typing.Optional[int] + stayActiveMs: typing.Optional[int] + + class CStruct(Structure): + _fields_ = [('symmetricKey', c_char_p), ('symmetricKeyLength', c_size_t), ('checkInNodeId', + c_uint64), ('monitoredSubject', c_uint64), ('stayActiveMsec', c_uint32)] + + def to_c(self): + return ICDRegistrationParameters.CStruct(self.symmetricKey, len(self.symmetricKey), self.checkInNodeId, self.monitoredSubject, self.stayActiveMs) + + @_DeviceAvailableCallbackFunct def _DeviceAvailableCallback(closure, device, err): closure.deviceAvailable(device, err) @@ -123,6 +139,77 @@ def _IssueNOCChainCallbackPythonCallback(devCtrl, status: PyChipError, noc: c_vo nocChain = NOCChain(nocBytes, icacBytes, rcacBytes, ipkBytes, adminSubject) devCtrl.NOCChainCallback(nocChain) + +# Methods for ICD +class ScopedNodeId(Structure): + _fields_ = [("nodeId", c_uint64), ("fabricIndex", c_uint8)] + + def __hash__(self): + return self.nodeId << 8 | self.fabricIndex + + def __str__(self): + return f"({self.fabricIndex}:{self.nodeId:16x})" + + def __eq__(self, other): + return self.nodeId == other.nodeId and self.fabricIndex == other.fabricIndex + + +_OnCheckInCompleteFunct = CFUNCTYPE(None, ScopedNodeId) + +_OnCheckInCompleteWaitListLock = threading.Lock() +_OnCheckInCompleteWaitList = dict() + + +@_OnCheckInCompleteFunct +def _OnCheckInComplete(scopedNodeId: ScopedNodeId): + callbacks = [] + with _OnCheckInCompleteWaitListLock: + callbacks = list(_OnCheckInCompleteWaitList.get(scopedNodeId, set())) + + for callback in callbacks: + callback(scopedNodeId) + + +def RegisterOnActiveCallback(scopedNodeId: ScopedNodeId, callback: typing.Callable[None, [ScopedNodeId]]): + ''' Registers a callback when the device with given (fabric index, node id) becomes active. + + Does nothing if the callback is already registered. + ''' + with _OnCheckInCompleteWaitListLock: + waitList = _OnCheckInCompleteWaitList.get(scopedNodeId, set()) + waitList.add(callback) + _OnCheckInCompleteWaitList[scopedNodeId] = waitList + + +def UnregisterOnActiveCallback(scopedNodeId: ScopedNodeId, callback: typing.Callable[None, [ScopedNodeId]]): + ''' Unregisters a callback when the device with given (fabric index, node id) becomes active. + + Does nothing if the callback has not been registered. + ''' + with _OnCheckInCompleteWaitListLock: + _OnCheckInCompleteWaitList.get(scopedNodeId, set()).remove(callback) + + +async def WaitForCheckIn(scopedNodeId: ScopedNodeId, timeoutSeconds: float): + ''' Waits for a device becomes active. + + Returns: + - A future, completes when the device becomes active. + ''' + eventLoop = asyncio.get_running_loop() + future = eventLoop.create_future() + + def OnCheckInCallback(nodeid): + eventLoop.call_soon_threadsafe(lambda: future.done() or future.set_result(None)) + + RegisterOnActiveCallback(scopedNodeId, OnCheckInCallback) + + try: + async with asyncio.timeout(timeoutSeconds): + await future + finally: + UnregisterOnActiveCallback(scopedNodeId, OnCheckInCallback) + # This is a fix for WEAV-429. Jay Logue recommends revisiting this at a later # date to allow for truly multiple instances so this is temporary. @@ -269,6 +356,7 @@ def HandleCommissioningComplete(nodeid, err): else: logging.warning("Failed to commission: {}".format(err)) + self._dmLib.pychip_DeviceController_SetIcdRegistrationParameters(False, None) self.state = DCState.IDLE self._ChipStack.callbackRes = err self._ChipStack.commissioningEventRes = err @@ -347,6 +435,7 @@ def HandlePASEEstablishmentComplete(err: PyChipError): self._isActive = True # Validate FabricID/NodeID followed from NOC Chain self._fabricId = self.GetFabricIdInternal() + self._fabricIndex = self.GetFabricIndexInternal() self._nodeId = self.GetNodeIdInternal() def _finish_init(self): @@ -766,6 +855,19 @@ def GetFabricIdInternal(self): return fabricid.value + def GetFabricIndexInternal(self): + """Get the fabric index from the object. Only used to validate cached value from property.""" + self.CheckIsActive() + + fabricindex = c_uint8(0) + + self._ChipStack.Call( + lambda: self._dmLib.pychip_DeviceController_GetFabricIndex( + self.devCtrl, pointer(fabricindex)) + ).raise_on_error() + + return fabricindex.value + def GetNodeIdInternal(self) -> int: """Get the node ID from the object. Only used to validate cached value from property.""" self.CheckIsActive() @@ -841,6 +943,18 @@ def deviceAvailable(self, device, err): return DeviceProxyWrapper(returnDevice, self._dmLib) + async def WaitForActive(self, nodeid, *, timeoutSeconds=30.0, stayActiveDurationMs=30000): + ''' Waits a LIT ICD device to become active. Will send a StayActive command to the device on active to allow human operations. + + nodeId: Node ID of the LID ICD + stayActiveDurationMs: The duration in the StayActive command, in milliseconds + + Returns: + - StayActiveResponse on success + ''' + await WaitForCheckIn(ScopedNodeId(nodeid, self._fabricIndex), timeoutSeconds=timeoutSeconds) + return await self.SendCommand(nodeid, 0, Clusters.IcdManagement.Commands.StayActiveRequest(stayActiveDuration=stayActiveDurationMs)) + async def GetConnectedDevice(self, nodeid, allowPASE: bool = True, timeoutMs: int = None): ''' Gets an OperationalDeviceProxy or CommissioneeDeviceProxy for the specified Node. @@ -1536,6 +1650,11 @@ def _InitLib(self): self._dmLib.pychip_DeviceController_SetCheckMatchingFabric.restype = PyChipError self._dmLib.pychip_DeviceController_SetCheckMatchingFabric.argtypes = [c_bool] + self._dmLib.pychip_DeviceController_SetIcdRegistrationParameters.restype = PyChipError + self._dmLib.pychip_DeviceController_SetIcdRegistrationParameters.argtypes = [ + c_bool, c_void_p + ] + self._dmLib.pychip_DeviceController_ResetCommissioningParameters.restype = PyChipError self._dmLib.pychip_DeviceController_ResetCommissioningParameters.argtypes = [] @@ -1722,6 +1841,9 @@ def _InitLib(self): self._dmLib.pychip_DeviceController_GetFabricId.argtypes = [c_void_p, POINTER(c_uint64)] self._dmLib.pychip_DeviceController_GetFabricId.restype = PyChipError + self._dmLib.pychip_DeviceController_GetFabricIndex.argtypes = [c_void_p, POINTER(c_uint8)] + self._dmLib.pychip_DeviceController_GetFabricIndex.restype = PyChipError + self._dmLib.pychip_DeviceController_GetLogFilter = [None] self._dmLib.pychip_DeviceController_GetLogFilter = c_uint8 @@ -1736,6 +1858,11 @@ def _InitLib(self): self._dmLib.pychip_DeviceController_SetIpk.argtypes = [c_void_p, POINTER(c_char), c_size_t] self._dmLib.pychip_DeviceController_SetIpk.restype = PyChipError + self._dmLib.pychip_CheckInDelegate_SetOnCheckInCompleteCallback.restype = None + self._dmLib.pychip_CheckInDelegate_SetOnCheckInCompleteCallback.argtypes = [_OnCheckInCompleteFunct] + + self._dmLib.pychip_CheckInDelegate_SetOnCheckInCompleteCallback(_OnCheckInComplete) + class ChipDeviceController(ChipDeviceControllerBase): ''' The ChipDeviceCommissioner binding, named as ChipDeviceController @@ -1884,6 +2011,38 @@ def SetCheckMatchingFabric(self, check: bool): lambda: self._dmLib.pychip_DeviceController_SetCheckMatchingFabric(check) ).raise_on_error() + def GenerateICDRegistrationParameters(self): + ''' Generates ICD registration parameters for this controller. ''' + return ICDRegistrationParameters( + secrets.token_bytes(16), + self._nodeId, + self._nodeId, + 30) + + def EnableICDRegistration(self, parameters: ICDRegistrationParameters): + ''' Enables ICD registration for the following commissioning session. + + Args: + parameters: A ICDRegistrationParameters for the parameters used for ICD registration, or None for default arguments. + ''' + if parameters is None: + raise ValueError("ICD registration parameter required.") + if len(parameters.symmetricKey) != 16: + raise ValueError("symmetricKey should be 16 bytes") + + self.CheckIsActive() + self._ChipStack.Call( + lambda: self._dmLib.pychip_DeviceController_SetIcdRegistrationParameters( + True, pointer(parameters.to_c())) + ).raise_on_error() + + def DisableICDRegistration(self): + ''' Disables ICD registration. ''' + self.CheckIsActive() + self._ChipStack.Call( + lambda: self._dmLib.pychip_DeviceController_SetIcdRegistrationParameters(False, None) + ).raise_on_error() + def GetFabricCheckResult(self) -> int: ''' Returns the fabric check result if SetCheckMatchingFabric was used.''' return self.fabricCheckNodeId diff --git a/src/controller/python/chip/ChipReplStartup.py b/src/controller/python/chip/ChipReplStartup.py index b75c77efcd5b2b..13a93a1efb453b 100644 --- a/src/controller/python/chip/ChipReplStartup.py +++ b/src/controller/python/chip/ChipReplStartup.py @@ -96,6 +96,8 @@ def main(): "-t", "--trust-store", help="Path to the PAA trust store.", action="store", default="./credentials/development/paa-root-certs") parser.add_argument( "-b", "--ble-adapter", help="Set the Bluetooth adapter index.", type=int, default=None) + parser.add_argument( + "-s", "--server-interactions", help="Enable server interactions.", action="store_true") args = parser.parse_args() if not os.path.exists(args.trust_store): @@ -139,7 +141,7 @@ def main(): ReplInit(args.debug) - chipStack = ChipStack(persistentStoragePath=args.storagepath, enableServerInteractions=False) + chipStack = ChipStack(persistentStoragePath=args.storagepath, enableServerInteractions=args.server_interactions) certificateAuthorityManager = chip.CertificateAuthority.CertificateAuthorityManager(chipStack, chipStack.GetStorageManager()) certificateAuthorityManager.LoadAuthoritiesFromStorage() diff --git a/src/controller/python/chip/icd/PyChipCheckInDelegate.cpp b/src/controller/python/chip/icd/PyChipCheckInDelegate.cpp new file mode 100644 index 00000000000000..03f6b7de1003e6 --- /dev/null +++ b/src/controller/python/chip/icd/PyChipCheckInDelegate.cpp @@ -0,0 +1,33 @@ +/* + * + * Copyright (c) 2024 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "PyChipCheckInDelegate.h" + +using namespace ::chip; +using namespace ::chip::app; +using namespace ::chip::Controller; + +void PyChipCheckInDelegate::OnCheckInComplete(const ICDClientInfo & clientInfo) +{ + DefaultCheckInDelegate::OnCheckInComplete(clientInfo); + + if (mCallback != nullptr) + { + mCallback(clientInfo.peer_node); + } +} diff --git a/src/controller/python/chip/icd/PyChipCheckInDelegate.h b/src/controller/python/chip/icd/PyChipCheckInDelegate.h new file mode 100644 index 00000000000000..3e3a3d9871af24 --- /dev/null +++ b/src/controller/python/chip/icd/PyChipCheckInDelegate.h @@ -0,0 +1,42 @@ +/* + * + * Copyright (c) 2024 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include + +namespace chip { +namespace Controller { + +class PyChipCheckInDelegate : public chip::app::DefaultCheckInDelegate +{ +public: + using OnCheckInCompleteCallback = void(chip::ScopedNodeId); + + virtual ~PyChipCheckInDelegate() = default; + + void OnCheckInComplete(const chip::app::ICDClientInfo & clientInfo) override; + + void SetOnCheckInCompleteCallback(OnCheckInCompleteCallback * callback) { mCallback = callback; } + +private: + OnCheckInCompleteCallback * mCallback; +}; + +} // namespace Controller +} // namespace chip diff --git a/src/controller/python/chip/internal/types.py b/src/controller/python/chip/internal/types.py index 190456969b2006..34c14737a47ff7 100644 --- a/src/controller/python/chip/internal/types.py +++ b/src/controller/python/chip/internal/types.py @@ -14,7 +14,7 @@ # limitations under the License. # -from ctypes import CFUNCTYPE, c_size_t, c_uint32, c_void_p +from ctypes import CFUNCTYPE, Structure, c_size_t, c_uint32, c_uint64, c_void_p # General callback of 'network credentials requested. No python-data # is available as the underlying callback is used internally @@ -26,3 +26,7 @@ # Notification that pairing has been coompleted PairingComplete = CFUNCTYPE(None, c_uint32) + + +class ScopedNodeId(Structure): + _fields_ = [("node_id", c_uint64), ("fabric_index", "c_uint8")] From 405a083d1235e84e033de269d4bddbcf0a472b9a Mon Sep 17 00:00:00 2001 From: joonhaengHeo <85541460+joonhaengHeo@users.noreply.github.com> Date: Wed, 5 Jun 2024 04:36:01 +0900 Subject: [PATCH 03/15] Add Compare IPAddress in OndiscoveredNode (#33583) * Add Compare IPAddress in discoveredNode * Restyled by clang-format * Fix function name, pointer -> array * Restyled by clang-format * Modify from comment * Restyled by clang-format * Update from comments * Update src/controller/AbstractDnssdDiscoveryController.cpp Co-authored-by: Andrei Litvin --------- Co-authored-by: Restyled.io Co-authored-by: yunhanw-google Co-authored-by: Andrei Litvin --- .../AbstractDnssdDiscoveryController.cpp | 33 +++++- .../TestCommissionableNodeController.cpp | 101 ++++++++++++++++++ 2 files changed, 131 insertions(+), 3 deletions(-) diff --git a/src/controller/AbstractDnssdDiscoveryController.cpp b/src/controller/AbstractDnssdDiscoveryController.cpp index 3d3ca4c8097955..9d59e2dfdbca03 100644 --- a/src/controller/AbstractDnssdDiscoveryController.cpp +++ b/src/controller/AbstractDnssdDiscoveryController.cpp @@ -22,9 +22,36 @@ #include #include +#include + namespace chip { namespace Controller { +static bool SameExceptOrder(const chip::Span & v1, const chip::Span & v2) +{ + std::bitset addressUsed; + + VerifyOrDie(v1.size() <= Dnssd::CommissionNodeData::kMaxIPAddresses && v2.size() <= Dnssd::CommissionNodeData::kMaxIPAddresses); + if (v1.size() != v2.size()) + { + return false; + } + + for (size_t s = 0; s < v1.size(); s++) + { + for (size_t d = 0; d < v2.size(); d++) + { + if (!addressUsed[d] && v1[s] == v2[d]) + { + // Change the used flag so that the compared target is no longer used + addressUsed.set(d, true); + break; + } + } + } + return addressUsed.count() == v2.size(); +} + void AbstractDnssdDiscoveryController::OnNodeDiscovered(const chip::Dnssd::DiscoveredNodeData & discNodeData) { VerifyOrReturn(discNodeData.Is()); @@ -38,10 +65,10 @@ void AbstractDnssdDiscoveryController::OnNodeDiscovered(const chip::Dnssd::Disco { continue; } - // TODO(#32576) Check if IP address are the same. Must account for `numIPs` in the list of `ipAddress`. - // Additionally, must NOT assume that the ordering is consistent. + chip::Span discoveredNodeIPAddressSpan(&discoveredNode.ipAddress[0], discoveredNode.numIPs); + chip::Span nodeDataIPAddressSpan(&nodeData.ipAddress[0], nodeData.numIPs); if (strcmp(discoveredNode.hostName, nodeData.hostName) == 0 && discoveredNode.port == nodeData.port && - discoveredNode.numIPs == nodeData.numIPs) + SameExceptOrder(discoveredNodeIPAddressSpan, nodeDataIPAddressSpan)) { discoveredNode = nodeData; if (mDeviceDiscoveryDelegate != nullptr) diff --git a/src/controller/tests/TestCommissionableNodeController.cpp b/src/controller/tests/TestCommissionableNodeController.cpp index b68d0748d62c42..6d9ef65db11e97 100644 --- a/src/controller/tests/TestCommissionableNodeController.cpp +++ b/src/controller/tests/TestCommissionableNodeController.cpp @@ -182,4 +182,105 @@ TEST_F(TestCommissionableNodeController, TestDiscoverCommissioners_DiscoverCommi EXPECT_NE(controller.DiscoverCommissioners(), CHIP_NO_ERROR); } +TEST_F(TestCommissionableNodeController, TestGetDiscoveredCommissioner_MultipleIPAddressDiscover) +{ + MockResolver resolver; + CommissionableNodeController controller(&resolver); + + // example 1 + chip::Dnssd::DiscoveredNodeData discNodeData1; + discNodeData1.Set(); + chip::Dnssd::CommissionNodeData & inNodeData1 = discNodeData1.Get(); + Platform::CopyString(inNodeData1.hostName, "mockHostName"); + Inet::IPAddress::FromString("fd11:1111:1122:2222:1111:2222:3333:4444", inNodeData1.ipAddress[0]); + inNodeData1.numIPs++; + Inet::IPAddress::FromString("fd11:1111:1122:2222:2222:3333:4444:5555", inNodeData1.ipAddress[1]); + inNodeData1.numIPs++; + inNodeData1.port = 5540; + + controller.OnNodeDiscovered(discNodeData1); + + // example 5 - exactly same as example 1 + chip::Dnssd::DiscoveredNodeData discNodeData5; + discNodeData5.Set(); + chip::Dnssd::CommissionNodeData & inNodeData5 = discNodeData5.Get(); + Platform::CopyString(inNodeData1.hostName, "mockHostName"); + Inet::IPAddress::FromString("fd11:1111:1122:2222:1111:2222:3333:4444", inNodeData5.ipAddress[0]); + inNodeData5.numIPs++; + Inet::IPAddress::FromString("fd11:1111:1122:2222:2222:3333:4444:5555", inNodeData5.ipAddress[1]); + inNodeData5.numIPs++; + inNodeData5.port = 5540; + + controller.OnNodeDiscovered(discNodeData5); + + // example 2 - same as example 1 (IPAdress sequence is only different.) + chip::Dnssd::DiscoveredNodeData discNodeData2; + discNodeData2.Set(); + chip::Dnssd::CommissionNodeData & inNodeData2 = discNodeData2.Get(); + Platform::CopyString(inNodeData2.hostName, "mockHostName"); + Inet::IPAddress::FromString("fd11:1111:1122:2222:2222:3333:4444:5555", inNodeData2.ipAddress[0]); + inNodeData2.numIPs++; + Inet::IPAddress::FromString("fd11:1111:1122:2222:1111:2222:3333:4444", inNodeData2.ipAddress[1]); + inNodeData2.numIPs++; + inNodeData2.port = 5540; + + controller.OnNodeDiscovered(discNodeData2); + + // example 3 - different example + chip::Dnssd::DiscoveredNodeData discNodeData3; + discNodeData3.Set(); + chip::Dnssd::CommissionNodeData & inNodeData3 = discNodeData3.Get(); + Platform::CopyString(inNodeData3.hostName, "mockHostName"); + Inet::IPAddress::FromString("fd11:1111:1122:2222:1111:2222:3333:4444", inNodeData3.ipAddress[0]); + inNodeData3.numIPs++; + Inet::IPAddress::FromString("fd11:1111:1122:2222:2222:3333:4444:6666", inNodeData3.ipAddress[1]); + inNodeData3.numIPs++; + inNodeData3.port = 5540; + + controller.OnNodeDiscovered(discNodeData3); + + // example 4 - different example (Different IP count) + chip::Dnssd::DiscoveredNodeData discNodeData4; + discNodeData4.Set(); + chip::Dnssd::CommissionNodeData & inNodeData4 = discNodeData4.Get(); + Platform::CopyString(inNodeData4.hostName, "mockHostName"); + Inet::IPAddress::FromString("fd11:1111:1122:2222:1111:2222:3333:4444", inNodeData4.ipAddress[0]); + inNodeData4.numIPs++; + Inet::IPAddress::FromString("fd11:1111:1122:2222:2222:3333:4444:6666", inNodeData4.ipAddress[1]); + inNodeData4.numIPs++; + Inet::IPAddress::FromString("fd11:1111:1122:2222:2222:3333:4444:7777", inNodeData4.ipAddress[2]); + inNodeData4.numIPs++; + inNodeData4.port = 5540; + + controller.OnNodeDiscovered(discNodeData4); + + // Example 2 result - example 1 is removed. (reason : duplicate) + ASSERT_NE(controller.GetDiscoveredCommissioner(0), nullptr); + EXPECT_STREQ(inNodeData1.hostName, controller.GetDiscoveredCommissioner(0)->hostName); + EXPECT_EQ(inNodeData2.ipAddress[0], controller.GetDiscoveredCommissioner(0)->ipAddress[0]); + EXPECT_EQ(inNodeData2.ipAddress[1], controller.GetDiscoveredCommissioner(0)->ipAddress[1]); + EXPECT_EQ(controller.GetDiscoveredCommissioner(0)->port, 5540); + EXPECT_EQ(controller.GetDiscoveredCommissioner(0)->numIPs, 2u); + + // Example 3 result + ASSERT_NE(controller.GetDiscoveredCommissioner(1), nullptr); + EXPECT_STREQ(inNodeData3.hostName, controller.GetDiscoveredCommissioner(1)->hostName); + EXPECT_EQ(inNodeData3.ipAddress[0], controller.GetDiscoveredCommissioner(1)->ipAddress[0]); + EXPECT_EQ(inNodeData3.ipAddress[1], controller.GetDiscoveredCommissioner(1)->ipAddress[1]); + EXPECT_EQ(controller.GetDiscoveredCommissioner(1)->port, 5540); + EXPECT_EQ(controller.GetDiscoveredCommissioner(1)->numIPs, 2u); + + // Example 4 result + ASSERT_NE(controller.GetDiscoveredCommissioner(2), nullptr); + EXPECT_STREQ(inNodeData4.hostName, controller.GetDiscoveredCommissioner(2)->hostName); + EXPECT_EQ(inNodeData4.ipAddress[0], controller.GetDiscoveredCommissioner(2)->ipAddress[0]); + EXPECT_EQ(inNodeData4.ipAddress[1], controller.GetDiscoveredCommissioner(2)->ipAddress[1]); + EXPECT_EQ(inNodeData4.ipAddress[2], controller.GetDiscoveredCommissioner(2)->ipAddress[2]); + EXPECT_EQ(controller.GetDiscoveredCommissioner(2)->port, 5540); + EXPECT_EQ(controller.GetDiscoveredCommissioner(2)->numIPs, 3u); + + // Total is 3. (Not 4) + ASSERT_EQ(controller.GetDiscoveredCommissioner(3), nullptr); +} + } // namespace From ef280569ad8c60ee1a58acba4a090479cce3bd0b Mon Sep 17 00:00:00 2001 From: yunhanw-google Date: Tue, 4 Jun 2024 12:51:33 -0700 Subject: [PATCH 04/15] [chip-tool][ICD] Store ICDClientInfo when running icd registration independently (#33690) * Store ICDClientInfo when running icd registration independently * Restyled by clang-format * address comments --------- Co-authored-by: Restyled.io --- .../commands/clusters/ClusterCommand.h | 39 +++++++++++++++++-- .../commands/clusters/ModelCommand.cpp | 18 ++++++++- .../commands/clusters/ModelCommand.h | 4 +- .../commands/clusters/ModelCommand.cpp | 7 +++- 4 files changed, 61 insertions(+), 7 deletions(-) diff --git a/examples/chip-tool/commands/clusters/ClusterCommand.h b/examples/chip-tool/commands/clusters/ClusterCommand.h index 171c664481c9dd..fe20f4f36b9f84 100644 --- a/examples/chip-tool/commands/clusters/ClusterCommand.h +++ b/examples/chip-tool/commands/clusters/ClusterCommand.h @@ -18,10 +18,9 @@ #pragma once -#include - #include "DataModelLogger.h" #include "ModelCommand.h" +#include class ClusterCommand : public InteractionModelCommands, public ModelCommand, public chip::app::CommandSender::Callback { @@ -64,6 +63,17 @@ class ClusterCommand : public InteractionModelCommands, public ModelCommand, pub return CHIP_NO_ERROR; } + CHIP_ERROR SendCommand(chip::DeviceProxy * device, chip::EndpointId endpointId, chip::ClusterId clusterId, + chip::CommandId commandId, + const chip::app::Clusters::IcdManagement::Commands::RegisterClient::Type & value) + { + ReturnErrorOnFailure(InteractionModelCommands::SendCommand(device, endpointId, clusterId, commandId, value)); + mScopedNodeId = chip::ScopedNodeId(value.checkInNodeID, device->GetSecureSession().Value()->GetFabricIndex()); + mMonitoredSubject = value.monitoredSubject; + memcpy(mICDSymmetricKey, value.key.data(), value.key.size()); + return CHIP_NO_ERROR; + } + CHIP_ERROR SendCommand(chip::DeviceProxy * device, chip::EndpointId endpointId, chip::ClusterId clusterId, chip::CommandId commandId, const chip::app::Clusters::DiagnosticLogs::Commands::RetrieveLogsRequest::Type & value) @@ -117,11 +127,32 @@ class ClusterCommand : public InteractionModelCommands, public ModelCommand, pub mError = error; return; } + if ((path.mEndpointId == chip::kRootEndpointId) && (path.mClusterId == chip::app::Clusters::IcdManagement::Id) && + (path.mCommandId == chip::app::Clusters::IcdManagement::Commands::RegisterClient::Id)) + { + chip::TLV::TLVReader counterTlvReader; + counterTlvReader.Init(*data); + chip::app::Clusters::IcdManagement::Commands::RegisterClientResponse::DecodableType value; + CHIP_ERROR err = chip::app::DataModel::Decode(counterTlvReader, value); + if (CHIP_NO_ERROR != err) + { + ChipLogError(chipTool, "Failed to decode ICD counter: %" CHIP_ERROR_FORMAT, err.Format()); + return; + } + + chip::app::ICDClientInfo clientInfo; + clientInfo.peer_node = mScopedNodeId; + clientInfo.monitored_subject = mMonitoredSubject; + clientInfo.start_icd_counter = value.ICDCounter; + + StoreICDEntryWithKey(clientInfo, chip::ByteSpan(mICDSymmetricKey)); + } } + if ((path.mEndpointId == chip::kRootEndpointId) && (path.mClusterId == chip::app::Clusters::IcdManagement::Id) && (path.mCommandId == chip::app::Clusters::IcdManagement::Commands::UnregisterClient::Id)) { - ModelCommand::ClearICDEntry(mScopedNodeId); + ClearICDEntry(mScopedNodeId); } } @@ -223,6 +254,8 @@ class ClusterCommand : public InteractionModelCommands, public ModelCommand, pub chip::ClusterId mClusterId; chip::CommandId mCommandId; chip::ScopedNodeId mScopedNodeId; + uint64_t mMonitoredSubject = static_cast(0); + uint8_t mICDSymmetricKey[chip::Crypto::kAES_CCM128_Key_Length]; CHIP_ERROR mError = CHIP_NO_ERROR; CustomArgument mPayload; }; diff --git a/examples/chip-tool/commands/clusters/ModelCommand.cpp b/examples/chip-tool/commands/clusters/ModelCommand.cpp index 2a549e62d4668b..b2e3b5616703a4 100644 --- a/examples/chip-tool/commands/clusters/ModelCommand.cpp +++ b/examples/chip-tool/commands/clusters/ModelCommand.cpp @@ -76,7 +76,7 @@ void ModelCommand::Shutdown() CHIPCommand::Shutdown(); } -void ModelCommand::ClearICDEntry(const chip::ScopedNodeId & nodeId) +void ModelCommand::ClearICDEntry(const ScopedNodeId & nodeId) { CHIP_ERROR deleteEntryError = CHIPCommand::sICDClientStorage.DeleteEntry(nodeId); if (deleteEntryError != CHIP_NO_ERROR) @@ -85,6 +85,22 @@ void ModelCommand::ClearICDEntry(const chip::ScopedNodeId & nodeId) } } +void ModelCommand::StoreICDEntryWithKey(app::ICDClientInfo & clientInfo, ByteSpan key) +{ + CHIP_ERROR err = CHIPCommand::sICDClientStorage.SetKey(clientInfo, key); + if (err == CHIP_NO_ERROR) + { + err = CHIPCommand::sICDClientStorage.StoreEntry(clientInfo); + } + + if (err != CHIP_NO_ERROR) + { + CHIPCommand::sICDClientStorage.RemoveKey(clientInfo); + ChipLogError(chipTool, "Failed to persist symmetric key with error: %" CHIP_ERROR_FORMAT, err.Format()); + return; + } +} + void ModelCommand::CheckPeerICDType() { if (mIsPeerLIT.HasValue()) diff --git a/examples/chip-tool/commands/clusters/ModelCommand.h b/examples/chip-tool/commands/clusters/ModelCommand.h index 79c31cf865930d..635c03a2ebdf7c 100644 --- a/examples/chip-tool/commands/clusters/ModelCommand.h +++ b/examples/chip-tool/commands/clusters/ModelCommand.h @@ -67,8 +67,8 @@ class ModelCommand : public CHIPCommand virtual CHIP_ERROR SendGroupCommand(chip::GroupId groupId, chip::FabricIndex fabricIndex) { return CHIP_ERROR_BAD_REQUEST; }; - virtual void ClearICDEntry(const chip::ScopedNodeId & nodeId); - + void ClearICDEntry(const chip::ScopedNodeId & nodeId); + void StoreICDEntryWithKey(chip::app::ICDClientInfo & clientinfo, chip::ByteSpan key); void Shutdown() override; protected: diff --git a/examples/tv-casting-app/tv-casting-common/commands/clusters/ModelCommand.cpp b/examples/tv-casting-app/tv-casting-common/commands/clusters/ModelCommand.cpp index dafa11f2381fed..e2d01e55d80506 100644 --- a/examples/tv-casting-app/tv-casting-common/commands/clusters/ModelCommand.cpp +++ b/examples/tv-casting-app/tv-casting-common/commands/clusters/ModelCommand.cpp @@ -82,11 +82,16 @@ void ModelCommand::Shutdown() mOnDeviceConnectionFailureCallback.Cancel(); } -void ModelCommand::ClearICDEntry(const chip::ScopedNodeId & nodeId) +void ModelCommand::ClearICDEntry(const ScopedNodeId & nodeId) { ChipLogError(chipTool, "ClearICDEntry is not implemented in tv-casting-app"); } +void ModelCommand::StoreICDEntryWithKey(app::ICDClientInfo & clientinfo, ByteSpan key) +{ + ChipLogError(chipTool, "StoreICDEntryWithKey is not implemented in tv-casting-app"); +} + bool ModelCommand::IsPeerLIT() { // Does not support tv-casting-app From a2dddd128c809ca692a69a79064b95a48bf7f559 Mon Sep 17 00:00:00 2001 From: paulr34 <64710345+paulr34@users.noreply.github.com> Date: Tue, 4 Jun 2024 18:09:48 -0400 Subject: [PATCH 05/15] marking signed types as signed for ZAP to consume (#33719) --- .../zcl/data-model/chip/chip-types.xml | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/app/zap-templates/zcl/data-model/chip/chip-types.xml b/src/app/zap-templates/zcl/data-model/chip/chip-types.xml index cae3f4a87df8c0..77fcb4df6b4fe1 100644 --- a/src/app/zap-templates/zcl/data-model/chip/chip-types.xml +++ b/src/app/zap-templates/zcl/data-model/chip/chip-types.xml @@ -37,14 +37,14 @@ limitations under the License. - - - - - - - - + + + + + + + + From 3a3b6edba6361014b3bf398f8ea99bb4b33fb930 Mon Sep 17 00:00:00 2001 From: Yufeng Wang Date: Tue, 4 Jun 2024 15:45:33 -0700 Subject: [PATCH 06/15] [Fabric-Sync] Add the IPC support between Fabric_Admin and Fabric_Bridge (#33603) * Add the RPC support between Fabric_Admin and Fabric_Bridge * Add bridge_enable_pw_rpc build flag * Address review comments * Add RpcClientProcessor * Update API comments --- examples/common/pigweed/BUILD.gn | 14 ++ .../pigweed/protos/fabric_admin_service.proto | 20 +++ .../protos/fabric_bridge_service.proto | 15 +++ .../common/pigweed/rpc_console/py/BUILD.gn | 2 + .../rpc_console/py/chip_rpc/console.py | 4 + .../common/pigweed/rpc_services/FabricAdmin.h | 44 +++++++ .../pigweed/rpc_services/FabricBridge.h | 44 +++++++ examples/fabric-admin/BUILD.gn | 47 +++++++ .../commands/fabric-sync/Commands.h | 33 +++++ .../fabric-sync/FabricSyncCommand.cpp | 45 +++++++ .../commands/fabric-sync/FabricSyncCommand.h | 40 ++++++ .../interactive/InteractiveCommands.cpp | 41 +++++- examples/fabric-admin/main.cpp | 18 +++ examples/fabric-admin/rpc/RpcClient.cpp | 89 +++++++++++++ examples/fabric-admin/rpc/RpcClient.h | 48 +++++++ examples/fabric-admin/rpc/RpcServer.cpp | 70 ++++++++++ examples/fabric-admin/rpc/RpcServer.h | 23 ++++ examples/fabric-admin/with_pw_rpc.gni | 42 ++++++ examples/fabric-bridge-app/linux/BUILD.gn | 51 +++++++ .../fabric-bridge-app/linux/RpcClient.cpp | 88 +++++++++++++ .../fabric-bridge-app/linux/RpcServer.cpp | 68 ++++++++++ .../linux/include/RpcClient.h | 44 +++++++ .../linux/include/RpcServer.h | 23 ++++ examples/fabric-bridge-app/linux/main.cpp | 41 +++++- .../fabric-bridge-app/linux/with_pw_rpc.gni | 42 ++++++ .../platform/linux/RpcClientProcessor.cpp | 124 ++++++++++++++++++ examples/platform/linux/RpcClientProcessor.h | 36 +++++ 27 files changed, 1149 insertions(+), 7 deletions(-) create mode 100644 examples/common/pigweed/protos/fabric_admin_service.proto create mode 100644 examples/common/pigweed/protos/fabric_bridge_service.proto create mode 100644 examples/common/pigweed/rpc_services/FabricAdmin.h create mode 100644 examples/common/pigweed/rpc_services/FabricBridge.h create mode 100644 examples/fabric-admin/commands/fabric-sync/Commands.h create mode 100644 examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.cpp create mode 100644 examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.h create mode 100644 examples/fabric-admin/rpc/RpcClient.cpp create mode 100644 examples/fabric-admin/rpc/RpcClient.h create mode 100644 examples/fabric-admin/rpc/RpcServer.cpp create mode 100644 examples/fabric-admin/rpc/RpcServer.h create mode 100644 examples/fabric-admin/with_pw_rpc.gni create mode 100644 examples/fabric-bridge-app/linux/RpcClient.cpp create mode 100644 examples/fabric-bridge-app/linux/RpcServer.cpp create mode 100644 examples/fabric-bridge-app/linux/include/RpcClient.h create mode 100644 examples/fabric-bridge-app/linux/include/RpcServer.h create mode 100644 examples/fabric-bridge-app/linux/with_pw_rpc.gni create mode 100644 examples/platform/linux/RpcClientProcessor.cpp create mode 100644 examples/platform/linux/RpcClientProcessor.h diff --git a/examples/common/pigweed/BUILD.gn b/examples/common/pigweed/BUILD.gn index c0178e419a1d5d..e523bea380c03f 100644 --- a/examples/common/pigweed/BUILD.gn +++ b/examples/common/pigweed/BUILD.gn @@ -80,6 +80,20 @@ pw_proto_library("button_service") { prefix = "button_service" } +pw_proto_library("fabric_admin_service") { + sources = [ "protos/fabric_admin_service.proto" ] + deps = [ "$dir_pw_protobuf:common_protos" ] + strip_prefix = "protos" + prefix = "fabric_admin_service" +} + +pw_proto_library("fabric_bridge_service") { + sources = [ "protos/fabric_bridge_service.proto" ] + deps = [ "$dir_pw_protobuf:common_protos" ] + strip_prefix = "protos" + prefix = "fabric_bridge_service" +} + pw_proto_library("lighting_service") { sources = [ "protos/lighting_service.proto" ] deps = [ "$dir_pw_protobuf:common_protos" ] diff --git a/examples/common/pigweed/protos/fabric_admin_service.proto b/examples/common/pigweed/protos/fabric_admin_service.proto new file mode 100644 index 00000000000000..e52fd2951ac0d7 --- /dev/null +++ b/examples/common/pigweed/protos/fabric_admin_service.proto @@ -0,0 +1,20 @@ +syntax = "proto3"; + +import 'pw_protobuf_protos/common.proto'; + +package chip.rpc; + +// Define the message for a synchronized end device with necessary fields +message DeviceInfo { + uint64 node_id = 1; +} + +// Define the response message to convey the status of the operation +message OperationStatus { + bool success = 1; +} + +service FabricAdmin { + rpc OpenCommissioningWindow(DeviceInfo) returns (OperationStatus){} +} + diff --git a/examples/common/pigweed/protos/fabric_bridge_service.proto b/examples/common/pigweed/protos/fabric_bridge_service.proto new file mode 100644 index 00000000000000..5bd4f8efd779e7 --- /dev/null +++ b/examples/common/pigweed/protos/fabric_bridge_service.proto @@ -0,0 +1,15 @@ +syntax = "proto3"; + +import 'pw_protobuf_protos/common.proto'; + +package chip.rpc; + +// Define the message for a synchronized end device with necessary fields +message SynchronizedDevice { + uint64 node_id = 1; +} + +service FabricBridge { + rpc AddSynchronizedDevice(SynchronizedDevice) returns (pw.protobuf.Empty){} +} + diff --git a/examples/common/pigweed/rpc_console/py/BUILD.gn b/examples/common/pigweed/rpc_console/py/BUILD.gn index a03dc980872739..db9f22fe45fff9 100644 --- a/examples/common/pigweed/rpc_console/py/BUILD.gn +++ b/examples/common/pigweed/rpc_console/py/BUILD.gn @@ -46,6 +46,8 @@ pw_python_package("chip_rpc") { "${chip_root}/examples/common/pigweed:descriptor_service.python", "${chip_root}/examples/common/pigweed:device_service.python", "${chip_root}/examples/common/pigweed:echo_service.python", + "${chip_root}/examples/common/pigweed:fabric_admin_service.python", + "${chip_root}/examples/common/pigweed:fabric_bridge_service.python", "${chip_root}/examples/common/pigweed:lighting_service.python", "${chip_root}/examples/common/pigweed:locking_service.python", "${chip_root}/examples/common/pigweed:ot_cli_service.python", diff --git a/examples/common/pigweed/rpc_console/py/chip_rpc/console.py b/examples/common/pigweed/rpc_console/py/chip_rpc/console.py index 1591722bfdbeab..50f0b030f51725 100644 --- a/examples/common/pigweed/rpc_console/py/chip_rpc/console.py +++ b/examples/common/pigweed/rpc_console/py/chip_rpc/console.py @@ -53,6 +53,8 @@ from descriptor_service import descriptor_service_pb2 from device_service import device_service_pb2 from echo_service import echo_pb2 +from fabric_admin_service import fabric_admin_service_pb2 +from fabric_bridge_service import fabric_bridge_service_pb2 from lighting_service import lighting_service_pb2 from locking_service import locking_service_pb2 from ot_cli_service import ot_cli_service_pb2 @@ -136,6 +138,8 @@ def show_console(device: str, baudrate: int, descriptor_service_pb2, device_service_pb2, echo_pb2, + fabric_admin_service_pb2, + fabric_bridge_service_pb2, lighting_service_pb2, locking_service_pb2, ot_cli_service_pb2, diff --git a/examples/common/pigweed/rpc_services/FabricAdmin.h b/examples/common/pigweed/rpc_services/FabricAdmin.h new file mode 100644 index 00000000000000..5254b9e9054a0c --- /dev/null +++ b/examples/common/pigweed/rpc_services/FabricAdmin.h @@ -0,0 +1,44 @@ +/* + * + * Copyright (c) 2024 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include "app/util/attribute-storage.h" +#include "fabric_admin_service/fabric_admin_service.rpc.pb.h" +#include "pigweed/rpc_services/internal/StatusUtils.h" +#include +#include +#include +#include + +namespace chip { +namespace rpc { + +class FabricAdmin : public pw_rpc::nanopb::FabricAdmin::Service +{ +public: + virtual ~FabricAdmin() = default; + + virtual pw::Status OpenCommissioningWindow(const chip_rpc_DeviceInfo & request, chip_rpc_OperationStatus & response) + { + return pw::Status::Unimplemented(); + } +}; + +} // namespace rpc +} // namespace chip diff --git a/examples/common/pigweed/rpc_services/FabricBridge.h b/examples/common/pigweed/rpc_services/FabricBridge.h new file mode 100644 index 00000000000000..bce32ebd3d99b2 --- /dev/null +++ b/examples/common/pigweed/rpc_services/FabricBridge.h @@ -0,0 +1,44 @@ +/* + * + * Copyright (c) 2024 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include "app/util/attribute-storage.h" +#include "fabric_bridge_service/fabric_bridge_service.rpc.pb.h" +#include "pigweed/rpc_services/internal/StatusUtils.h" +#include +#include +#include +#include + +namespace chip { +namespace rpc { + +class FabricBridge : public pw_rpc::nanopb::FabricBridge::Service +{ +public: + virtual ~FabricBridge() = default; + + virtual pw::Status AddSynchronizedDevice(const chip_rpc_SynchronizedDevice & request, pw_protobuf_Empty & response) + { + return pw::Status::Unimplemented(); + } +}; + +} // namespace rpc +} // namespace chip diff --git a/examples/fabric-admin/BUILD.gn b/examples/fabric-admin/BUILD.gn index ddaa33483257b1..ad7eb217f9914c 100644 --- a/examples/fabric-admin/BUILD.gn +++ b/examples/fabric-admin/BUILD.gn @@ -22,10 +22,18 @@ import("${chip_root}/src/lib/core/core.gni") assert(chip_build_tools) +import("${chip_root}/examples/common/pigweed/pigweed_rpcs.gni") + +if (chip_enable_pw_rpc) { + import("//build_overrides/pigweed.gni") + import("$dir_pw_build/target_types.gni") +} + config("config") { include_dirs = [ ".", "${chip_root}/examples/common", + "${chip_root}/examples/platform/linux", "${chip_root}/zzz_generated/app-common/app-common", "${chip_root}/zzz_generated/chip-tool", "${chip_root}/src/lib", @@ -39,6 +47,10 @@ config("config") { } cflags = [ "-Wconversion" ] + + if (chip_enable_pw_rpc) { + defines += [ "PW_RPC_ENABLED" ] + } } static_library("fabric-admin-utils") { @@ -59,6 +71,7 @@ static_library("fabric-admin-utils") { "commands/common/HexConversion.h", "commands/common/RemoteDataModelLogger.cpp", "commands/common/RemoteDataModelLogger.h", + "commands/fabric-sync/FabricSyncCommand.cpp", "commands/pairing/OpenCommissioningWindowCommand.cpp", "commands/pairing/OpenCommissioningWindowCommand.h", "commands/pairing/PairingCommand.cpp", @@ -95,6 +108,40 @@ static_library("fabric-admin-utils") { public_configs = [ ":config" ] + if (chip_enable_pw_rpc) { + defines = [ + "PW_RPC_FABRIC_ADMIN_SERVICE=1", + "PW_RPC_FABRIC_BRIDGE_SERVICE=1", + ] + + sources += [ + "${chip_root}/examples/platform/linux/RpcClientProcessor.cpp", + "${chip_root}/examples/platform/linux/RpcClientProcessor.h", + "${chip_root}/examples/platform/linux/system_rpc_server.cc", + "rpc/RpcClient.cpp", + "rpc/RpcClient.h", + "rpc/RpcServer.cpp", + "rpc/RpcServer.h", + ] + + deps += [ + "$dir_pw_hdlc:default_addresses", + "$dir_pw_hdlc:rpc_channel_output", + "$dir_pw_log", + "$dir_pw_rpc:server", + "$dir_pw_rpc/system_server:facade", + "$dir_pw_rpc/system_server:socket", + "$dir_pw_stream:socket_stream", + "$dir_pw_sync:mutex", + "${chip_root}/config/linux/lib/pw_rpc:pw_rpc", + "${chip_root}/examples/common/pigweed:fabric_admin_service.nanopb_rpc", + "${chip_root}/examples/common/pigweed:fabric_bridge_service.nanopb_rpc", + "${chip_root}/examples/common/pigweed:rpc_services", + ] + + deps += pw_build_LINK_DEPS + } + if (chip_enable_transport_trace) { public_deps += [ "${chip_root}/examples/common/tracing:trace_handlers_decoder" ] diff --git a/examples/fabric-admin/commands/fabric-sync/Commands.h b/examples/fabric-admin/commands/fabric-sync/Commands.h new file mode 100644 index 00000000000000..f2be577065b617 --- /dev/null +++ b/examples/fabric-admin/commands/fabric-sync/Commands.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2024 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#pragma once + +#include +#include + +void registerCommandsFabricSync(Commands & commands, CredentialIssuerCommands * credsIssuerConfig) +{ + const char * clusterName = "FabricSync"; + + commands_list clusterCommands = { + make_unique(credsIssuerConfig), + }; + + commands.RegisterCommandSet(clusterName, clusterCommands, "Commands for fabric synchronization."); +} diff --git a/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.cpp b/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.cpp new file mode 100644 index 00000000000000..c2a1b5df8fb80e --- /dev/null +++ b/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.cpp @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2024 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include "FabricSyncCommand.h" +#include +#include +#include + +#if defined(PW_RPC_ENABLED) +#include "pw_assert/check.h" +#include "pw_hdlc/decoder.h" +#include "pw_hdlc/default_addresses.h" +#include "pw_hdlc/rpc_channel.h" +#include "pw_rpc/client.h" +#include "pw_stream/socket_stream.h" + +#include +#endif + +using namespace ::chip; + +CHIP_ERROR FabricSyncAddDeviceCommand::RunCommand(NodeId remoteId) +{ +#if defined(PW_RPC_ENABLED) + AddSynchronizedDevice(remoteId); + return CHIP_NO_ERROR; +#else + return CHIP_ERROR_NOT_IMPLEMENTED; +#endif +} diff --git a/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.h b/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.h new file mode 100644 index 00000000000000..cf739ccfb3a520 --- /dev/null +++ b/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2024 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#pragma once + +#include + +class FabricSyncAddDeviceCommand : public CHIPCommand +{ +public: + FabricSyncAddDeviceCommand(CredentialIssuerCommands * credIssuerCommands) : CHIPCommand("add-device", credIssuerCommands) + { + AddArgument("nodeid", 0, UINT64_MAX, &mNodeId); + } + + /////////// CHIPCommand Interface ///////// + CHIP_ERROR RunCommand() override { return RunCommand(mNodeId); } + + chip::System::Clock::Timeout GetWaitDuration() const override { return chip::System::Clock::Seconds16(1); } + +private: + chip::NodeId mNodeId; + + CHIP_ERROR RunCommand(NodeId remoteId); +}; diff --git a/examples/fabric-admin/commands/interactive/InteractiveCommands.cpp b/examples/fabric-admin/commands/interactive/InteractiveCommands.cpp index aaf3c36461cffb..c5c844256f5351 100644 --- a/examples/fabric-admin/commands/interactive/InteractiveCommands.cpp +++ b/examples/fabric-admin/commands/interactive/InteractiveCommands.cpp @@ -28,11 +28,18 @@ #include #include +#if defined(PW_RPC_ENABLED) +#include +#endif + +using namespace chip; + +namespace { + constexpr char kInteractiveModePrompt[] = ">>> "; constexpr char kInteractiveModeHistoryFileName[] = "chip_tool_history"; constexpr char kInteractiveModeStopCommand[] = "quit()"; - -namespace { +constexpr uint16_t kRetryIntervalS = 5; // File pointer for the log file FILE * sLogFile = nullptr; @@ -67,7 +74,7 @@ void ENFORCE_FORMAT(3, 0) LoggingCallback(const char * module, uint8_t category, return; } - uint64_t timeMs = chip::System::SystemClock().GetMonotonicMilliseconds64().count(); + uint64_t timeMs = System::SystemClock().GetMonotonicMilliseconds64().count(); uint64_t seconds = timeMs / 1000; uint64_t milliseconds = timeMs % 1000; @@ -82,6 +89,26 @@ void ENFORCE_FORMAT(3, 0) LoggingCallback(const char * module, uint8_t category, funlockfile(sLogFile); } +#if defined(PW_RPC_ENABLED) +void AttemptRpcClientConnect(System::Layer * systemLayer, void * appState) +{ + if (InitRpcClient(kFabricBridgeServerPort) == CHIP_NO_ERROR) + { + ChipLogProgress(NotSpecified, "Connected to Fabric-Bridge"); + } + else + { + ChipLogError(NotSpecified, "Failed to connect to Fabric-Bridge, retry in %d seconds....", kRetryIntervalS); + systemLayer->StartTimer(System::Clock::Seconds16(kRetryIntervalS), AttemptRpcClientConnect, nullptr); + } +} + +void ExecuteDeferredConnect(intptr_t ignored) +{ + AttemptRpcClientConnect(&DeviceLayer::SystemLayer(), nullptr); +} +#endif + } // namespace char * InteractiveStartCommand::GetCommand(char * command) @@ -134,9 +161,13 @@ CHIP_ERROR InteractiveStartCommand::RunCommand() OpenLogFile(mLogFilePath.Value()); // Redirect logs to the custom logging callback - chip::Logging::SetLogRedirectCallback(LoggingCallback); + Logging::SetLogRedirectCallback(LoggingCallback); } +#if defined(PW_RPC_ENABLED) + DeviceLayer::PlatformMgr().ScheduleWork(ExecuteDeferredConnect, 0); +#endif + char * command = nullptr; int status; while (true) @@ -167,7 +198,7 @@ bool InteractiveCommand::ParseCommand(char * command, int * status) // If scheduling the cleanup fails, there is not much we can do. // But if something went wrong while the application is leaving it could be because things have // not been cleaned up properly, so it is still useful to log the failure. - LogErrorOnFailure(chip::DeviceLayer::PlatformMgr().ScheduleWork(ExecuteDeferredCleanups, 0)); + LogErrorOnFailure(DeviceLayer::PlatformMgr().ScheduleWork(ExecuteDeferredCleanups, 0)); return false; } diff --git a/examples/fabric-admin/main.cpp b/examples/fabric-admin/main.cpp index a1002d83170d5b..f5f98cc0d960db 100644 --- a/examples/fabric-admin/main.cpp +++ b/examples/fabric-admin/main.cpp @@ -18,6 +18,7 @@ #include #include +#include #include #include #include @@ -26,6 +27,20 @@ #include #include +#if defined(PW_RPC_ENABLED) +#include +#endif + +using namespace chip; + +void ApplicationInit() +{ +#if defined(PW_RPC_ENABLED) + InitRpcServer(kFabricAdminServerPort); + ChipLogProgress(NotSpecified, "PW_RPC initialized."); +#endif +} + // ================================================================================ // Main Code // ================================================================================ @@ -45,6 +60,7 @@ int main(int argc, char * argv[]) ExampleCredentialIssuerCommands credIssuerCommands; Commands commands; + registerCommandsFabricSync(commands, &credIssuerCommands); registerCommandsInteractive(commands, &credIssuerCommands); registerCommandsPairing(commands, &credIssuerCommands); registerClusters(commands, &credIssuerCommands); @@ -56,5 +72,7 @@ int main(int argc, char * argv[]) c_args.push_back(const_cast(arg.c_str())); } + ApplicationInit(); + return commands.Run(static_cast(c_args.size()), c_args.data()); } diff --git a/examples/fabric-admin/rpc/RpcClient.cpp b/examples/fabric-admin/rpc/RpcClient.cpp new file mode 100644 index 00000000000000..a1a34d309ba17a --- /dev/null +++ b/examples/fabric-admin/rpc/RpcClient.cpp @@ -0,0 +1,89 @@ +/* + * + * Copyright (c) 2024 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "RpcClient.h" +#include "RpcClientProcessor.h" + +#include +#include +#include + +#include "fabric_bridge_service/fabric_bridge_service.rpc.pb.h" +#include "pw_assert/check.h" +#include "pw_function/function.h" +#include "pw_hdlc/decoder.h" +#include "pw_hdlc/default_addresses.h" +#include "pw_hdlc/rpc_channel.h" +#include "pw_rpc/client.h" +#include "pw_stream/socket_stream.h" + +using namespace chip; + +namespace { + +// Constants +constexpr uint32_t kDefaultChannelId = 1; + +// Fabric Bridge Client +rpc::pw_rpc::nanopb::FabricBridge::Client fabricBridgeClient(rpc::client::GetDefaultRpcClient(), kDefaultChannelId); +pw::rpc::NanopbUnaryReceiver<::pw_protobuf_Empty> addSynchronizedDeviceCall; + +// Callback function to be called when the RPC response is received +void OnAddDeviceResponseCompleted(const pw_protobuf_Empty & response, pw::Status status) +{ + if (status.ok()) + { + ChipLogProgress(NotSpecified, "AddSynchronizedDevice RPC call succeeded!"); + } + else + { + ChipLogProgress(NotSpecified, "AddSynchronizedDevice RPC call failed with status: %d\n", status.code()); + } +} + +} // namespace + +CHIP_ERROR InitRpcClient(uint16_t rpcServerPort) +{ + rpc::client::SetRpcServerPort(rpcServerPort); + return rpc::client::StartPacketProcessing(); +} + +CHIP_ERROR AddSynchronizedDevice(chip::NodeId nodeId) +{ + ChipLogProgress(NotSpecified, "AddSynchronizedDevice"); + + if (addSynchronizedDeviceCall.active()) + { + ChipLogError(NotSpecified, "OpenCommissioningWindow is in progress\n"); + return CHIP_ERROR_BUSY; + } + + chip_rpc_SynchronizedDevice device; + device.node_id = nodeId; + + // The RPC will remain active as long as `addSynchronizedDeviceCall` is alive. + addSynchronizedDeviceCall = fabricBridgeClient.AddSynchronizedDevice(device, OnAddDeviceResponseCompleted); + + if (!addSynchronizedDeviceCall.active()) + { + return CHIP_ERROR_INTERNAL; + } + + return CHIP_NO_ERROR; +} diff --git a/examples/fabric-admin/rpc/RpcClient.h b/examples/fabric-admin/rpc/RpcClient.h new file mode 100644 index 00000000000000..efe3c24acc3b23 --- /dev/null +++ b/examples/fabric-admin/rpc/RpcClient.h @@ -0,0 +1,48 @@ +/* + * + * Copyright (c) 2024 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include + +constexpr uint16_t kFabricBridgeServerPort = 33002; + +/** + * @brief Initializes the RPC client with the specified server port. + * + * This function sets the RPC server port and starts packet processing for the RPC client. + * + * @param rpcServerPort The port number on which the RPC server is running. + * @return CHIP_NO_ERROR on successful initialization, or an appropriate CHIP_ERROR on failure. + */ +CHIP_ERROR InitRpcClient(uint16_t rpcServerPort); + +/** + * @brief Adds a synchronized device to the RPC client. + * + * This function attempts to add a device identified by its `nodeId` to the synchronized device list. + * It logs the progress and checks if an `OpenCommissioningWindow` operation is already in progress. + * If an operation is in progress, it returns `CHIP_ERROR_BUSY`. + * + * @param nodeId The Node ID of the device to be added. + * @return CHIP_ERROR An error code indicating the success or failure of the operation. + * - CHIP_NO_ERROR: The RPC command was successfully sent. + * - CHIP_ERROR_BUSY: Another operation is currently in progress. + * - CHIP_ERROR_INTERNAL: An internal error occurred while activating the RPC call. + */ +CHIP_ERROR AddSynchronizedDevice(chip::NodeId nodeId); diff --git a/examples/fabric-admin/rpc/RpcServer.cpp b/examples/fabric-admin/rpc/RpcServer.cpp new file mode 100644 index 00000000000000..b3cbdcea05409a --- /dev/null +++ b/examples/fabric-admin/rpc/RpcServer.cpp @@ -0,0 +1,70 @@ +/* + * + * Copyright (c) 2024 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "pw_rpc/server.h" +#include "pw_rpc_system_server/rpc_server.h" +#include "pw_rpc_system_server/socket.h" + +#include +#include + +#if defined(PW_RPC_FABRIC_ADMIN_SERVICE) && PW_RPC_FABRIC_ADMIN_SERVICE +#include "pigweed/rpc_services/FabricAdmin.h" +#endif + +namespace { + +#if defined(PW_RPC_FABRIC_ADMIN_SERVICE) && PW_RPC_FABRIC_ADMIN_SERVICE +class FabricAdmin final : public chip::rpc::FabricAdmin +{ +public: + pw::Status OpenCommissioningWindow(const chip_rpc_DeviceInfo & request, chip_rpc_OperationStatus & response) override + { + chip::NodeId nodeId = request.node_id; + ChipLogProgress(NotSpecified, "Received OpenCommissioningWindow request: 0x%lx", nodeId); + response.success = false; + + return pw::OkStatus(); + } +}; + +FabricAdmin fabric_admin_service; +#endif // defined(PW_RPC_FABRIC_ADMIN_SERVICE) && PW_RPC_FABRIC_ADMIN_SERVICE + +void RegisterServices(pw::rpc::Server & server) +{ +#if defined(PW_RPC_FABRIC_ADMIN_SERVICE) && PW_RPC_FABRIC_ADMIN_SERVICE + server.RegisterService(fabric_admin_service); +#endif +} + +} // namespace + +void RunRpcService() +{ + pw::rpc::system_server::Init(); + RegisterServices(pw::rpc::system_server::Server()); + pw::rpc::system_server::Start(); +} + +void InitRpcServer(uint16_t rpcServerPort) +{ + pw::rpc::system_server::set_socket_port(rpcServerPort); + std::thread rpc_service(RunRpcService); + rpc_service.detach(); +} diff --git a/examples/fabric-admin/rpc/RpcServer.h b/examples/fabric-admin/rpc/RpcServer.h new file mode 100644 index 00000000000000..bc03bc0ac4abd3 --- /dev/null +++ b/examples/fabric-admin/rpc/RpcServer.h @@ -0,0 +1,23 @@ +/* + * + * Copyright (c) 2024 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +constexpr uint16_t kFabricAdminServerPort = 33001; + +void InitRpcServer(uint16_t rpcServerPort); diff --git a/examples/fabric-admin/with_pw_rpc.gni b/examples/fabric-admin/with_pw_rpc.gni new file mode 100644 index 00000000000000..abb9ac65f27e78 --- /dev/null +++ b/examples/fabric-admin/with_pw_rpc.gni @@ -0,0 +1,42 @@ +# Copyright (c) 2024 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# add this gni as import in your build args to use pigweed in the example +# 'import("//with_pw_rpc.gni")' + +import("//build_overrides/chip.gni") + +import("${chip_root}/config/standalone/args.gni") + +import("//build_overrides/pigweed.gni") + +pw_log_BACKEND = "$dir_pw_log_basic" +pw_assert_BACKEND = "$dir_pw_assert_log:check_backend" +pw_sys_io_BACKEND = "$dir_pw_sys_io_stdio" +pw_trace_BACKEND = "$dir_pw_trace_tokenized" +pw_unit_test_MAIN = "$dir_pw_unit_test:logging_main" +pw_rpc_system_server_BACKEND = "${chip_root}/config/linux/lib/pw_rpc:pw_rpc" +dir_pw_third_party_nanopb = "${chip_root}/third_party/nanopb/repo" +pw_chrono_SYSTEM_CLOCK_BACKEND = "$dir_pw_chrono_stl:system_clock" +pw_sync_MUTEX_BACKEND = "$dir_pw_sync_stl:mutex_backend" +pw_thread_YIELD_BACKEND = "$dir_pw_thread_stl:yield" +pw_thread_SLEEP_BACKEND = "$dir_pw_thread_stl:sleep" + +pw_build_LINK_DEPS = [ + "$dir_pw_assert:impl", + "$dir_pw_log:impl", +] + +chip_enable_pw_rpc = true +chip_use_pw_logging = true diff --git a/examples/fabric-bridge-app/linux/BUILD.gn b/examples/fabric-bridge-app/linux/BUILD.gn index ea7e6e0b31b331..3e82f044c047f9 100644 --- a/examples/fabric-bridge-app/linux/BUILD.gn +++ b/examples/fabric-bridge-app/linux/BUILD.gn @@ -16,8 +16,20 @@ import("//build_overrides/chip.gni") import("${chip_root}/build/chip/tools.gni") +import("//with_pw_rpc.gni") + assert(chip_build_tools) +declare_args() { + bridge_enable_pw_rpc = false +} + +if (bridge_enable_pw_rpc) { + import("//build_overrides/pigweed.gni") + import("$dir_pw_build/target_types.gni") + import("${chip_root}/examples/common/pigweed/pigweed_rpcs.gni") +} + executable("fabric-bridge-app") { sources = [ "${chip_root}/examples/fabric-bridge-app/fabric-bridge-common/include/CHIPProjectAppConfig.h", @@ -38,6 +50,45 @@ executable("fabric-bridge-app") { include_dirs = [ "include" ] + if (bridge_enable_pw_rpc) { + defines = [ + "PW_RPC_FABRIC_ADMIN_SERVICE=1", + "PW_RPC_FABRIC_BRIDGE_SERVICE=1", + ] + + sources += [ + "${chip_root}/examples/platform/linux/RpcClientProcessor.cpp", + "${chip_root}/examples/platform/linux/RpcClientProcessor.h", + "${chip_root}/examples/platform/linux/system_rpc_server.cc", + "RpcClient.cpp", + "RpcServer.cpp", + "include/RpcClient.h", + "include/RpcServer.h", + ] + + deps += [ + "$dir_pw_hdlc:default_addresses", + "$dir_pw_hdlc:rpc_channel_output", + "$dir_pw_log", + "$dir_pw_rpc:server", + "$dir_pw_rpc/system_server:facade", + "$dir_pw_rpc/system_server:socket", + "$dir_pw_stream:socket_stream", + "$dir_pw_sync:mutex", + "${chip_root}/config/linux/lib/pw_rpc:pw_rpc", + "${chip_root}/examples/common/pigweed:fabric_admin_service.nanopb_rpc", + "${chip_root}/examples/common/pigweed:fabric_bridge_service.nanopb_rpc", + "${chip_root}/examples/common/pigweed:rpc_services", + ] + + deps += pw_build_LINK_DEPS + + include_dirs += [ + "${chip_root}/examples/common", + "${chip_root}/examples/platform/linux", + ] + } + output_dir = root_out_dir } diff --git a/examples/fabric-bridge-app/linux/RpcClient.cpp b/examples/fabric-bridge-app/linux/RpcClient.cpp new file mode 100644 index 00000000000000..c09a447cff28c9 --- /dev/null +++ b/examples/fabric-bridge-app/linux/RpcClient.cpp @@ -0,0 +1,88 @@ +/* + * + * Copyright (c) 2024 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "RpcClient.h" +#include "RpcClientProcessor.h" + +#include +#include +#include + +#include "fabric_admin_service/fabric_admin_service.rpc.pb.h" +#include "pw_assert/check.h" +#include "pw_hdlc/decoder.h" +#include "pw_hdlc/default_addresses.h" +#include "pw_hdlc/rpc_channel.h" +#include "pw_rpc/client.h" +#include "pw_stream/socket_stream.h" + +using namespace chip; + +namespace { + +// Constants +constexpr uint32_t kDefaultChannelId = 1; + +// Fabric Admin Client +rpc::pw_rpc::nanopb::FabricAdmin::Client fabricAdminClient(rpc::client::GetDefaultRpcClient(), kDefaultChannelId); +pw::rpc::NanopbUnaryReceiver<::chip_rpc_OperationStatus> openCommissioningWindowCall; + +// Callback function to be called when the RPC response is received +void OnOpenCommissioningWindowCompleted(const chip_rpc_OperationStatus & response, pw::Status status) +{ + if (status.ok()) + { + ChipLogProgress(NotSpecified, "OpenCommissioningWindow received operation status: %d", response.success); + } + else + { + ChipLogProgress(NotSpecified, "OpenCommissioningWindow RPC call failed with status: %d\n", status.code()); + } +} + +} // namespace + +CHIP_ERROR InitRpcClient(uint16_t rpcServerPort) +{ + rpc::client::SetRpcServerPort(rpcServerPort); + return rpc::client::StartPacketProcessing(); +} + +CHIP_ERROR OpenCommissioningWindow(NodeId nodeId) +{ + ChipLogProgress(NotSpecified, "OpenCommissioningWindow\n"); + + if (openCommissioningWindowCall.active()) + { + ChipLogError(NotSpecified, "OpenCommissioningWindow is in progress\n"); + return CHIP_ERROR_BUSY; + } + + chip_rpc_DeviceInfo device; + device.node_id = nodeId; + + // The RPC will remain active as long as `openCommissioningWindowCall` is alive. + openCommissioningWindowCall = fabricAdminClient.OpenCommissioningWindow(device, OnOpenCommissioningWindowCompleted); + + if (!openCommissioningWindowCall.active()) + { + return CHIP_ERROR_INTERNAL; + } + + return CHIP_NO_ERROR; +} diff --git a/examples/fabric-bridge-app/linux/RpcServer.cpp b/examples/fabric-bridge-app/linux/RpcServer.cpp new file mode 100644 index 00000000000000..c971811b193016 --- /dev/null +++ b/examples/fabric-bridge-app/linux/RpcServer.cpp @@ -0,0 +1,68 @@ +/* + * + * Copyright (c) 2024 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "pw_rpc/server.h" +#include "pw_rpc_system_server/rpc_server.h" +#include "pw_rpc_system_server/socket.h" + +#include +#include + +#if defined(PW_RPC_FABRIC_BRIDGE_SERVICE) && PW_RPC_FABRIC_BRIDGE_SERVICE +#include "pigweed/rpc_services/FabricBridge.h" +#endif + +namespace { + +#if defined(PW_RPC_FABRIC_BRIDGE_SERVICE) && PW_RPC_FABRIC_BRIDGE_SERVICE +class FabricBridge final : public chip::rpc::FabricBridge +{ +public: + pw::Status AddSynchronizedDevice(const chip_rpc_SynchronizedDevice & request, pw_protobuf_Empty & response) override + { + chip::NodeId nodeId = request.node_id; + ChipLogProgress(NotSpecified, "Received AddSynchronizedDevice: " ChipLogFormatX64, ChipLogValueX64(nodeId)); + return pw::OkStatus(); + } +}; + +FabricBridge fabric_bridge_service; +#endif // defined(PW_RPC_FABRIC_BRIDGE_SERVICE) && PW_RPC_FABRIC_BRIDGE_SERVICE + +void RegisterServices(pw::rpc::Server & server) +{ +#if defined(PW_RPC_FABRIC_BRIDGE_SERVICE) && PW_RPC_FABRIC_BRIDGE_SERVICE + server.RegisterService(fabric_bridge_service); +#endif +} + +} // namespace + +void RunRpcService() +{ + pw::rpc::system_server::Init(); + RegisterServices(pw::rpc::system_server::Server()); + pw::rpc::system_server::Start(); +} + +void InitRpcServer(uint16_t rpcServerPort) +{ + pw::rpc::system_server::set_socket_port(rpcServerPort); + std::thread rpc_service(RunRpcService); + rpc_service.detach(); +} diff --git a/examples/fabric-bridge-app/linux/include/RpcClient.h b/examples/fabric-bridge-app/linux/include/RpcClient.h new file mode 100644 index 00000000000000..bd424e9d275910 --- /dev/null +++ b/examples/fabric-bridge-app/linux/include/RpcClient.h @@ -0,0 +1,44 @@ +/* + * + * Copyright (c) 2024 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include + +constexpr uint16_t kFabricAdminServerPort = 33001; + +/** + * Initializes the RPC client by setting the server port and starting packet processing. + * + * @param rpcServerPort The port number of the RPC server. + * @return CHIP_ERROR An error code indicating the success or failure of the initialization process. + * - CHIP_NO_ERROR: Initialization was successful. + * - Other error codes indicating specific failure reasons. + */ +CHIP_ERROR InitRpcClient(uint16_t rpcServerPort); + +/** + * Opens a commissioning window for a specified node. + * + * @param nodeId The identifier of the node for which the commissioning window should be opened. + * @return CHIP_ERROR An error code indicating the success or failure of the operation. + * - CHIP_NO_ERROR: The RPC command was successfully sent. + * - CHIP_ERROR_BUSY: Another commissioning window is currently in progress. + * - CHIP_ERROR_INTERNAL: An internal error occurred. + */ +CHIP_ERROR OpenCommissioningWindow(chip::NodeId nodeId); diff --git a/examples/fabric-bridge-app/linux/include/RpcServer.h b/examples/fabric-bridge-app/linux/include/RpcServer.h new file mode 100644 index 00000000000000..f86858b19bdfe3 --- /dev/null +++ b/examples/fabric-bridge-app/linux/include/RpcServer.h @@ -0,0 +1,23 @@ +/* + * + * Copyright (c) 2024 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +constexpr uint16_t kFabricBridgeServerPort = 33002; + +void InitRpcServer(uint16_t rpcServerPort); diff --git a/examples/fabric-bridge-app/linux/main.cpp b/examples/fabric-bridge-app/linux/main.cpp index 600d4a2a376d55..47670561430c90 100644 --- a/examples/fabric-bridge-app/linux/main.cpp +++ b/examples/fabric-bridge-app/linux/main.cpp @@ -25,19 +25,26 @@ #include #include +#if defined(PW_RPC_FABRIC_BRIDGE_SERVICE) && PW_RPC_FABRIC_BRIDGE_SERVICE +#include "RpcClient.h" +#include "RpcServer.h" +#endif + #include #include #include using namespace chip; -#define POLL_INTERVAL_MS (100) #define ZCL_DESCRIPTOR_CLUSTER_REVISION (1u) #define ZCL_BRIDGED_DEVICE_BASIC_INFORMATION_CLUSTER_REVISION (2u) #define ZCL_BRIDGED_DEVICE_BASIC_INFORMATION_FEATURE_MAP (0u) namespace { +constexpr uint16_t kPollIntervalMs = 100; +constexpr uint16_t kRetryIntervalS = 3; + bool KeyboardHit() { int bytesWaiting; @@ -57,13 +64,38 @@ void BridgePollingThread() ChipLogProgress(NotSpecified, "Exiting....."); exit(0); } +#if defined(PW_RPC_FABRIC_BRIDGE_SERVICE) && PW_RPC_FABRIC_BRIDGE_SERVICE + else if (ch == 'o') + { + CHIP_ERROR err = OpenCommissioningWindow(0x1234); + if (err != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to call OpenCommissioningWindow RPC: %" CHIP_ERROR_FORMAT, err.Format()); + } + } +#endif // defined(PW_RPC_FABRIC_BRIDGE_SERVICE) && PW_RPC_FABRIC_BRIDGE_SERVICE continue; } // Sleep to avoid tight loop reading commands - usleep(POLL_INTERVAL_MS * 1000); + usleep(kPollIntervalMs * 1000); + } +} + +#if defined(PW_RPC_FABRIC_BRIDGE_SERVICE) && PW_RPC_FABRIC_BRIDGE_SERVICE +void AttemptRpcClientConnect(System::Layer * systemLayer, void * appState) +{ + if (InitRpcClient(kFabricAdminServerPort) == CHIP_NO_ERROR) + { + ChipLogProgress(NotSpecified, "Connected to Fabric-Admin"); + } + else + { + ChipLogError(NotSpecified, "Failed to connect to Fabric-Admin, retry in %d seconds....", kRetryIntervalS); + systemLayer->StartTimer(System::Clock::Seconds16(kRetryIntervalS), AttemptRpcClientConnect, nullptr); } } +#endif // defined(PW_RPC_FABRIC_BRIDGE_SERVICE) && PW_RPC_FABRIC_BRIDGE_SERVICE DeviceManager gDeviceManager; @@ -71,6 +103,11 @@ DeviceManager gDeviceManager; void ApplicationInit() { +#if defined(PW_RPC_FABRIC_BRIDGE_SERVICE) && PW_RPC_FABRIC_BRIDGE_SERVICE + InitRpcServer(kFabricBridgeServerPort); + AttemptRpcClientConnect(&DeviceLayer::SystemLayer(), nullptr); +#endif + // Start a thread for bridge polling std::thread pollingThread(BridgePollingThread); pollingThread.detach(); diff --git a/examples/fabric-bridge-app/linux/with_pw_rpc.gni b/examples/fabric-bridge-app/linux/with_pw_rpc.gni new file mode 100644 index 00000000000000..e1bd567cf22db2 --- /dev/null +++ b/examples/fabric-bridge-app/linux/with_pw_rpc.gni @@ -0,0 +1,42 @@ +# Copyright (c) 2024 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# add this gni as import in your build args to use pigweed in the example +# 'import("//with_pw_rpc.gni")' + +import("//build_overrides/chip.gni") + +import("${chip_root}/config/standalone/args.gni") + +import("//build_overrides/pigweed.gni") + +pw_log_BACKEND = "$dir_pw_log_basic" +pw_assert_BACKEND = "$dir_pw_assert_log:check_backend" +pw_sys_io_BACKEND = "$dir_pw_sys_io_stdio" +pw_trace_BACKEND = "$dir_pw_trace_tokenized" +pw_unit_test_MAIN = "$dir_pw_unit_test:logging_main" +pw_rpc_system_server_BACKEND = "${chip_root}/config/linux/lib/pw_rpc:pw_rpc" +dir_pw_third_party_nanopb = "${chip_root}/third_party/nanopb/repo" +pw_chrono_SYSTEM_CLOCK_BACKEND = "$dir_pw_chrono_stl:system_clock" +pw_sync_MUTEX_BACKEND = "$dir_pw_sync_stl:mutex_backend" +pw_thread_YIELD_BACKEND = "$dir_pw_thread_stl:yield" +pw_thread_SLEEP_BACKEND = "$dir_pw_thread_stl:sleep" + +pw_build_LINK_DEPS = [ + "$dir_pw_assert:impl", + "$dir_pw_log:impl", +] + +chip_use_pw_logging = true +bridge_enable_pw_rpc = true diff --git a/examples/platform/linux/RpcClientProcessor.cpp b/examples/platform/linux/RpcClientProcessor.cpp new file mode 100644 index 00000000000000..a2cbe5694f531d --- /dev/null +++ b/examples/platform/linux/RpcClientProcessor.cpp @@ -0,0 +1,124 @@ +/* + * + * Copyright (c) 2024 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "RpcClientProcessor.h" + +#include +#include + +#include "pw_hdlc/decoder.h" +#include "pw_hdlc/default_addresses.h" +#include "pw_hdlc/rpc_channel.h" +#include "pw_stream/socket_stream.h" + +namespace chip { +namespace rpc { +namespace client { +namespace { + +// Constants +constexpr size_t kMaxTransmissionUnit = 256; +constexpr uint32_t kDefaultChannelId = 1; +const char * kDefaultRpcServerAddress = "127.0.0.1"; + +// RPC Stream and Channel Setup +pw::stream::SocketStream rpcSocketStream; +pw::hdlc::RpcChannelOutput hdlcChannelOutput(rpcSocketStream, pw::hdlc::kDefaultRpcAddress, "HDLC channel"); +pw::rpc::Channel channels[] = { pw::rpc::Channel::Create<1>(&hdlcChannelOutput) }; +pw::rpc::Client rpcClient(channels); + +// RPC Stream and Channel Setup +uint16_t rpcServerPort = 0; +const char * rpcServerAddress = kDefaultRpcServerAddress; + +// Function to process incoming packets +void ProcessPackets() +{ + std::array inputBuf; + pw::hdlc::Decoder decoder(inputBuf); + + while (true) + { + std::array data; + auto ret = rpcSocketStream.Read(data); + if (!ret.ok()) + { + if (ret.status() == pw::Status::OutOfRange()) + { + // Handle remote disconnect + rpcSocketStream.Close(); + return; + } + continue; + } + + for (std::byte byte : ret.value()) + { + auto result = decoder.Process(byte); + if (!result.ok()) + { + // Wait for more bytes that form a complete packet + continue; + } + pw::hdlc::Frame & frame = result.value(); + if (frame.address() != pw::hdlc::kDefaultRpcAddress) + { + // Wrong address; ignore the packet + continue; + } + + rpcClient.ProcessPacket(frame.data()).IgnoreError(); + } + } +} + +} // namespace + +void SetRpcServerAddress(const char * address) +{ + rpcServerAddress = address; +} + +void SetRpcServerPort(uint16_t port) +{ + rpcServerPort = port; +} + +pw::rpc::Client & GetDefaultRpcClient() +{ + return rpcClient; +} + +CHIP_ERROR StartPacketProcessing() +{ + if (rpcSocketStream.Connect(rpcServerAddress, rpcServerPort) != PW_STATUS_OK) + { + // Handle connection error + return CHIP_ERROR_NOT_CONNECTED; + } + + // Start a thread to process incoming packets + std::thread packet_processor(ProcessPackets); + packet_processor.detach(); + + return CHIP_NO_ERROR; +} + +} // namespace client +} // namespace rpc +} // namespace chip diff --git a/examples/platform/linux/RpcClientProcessor.h b/examples/platform/linux/RpcClientProcessor.h new file mode 100644 index 00000000000000..f2305df7aa046c --- /dev/null +++ b/examples/platform/linux/RpcClientProcessor.h @@ -0,0 +1,36 @@ +/* + * + * Copyright (c) 2024 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include "pw_rpc/client.h" +#include +#include + +namespace chip { +namespace rpc { +namespace client { + +void SetRpcServerAddress(const char * address); +void SetRpcServerPort(uint16_t port); +pw::rpc::Client & GetDefaultRpcClient(); +CHIP_ERROR StartPacketProcessing(); + +} // namespace client +} // namespace rpc +} // namespace chip From 994a98d5f8568b68b29ccd0e8bfedc54fcee70d2 Mon Sep 17 00:00:00 2001 From: Kiel Oleson Date: Tue, 4 Jun 2024 16:12:06 -0700 Subject: [PATCH 07/15] Darwin: add helpers for essential attributes for logging; log unexpected C-quality attributes (#33560) * add metric keys for additional metrics * add metric collection for unexpected C Quality attribute update * unwind premature optimization placeholders/comments * rename to indicate the attributes are for logging / informational use * simplify - pull attributes from cache without intermediate object, should be fast enough * revert accidental whitespace change * Restyled by whitespace * Restyled by clang-format * make `nil` case possibility more obvious --------- Co-authored-by: Restyled.io --- src/darwin/Framework/CHIP/MTRDevice.mm | 55 ++++++++++++++++++++++- src/darwin/Framework/CHIP/MTRMetricKeys.h | 6 +++ 2 files changed, 59 insertions(+), 2 deletions(-) diff --git a/src/darwin/Framework/CHIP/MTRDevice.mm b/src/darwin/Framework/CHIP/MTRDevice.mm index 4014bd5f6924bf..dcb6a9acd8da64 100644 --- a/src/darwin/Framework/CHIP/MTRDevice.mm +++ b/src/darwin/Framework/CHIP/MTRDevice.mm @@ -35,6 +35,8 @@ #import "MTRError_Internal.h" #import "MTREventTLVValueDecoder_Internal.h" #import "MTRLogging_Internal.h" +#import "MTRMetricKeys.h" +#import "MTRMetricsCollector.h" #import "MTRTimeUtils.h" #import "MTRUnfairLock.h" #import "zap-generated/MTRCommandPayloads_Internal.h" @@ -1886,9 +1888,16 @@ - (void)_setCachedAttributeValue:(MTRDeviceDataValueDictionary _Nullable)value f && isFromSubscription && !_receivingPrimingReport && AttributeHasChangesOmittedQuality(path)) { - // Do not persist new values for Changes Omitted Quality attributes unless - // they're part of a Priming Report or from a read response. + // Do not persist new values for Changes Omitted Quality (aka C Quality) + // attributes unless they're part of a Priming Report or from a read response. // (removals are OK) + + // log when a device violates expectations for Changes Omitted Quality attributes. + using namespace chip::Tracing::DarwinFramework; + MATTER_LOG_METRIC_BEGIN(kMetricUnexpectedCQualityUpdate); + [self _addInformationalAttributesToCurrentMetricScope]; + MATTER_LOG_METRIC_END(kMetricUnexpectedCQualityUpdate); + return; } @@ -3642,6 +3651,48 @@ - (void)removeClientDataForKey:(NSString *)key endpointID:(NSNumber *)endpointID [self.temporaryMetaDataCache removeObjectForKey:[NSString stringWithFormat:@"%@:%@", key, endpointID]]; } +#pragma mark Log Help + +- (nullable NSNumber *)_informationalNumberAtAttributePath:(MTRAttributePath *)attributePath +{ + auto * cachedData = [self _cachedAttributeValueForPath:attributePath]; + + auto * attrReport = [[MTRAttributeReport alloc] initWithResponseValue:@{ + MTRAttributePathKey : attributePath, + MTRDataKey : cachedData, + } + error:nil]; + + return attrReport.value; +} + +- (nullable NSNumber *)_informationalVendorID +{ + auto * vendorIDPath = [MTRAttributePath attributePathWithEndpointID:@(kRootEndpointId) + clusterID:@(MTRClusterIDTypeBasicInformationID) + attributeID:@(MTRClusterBasicAttributeVendorIDID)]; + + return [self _informationalNumberAtAttributePath:vendorIDPath]; +} + +- (nullable NSNumber *)_informationalProductID +{ + auto * productIDPath = [MTRAttributePath attributePathWithEndpointID:@(kRootEndpointId) + clusterID:@(MTRClusterIDTypeBasicInformationID) + attributeID:@(MTRClusterBasicAttributeProductIDID)]; + + return [self _informationalNumberAtAttributePath:productIDPath]; +} + +- (void)_addInformationalAttributesToCurrentMetricScope +{ + using namespace chip::Tracing::DarwinFramework; + MATTER_LOG_METRIC(kMetricDeviceVendorID, [self _informationalVendorID].unsignedShortValue); + MATTER_LOG_METRIC(kMetricDeviceProductID, [self _informationalProductID].unsignedShortValue); + BOOL usesThread = [self _deviceUsesThread]; + MATTER_LOG_METRIC(kMetricDeviceUsesThread, usesThread); +} + @end /* BEGIN DRAGONS: Note methods here cannot be renamed, and are used by private callers, do not rename, remove or modify behavior here */ diff --git a/src/darwin/Framework/CHIP/MTRMetricKeys.h b/src/darwin/Framework/CHIP/MTRMetricKeys.h index 5ea03da70d9752..536da36b582053 100644 --- a/src/darwin/Framework/CHIP/MTRMetricKeys.h +++ b/src/darwin/Framework/CHIP/MTRMetricKeys.h @@ -69,6 +69,9 @@ constexpr Tracing::MetricKey kMetricDeviceVendorID = "dwnfw_device_vendor_id"; // Device Product ID constexpr Tracing::MetricKey kMetricDeviceProductID = "dwnfw_device_product_id"; +// Device Uses Thread +constexpr Tracing::MetricKey kMetricDeviceUsesThread = "dwnfw_device_uses_thread_bool"; + // Counter of number of devices discovered on the network during setup constexpr Tracing::MetricKey kMetricOnNetworkDevicesAdded = "dwnfw_onnet_devices_added"; @@ -81,6 +84,9 @@ constexpr Tracing::MetricKey kMetricBLEDevicesAdded = "dwnfw_ble_devices_added"; // Counter of number of BLE devices removed during setup constexpr Tracing::MetricKey kMetricBLEDevicesRemoved = "dwnfw_ble_devices_removed"; +// Unexpected C quality attribute update outside of priming +constexpr Tracing::MetricKey kMetricUnexpectedCQualityUpdate = "dwnpm_bad_c_attr_update"; + } // namespace DarwinFramework } // namespace Tracing } // namespace chip From ca33a408fb42f6199be57aee423eacaea464de37 Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Tue, 4 Jun 2024 23:26:51 -0400 Subject: [PATCH 08/15] Increase the poll rate for BDX diagnostic log downloads. (#33741) The default rate used by bdx::Responder is once every 500ms, which means you maybe manage to get 1kB/s of log through the network. We should allow this process to go faster. Switch to once every 50ms, to match all the other BDX transfers we have around that poll like this. --- src/protocols/bdx/BdxTransferDiagnosticLog.cpp | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/protocols/bdx/BdxTransferDiagnosticLog.cpp b/src/protocols/bdx/BdxTransferDiagnosticLog.cpp index 8b349fed31e8f5..51e56fba9ac254 100644 --- a/src/protocols/bdx/BdxTransferDiagnosticLog.cpp +++ b/src/protocols/bdx/BdxTransferDiagnosticLog.cpp @@ -25,6 +25,12 @@ namespace { // Max block size for the BDX transfer. constexpr uint32_t kMaxBdxBlockSize = 1024; +// How often we poll our transfer session. Sadly, we get allocated on +// unsolicited message, which makes it hard for our clients to configure this. +// But the default poll interval is 500ms, which makes log downloads extremely +// slow. +constexpr System::Clock::Timeout kBdxPollInterval = System::Clock::Milliseconds32(50); + // Timeout for the BDX transfer session.. constexpr System::Clock::Timeout kBdxTimeout = System::Clock::Seconds16(5 * 60); constexpr TransferRole kBdxRole = TransferRole::kReceiver; @@ -95,7 +101,8 @@ CHIP_ERROR BdxTransferDiagnosticLog::OnMessageReceived(Messaging::ExchangeContex mTransferProxy.SetFabricIndex(fabricIndex); mTransferProxy.SetPeerNodeId(peerNodeId); auto flags(TransferControlFlags::kSenderDrive); - ReturnLogErrorOnFailure(Responder::PrepareForTransfer(mSystemLayer, kBdxRole, flags, kMaxBdxBlockSize, kBdxTimeout)); + ReturnLogErrorOnFailure( + Responder::PrepareForTransfer(mSystemLayer, kBdxRole, flags, kMaxBdxBlockSize, kBdxTimeout, kBdxPollInterval)); } return TransferFacilitator::OnMessageReceived(ec, payloadHeader, std::move(payload)); From 24bbdf431afcec27a90f793e1c99eb65e9cadea8 Mon Sep 17 00:00:00 2001 From: cdj <45139296+DejinChen@users.noreply.github.com> Date: Wed, 5 Jun 2024 12:29:08 +0800 Subject: [PATCH 09/15] Added secondary network interface device type (#33682) --- .../all-clusters-app.matter | 2 +- .../all-clusters-common/all-clusters-app.zap | 20 +++++++++---------- .../all-clusters-minimal-app.matter | 2 +- .../all-clusters-minimal-app.zap | 20 +++++++++---------- .../ota-requestor-app.matter | 2 +- .../ota-requestor-app.zap | 20 +++++++++---------- .../zap/tests/inputs/all-clusters-app.zap | 20 +++++++++---------- .../app-templates/endpoint_config.h | 2 +- .../zcl/data-model/chip/matter-devices.xml | 11 +++++++--- .../zap-generated/MTRDeviceTypeMetadata.mm | 2 +- 10 files changed, 53 insertions(+), 48 deletions(-) diff --git a/examples/all-clusters-app/all-clusters-common/all-clusters-app.matter b/examples/all-clusters-app/all-clusters-common/all-clusters-app.matter index 804d1eae5fbd32..8c5f9766970adc 100644 --- a/examples/all-clusters-app/all-clusters-common/all-clusters-app.matter +++ b/examples/all-clusters-app/all-clusters-common/all-clusters-app.matter @@ -9211,7 +9211,7 @@ endpoint 2 { } } endpoint 65534 { - device type ma_secondary_network_commissioning = 4293984258, version 1; + device type ma_secondary_network_interface = 25, version 1; server cluster Descriptor { diff --git a/examples/all-clusters-app/all-clusters-common/all-clusters-app.zap b/examples/all-clusters-app/all-clusters-common/all-clusters-app.zap index 683f2dd75658ba..14c5f68d26e89c 100644 --- a/examples/all-clusters-app/all-clusters-common/all-clusters-app.zap +++ b/examples/all-clusters-app/all-clusters-common/all-clusters-app.zap @@ -1,6 +1,6 @@ { "fileFormat": 2, - "featureLevel": 100, + "featureLevel": 102, "creator": "zap", "keyValuePairs": [ { @@ -24779,27 +24779,27 @@ "id": 4, "name": "Anonymous Endpoint Type", "deviceTypeRef": { - "code": 4293984258, + "code": 25, "profileId": 259, - "label": "MA-secondary-network-commissioning", - "name": "MA-secondary-network-commissioning" + "label": "MA-secondary-network-interface", + "name": "MA-secondary-network-interface" }, "deviceTypes": [ { - "code": 4293984258, + "code": 25, "profileId": 259, - "label": "MA-secondary-network-commissioning", - "name": "MA-secondary-network-commissioning" + "label": "MA-secondary-network-interface", + "name": "MA-secondary-network-interface" } ], "deviceVersions": [ 1 ], "deviceIdentifiers": [ - 4293984258 + 25 ], - "deviceTypeName": "MA-secondary-network-commissioning", - "deviceTypeCode": 4293984258, + "deviceTypeName": "MA-secondary-network-interface", + "deviceTypeCode": 25, "deviceTypeProfileId": 259, "clusters": [ { diff --git a/examples/all-clusters-minimal-app/all-clusters-common/all-clusters-minimal-app.matter b/examples/all-clusters-minimal-app/all-clusters-common/all-clusters-minimal-app.matter index 0c9569504c7846..58e57000bae2eb 100644 --- a/examples/all-clusters-minimal-app/all-clusters-common/all-clusters-minimal-app.matter +++ b/examples/all-clusters-minimal-app/all-clusters-common/all-clusters-minimal-app.matter @@ -6920,7 +6920,7 @@ endpoint 2 { } } endpoint 65534 { - device type ma_secondary_network_commissioning = 4293984258, version 1; + device type ma_secondary_network_interface = 25, version 1; server cluster Descriptor { diff --git a/examples/all-clusters-minimal-app/all-clusters-common/all-clusters-minimal-app.zap b/examples/all-clusters-minimal-app/all-clusters-common/all-clusters-minimal-app.zap index 3294f430a3e337..a4d3b3858ef160 100644 --- a/examples/all-clusters-minimal-app/all-clusters-common/all-clusters-minimal-app.zap +++ b/examples/all-clusters-minimal-app/all-clusters-common/all-clusters-minimal-app.zap @@ -1,6 +1,6 @@ { "fileFormat": 2, - "featureLevel": 100, + "featureLevel": 102, "creator": "zap", "keyValuePairs": [ { @@ -11837,27 +11837,27 @@ "id": 4, "name": "Anonymous Endpoint Type", "deviceTypeRef": { - "code": 4293984258, + "code": 25, "profileId": 259, - "label": "MA-secondary-network-commissioning", - "name": "MA-secondary-network-commissioning" + "label": "MA-secondary-network-interface", + "name": "MA-secondary-network-interface" }, "deviceTypes": [ { - "code": 4293984258, + "code": 25, "profileId": 259, - "label": "MA-secondary-network-commissioning", - "name": "MA-secondary-network-commissioning" + "label": "MA-secondary-network-interface", + "name": "MA-secondary-network-interface" } ], "deviceVersions": [ 1 ], "deviceIdentifiers": [ - 4293984258 + 25 ], - "deviceTypeName": "MA-secondary-network-commissioning", - "deviceTypeCode": 4293984258, + "deviceTypeName": "MA-secondary-network-interface", + "deviceTypeCode": 25, "deviceTypeProfileId": 259, "clusters": [ { diff --git a/examples/ota-requestor-app/ota-requestor-common/ota-requestor-app.matter b/examples/ota-requestor-app/ota-requestor-common/ota-requestor-app.matter index da7faa284f9927..3e49c28226637a 100644 --- a/examples/ota-requestor-app/ota-requestor-common/ota-requestor-app.matter +++ b/examples/ota-requestor-app/ota-requestor-common/ota-requestor-app.matter @@ -1560,7 +1560,7 @@ endpoint 1 { } } endpoint 65534 { - device type ma_secondary_network_commissioning = 4293984258, version 1; + device type ma_secondary_network_interface = 25, version 1; server cluster Descriptor { diff --git a/examples/ota-requestor-app/ota-requestor-common/ota-requestor-app.zap b/examples/ota-requestor-app/ota-requestor-common/ota-requestor-app.zap index 686335a5b3c3b7..e4133c02918306 100644 --- a/examples/ota-requestor-app/ota-requestor-common/ota-requestor-app.zap +++ b/examples/ota-requestor-app/ota-requestor-common/ota-requestor-app.zap @@ -1,6 +1,6 @@ { "fileFormat": 2, - "featureLevel": 100, + "featureLevel": 102, "creator": "zap", "keyValuePairs": [ { @@ -2946,27 +2946,27 @@ "id": 3, "name": "Anonymous Endpoint Type", "deviceTypeRef": { - "code": 4293984258, + "code": 25, "profileId": 259, - "label": "MA-secondary-network-commissioning", - "name": "MA-secondary-network-commissioning" + "label": "MA-secondary-network-interface", + "name": "MA-secondary-network-interface" }, "deviceTypes": [ { - "code": 4293984258, + "code": 25, "profileId": 259, - "label": "MA-secondary-network-commissioning", - "name": "MA-secondary-network-commissioning" + "label": "MA-secondary-network-interface", + "name": "MA-secondary-network-interface" } ], "deviceVersions": [ 1 ], "deviceIdentifiers": [ - 4293984258 + 25 ], - "deviceTypeName": "MA-secondary-network-commissioning", - "deviceTypeCode": 4293984258, + "deviceTypeName": "MA-secondary-network-interface", + "deviceTypeCode": 25, "deviceTypeProfileId": 259, "clusters": [ { diff --git a/scripts/tools/zap/tests/inputs/all-clusters-app.zap b/scripts/tools/zap/tests/inputs/all-clusters-app.zap index 04f2c793285f9f..784c8dfddb7664 100644 --- a/scripts/tools/zap/tests/inputs/all-clusters-app.zap +++ b/scripts/tools/zap/tests/inputs/all-clusters-app.zap @@ -1,6 +1,6 @@ { "fileFormat": 2, - "featureLevel": 100, + "featureLevel": 102, "creator": "zap", "keyValuePairs": [ { @@ -16043,27 +16043,27 @@ "id": 4, "name": "Anonymous Endpoint Type", "deviceTypeRef": { - "code": 4293984258, + "code": 25, "profileId": 259, - "label": "MA-secondary-network-commissioning", - "name": "MA-secondary-network-commissioning" + "label": "MA-secondary-network-interface", + "name": "MA-secondary-network-interface" }, "deviceTypes": [ { - "code": 4293984258, + "code": 25, "profileId": 259, - "label": "MA-secondary-network-commissioning", - "name": "MA-secondary-network-commissioning" + "label": "MA-secondary-network-interface", + "name": "MA-secondary-network-interface" } ], "deviceVersions": [ 1 ], "deviceIdentifiers": [ - 4293984258 + 25 ], - "deviceTypeName": "MA-secondary-network-commissioning", - "deviceTypeCode": 4293984258, + "deviceTypeName": "MA-secondary-network-interface", + "deviceTypeCode": 25, "deviceTypeProfileId": 259, "clusters": [ { diff --git a/scripts/tools/zap/tests/outputs/all-clusters-app/app-templates/endpoint_config.h b/scripts/tools/zap/tests/outputs/all-clusters-app/app-templates/endpoint_config.h index ca2e15eedf5683..55da8ec3f3f136 100644 --- a/scripts/tools/zap/tests/outputs/all-clusters-app/app-templates/endpoint_config.h +++ b/scripts/tools/zap/tests/outputs/all-clusters-app/app-templates/endpoint_config.h @@ -3047,7 +3047,7 @@ static_assert(ATTRIBUTE_LARGEST <= CHIP_CONFIG_MAX_ATTRIBUTE_STORE_ELEMENT_SIZE, { \ { 0x00000011, 1 }, { 0x00000016, 1 }, { 0x00000100, 1 }, { 0x00000011, 1 }, { 0x00000100, 1 }, { 0x00000011, 1 }, \ { \ - 0xFFF10002, 1 \ + 0x00000019, 1 \ } \ } diff --git a/src/app/zap-templates/zcl/data-model/chip/matter-devices.xml b/src/app/zap-templates/zcl/data-model/chip/matter-devices.xml index 83a462c4a64a4a..2aad342ea71311 100644 --- a/src/app/zap-templates/zcl/data-model/chip/matter-devices.xml +++ b/src/app/zap-templates/zcl/data-model/chip/matter-devices.xml @@ -2590,11 +2590,13 @@ limitations under the License. - MA-secondary-network-commissioning + MA-secondary-network-interface CHIP - Matter Secondary Network Commissioning Device Type + Matter Secondary Network Interface Device Type 0x0103 - 0xFFF10002 + 0x0019 + Utility + Endpoint @@ -2603,6 +2605,9 @@ limitations under the License. CLIENT_LIST PARTS_LIST + + + diff --git a/src/darwin/Framework/CHIP/zap-generated/MTRDeviceTypeMetadata.mm b/src/darwin/Framework/CHIP/zap-generated/MTRDeviceTypeMetadata.mm index 06042f32f9f1d8..1dcb80d7fd1e99 100644 --- a/src/darwin/Framework/CHIP/zap-generated/MTRDeviceTypeMetadata.mm +++ b/src/darwin/Framework/CHIP/zap-generated/MTRDeviceTypeMetadata.mm @@ -44,6 +44,7 @@ { 0x00000014, DeviceTypeClass::Utility, "Matter OTA Provider" }, { 0x00000015, DeviceTypeClass::Simple, "Matter Contact Sensor" }, { 0x00000016, DeviceTypeClass::Node, "Matter Root Node" }, + { 0x00000019, DeviceTypeClass::Utility, "Matter Secondary Network Interface Device Type" }, { 0x00000022, DeviceTypeClass::Simple, "Matter Speaker" }, { 0x00000023, DeviceTypeClass::Simple, "Matter Casting Video Player" }, { 0x00000024, DeviceTypeClass::Simple, "Matter Content App" }, @@ -100,7 +101,6 @@ }; static_assert(ExtractVendorFromMEI(0xFFF10001) != 0, "Must have class defined for \"Matter Orphan Clusters\" if it's a standard device type"); -static_assert(ExtractVendorFromMEI(0xFFF10002) != 0, "Must have class defined for \"Matter Secondary Network Commissioning Device Type\" if it's a standard device type"); static_assert(ExtractVendorFromMEI(0xFFF10003) != 0, "Must have class defined for \"Matter All-clusters-app Server Example\" if it's a standard device type"); } // anonymous namespace From 0050994833d1402c055fea85b4c3cfbb74f8e1b0 Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Wed, 5 Jun 2024 01:36:58 -0400 Subject: [PATCH 10/15] Fix advertised device type for all-clusters-app to match data model. (#33715) * Fix advertised device type for all-clusters-app to match data model. We were claiming a device type of 0x0101 in the Descriptor DeviceTypeList on endpoint 1, but claiming a device type of 0xFFFF (not even a valid value) via DNS-SD advertising. Align our advertising behavior with the data model values. Fixes https://github.com/project-chip/connectedhomeip/issues/33697 * Address review comment. --- .../all-clusters-app/linux/include/CHIPProjectAppConfig.h | 4 ++++ .../all-clusters-app/tizen/include/CHIPProjectAppConfig.h | 4 ++++ src/app/tests/suites/TestDiscovery.yaml | 5 ++++- 3 files changed, 12 insertions(+), 1 deletion(-) diff --git a/examples/all-clusters-app/linux/include/CHIPProjectAppConfig.h b/examples/all-clusters-app/linux/include/CHIPProjectAppConfig.h index 440ba53f4ee3ba..0285563216e706 100644 --- a/examples/all-clusters-app/linux/include/CHIPProjectAppConfig.h +++ b/examples/all-clusters-app/linux/include/CHIPProjectAppConfig.h @@ -47,3 +47,7 @@ #define CHIP_CONFIG_MAX_PATHS_PER_INVOKE 5 #define CHIP_CONFIG_ENABLE_BDX_LOG_TRANSFER 1 + +// Claim a device type while advertising that matches the device type on our +// endpoint 1. 0x0101 is the "Dimmable Light" device type. +#define CHIP_DEVICE_CONFIG_DEVICE_TYPE 0x0101 diff --git a/examples/all-clusters-app/tizen/include/CHIPProjectAppConfig.h b/examples/all-clusters-app/tizen/include/CHIPProjectAppConfig.h index 38f322eecaab66..3d67773217a22a 100644 --- a/examples/all-clusters-app/tizen/include/CHIPProjectAppConfig.h +++ b/examples/all-clusters-app/tizen/include/CHIPProjectAppConfig.h @@ -33,3 +33,7 @@ // All clusters app has 3 group endpoints. This needs to defined here so that // CHIP_CONFIG_MAX_GROUPS_PER_FABRIC is properly configured. #define CHIP_CONFIG_MAX_GROUP_ENDPOINTS_PER_FABRIC 3 + +// Claim a device type while advertising that matches the device type on our +// endpoint 1. 0x0101 is the "Dimmable Light" device type. +#define CHIP_DEVICE_CONFIG_DEVICE_TYPE 0x0101 diff --git a/src/app/tests/suites/TestDiscovery.yaml b/src/app/tests/suites/TestDiscovery.yaml index 77c0615a27bc8d..0cb6a033cc50ae 100644 --- a/src/app/tests/suites/TestDiscovery.yaml +++ b/src/app/tests/suites/TestDiscovery.yaml @@ -17,6 +17,9 @@ name: Test Discovery config: nodeId: 0x12344321 endpoint: 0 + # These defaults correspond to the behavior of all-clusters-app, and + # different values should be passed on the command line when testing + # against any other server. discriminator: type: int16u defaultValue: 3840 @@ -31,7 +34,7 @@ config: defaultValue: 32769 deviceType: type: int16u - defaultValue: 65535 + defaultValue: 0x0101 tests: - label: "Stop target device" From 4a8dc7371ec95e4a9c8e1210fd5757a8b8aaeeac Mon Sep 17 00:00:00 2001 From: Jakub Latusek Date: Wed, 5 Jun 2024 14:35:44 +0200 Subject: [PATCH 11/15] Replace ChipBleUUID local variables for all platform (#33713) * Replace uuid for rest platform * Restyle * Update define for webos * Fix typo --- src/platform/ASR/BLEManagerImpl.cpp | 19 +++------- src/platform/Ameba/BLEManagerImpl.cpp | 13 +++---- src/platform/Beken/BLEManagerImpl.cpp | 14 +++----- .../ESP32/bluedroid/BLEManagerImpl.cpp | 20 +++++------ src/platform/ESP32/nimble/BLEManagerImpl.cpp | 22 +++++------- .../Infineon/CYW30739/BLEManagerImpl.cpp | 18 +++------- .../Infineon/PSOC6/BLEManagerImpl.cpp | 17 +++------ src/platform/Linux/BLEManagerImpl.cpp | 27 ++++++-------- src/platform/NuttX/BLEManagerImpl.cpp | 27 ++++++-------- src/platform/Zephyr/BLEManagerImpl.cpp | 14 +++----- .../bouffalolab/common/BLEManagerImpl.cpp | 13 +++---- src/platform/cc13xx_26xx/BLEManagerImpl.cpp | 8 ++--- .../cc13xx_26xx/cc13x4_26x4/BLEManagerImpl.h | 5 --- src/platform/mbed/BLEManagerImpl.cpp | 16 ++++----- src/platform/mt793x/BLEManagerImpl.cpp | 16 +++------ .../nxp/k32w/common/BLEManagerCommon.cpp | 16 ++++----- src/platform/qpg/BLEManagerImpl.cpp | 27 +++++--------- src/platform/silabs/efr32/BLEManagerImpl.cpp | 20 +++++------ src/platform/silabs/rs911x/BLEManagerImpl.cpp | 18 ++++------ src/platform/stm32/BLEManagerImpl.cpp | 14 +++----- src/platform/telink/BLEManagerImpl.cpp | 14 +++----- src/platform/webos/BLEManagerImpl.cpp | 36 ++++++++----------- 22 files changed, 136 insertions(+), 258 deletions(-) diff --git a/src/platform/ASR/BLEManagerImpl.cpp b/src/platform/ASR/BLEManagerImpl.cpp index 88f7460a962a3a..681639dda50a4a 100644 --- a/src/platform/ASR/BLEManagerImpl.cpp +++ b/src/platform/ASR/BLEManagerImpl.cpp @@ -62,15 +62,6 @@ namespace { const uint8_t ShortUUID_CHIPoBLEService[] = { 0xF6, 0xFF }; -const ChipBleUUID ChipUUID_CHIPoBLEChar_RX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, - 0x9D, 0x11 } }; - -const ChipBleUUID ChipUUID_CHIPoBLEChar_TX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, - 0x9D, 0x12 } }; -#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING -const ChipBleUUID ChipUUID_CHIPoBLEChar_C3 = { { 0x64, 0x63, 0x02, 0x38, 0x87, 0x72, 0x45, 0xF2, 0xB8, 0x7D, 0x74, 0x8A, 0x83, 0x21, - 0x8F, 0x04 } }; -#endif static constexpr System::Clock::Timeout kFastAdvertiseTimeout = System::Clock::Milliseconds32(CHIP_DEVICE_CONFIG_BLE_ADVERTISING_INTERVAL_CHANGE_TIME); System::Clock::Timestamp mAdvertiseStartTime; @@ -254,7 +245,7 @@ void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) switch (event->Type) { case DeviceEventType::kCHIPoBLESubscribe: - HandleSubscribeReceived(event->CHIPoBLESubscribe.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); + HandleSubscribeReceived(event->CHIPoBLESubscribe.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); { ChipDeviceEvent connectionEvent; connectionEvent.Type = DeviceEventType::kCHIPoBLEConnectionEstablished; @@ -263,20 +254,20 @@ void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) break; case DeviceEventType::kCHIPoBLEUnsubscribe: - HandleUnsubscribeReceived(event->CHIPoBLEUnsubscribe.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); + HandleUnsubscribeReceived(event->CHIPoBLEUnsubscribe.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); break; case DeviceEventType::kCHIPoBLEWriteReceived: - HandleWriteReceived(event->CHIPoBLEWriteReceived.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_RX, + HandleWriteReceived(event->CHIPoBLEWriteReceived.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_1_UUID, PacketBufferHandle::Adopt(event->CHIPoBLEWriteReceived.Data)); break; case DeviceEventType::kCHIPoBLENotifyConfirm: - HandleIndicationConfirmation(event->CHIPoBLENotifyConfirm.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); + HandleIndicationConfirmation(event->CHIPoBLENotifyConfirm.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); break; case DeviceEventType::kCHIPoBLEIndicateConfirm: - HandleIndicationConfirmation(event->CHIPoBLEIndicateConfirm.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); + HandleIndicationConfirmation(event->CHIPoBLEIndicateConfirm.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); break; case DeviceEventType::kCHIPoBLEConnectionError: diff --git a/src/platform/Ameba/BLEManagerImpl.cpp b/src/platform/Ameba/BLEManagerImpl.cpp index 2d0a6d99515367..e4e881357d95fa 100644 --- a/src/platform/Ameba/BLEManagerImpl.cpp +++ b/src/platform/Ameba/BLEManagerImpl.cpp @@ -127,11 +127,6 @@ typedef struct const ble_uuid16_t ShortUUID_CHIPoBLEService = { BLE_UUID_TYPE_16, 0xFFF6 }; -const ChipBleUUID ChipUUID_CHIPoBLEChar_RX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, - 0x9D, 0x11 } }; -const ChipBleUUID ChipUUID_CHIPoBLEChar_TX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, - 0x9D, 0x12 } }; - static constexpr System::Clock::Timeout kFastAdvertiseTimeout = System::Clock::Milliseconds32(CHIP_DEVICE_CONFIG_BLE_ADVERTISING_INTERVAL_CHANGE_TIME); System::Clock::Timestamp mAdvertiseStartTime; @@ -469,7 +464,7 @@ void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) { // Platform specific events case DeviceEventType::kCHIPoBLESubscribe: - HandleSubscribeReceived(event->CHIPoBLESubscribe.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); + HandleSubscribeReceived(event->CHIPoBLESubscribe.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); { ChipDeviceEvent connEstEvent; connEstEvent.Type = DeviceEventType::kCHIPoBLEConnectionEstablished; @@ -479,13 +474,13 @@ void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) case DeviceEventType::kCHIPoBLEUnsubscribe: { ChipLogProgress(DeviceLayer, "_OnPlatformEvent kCHIPoBLEUnsubscribe"); - HandleUnsubscribeReceived(event->CHIPoBLEUnsubscribe.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); + HandleUnsubscribeReceived(event->CHIPoBLEUnsubscribe.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); } break; case DeviceEventType::kCHIPoBLEWriteReceived: { ChipLogProgress(DeviceLayer, "_OnPlatformEvent kCHIPoBLEWriteReceived"); - HandleWriteReceived(event->CHIPoBLEWriteReceived.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_RX, + HandleWriteReceived(event->CHIPoBLEWriteReceived.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_1_UUID, PacketBufferHandle::Adopt(event->CHIPoBLEWriteReceived.Data)); } break; @@ -498,7 +493,7 @@ void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) case DeviceEventType::kCHIPoBLEIndicateConfirm: { ChipLogProgress(DeviceLayer, "_OnPlatformEvent kCHIPoBLEIndicateConfirm"); - HandleIndicationConfirmation(event->CHIPoBLEIndicateConfirm.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); + HandleIndicationConfirmation(event->CHIPoBLEIndicateConfirm.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); } break; diff --git a/src/platform/Beken/BLEManagerImpl.cpp b/src/platform/Beken/BLEManagerImpl.cpp index 37f9fea9b9106e..4cd53bd5cd2d89 100644 --- a/src/platform/Beken/BLEManagerImpl.cpp +++ b/src/platform/Beken/BLEManagerImpl.cpp @@ -73,11 +73,7 @@ enum DriveBLEExtPerfEvt_DISCONNECT = 0, }; -const ChipBleUUID ChipUUID_CHIPoBLEChar_RX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, - 0x9D, 0x11 } }; -const ChipBleUUID ChipUUID_CHIPoBLEChar_TX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, - 0x9D, 0x12 } }; -static const uint8_t _svc_uuid[16] = { 0xF6, 0xFF, 0, 0, 0x0, 0x0, 0, 0, 0, 0, 0x0, 0x0, 0, 0, 0, 0 }; +static const uint8_t _svc_uuid[16] = { 0xF6, 0xFF, 0, 0, 0x0, 0x0, 0, 0, 0, 0, 0x0, 0x0, 0, 0, 0, 0 }; #define UUID_CHIPoBLECharact_RX \ { \ @@ -498,7 +494,7 @@ void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) { // Platform specific events case DeviceEventType::kCHIPoBLESubscribe: - HandleSubscribeReceived(event->CHIPoBLESubscribe.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); + HandleSubscribeReceived(event->CHIPoBLESubscribe.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); { ChipDeviceEvent connEstEvent; connEstEvent.Type = DeviceEventType::kCHIPoBLEConnectionEstablished; @@ -508,13 +504,13 @@ void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) case DeviceEventType::kCHIPoBLEUnsubscribe: { ChipLogProgress(DeviceLayer, "_OnPlatformEvent kCHIPoBLEUnsubscribe"); - HandleUnsubscribeReceived(event->CHIPoBLEUnsubscribe.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); + HandleUnsubscribeReceived(event->CHIPoBLEUnsubscribe.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); } break; case DeviceEventType::kCHIPoBLEWriteReceived: { ChipLogProgress(DeviceLayer, "_OnPlatformEvent kCHIPoBLEWriteReceived"); - HandleWriteReceived(event->CHIPoBLEWriteReceived.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_RX, + HandleWriteReceived(event->CHIPoBLEWriteReceived.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_1_UUID, PacketBufferHandle::Adopt(event->CHIPoBLEWriteReceived.Data)); } break; @@ -527,7 +523,7 @@ void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) case DeviceEventType::kCHIPoBLEIndicateConfirm: { ChipLogProgress(DeviceLayer, "_OnPlatformEvent kCHIPoBLEIndicateConfirm"); - HandleIndicationConfirmation(event->CHIPoBLEIndicateConfirm.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); + HandleIndicationConfirmation(event->CHIPoBLEIndicateConfirm.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); } break; diff --git a/src/platform/ESP32/bluedroid/BLEManagerImpl.cpp b/src/platform/ESP32/bluedroid/BLEManagerImpl.cpp index 3e5cc6091e9314..e2fe1627812e82 100644 --- a/src/platform/ESP32/bluedroid/BLEManagerImpl.cpp +++ b/src/platform/ESP32/bluedroid/BLEManagerImpl.cpp @@ -99,10 +99,6 @@ const uint8_t UUID_CHIPoBLEChar_TX[] = { 0x12, 0x9D, 0x9F, 0x42, 0x9C, 0x4F #ifdef CONFIG_ENABLE_ESP32_BLE_CONTROLLER const uint8_t ShortUUID_CHIPoBLE_CharTx_Desc[] = { 0x02, 0x29 }; #endif -const ChipBleUUID ChipUUID_CHIPoBLEChar_RX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, - 0x9D, 0x11 } }; -const ChipBleUUID ChipUUID_CHIPoBLEChar_TX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, - 0x9D, 0x12 } }; const uint8_t CharProps_ReadNotify = ESP_GATT_CHAR_PROP_BIT_READ | ESP_GATT_CHAR_PROP_BIT_NOTIFY; const uint8_t CharProps_Write = ESP_GATT_CHAR_PROP_BIT_WRITE; @@ -324,7 +320,7 @@ void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) switch (event->Type) { case DeviceEventType::kCHIPoBLESubscribe: - HandleSubscribeReceived(event->CHIPoBLESubscribe.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); + HandleSubscribeReceived(event->CHIPoBLESubscribe.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); { ChipDeviceEvent connectionEvent; connectionEvent.Type = DeviceEventType::kCHIPoBLEConnectionEstablished; @@ -333,16 +329,16 @@ void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) break; case DeviceEventType::kCHIPoBLEUnsubscribe: - HandleUnsubscribeReceived(event->CHIPoBLEUnsubscribe.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); + HandleUnsubscribeReceived(event->CHIPoBLEUnsubscribe.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); break; case DeviceEventType::kCHIPoBLEWriteReceived: - HandleWriteReceived(event->CHIPoBLEWriteReceived.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_RX, + HandleWriteReceived(event->CHIPoBLEWriteReceived.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_1_UUID, PacketBufferHandle::Adopt(event->CHIPoBLEWriteReceived.Data)); break; case DeviceEventType::kCHIPoBLEIndicateConfirm: - HandleIndicationConfirmation(event->CHIPoBLEIndicateConfirm.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); + HandleIndicationConfirmation(event->CHIPoBLEIndicateConfirm.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); break; case DeviceEventType::kCHIPoBLEConnectionError: @@ -393,20 +389,20 @@ void BLEManagerImpl::HandlePlatformSpecificBLEEvent(const ChipDeviceEvent * apEv break; case DeviceEventType::kPlatformESP32BLEWriteComplete: - HandleWriteConfirmation(apEvent->Platform.BLEWriteComplete.mConnection, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_RX); + HandleWriteConfirmation(apEvent->Platform.BLEWriteComplete.mConnection, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_1_UUID); break; case DeviceEventType::kPlatformESP32BLESubscribeOpComplete: if (apEvent->Platform.BLESubscribeOpComplete.mIsSubscribed) HandleSubscribeComplete(apEvent->Platform.BLESubscribeOpComplete.mConnection, &CHIP_BLE_SVC_ID, - &ChipUUID_CHIPoBLEChar_TX); + &Ble::CHIP_BLE_CHAR_2_UUID); else HandleUnsubscribeComplete(apEvent->Platform.BLESubscribeOpComplete.mConnection, &CHIP_BLE_SVC_ID, - &ChipUUID_CHIPoBLEChar_TX); + &Ble::CHIP_BLE_CHAR_2_UUID); break; case DeviceEventType::kPlatformESP32BLEIndicationReceived: - HandleIndicationReceived(apEvent->Platform.BLEIndicationReceived.mConnection, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX, + HandleIndicationReceived(apEvent->Platform.BLEIndicationReceived.mConnection, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID, PacketBufferHandle::Adopt(apEvent->Platform.BLEIndicationReceived.mData)); break; diff --git a/src/platform/ESP32/nimble/BLEManagerImpl.cpp b/src/platform/ESP32/nimble/BLEManagerImpl.cpp index c153e4b592c8ea..cff25239fc6c8d 100644 --- a/src/platform/ESP32/nimble/BLEManagerImpl.cpp +++ b/src/platform/ESP32/nimble/BLEManagerImpl.cpp @@ -103,12 +103,8 @@ const ble_uuid16_t ShortUUID_CHIPoBLE_CharTx_Desc = { BLE_UUID_TYPE_16, 0x2902 } const ble_uuid128_t UUID128_CHIPoBLEChar_RX = { BLE_UUID_TYPE_128, { 0x11, 0x9D, 0x9F, 0x42, 0x9C, 0x4F, 0x9F, 0x95, 0x59, 0x45, 0x3D, 0x26, 0xF5, 0x2E, 0xEE, 0x18 } }; -const ChipBleUUID chipUUID_CHIPoBLEChar_RX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, - 0x9D, 0x11 } }; -const ChipBleUUID chipUUID_CHIPoBLEChar_TX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, - 0x9D, 0x12 } }; -const ble_uuid128_t UUID_CHIPoBLEChar_TX = { +const ble_uuid128_t UUID_CHIPoBLEChar_TX = { { BLE_UUID_TYPE_128 }, { 0x12, 0x9D, 0x9F, 0x42, 0x9C, 0x4F, 0x9F, 0x95, 0x59, 0x45, 0x3D, 0x26, 0xF5, 0x2E, 0xEE, 0x18 } }; @@ -374,7 +370,7 @@ void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) switch (event->Type) { case DeviceEventType::kCHIPoBLESubscribe: - HandleSubscribeReceived(event->CHIPoBLESubscribe.ConId, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_TX); + HandleSubscribeReceived(event->CHIPoBLESubscribe.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); { ChipDeviceEvent connectionEvent; connectionEvent.Type = DeviceEventType::kCHIPoBLEConnectionEstablished; @@ -383,16 +379,16 @@ void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) break; case DeviceEventType::kCHIPoBLEUnsubscribe: - HandleUnsubscribeReceived(event->CHIPoBLEUnsubscribe.ConId, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_TX); + HandleUnsubscribeReceived(event->CHIPoBLEUnsubscribe.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); break; case DeviceEventType::kCHIPoBLEWriteReceived: - HandleWriteReceived(event->CHIPoBLEWriteReceived.ConId, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_RX, + HandleWriteReceived(event->CHIPoBLEWriteReceived.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_1_UUID, PacketBufferHandle::Adopt(event->CHIPoBLEWriteReceived.Data)); break; case DeviceEventType::kCHIPoBLEIndicateConfirm: - HandleIndicationConfirmation(event->CHIPoBLEIndicateConfirm.ConId, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_TX); + HandleIndicationConfirmation(event->CHIPoBLEIndicateConfirm.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); break; case DeviceEventType::kCHIPoBLEConnectionError: @@ -443,20 +439,20 @@ void BLEManagerImpl::HandlePlatformSpecificBLEEvent(const ChipDeviceEvent * apEv break; case DeviceEventType::kPlatformESP32BLEWriteComplete: - HandleWriteConfirmation(apEvent->Platform.BLEWriteComplete.mConnection, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_RX); + HandleWriteConfirmation(apEvent->Platform.BLEWriteComplete.mConnection, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_1_UUID); break; case DeviceEventType::kPlatformESP32BLESubscribeOpComplete: if (apEvent->Platform.BLESubscribeOpComplete.mIsSubscribed) HandleSubscribeComplete(apEvent->Platform.BLESubscribeOpComplete.mConnection, &CHIP_BLE_SVC_ID, - &chipUUID_CHIPoBLEChar_TX); + &Ble::CHIP_BLE_CHAR_2_UUID); else HandleUnsubscribeComplete(apEvent->Platform.BLESubscribeOpComplete.mConnection, &CHIP_BLE_SVC_ID, - &chipUUID_CHIPoBLEChar_TX); + &Ble::CHIP_BLE_CHAR_2_UUID); break; case DeviceEventType::kPlatformESP32BLEIndicationReceived: - HandleIndicationReceived(apEvent->Platform.BLEIndicationReceived.mConnection, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_TX, + HandleIndicationReceived(apEvent->Platform.BLEIndicationReceived.mConnection, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID, PacketBufferHandle::Adopt(apEvent->Platform.BLEIndicationReceived.mData)); break; diff --git a/src/platform/Infineon/CYW30739/BLEManagerImpl.cpp b/src/platform/Infineon/CYW30739/BLEManagerImpl.cpp index ab4deef1f91924..cc381e131154dc 100644 --- a/src/platform/Infineon/CYW30739/BLEManagerImpl.cpp +++ b/src/platform/Infineon/CYW30739/BLEManagerImpl.cpp @@ -49,16 +49,6 @@ namespace chip { namespace DeviceLayer { namespace Internal { -namespace { - -const ChipBleUUID chipUUID_CHIPoBLEChar_RX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, - 0x9D, 0x11 } }; - -const ChipBleUUID ChipUUID_CHIPoBLEChar_TX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, - 0x9D, 0x12 } }; - -} // unnamed namespace - BLEManagerImpl BLEManagerImpl::sInstance; wiced_bt_gatt_status_t app_gatts_callback(wiced_bt_gatt_evt_t event, wiced_bt_gatt_event_data_t * p_data); @@ -198,7 +188,7 @@ void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) switch (event->Type) { case DeviceEventType::kCHIPoBLESubscribe: - HandleSubscribeReceived(event->CHIPoBLESubscribe.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); + HandleSubscribeReceived(event->CHIPoBLESubscribe.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); { ChipDeviceEvent _event; _event.Type = DeviceEventType::kCHIPoBLEConnectionEstablished; @@ -207,17 +197,17 @@ void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) break; case DeviceEventType::kCHIPoBLEUnsubscribe: - HandleUnsubscribeReceived(event->CHIPoBLEUnsubscribe.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); + HandleUnsubscribeReceived(event->CHIPoBLEUnsubscribe.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); break; case DeviceEventType::kCHIPoBLEWriteReceived: ChipLogProgress(DeviceLayer, "_OnPlatformEvent kCHIPoBLEWriteReceived"); - HandleWriteReceived(event->CHIPoBLEWriteReceived.ConId, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_RX, + HandleWriteReceived(event->CHIPoBLEWriteReceived.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_1_UUID, PacketBufferHandle::Adopt(event->CHIPoBLEWriteReceived.Data)); break; case DeviceEventType::kCHIPoBLEIndicateConfirm: - HandleIndicationConfirmation(event->CHIPoBLEIndicateConfirm.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); + HandleIndicationConfirmation(event->CHIPoBLEIndicateConfirm.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); break; case DeviceEventType::kCHIPoBLEConnectionError: diff --git a/src/platform/Infineon/PSOC6/BLEManagerImpl.cpp b/src/platform/Infineon/PSOC6/BLEManagerImpl.cpp index cb2b01197669e7..cfe49953676d65 100644 --- a/src/platform/Infineon/PSOC6/BLEManagerImpl.cpp +++ b/src/platform/Infineon/PSOC6/BLEManagerImpl.cpp @@ -60,14 +60,7 @@ namespace chip { namespace DeviceLayer { namespace Internal { -namespace { -const ChipBleUUID chipUUID_CHIPoBLEChar_RX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, - 0x9D, 0x11 } }; - -const ChipBleUUID ChipUUID_CHIPoBLEChar_TX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, - 0x9D, 0x12 } }; - -} // unnamed namespace +namespace {} // unnamed namespace BLEManagerImpl BLEManagerImpl::sInstance; @@ -240,7 +233,7 @@ void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) break; case DeviceEventType::kCHIPoBLESubscribe: - HandleSubscribeReceived(event->CHIPoBLESubscribe.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); + HandleSubscribeReceived(event->CHIPoBLESubscribe.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); { ChipDeviceEvent _event; _event.Type = DeviceEventType::kCHIPoBLEConnectionEstablished; @@ -249,16 +242,16 @@ void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) break; case DeviceEventType::kCHIPoBLEUnsubscribe: - HandleUnsubscribeReceived(event->CHIPoBLEUnsubscribe.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); + HandleUnsubscribeReceived(event->CHIPoBLEUnsubscribe.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); break; case DeviceEventType::kCHIPoBLEWriteReceived: - HandleWriteReceived(event->CHIPoBLEWriteReceived.ConId, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_RX, + HandleWriteReceived(event->CHIPoBLEWriteReceived.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_1_UUID, PacketBufferHandle::Adopt(event->CHIPoBLEWriteReceived.Data)); break; case DeviceEventType::kCHIPoBLEIndicateConfirm: - HandleIndicationConfirmation(event->CHIPoBLEIndicateConfirm.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); + HandleIndicationConfirmation(event->CHIPoBLEIndicateConfirm.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); break; case DeviceEventType::kCHIPoBLEConnectionError: diff --git a/src/platform/Linux/BLEManagerImpl.cpp b/src/platform/Linux/BLEManagerImpl.cpp index a61c6e2403de02..251f4f0d9261dd 100644 --- a/src/platform/Linux/BLEManagerImpl.cpp +++ b/src/platform/Linux/BLEManagerImpl.cpp @@ -72,11 +72,6 @@ static_assert(CHIP_DEVICE_CONFIG_BLE_EXT_ADVERTISING_INTERVAL_CHANGE_TIME_MS >= "The extended advertising interval change time must be greater than the fast advertising interval change time"); #endif -const ChipBleUUID ChipUUID_CHIPoBLEChar_RX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, - 0x9D, 0x11 } }; -const ChipBleUUID ChipUUID_CHIPoBLEChar_TX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, - 0x9D, 0x12 } }; - } // namespace BLEManagerImpl BLEManagerImpl::sInstance; @@ -202,7 +197,7 @@ void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) switch (event->Type) { case DeviceEventType::kCHIPoBLESubscribe: - HandleSubscribeReceived(event->CHIPoBLESubscribe.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); + HandleSubscribeReceived(event->CHIPoBLESubscribe.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); { ChipDeviceEvent connectionEvent{ .Type = DeviceEventType::kCHIPoBLEConnectionEstablished }; PlatformMgr().PostEventOrDie(&connectionEvent); @@ -210,16 +205,16 @@ void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) break; case DeviceEventType::kCHIPoBLEUnsubscribe: - HandleUnsubscribeReceived(event->CHIPoBLEUnsubscribe.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); + HandleUnsubscribeReceived(event->CHIPoBLEUnsubscribe.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); break; case DeviceEventType::kCHIPoBLEWriteReceived: - HandleWriteReceived(event->CHIPoBLEWriteReceived.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_RX, + HandleWriteReceived(event->CHIPoBLEWriteReceived.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_1_UUID, PacketBufferHandle::Adopt(event->CHIPoBLEWriteReceived.Data)); break; case DeviceEventType::kCHIPoBLEIndicateConfirm: - HandleIndicationConfirmation(event->CHIPoBLEIndicateConfirm.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); + HandleIndicationConfirmation(event->CHIPoBLEIndicateConfirm.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); break; case DeviceEventType::kCHIPoBLEConnectionError: @@ -290,18 +285,18 @@ void BLEManagerImpl::HandlePlatformSpecificBLEEvent(const ChipDeviceEvent * apEv } break; case DeviceEventType::kPlatformLinuxBLEWriteComplete: - HandleWriteConfirmation(apEvent->Platform.BLEWriteComplete.mConnection, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_RX); + HandleWriteConfirmation(apEvent->Platform.BLEWriteComplete.mConnection, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_1_UUID); break; case DeviceEventType::kPlatformLinuxBLESubscribeOpComplete: if (apEvent->Platform.BLESubscribeOpComplete.mIsSubscribed) HandleSubscribeComplete(apEvent->Platform.BLESubscribeOpComplete.mConnection, &CHIP_BLE_SVC_ID, - &ChipUUID_CHIPoBLEChar_TX); + &Ble::CHIP_BLE_CHAR_2_UUID); else HandleUnsubscribeComplete(apEvent->Platform.BLESubscribeOpComplete.mConnection, &CHIP_BLE_SVC_ID, - &ChipUUID_CHIPoBLEChar_TX); + &Ble::CHIP_BLE_CHAR_2_UUID); break; case DeviceEventType::kPlatformLinuxBLEIndicationReceived: - HandleIndicationReceived(apEvent->Platform.BLEIndicationReceived.mConnection, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX, + HandleIndicationReceived(apEvent->Platform.BLEIndicationReceived.mConnection, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID, PacketBufferHandle::Adopt(apEvent->Platform.BLEIndicationReceived.mData)); break; case DeviceEventType::kPlatformLinuxBLEPeripheralAdvStartComplete: @@ -368,7 +363,7 @@ bool BLEManagerImpl::SubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const ChipLogError(DeviceLayer, "BLE connection is not initialized in %s", __func__)); VerifyOrExit(Ble::UUIDsMatch(svcId, &CHIP_BLE_SVC_ID), ChipLogError(DeviceLayer, "SubscribeCharacteristic() called with invalid service ID")); - VerifyOrExit(Ble::UUIDsMatch(charId, &ChipUUID_CHIPoBLEChar_TX), + VerifyOrExit(Ble::UUIDsMatch(charId, &Ble::CHIP_BLE_CHAR_2_UUID), ChipLogError(DeviceLayer, "SubscribeCharacteristic() called with invalid characteristic ID")); VerifyOrExit(conId->SubscribeCharacteristic() == CHIP_NO_ERROR, ChipLogError(DeviceLayer, "SubscribeCharacteristic() failed")); @@ -386,7 +381,7 @@ bool BLEManagerImpl::UnsubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, cons ChipLogError(DeviceLayer, "BLE connection is not initialized in %s", __func__)); VerifyOrExit(Ble::UUIDsMatch(svcId, &CHIP_BLE_SVC_ID), ChipLogError(DeviceLayer, "UnsubscribeCharacteristic() called with invalid service ID")); - VerifyOrExit(Ble::UUIDsMatch(charId, &ChipUUID_CHIPoBLEChar_TX), + VerifyOrExit(Ble::UUIDsMatch(charId, &Ble::CHIP_BLE_CHAR_2_UUID), ChipLogError(DeviceLayer, "UnsubscribeCharacteristic() called with invalid characteristic ID")); VerifyOrExit(conId->UnsubscribeCharacteristic() == CHIP_NO_ERROR, @@ -435,7 +430,7 @@ bool BLEManagerImpl::SendWriteRequest(BLE_CONNECTION_OBJECT conId, const Ble::Ch ChipLogError(DeviceLayer, "BLE connection is not initialized in %s", __func__)); VerifyOrExit(Ble::UUIDsMatch(svcId, &CHIP_BLE_SVC_ID), ChipLogError(DeviceLayer, "SendWriteRequest() called with invalid service ID")); - VerifyOrExit(Ble::UUIDsMatch(charId, &ChipUUID_CHIPoBLEChar_RX), + VerifyOrExit(Ble::UUIDsMatch(charId, &Ble::CHIP_BLE_CHAR_1_UUID), ChipLogError(DeviceLayer, "SendWriteRequest() called with invalid characteristic ID")); VerifyOrExit(conId->SendWriteRequest(std::move(pBuf)) == CHIP_NO_ERROR, ChipLogError(DeviceLayer, "SendWriteRequest() failed")); diff --git a/src/platform/NuttX/BLEManagerImpl.cpp b/src/platform/NuttX/BLEManagerImpl.cpp index e472e805a1154e..980a07983018c6 100644 --- a/src/platform/NuttX/BLEManagerImpl.cpp +++ b/src/platform/NuttX/BLEManagerImpl.cpp @@ -71,11 +71,6 @@ static_assert(CHIP_DEVICE_CONFIG_BLE_EXT_ADVERTISING_INTERVAL_CHANGE_TIME_MS >= "The extended advertising interval change time must be greater than the fast advertising interval change time"); #endif -const ChipBleUUID ChipUUID_CHIPoBLEChar_RX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, - 0x9D, 0x11 } }; -const ChipBleUUID ChipUUID_CHIPoBLEChar_TX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, - 0x9D, 0x12 } }; - void HandleConnectTimeout(chip::System::Layer *, void * apEndpoint) { VerifyOrDie(apEndpoint != nullptr); @@ -213,7 +208,7 @@ void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) switch (event->Type) { case DeviceEventType::kCHIPoBLESubscribe: - HandleSubscribeReceived(event->CHIPoBLESubscribe.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); + HandleSubscribeReceived(event->CHIPoBLESubscribe.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); { ChipDeviceEvent connectionEvent; connectionEvent.Type = DeviceEventType::kCHIPoBLEConnectionEstablished; @@ -222,16 +217,16 @@ void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) break; case DeviceEventType::kCHIPoBLEUnsubscribe: - HandleUnsubscribeReceived(event->CHIPoBLEUnsubscribe.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); + HandleUnsubscribeReceived(event->CHIPoBLEUnsubscribe.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); break; case DeviceEventType::kCHIPoBLEWriteReceived: - HandleWriteReceived(event->CHIPoBLEWriteReceived.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_RX, + HandleWriteReceived(event->CHIPoBLEWriteReceived.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_1_UUID, PacketBufferHandle::Adopt(event->CHIPoBLEWriteReceived.Data)); break; case DeviceEventType::kCHIPoBLEIndicateConfirm: - HandleIndicationConfirmation(event->CHIPoBLEIndicateConfirm.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); + HandleIndicationConfirmation(event->CHIPoBLEIndicateConfirm.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); break; case DeviceEventType::kCHIPoBLEConnectionError: @@ -272,18 +267,18 @@ void BLEManagerImpl::HandlePlatformSpecificBLEEvent(const ChipDeviceEvent * apEv } break; case DeviceEventType::kPlatformLinuxBLEWriteComplete: - HandleWriteConfirmation(apEvent->Platform.BLEWriteComplete.mConnection, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_RX); + HandleWriteConfirmation(apEvent->Platform.BLEWriteComplete.mConnection, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_1_UUID); break; case DeviceEventType::kPlatformLinuxBLESubscribeOpComplete: if (apEvent->Platform.BLESubscribeOpComplete.mIsSubscribed) HandleSubscribeComplete(apEvent->Platform.BLESubscribeOpComplete.mConnection, &CHIP_BLE_SVC_ID, - &ChipUUID_CHIPoBLEChar_TX); + &Ble::CHIP_BLE_CHAR_2_UUID); else HandleUnsubscribeComplete(apEvent->Platform.BLESubscribeOpComplete.mConnection, &CHIP_BLE_SVC_ID, - &ChipUUID_CHIPoBLEChar_TX); + &Ble::CHIP_BLE_CHAR_2_UUID); break; case DeviceEventType::kPlatformLinuxBLEIndicationReceived: - HandleIndicationReceived(apEvent->Platform.BLEIndicationReceived.mConnection, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX, + HandleIndicationReceived(apEvent->Platform.BLEIndicationReceived.mConnection, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID, PacketBufferHandle::Adopt(apEvent->Platform.BLEIndicationReceived.mData)); break; case DeviceEventType::kPlatformLinuxBLEPeripheralAdvStartComplete: @@ -358,7 +353,7 @@ bool BLEManagerImpl::SubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const ChipLogError(DeviceLayer, "BLE connection is not initialized in %s", __func__)); VerifyOrExit(Ble::UUIDsMatch(svcId, &CHIP_BLE_SVC_ID), ChipLogError(DeviceLayer, "SubscribeCharacteristic() called with invalid service ID")); - VerifyOrExit(Ble::UUIDsMatch(charId, &ChipUUID_CHIPoBLEChar_TX), + VerifyOrExit(Ble::UUIDsMatch(charId, &Ble::CHIP_BLE_CHAR_2_UUID), ChipLogError(DeviceLayer, "SubscribeCharacteristic() called with invalid characteristic ID")); VerifyOrExit(conId->SubscribeCharacteristic() == CHIP_NO_ERROR, ChipLogError(DeviceLayer, "SubscribeCharacteristic() failed")); @@ -376,7 +371,7 @@ bool BLEManagerImpl::UnsubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, cons ChipLogError(DeviceLayer, "BLE connection is not initialized in %s", __func__)); VerifyOrExit(Ble::UUIDsMatch(svcId, &CHIP_BLE_SVC_ID), ChipLogError(DeviceLayer, "UnsubscribeCharacteristic() called with invalid service ID")); - VerifyOrExit(Ble::UUIDsMatch(charId, &ChipUUID_CHIPoBLEChar_TX), + VerifyOrExit(Ble::UUIDsMatch(charId, &Ble::CHIP_BLE_CHAR_2_UUID), ChipLogError(DeviceLayer, "UnsubscribeCharacteristic() called with invalid characteristic ID")); VerifyOrExit(conId->UnsubscribeCharacteristic() == CHIP_NO_ERROR, @@ -425,7 +420,7 @@ bool BLEManagerImpl::SendWriteRequest(BLE_CONNECTION_OBJECT conId, const Ble::Ch ChipLogError(DeviceLayer, "BLE connection is not initialized in %s", __func__)); VerifyOrExit(Ble::UUIDsMatch(svcId, &CHIP_BLE_SVC_ID), ChipLogError(DeviceLayer, "SendWriteRequest() called with invalid service ID")); - VerifyOrExit(Ble::UUIDsMatch(charId, &ChipUUID_CHIPoBLEChar_RX), + VerifyOrExit(Ble::UUIDsMatch(charId, &Ble::CHIP_BLE_CHAR_1_UUID), ChipLogError(DeviceLayer, "SendWriteRequest() called with invalid characteristic ID")); VerifyOrExit(conId->SendWriteRequest(std::move(pBuf)) == CHIP_NO_ERROR, ChipLogError(DeviceLayer, "SendWriteRequest() failed")); diff --git a/src/platform/Zephyr/BLEManagerImpl.cpp b/src/platform/Zephyr/BLEManagerImpl.cpp index 09bb9c0c8d71cb..03341b59dd903e 100644 --- a/src/platform/Zephyr/BLEManagerImpl.cpp +++ b/src/platform/Zephyr/BLEManagerImpl.cpp @@ -75,12 +75,6 @@ const bt_uuid_128 UUID128_CHIPoBLEChar_C3 = bt_uuid_16 UUID16_CHIPoBLEService = BT_UUID_INIT_16(0xFFF6); -const ChipBleUUID chipUUID_CHIPoBLEChar_RX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, - 0x9D, 0x11 } }; - -const ChipBleUUID chipUUID_CHIPoBLEChar_TX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, - 0x9D, 0x12 } }; - _bt_gatt_ccc CHIPoBLEChar_TX_CCC = BT_GATT_CCC_INITIALIZER(nullptr, BLEManagerImpl::HandleTXCCCWrite, nullptr); // clang-format off @@ -606,7 +600,7 @@ CHIP_ERROR BLEManagerImpl::HandleTXCharCCCDWrite(const ChipDeviceEvent * event) if (writeEvent->Value == BT_GATT_CCC_INDICATE && SetSubscribed(writeEvent->BtConn)) { // Alert the BLE layer that CHIPoBLE "subscribe" has been received and increment the bt_conn reference counter. - HandleSubscribeReceived(writeEvent->BtConn, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_TX); + HandleSubscribeReceived(writeEvent->BtConn, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); ChipLogProgress(DeviceLayer, "CHIPoBLE connection established (ConnId: 0x%02x, GATT MTU: %u)", bt_conn_index(writeEvent->BtConn), GetMTU(writeEvent->BtConn)); @@ -622,7 +616,7 @@ CHIP_ERROR BLEManagerImpl::HandleTXCharCCCDWrite(const ChipDeviceEvent * event) { if (UnsetSubscribed(writeEvent->BtConn)) { - HandleUnsubscribeReceived(writeEvent->BtConn, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_TX); + HandleUnsubscribeReceived(writeEvent->BtConn, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); } } @@ -638,7 +632,7 @@ CHIP_ERROR BLEManagerImpl::HandleRXCharWrite(const ChipDeviceEvent * event) ChipLogDetail(DeviceLayer, "Write request received for CHIPoBLE RX characteristic (ConnId 0x%02x)", bt_conn_index(c1WriteEvent->BtConn)); - HandleWriteReceived(c1WriteEvent->BtConn, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_RX, + HandleWriteReceived(c1WriteEvent->BtConn, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_1_UUID, PacketBufferHandle::Adopt(c1WriteEvent->Data)); bt_conn_unref(c1WriteEvent->BtConn); @@ -653,7 +647,7 @@ CHIP_ERROR BLEManagerImpl::HandleTXCharComplete(const ChipDeviceEvent * event) bt_conn_index(c2IndDoneEvent->BtConn), c2IndDoneEvent->Result); // Signal the BLE Layer that the outstanding indication is complete. - HandleIndicationConfirmation(c2IndDoneEvent->BtConn, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_TX); + HandleIndicationConfirmation(c2IndDoneEvent->BtConn, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); bt_conn_unref(c2IndDoneEvent->BtConn); return CHIP_NO_ERROR; diff --git a/src/platform/bouffalolab/common/BLEManagerImpl.cpp b/src/platform/bouffalolab/common/BLEManagerImpl.cpp index 0b1679ef2aeb09..f3655fa2bf5bf5 100644 --- a/src/platform/bouffalolab/common/BLEManagerImpl.cpp +++ b/src/platform/bouffalolab/common/BLEManagerImpl.cpp @@ -57,11 +57,6 @@ const bt_uuid_128 UUID128_CHIPoBLEChar_TX = BT_UUID_INIT_128(0x12, 0x9D, 0x9F, 0x42, 0x9C, 0x4F, 0x9F, 0x95, 0x59, 0x45, 0x3D, 0x26, 0xF5, 0x2E, 0xEE, 0x18); bt_uuid_16 UUID16_CHIPoBLEService = BT_UUID_INIT_16(0xFFF6); -const ChipBleUUID chipUUID_CHIPoBLEChar_RX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, - 0x9D, 0x11 } }; - -const ChipBleUUID chipUUID_CHIPoBLEChar_TX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, - 0x9D, 0x12 } }; #if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING const bt_uuid_128 UUID128_CHIPoBLEChar_C3 = BT_UUID_INIT_128(0x04, 0x8F, 0x21, 0x83, 0x8A, 0x74, 0x7D, 0xB8, 0xF2, 0x45, 0x72, 0x87, 0x38, 0x02, 0x63, 0x64); @@ -496,7 +491,7 @@ CHIP_ERROR BLEManagerImpl::HandleTXCharCCCDWrite(const ChipDeviceEvent * event) if (writeEvent->Value == BT_GATT_CCC_INDICATE && SetSubscribed(writeEvent->BtConn)) { // Alert the BLE layer that CHIPoBLE "subscribe" has been received and increment the bt_conn reference counter. - HandleSubscribeReceived(writeEvent->BtConn, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_TX); + HandleSubscribeReceived(writeEvent->BtConn, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); ChipLogProgress(DeviceLayer, "CHIPoBLE connection established (ConnId: 0x%02x, GATT MTU: %u)", bt_conn_index(writeEvent->BtConn), GetMTU(writeEvent->BtConn)); @@ -512,7 +507,7 @@ CHIP_ERROR BLEManagerImpl::HandleTXCharCCCDWrite(const ChipDeviceEvent * event) { if (UnsetSubscribed(writeEvent->BtConn)) { - HandleUnsubscribeReceived(writeEvent->BtConn, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_TX); + HandleUnsubscribeReceived(writeEvent->BtConn, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); } } @@ -528,7 +523,7 @@ CHIP_ERROR BLEManagerImpl::HandleRXCharWrite(const ChipDeviceEvent * event) ChipLogDetail(DeviceLayer, "Write request received for CHIPoBLE RX characteristic (ConnId 0x%02x)", bt_conn_index(c1WriteEvent->BtConn)); - HandleWriteReceived(c1WriteEvent->BtConn, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_RX, + HandleWriteReceived(c1WriteEvent->BtConn, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_1_UUID, PacketBufferHandle::Adopt(c1WriteEvent->Data)); bt_conn_unref(c1WriteEvent->BtConn); @@ -543,7 +538,7 @@ CHIP_ERROR BLEManagerImpl::HandleTXCharComplete(const ChipDeviceEvent * event) bt_conn_index(c2IndDoneEvent->BtConn), c2IndDoneEvent->Result); // Signal the BLE Layer that the outstanding indication is complete. - HandleIndicationConfirmation(c2IndDoneEvent->BtConn, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_TX); + HandleIndicationConfirmation(c2IndDoneEvent->BtConn, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); bt_conn_unref(c2IndDoneEvent->BtConn); return CHIP_NO_ERROR; diff --git a/src/platform/cc13xx_26xx/BLEManagerImpl.cpp b/src/platform/cc13xx_26xx/BLEManagerImpl.cpp index e8bb817a5ad48c..6d2b1c2f1523ed 100644 --- a/src/platform/cc13xx_26xx/BLEManagerImpl.cpp +++ b/src/platform/cc13xx_26xx/BLEManagerImpl.cpp @@ -223,7 +223,7 @@ void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) ChipDeviceEvent connEstEvent; BLEMGR_LOG("BLEMGR: OnPlatformEvent, kCHIPoBLESubscribe"); - HandleSubscribeReceived(event->CHIPoBLESubscribe.ConId, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_TX); + HandleSubscribeReceived(event->CHIPoBLESubscribe.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); connEstEvent.Type = DeviceEventType::kCHIPoBLEConnectionEstablished; @@ -233,19 +233,19 @@ void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) case DeviceEventType::kCHIPoBLEUnsubscribe: { BLEMGR_LOG("BLEMGR: OnPlatformEvent, kCHIPoBLEUnsubscribe"); - HandleUnsubscribeReceived(event->CHIPoBLEUnsubscribe.ConId, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_TX); + HandleUnsubscribeReceived(event->CHIPoBLEUnsubscribe.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); } break; case DeviceEventType::kCHIPoBLEWriteReceived: { BLEMGR_LOG("BLEMGR: OnPlatformEvent, kCHIPoBLEWriteReceived"); - HandleWriteReceived(event->CHIPoBLEWriteReceived.ConId, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_RX, + HandleWriteReceived(event->CHIPoBLEWriteReceived.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_1_UUID, PacketBufferHandle::Adopt(event->CHIPoBLEWriteReceived.Data)); } break; case DeviceEventType::kCHIPoBLEIndicateConfirm: - HandleIndicationConfirmation(event->CHIPoBLEIndicateConfirm.ConId, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_TX); + HandleIndicationConfirmation(event->CHIPoBLEIndicateConfirm.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); break; case DeviceEventType::kCHIPoBLEConnectionError: { diff --git a/src/platform/cc13xx_26xx/cc13x4_26x4/BLEManagerImpl.h b/src/platform/cc13xx_26xx/cc13x4_26x4/BLEManagerImpl.h index 16512930e9fa88..a5e2d31abaa6c7 100644 --- a/src/platform/cc13xx_26xx/cc13x4_26x4/BLEManagerImpl.h +++ b/src/platform/cc13xx_26xx/cc13x4_26x4/BLEManagerImpl.h @@ -240,11 +240,6 @@ class BLEManagerImpl final : public BLEManager, private BleLayer, private BlePla void NotifyChipConnectionClosed(BLE_CONNECTION_OBJECT conId) override; - const ChipBleUUID chipUUID_CHIPoBLEChar_RX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, - 0x9F, 0x9D, 0x11 } }; - const ChipBleUUID chipUUID_CHIPoBLEChar_TX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, - 0x9F, 0x9D, 0x12 } }; - friend BLEManager & BLEMgr(void); friend BLEManagerImpl & BLEMgrImpl(void); diff --git a/src/platform/mbed/BLEManagerImpl.cpp b/src/platform/mbed/BLEManagerImpl.cpp index 5048a92b1c48f3..79033dc37c6b07 100644 --- a/src/platform/mbed/BLEManagerImpl.cpp +++ b/src/platform/mbed/BLEManagerImpl.cpp @@ -63,12 +63,8 @@ namespace { const UUID ShortUUID_CHIPoBLEService(0xFFF6); // RX = BleLayer::CHIP_BLE_CHAR_1_ID const UUID LongUUID_CHIPoBLEChar_RX("18EE2EF5-263D-4559-959F-4F9C429F9D11"); -const ChipBleUUID ChipUUID_CHIPoBLEChar_RX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, - 0x9D, 0x11 } }; // TX = BleLayer::CHIP_BLE_CHAR_2_ID const UUID LongUUID_CHIPoBLEChar_TX("18EE2EF5-263D-4559-959F-4F9C429F9D12"); -const ChipBleUUID ChipUUID_CHIPoBLEChar_TX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, - 0x9D, 0x12 } }; } // namespace #if _BLEMGRIMPL_USE_LEDS @@ -905,7 +901,7 @@ void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) ChipDeviceEvent connEstEvent; ChipLogDetail(DeviceLayer, "_OnPlatformEvent kCHIPoBLESubscribe"); - HandleSubscribeReceived(event->CHIPoBLESubscribe.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); + HandleSubscribeReceived(event->CHIPoBLESubscribe.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); connEstEvent.Type = DeviceEventType::kCHIPoBLEConnectionEstablished; PlatformMgrImpl().PostEventOrDie(&connEstEvent); } @@ -913,13 +909,13 @@ void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) case DeviceEventType::kCHIPoBLEUnsubscribe: { ChipLogDetail(DeviceLayer, "_OnPlatformEvent kCHIPoBLEUnsubscribe"); - HandleUnsubscribeReceived(event->CHIPoBLEUnsubscribe.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); + HandleUnsubscribeReceived(event->CHIPoBLEUnsubscribe.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); } break; case DeviceEventType::kCHIPoBLEWriteReceived: { ChipLogDetail(DeviceLayer, "_OnPlatformEvent kCHIPoBLEWriteReceived"); - HandleWriteReceived(event->CHIPoBLEWriteReceived.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_RX, + HandleWriteReceived(event->CHIPoBLEWriteReceived.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_1_UUID, PacketBufferHandle::Adopt(event->CHIPoBLEWriteReceived.Data)); } break; @@ -932,7 +928,7 @@ void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) case DeviceEventType::kCHIPoBLEIndicateConfirm: { ChipLogDetail(DeviceLayer, "_OnPlatformEvent kCHIPoBLEIndicateConfirm"); - HandleIndicationConfirmation(event->CHIPoBLEIndicateConfirm.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); + HandleIndicationConfirmation(event->CHIPoBLEIndicateConfirm.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); } break; @@ -989,11 +985,11 @@ bool BLEManagerImpl::SendIndication(BLE_CONNECTION_OBJECT conId, const ChipBleUU VerifyOrExit(CanCastTo(pBuf->DataLength()), err = CHIP_ERROR_MESSAGE_TOO_LONG); // No need to do anything fancy here. Only 3 handles are used in this impl. - if (UUIDsMatch(charId, &ChipUUID_CHIPoBLEChar_TX)) + if (UUIDsMatch(charId, &Ble::CHIP_BLE_CHAR_2_UUID)) { att_handle = sCHIPService.getTxHandle(); } - else if (UUIDsMatch(charId, &ChipUUID_CHIPoBLEChar_RX)) + else if (UUIDsMatch(charId, &Ble::CHIP_BLE_CHAR_1_UUID)) { // TODO does this make sense? att_handle = sCHIPService.getRxHandle(); diff --git a/src/platform/mt793x/BLEManagerImpl.cpp b/src/platform/mt793x/BLEManagerImpl.cpp index 0a90f2e2a733ba..bc222c607833a5 100644 --- a/src/platform/mt793x/BLEManagerImpl.cpp +++ b/src/platform/mt793x/BLEManagerImpl.cpp @@ -79,11 +79,6 @@ const uint8_t ShortUUID_CHIPoBLEService[] = { 0xF6, 0xFF }; TimerHandle_t sbleAdvTimeoutTimer; // FreeRTOS sw timer. EventGroupHandle_t xBleEventGroup; -const ChipBleUUID ChipUUID_CHIPoBLEChar_RX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, - 0x9D, 0x11 } }; -const ChipBleUUID ChipUUID_CHIPoBLEChar_TX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, - 0x9D, 0x12 } }; - } // namespace BLEManagerImpl BLEManagerImpl::sInstance; @@ -249,7 +244,7 @@ void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) ChipDeviceEvent connEstEvent; ChipLogProgress(DeviceLayer, "_OnBlePlatformEvent kCHIPoBLESubscribe"); - HandleSubscribeReceived(event->CHIPoBLESubscribe.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); + HandleSubscribeReceived(event->CHIPoBLESubscribe.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); connEstEvent.Type = DeviceEventType::kCHIPoBLEConnectionEstablished; PlatformMgr().PostEventOrDie(&connEstEvent); } @@ -257,13 +252,13 @@ void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) case DeviceEventType::kCHIPoBLEUnsubscribe: { ChipLogProgress(DeviceLayer, "_OnBlePlatformEvent kCHIPoBLEUnsubscribe"); - HandleUnsubscribeReceived(event->CHIPoBLEUnsubscribe.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); + HandleUnsubscribeReceived(event->CHIPoBLEUnsubscribe.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); } break; case DeviceEventType::kCHIPoBLEWriteReceived: { ChipLogProgress(DeviceLayer, "_OnBlePlatformEvent kCHIPoBLEWriteReceived"); - HandleWriteReceived(event->CHIPoBLEWriteReceived.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_RX, + HandleWriteReceived(event->CHIPoBLEWriteReceived.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_1_UUID, PacketBufferHandle::Adopt(event->CHIPoBLEWriteReceived.Data)); } break; @@ -277,7 +272,7 @@ void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) case DeviceEventType::kCHIPoBLEIndicateConfirm: { ChipLogProgress(DeviceLayer, "_OnBlePlatformEvent kCHIPoBLEIndicateConfirm, ConId %04x", event->CHIPoBLEIndicateConfirm.ConId); - HandleIndicationConfirmation(event->CHIPoBLEIndicateConfirm.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); + HandleIndicationConfirmation(event->CHIPoBLEIndicateConfirm.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); } break; @@ -346,8 +341,7 @@ bool BLEManagerImpl::SendIndication(BLE_CONNECTION_OBJECT conId, const ChipBleUU ChipDeviceEvent event; bt_status_t ret; - VerifyOrExit(UUIDsMatch(&ChipUUID_CHIPoBLEChar_TX, charId), err = CHIP_ERROR_INVALID_MESSAGE_TYPE); - VerifyOrExit(UUIDsMatch(&ChipUUID_CHIPoBLEChar_TX, charId), err = CHIP_ERROR_INVALID_MESSAGE_TYPE); + VerifyOrExit(UUIDsMatch(&Ble::CHIP_BLE_CHAR_2_UUID, charId), err = CHIP_ERROR_INVALID_MESSAGE_TYPE); ChipLogProgress(DeviceLayer, "SendIndication(): conId %d, len %d", conId, data->DataLength()); diff --git a/src/platform/nxp/k32w/common/BLEManagerCommon.cpp b/src/platform/nxp/k32w/common/BLEManagerCommon.cpp index 4c9048a3f68192..0f70d5bb851e5b 100644 --- a/src/platform/nxp/k32w/common/BLEManagerCommon.cpp +++ b/src/platform/nxp/k32w/common/BLEManagerCommon.cpp @@ -125,11 +125,7 @@ EventGroupHandle_t sEventGroup; TimerHandle_t connectionTimeout; -const uint8_t ShortUUID_CHIPoBLEService[] = { 0xF6, 0xFF }; -const ChipBleUUID ChipUUID_CHIPoBLEChar_RX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, - 0x9D, 0x11 } }; -const ChipBleUUID ChipUUID_CHIPoBLEChar_TX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, - 0x9D, 0x12 } }; +const uint8_t ShortUUID_CHIPoBLEService[] = { 0xF6, 0xFF }; #if defined(chip_with_low_power) && (chip_with_low_power == 1) static bool bleAppStopInProgress; @@ -319,17 +315,17 @@ void BLEManagerCommon::_OnPlatformEvent(const ChipDeviceEvent * event) case DeviceEventType::kCHIPoBLESubscribe: ChipDeviceEvent connEstEvent; - HandleSubscribeReceived(event->CHIPoBLESubscribe.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); + HandleSubscribeReceived(event->CHIPoBLESubscribe.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); connEstEvent.Type = DeviceEventType::kCHIPoBLEConnectionEstablished; PlatformMgr().PostEventOrDie(&connEstEvent); break; case DeviceEventType::kCHIPoBLEUnsubscribe: - HandleUnsubscribeReceived(event->CHIPoBLEUnsubscribe.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); + HandleUnsubscribeReceived(event->CHIPoBLEUnsubscribe.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); break; case DeviceEventType::kCHIPoBLEWriteReceived: - HandleWriteReceived(event->CHIPoBLEWriteReceived.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_RX, + HandleWriteReceived(event->CHIPoBLEWriteReceived.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_1_UUID, PacketBufferHandle::Adopt(event->CHIPoBLEWriteReceived.Data)); break; @@ -338,7 +334,7 @@ void BLEManagerCommon::_OnPlatformEvent(const ChipDeviceEvent * event) break; case DeviceEventType::kCHIPoBLEIndicateConfirm: - HandleIndicationConfirmation(event->CHIPoBLEIndicateConfirm.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); + HandleIndicationConfirmation(event->CHIPoBLEIndicateConfirm.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); break; default: @@ -401,7 +397,7 @@ bool BLEManagerCommon::SendIndication(BLE_CONNECTION_OBJECT conId, const ChipBle PacketBufferHandle data) { CHIP_ERROR err = CHIP_NO_ERROR; - uint16_t cId = (UUIDsMatch(&ChipUUID_CHIPoBLEChar_TX, charId) ? value_chipoble_tx : 0); + uint16_t cId = (UUIDsMatch(&Ble::CHIP_BLE_CHAR_2_UUID, charId) ? value_chipoble_tx : 0); ChipDeviceEvent event; if (cId != 0) diff --git a/src/platform/qpg/BLEManagerImpl.cpp b/src/platform/qpg/BLEManagerImpl.cpp index 45d291e651146d..73b18e7046bd7f 100644 --- a/src/platform/qpg/BLEManagerImpl.cpp +++ b/src/platform/qpg/BLEManagerImpl.cpp @@ -65,17 +65,6 @@ StaticTimer_t sbleAdvTimeoutTimerBuffer; // Full service UUID - CHIP_BLE_SVC_ID - taken from BleUUID.h header const uint8_t chipUUID_CHIPoBLE_Service[CHIP_ADV_SHORT_UUID_LEN] = { 0xFF, 0xF6 }; -const ChipBleUUID chipUUID_CHIPoBLEChar_RX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, - 0x9D, 0x11 } }; - -const ChipBleUUID chipUUID_CHIPoBLEChar_TX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, - 0x9D, 0x12 } }; - -#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING -const ChipBleUUID chipUUID_CHIPoBLEChar_C3 = { { 0x64, 0x63, 0x02, 0x38, 0x87, 0x72, 0x45, 0xF2, 0xB8, 0x7D, 0x74, 0x8A, 0x83, 0x21, - 0x8F, 0x04 } }; -#endif /* CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING */ - } // unnamed namespace BLEManagerImpl BLEManagerImpl::sInstance; @@ -104,10 +93,10 @@ CHIP_ERROR BLEManagerImpl::_Init() appCbacks.cccCallback = _handleTXCharCCCDWrite; #if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING - qvCHIP_BleSetUUIDs(chipUUID_CHIPoBLE_Service, chipUUID_CHIPoBLEChar_TX.bytes, chipUUID_CHIPoBLEChar_RX.bytes, - chipUUID_CHIPoBLEChar_C3.bytes); + qvCHIP_BleSetUUIDs(chipUUID_CHIPoBLE_Service, Ble::CHIP_BLE_CHAR_2_UUID.bytes, Ble::CHIP_BLE_CHAR_1_UUID.bytes, + Ble::CHIP_BLE_CHAR_3_UUID.bytes); #else - qvCHIP_BleSetUUIDs(chipUUID_CHIPoBLE_Service, chipUUID_CHIPoBLEChar_TX.bytes, chipUUID_CHIPoBLEChar_RX.bytes, nullptr); + qvCHIP_BleSetUUIDs(chipUUID_CHIPoBLE_Service, Ble::CHIP_BLE_CHAR_2_UUID.bytes, Ble::CHIP_BLE_CHAR_1_UUID.bytes, nullptr); #endif /* CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING */ qvCHIP_BleInit(&appCbacks); @@ -211,7 +200,7 @@ void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) ChipDeviceEvent connEstEvent; ChipLogDetail(DeviceLayer, "_OnPlatformEvent kCHIPoBLESubscribe"); - HandleSubscribeReceived(event->CHIPoBLESubscribe.ConId, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_TX); + HandleSubscribeReceived(event->CHIPoBLESubscribe.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); connEstEvent.Type = DeviceEventType::kCHIPoBLEConnectionEstablished; PlatformMgr().PostEventOrDie(&connEstEvent); } @@ -221,7 +210,7 @@ void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) ChipDeviceEvent connClosedEvent; ChipLogDetail(DeviceLayer, "_OnPlatformEvent kCHIPoBLEUnsubscribe"); - HandleUnsubscribeReceived(event->CHIPoBLEUnsubscribe.ConId, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_TX); + HandleUnsubscribeReceived(event->CHIPoBLEUnsubscribe.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); connClosedEvent.Type = DeviceEventType::kCHIPoBLEConnectionClosed; PlatformMgr().PostEventOrDie(&connClosedEvent); } @@ -229,7 +218,7 @@ void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) case DeviceEventType::kCHIPoBLEWriteReceived: { ChipLogDetail(DeviceLayer, "_OnPlatformEvent kCHIPoBLEWriteReceived"); - HandleWriteReceived(event->CHIPoBLEWriteReceived.ConId, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_RX, + HandleWriteReceived(event->CHIPoBLEWriteReceived.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_1_UUID, PacketBufferHandle::Adopt(event->CHIPoBLEWriteReceived.Data)); } break; @@ -251,7 +240,7 @@ void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) case DeviceEventType::kCHIPoBLEIndicateConfirm: { ChipLogDetail(DeviceLayer, "_OnPlatformEvent kCHIPoBLEIndicateConfirm"); - HandleIndicationConfirmation(event->CHIPoBLEIndicateConfirm.ConId, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_TX); + HandleIndicationConfirmation(event->CHIPoBLEIndicateConfirm.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); } break; @@ -311,7 +300,7 @@ bool BLEManagerImpl::SendIndication(BLE_CONNECTION_OBJECT conId, const ChipBleUU VerifyOrExit(IsSubscribed(conId), err = CHIP_ERROR_INVALID_ARGUMENT); ChipLogDetail(DeviceLayer, "Sending indication for CHIPoBLE Client TX (con %u, len %u)", conId, dataLen); - isRxHandle = UUIDsMatch(&chipUUID_CHIPoBLEChar_RX, charId); + isRxHandle = UUIDsMatch(&Ble::CHIP_BLE_CHAR_1_UUID, charId); cId = qvCHIP_BleGetHandle(isRxHandle); qvCHIP_BleSendIndication(conId, cId, dataLen, data->Start()); diff --git a/src/platform/silabs/efr32/BLEManagerImpl.cpp b/src/platform/silabs/efr32/BLEManagerImpl.cpp index 4a6d78574005c1..18d7578f8f0f76 100644 --- a/src/platform/silabs/efr32/BLEManagerImpl.cpp +++ b/src/platform/silabs/efr32/BLEManagerImpl.cpp @@ -100,13 +100,9 @@ namespace { TimerHandle_t sbleAdvTimeoutTimer; // FreeRTOS sw timer. -const uint8_t UUID_CHIPoBLEService[] = { 0xFB, 0x34, 0x9B, 0x5F, 0x80, 0x00, 0x00, 0x80, - 0x00, 0x10, 0x00, 0x00, 0xF6, 0xFF, 0x00, 0x00 }; -const uint8_t ShortUUID_CHIPoBLEService[] = { 0xF6, 0xFF }; -const ChipBleUUID ChipUUID_CHIPoBLEChar_RX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, - 0x9D, 0x11 } }; -const ChipBleUUID ChipUUID_CHIPoBLEChar_TX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, - 0x9D, 0x12 } }; +const uint8_t UUID_CHIPoBLEService[] = { 0xFB, 0x34, 0x9B, 0x5F, 0x80, 0x00, 0x00, 0x80, + 0x00, 0x10, 0x00, 0x00, 0xF6, 0xFF, 0x00, 0x00 }; +const uint8_t ShortUUID_CHIPoBLEService[] = { 0xF6, 0xFF }; bd_addr randomizedAddr = { 0 }; @@ -243,7 +239,7 @@ void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) ChipDeviceEvent connEstEvent; ChipLogProgress(DeviceLayer, "_OnPlatformEvent kCHIPoBLESubscribe"); - HandleSubscribeReceived(event->CHIPoBLESubscribe.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); + HandleSubscribeReceived(event->CHIPoBLESubscribe.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); connEstEvent.Type = DeviceEventType::kCHIPoBLEConnectionEstablished; PlatformMgr().PostEventOrDie(&connEstEvent); } @@ -251,13 +247,13 @@ void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) case DeviceEventType::kCHIPoBLEUnsubscribe: { ChipLogProgress(DeviceLayer, "_OnPlatformEvent kCHIPoBLEUnsubscribe"); - HandleUnsubscribeReceived(event->CHIPoBLEUnsubscribe.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); + HandleUnsubscribeReceived(event->CHIPoBLEUnsubscribe.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); } break; case DeviceEventType::kCHIPoBLEWriteReceived: { ChipLogProgress(DeviceLayer, "_OnPlatformEvent kCHIPoBLEWriteReceived"); - HandleWriteReceived(event->CHIPoBLEWriteReceived.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_RX, + HandleWriteReceived(event->CHIPoBLEWriteReceived.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_1_UUID, PacketBufferHandle::Adopt(event->CHIPoBLEWriteReceived.Data)); } break; @@ -270,7 +266,7 @@ void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) case DeviceEventType::kCHIPoBLEIndicateConfirm: { ChipLogProgress(DeviceLayer, "_OnPlatformEvent kCHIPoBLEIndicateConfirm"); - HandleIndicationConfirmation(event->CHIPoBLEIndicateConfirm.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); + HandleIndicationConfirmation(event->CHIPoBLEIndicateConfirm.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); } break; @@ -322,7 +318,7 @@ bool BLEManagerImpl::SendIndication(BLE_CONNECTION_OBJECT conId, const ChipBleUU CHIP_ERROR err = CHIP_NO_ERROR; CHIPoBLEConState * conState = GetConnectionState(conId); sl_status_t ret; - uint16_t cId = (UUIDsMatch(&ChipUUID_CHIPoBLEChar_RX, charId) ? gattdb_CHIPoBLEChar_Rx : gattdb_CHIPoBLEChar_Tx); + uint16_t cId = (UUIDsMatch(&Ble::CHIP_BLE_CHAR_1_UUID, charId) ? gattdb_CHIPoBLEChar_Rx : gattdb_CHIPoBLEChar_Tx); uint8_t timerHandle = GetTimerHandle(conId, true); VerifyOrExit(((conState != NULL) && (conState->subscribed != 0)), err = CHIP_ERROR_INVALID_ARGUMENT); diff --git a/src/platform/silabs/rs911x/BLEManagerImpl.cpp b/src/platform/silabs/rs911x/BLEManagerImpl.cpp index e7495322018170..3794eaef395318 100644 --- a/src/platform/silabs/rs911x/BLEManagerImpl.cpp +++ b/src/platform/silabs/rs911x/BLEManagerImpl.cpp @@ -255,13 +255,9 @@ namespace { TimerHandle_t sbleAdvTimeoutTimer; // FreeRTOS sw timer. -const uint8_t UUID_CHIPoBLEService[] = { 0xFB, 0x34, 0x9B, 0x5F, 0x80, 0x00, 0x00, 0x80, - 0x00, 0x10, 0x00, 0x00, 0xF6, 0xFF, 0x00, 0x00 }; -const uint8_t ShortUUID_CHIPoBLEService[] = { 0xF6, 0xFF }; -const ChipBleUUID ChipUUID_CHIPoBLEChar_RX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, - 0x9D, 0x11 } }; -const ChipBleUUID ChipUUID_CHIPoBLEChar_TX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, - 0x9D, 0x12 } }; +const uint8_t UUID_CHIPoBLEService[] = { 0xFB, 0x34, 0x9B, 0x5F, 0x80, 0x00, 0x00, 0x80, + 0x00, 0x10, 0x00, 0x00, 0xF6, 0xFF, 0x00, 0x00 }; +const uint8_t ShortUUID_CHIPoBLEService[] = { 0xF6, 0xFF }; } // namespace @@ -413,7 +409,7 @@ void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) ChipDeviceEvent connEstEvent; ChipLogProgress(DeviceLayer, "_OnPlatformEvent kCHIPoBLESubscribe"); - HandleSubscribeReceived(event->CHIPoBLESubscribe.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); + HandleSubscribeReceived(event->CHIPoBLESubscribe.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); connEstEvent.Type = DeviceEventType::kCHIPoBLEConnectionEstablished; PlatformMgr().PostEventOrDie(&connEstEvent); } @@ -421,13 +417,13 @@ void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) case DeviceEventType::kCHIPoBLEUnsubscribe: { ChipLogProgress(DeviceLayer, "_OnPlatformEvent kCHIPoBLEUnsubscribe"); - HandleUnsubscribeReceived(event->CHIPoBLEUnsubscribe.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); + HandleUnsubscribeReceived(event->CHIPoBLEUnsubscribe.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); } break; case DeviceEventType::kCHIPoBLEWriteReceived: { ChipLogProgress(DeviceLayer, "_OnPlatformEvent kCHIPoBLEWriteReceived"); - HandleWriteReceived(event->CHIPoBLEWriteReceived.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_RX, + HandleWriteReceived(event->CHIPoBLEWriteReceived.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_1_UUID, PacketBufferHandle::Adopt(event->CHIPoBLEWriteReceived.Data)); } break; @@ -441,7 +437,7 @@ void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) case DeviceEventType::kCHIPoBLEIndicateConfirm: { ChipLogProgress(DeviceLayer, "_OnPlatformEvent kCHIPoBLEIndicateConfirm"); DeviceLayer::SystemLayer().CancelTimer(OnSendIndicationTimeout, this); - HandleIndicationConfirmation(event->CHIPoBLEIndicateConfirm.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); + HandleIndicationConfirmation(event->CHIPoBLEIndicateConfirm.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); } break; diff --git a/src/platform/stm32/BLEManagerImpl.cpp b/src/platform/stm32/BLEManagerImpl.cpp index 7a040a5fb93ba3..60b888d5ebc99b 100644 --- a/src/platform/stm32/BLEManagerImpl.cpp +++ b/src/platform/stm32/BLEManagerImpl.cpp @@ -63,12 +63,6 @@ TimerHandle_t sbleAdvTimeoutTimer; // Full service UUID - CHIP_BLE_SVC_ID - taken from BleUUID.h header const uint8_t chipUUID_CHIPoBLE_Service[CHIP_ADV_SHORT_UUID_LEN] = { 0xFF, 0xF6 }; -const ChipBleUUID chipUUID_CHIPoBLEChar_RX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, - 0x9D, 0x11 } }; - -const ChipBleUUID chipUUID_CHIPoBLEChar_TX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, - 0x9D, 0x12 } }; - } // unnamed namespace BLEManagerImpl BLEManagerImpl::sInstance; @@ -198,19 +192,19 @@ void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) // Platform specific events case DeviceEventType::kCHIPoBLESubscribe: { ChipDeviceEvent connEstEvent; - HandleSubscribeReceived(event->CHIPoBLESubscribe.ConId, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_TX); + HandleSubscribeReceived(event->CHIPoBLESubscribe.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); connEstEvent.Type = DeviceEventType::kCHIPoBLEConnectionEstablished; PlatformMgr().PostEventOrDie(&connEstEvent); } break; case DeviceEventType::kCHIPoBLEUnsubscribe: { - HandleUnsubscribeReceived(event->CHIPoBLEUnsubscribe.ConId, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_TX); + HandleUnsubscribeReceived(event->CHIPoBLEUnsubscribe.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); } break; case DeviceEventType::kCHIPoBLEWriteReceived: { - HandleWriteReceived(event->CHIPoBLEWriteReceived.ConId, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_RX, + HandleWriteReceived(event->CHIPoBLEWriteReceived.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_1_UUID, PacketBufferHandle::Adopt(event->CHIPoBLEWriteReceived.Data)); } break; @@ -230,7 +224,7 @@ void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) break; case DeviceEventType::kCHIPoBLEIndicateConfirm: { - HandleIndicationConfirmation(event->CHIPoBLEIndicateConfirm.ConId, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_TX); + HandleIndicationConfirmation(event->CHIPoBLEIndicateConfirm.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); } break; diff --git a/src/platform/telink/BLEManagerImpl.cpp b/src/platform/telink/BLEManagerImpl.cpp index 69252b66a0ecef..c33de4264e1edd 100644 --- a/src/platform/telink/BLEManagerImpl.cpp +++ b/src/platform/telink/BLEManagerImpl.cpp @@ -79,12 +79,6 @@ const bt_uuid_128 UUID128_CHIPoBLEChar_C3 = bt_uuid_16 UUID16_CHIPoBLEService = BT_UUID_INIT_16(0xFFF6); -const ChipBleUUID chipUUID_CHIPoBLEChar_RX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, - 0x9D, 0x11 } }; - -const ChipBleUUID chipUUID_CHIPoBLEChar_TX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, - 0x9D, 0x12 } }; - _bt_gatt_ccc CHIPoBLEChar_TX_CCC = BT_GATT_CCC_INITIALIZER(nullptr, BLEManagerImpl::HandleTXCCCWrite, nullptr); // clang-format off @@ -544,7 +538,7 @@ CHIP_ERROR BLEManagerImpl::HandleTXCharCCCDWrite(const ChipDeviceEvent * event) if (writeEvent->Value == BT_GATT_CCC_INDICATE && SetSubscribed(writeEvent->BtConn)) { // Alert the BLE layer that CHIPoBLE "subscribe" has been received and increment the bt_conn reference counter. - HandleSubscribeReceived(writeEvent->BtConn, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_TX); + HandleSubscribeReceived(writeEvent->BtConn, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); ChipLogProgress(DeviceLayer, "CHIPoBLE connection established (ConnId: 0x%02x, GATT MTU: %u)", bt_conn_index(writeEvent->BtConn), GetMTU(writeEvent->BtConn)); @@ -560,7 +554,7 @@ CHIP_ERROR BLEManagerImpl::HandleTXCharCCCDWrite(const ChipDeviceEvent * event) { if (UnsetSubscribed(writeEvent->BtConn)) { - HandleUnsubscribeReceived(writeEvent->BtConn, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_TX); + HandleUnsubscribeReceived(writeEvent->BtConn, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); } } @@ -576,7 +570,7 @@ CHIP_ERROR BLEManagerImpl::HandleRXCharWrite(const ChipDeviceEvent * event) ChipLogDetail(DeviceLayer, "Write request received for CHIPoBLE RX characteristic (ConnId 0x%02x)", bt_conn_index(c1WriteEvent->BtConn)); - HandleWriteReceived(c1WriteEvent->BtConn, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_RX, + HandleWriteReceived(c1WriteEvent->BtConn, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_1_UUID, PacketBufferHandle::Adopt(c1WriteEvent->Data)); bt_conn_unref(c1WriteEvent->BtConn); @@ -591,7 +585,7 @@ CHIP_ERROR BLEManagerImpl::HandleTXCharComplete(const ChipDeviceEvent * event) bt_conn_index(c2IndDoneEvent->BtConn), c2IndDoneEvent->Result); // Signal the BLE Layer that the outstanding indication is complete. - HandleIndicationConfirmation(c2IndDoneEvent->BtConn, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_TX); + HandleIndicationConfirmation(c2IndDoneEvent->BtConn, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); bt_conn_unref(c2IndDoneEvent->BtConn); return CHIP_NO_ERROR; diff --git a/src/platform/webos/BLEManagerImpl.cpp b/src/platform/webos/BLEManagerImpl.cpp index 786ded0d3f4029..c488c1cf85e28a 100644 --- a/src/platform/webos/BLEManagerImpl.cpp +++ b/src/platform/webos/BLEManagerImpl.cpp @@ -56,14 +56,6 @@ namespace { static constexpr unsigned kNewConnectionScanTimeoutMs = 10000; static constexpr System::Clock::Timeout kConnectTimeout = System::Clock::Seconds16(10); -const ChipBleUUID ChipUUID_CHIPoBLEChar_RX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, - 0x9D, 0x11 } }; -const ChipBleUUID ChipUUID_CHIPoBLEChar_TX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, - 0x9D, 0x12 } }; -#define CHIP_BLE_GATT_SERVICE "0000fff6-0000-1000-8000-00805f9b34fb" -#define CHIP_BLE_GATT_CHAR_WRITE "18ee2ef5-263d-4559-959f-4f9c429f9d11" -#define CHIP_BLE_GATT_CHAR_READ "18ee2ef5-263d-4559-959f-4f9c429f9d12" - } // namespace BLEManagerImpl BLEManagerImpl::sInstance; @@ -225,7 +217,7 @@ void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) switch (event->Type) { case DeviceEventType::kCHIPoBLESubscribe: - HandleSubscribeReceived(event->CHIPoBLESubscribe.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); + HandleSubscribeReceived(event->CHIPoBLESubscribe.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); { ChipDeviceEvent connectionEvent; connectionEvent.Type = DeviceEventType::kCHIPoBLEConnectionEstablished; @@ -234,16 +226,16 @@ void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) break; case DeviceEventType::kCHIPoBLEUnsubscribe: - HandleUnsubscribeReceived(event->CHIPoBLEUnsubscribe.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); + HandleUnsubscribeReceived(event->CHIPoBLEUnsubscribe.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); break; case DeviceEventType::kCHIPoBLEWriteReceived: - HandleWriteReceived(event->CHIPoBLEWriteReceived.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_RX, + HandleWriteReceived(event->CHIPoBLEWriteReceived.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_1_UUID, PacketBufferHandle::Adopt(event->CHIPoBLEWriteReceived.Data)); break; case DeviceEventType::kCHIPoBLEIndicateConfirm: - HandleIndicationConfirmation(event->CHIPoBLEIndicateConfirm.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); + HandleIndicationConfirmation(event->CHIPoBLEIndicateConfirm.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID); break; case DeviceEventType::kCHIPoBLEConnectionError: @@ -284,18 +276,18 @@ void BLEManagerImpl::HandlePlatformSpecificBLEEvent(const ChipDeviceEvent * apEv } break; case DeviceEventType::kPlatformWebOSBLEWriteComplete: - HandleWriteConfirmation(apEvent->Platform.BLEWriteComplete.mConnection, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_RX); + HandleWriteConfirmation(apEvent->Platform.BLEWriteComplete.mConnection, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_1_UUID); break; case DeviceEventType::kPlatformWebOSBLESubscribeOpComplete: if (apEvent->Platform.BLESubscribeOpComplete.mIsSubscribed) HandleSubscribeComplete(apEvent->Platform.BLESubscribeOpComplete.mConnection, &CHIP_BLE_SVC_ID, - &ChipUUID_CHIPoBLEChar_TX); + &Ble::CHIP_BLE_CHAR_2_UUID); else HandleUnsubscribeComplete(apEvent->Platform.BLESubscribeOpComplete.mConnection, &CHIP_BLE_SVC_ID, - &ChipUUID_CHIPoBLEChar_TX); + &Ble::CHIP_BLE_CHAR_2_UUID); break; case DeviceEventType::kPlatformWebOSBLEIndicationReceived: - HandleIndicationReceived(apEvent->Platform.BLEIndicationReceived.mConnection, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX, + HandleIndicationReceived(apEvent->Platform.BLEIndicationReceived.mConnection, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID, PacketBufferHandle::Adopt(apEvent->Platform.BLEIndicationReceived.mData)); break; case DeviceEventType::kPlatformWebOSBLEPeripheralAdvConfiguredComplete: @@ -434,9 +426,9 @@ bool BLEManagerImpl::SubscribeCharacteristicToWebOS(void * bleConnObj, const uin pbnjson::JValue valueForMonitor = pbnjson::JObject(); valueForMonitor.put("clientId", std::string(mClientId)); - valueForMonitor.put("service", std::string(CHIP_BLE_GATT_SERVICE)); + valueForMonitor.put("service", std::string(Ble::CHIP_BLE_SERVICE_LONG_UUID_STR)); pbnjson::JValue bytesJArray = pbnjson::JArray(); - bytesJArray.append(std::string(CHIP_BLE_GATT_CHAR_READ)); + bytesJArray.append(std::string(Ble::CHIP_BLE_CHAR_2_UUID_STR)); valueForMonitor.put("characteristics", bytesJArray); valueForMonitor.put("subscribe", true); @@ -456,8 +448,8 @@ bool BLEManagerImpl::SubscribeCharacteristicToWebOS(void * bleConnObj, const uin pbnjson::JValue valueForDescriptor = pbnjson::JObject(); valueForDescriptor.put("clientId", std::string(mClientId)); - valueForDescriptor.put("service", std::string(CHIP_BLE_GATT_SERVICE)); - valueForDescriptor.put("characteristic", std::string(CHIP_BLE_GATT_CHAR_READ)); + valueForDescriptor.put("service", std::string(Ble::CHIP_BLE_SERVICE_LONG_UUID_STR)); + valueForDescriptor.put("characteristic", std::string(Ble::CHIP_BLE_CHAR_2_UUID_STR)); valueForDescriptor.put("descriptor", std::string("00002902-0000-1000-8000-00805f9b34fb")); @@ -568,8 +560,8 @@ bool BLEManagerImpl::SendWriteRequestToWebOS(void * bleConnObj, const uint8_t * pbnjson::JValue param = pbnjson::JObject(); pbnjson::JValue valueParam = pbnjson::JObject(); param.put("clientId", clientId); - param.put("service", std::string(CHIP_BLE_GATT_SERVICE)); - param.put("characteristic", std::string(CHIP_BLE_GATT_CHAR_WRITE)); + param.put("service", std::string(Ble::CHIP_BLE_SERVICE_LONG_UUID_STR)); + param.put("characteristic", std::string(Ble::CHIP_BLE_CHAR_1_UUID_STR)); if (valueType == "byte") { From e445e8a214250a297c699953c5da62d68380b190 Mon Sep 17 00:00:00 2001 From: Arkadiusz Bokowy Date: Wed, 5 Jun 2024 15:19:14 +0200 Subject: [PATCH 12/15] [Tizen] Allow to pass CHIP error to device event (#33744) * Create GATT service with short Bluetooth SIG UUID * Do not initialize characteristics with dummy values * Do not keep non-Matter UUIDs in BleUUID.h * Pass CHIP_ERROR to device event * Simplify ChipDeviceEvent initialization * Restyled by clang-format --------- Co-authored-by: Restyled.io --- src/ble/BleUUID.h | 1 - src/platform/Linux/CHIPDevicePlatformEvent.h | 1 + src/platform/Tizen/BLEManagerImpl.cpp | 139 +++++++++---------- src/platform/Tizen/BLEManagerImpl.h | 14 +- src/platform/Tizen/CHIPDevicePlatformEvent.h | 13 +- 5 files changed, 75 insertions(+), 93 deletions(-) diff --git a/src/ble/BleUUID.h b/src/ble/BleUUID.h index 37e2fdc1180f5e..1c0eefd514100a 100644 --- a/src/ble/BleUUID.h +++ b/src/ble/BleUUID.h @@ -101,7 +101,6 @@ constexpr std::pair StringToUUID(const char (&str)[N]) // BlueZ API https://git.kernel.org/pub/scm/bluetooth/bluez.git/tree/doc/org.bluez.Device.rst // describes ServiceData as "Keys are the UUIDs in string format" however no description // on actual case required -inline constexpr char CHIP_BLE_DESC_SHORT_UUID_STR[] = "2902"; inline constexpr char CHIP_BLE_SERVICE_SHORT_UUID_STR[] = "fff6"; inline constexpr char CHIP_BLE_SERVICE_LONG_UUID_STR[] = "0000fff6-0000-1000-8000-00805f9b34fb"; inline constexpr char CHIP_BLE_CHAR_1_UUID_STR[] = "18ee2ef5-263d-4559-959f-4f9c429f9d11"; diff --git a/src/platform/Linux/CHIPDevicePlatformEvent.h b/src/platform/Linux/CHIPDevicePlatformEvent.h index 18ed55a1ef28d4..a70411888413c1 100644 --- a/src/platform/Linux/CHIPDevicePlatformEvent.h +++ b/src/platform/Linux/CHIPDevicePlatformEvent.h @@ -23,6 +23,7 @@ #pragma once +#include #include #include diff --git a/src/platform/Tizen/BLEManagerImpl.cpp b/src/platform/Tizen/BLEManagerImpl.cpp index 209c5fb2337356..247719a9199b76 100644 --- a/src/platform/Tizen/BLEManagerImpl.cpp +++ b/src/platform/Tizen/BLEManagerImpl.cpp @@ -74,6 +74,9 @@ namespace Internal { namespace { +// Bluetooth SIG defined UUID for Client Characteristic Configuration Descriptor +constexpr const char * kClientCharacteristicConfigurationUUID = "2902"; + constexpr System::Clock::Timeout kNewConnectionScanTimeout = System::Clock::Seconds16(20); constexpr System::Clock::Timeout kConnectTimeout = System::Clock::Seconds16(20); constexpr System::Clock::Timeout kFastAdvertiseTimeout = @@ -208,7 +211,10 @@ void BLEManagerImpl::ReadValueRequestedCb(const char * remoteAddress, int reques ChipLogByteSpan(DeviceLayer, ByteSpan(Uint8::from_const_char(value.get()), len)); - ret = bt_gatt_server_send_response(requestId, BT_GATT_REQUEST_TYPE_READ, offset, 0x00, value.get(), len); + char dummyValue[] = ""; + // Tizen API does not like NULLs even for zero-length values. + char * valuePtr = value ? value.get() : dummyValue; + ret = bt_gatt_server_send_response(requestId, BT_GATT_REQUEST_TYPE_READ, offset, BT_ATT_ERROR_NONE, valuePtr, len); VerifyOrReturn(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_gatt_server_send_response() failed: %s", get_error_message(ret))); } @@ -233,7 +239,7 @@ void BLEManagerImpl::WriteValueRequestedCb(const char * remoteAddress, int reque ret = bt_gatt_set_value(gattHandle, value, len); VerifyOrReturn(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_gatt_set_value() failed: %s", get_error_message(ret))); - ret = bt_gatt_server_send_response(requestId, BT_GATT_REQUEST_TYPE_WRITE, offset, 0x00, nullptr, 0); + ret = bt_gatt_server_send_response(requestId, BT_GATT_REQUEST_TYPE_WRITE, offset, BT_ATT_ERROR_NONE, nullptr, 0); VerifyOrReturn(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_gatt_server_send_response() failed: %s", get_error_message(ret))); @@ -265,7 +271,7 @@ void BLEManagerImpl::NotificationStateChangedCb(bool notify, bt_gatt_server_h se ChipLogProgress(DeviceLayer, "Notification State Changed %d on %s: %s", notify, __ConvertAttTypeToStr(type), StringOrNullMarker(uuid.get())); - NotifyBLESubscribed(notify ? true : false, conn); + NotifyBLESubscribed(conn, notify ? true : false); } void BLEManagerImpl::WriteCompletedCb(int result, bt_gatt_h gattHandle, void * userData) @@ -314,7 +320,7 @@ void BLEManagerImpl::AdvertisingStateChangedCb(int result, bt_advertiser_h adver if (advState == BT_ADAPTER_LE_ADVERTISING_STARTED) { mFlags.Set(Flags::kAdvertising); - NotifyBLEPeripheralAdvStartComplete(true, nullptr); + NotifyBLEPeripheralAdvStartComplete(CHIP_NO_ERROR); DeviceLayer::SystemLayer().ScheduleLambda([this] { // Start a timer to make sure that the fast advertising is stopped after specified timeout. DeviceLayer::SystemLayer().StartTimer(kFastAdvertiseTimeout, HandleAdvertisingTimeout, this); @@ -323,7 +329,7 @@ void BLEManagerImpl::AdvertisingStateChangedCb(int result, bt_advertiser_h adver else { mFlags.Clear(Flags::kAdvertising); - NotifyBLEPeripheralAdvStopComplete(true, nullptr); + NotifyBLEPeripheralAdvStopComplete(CHIP_NO_ERROR); DeviceLayer::SystemLayer().ScheduleLambda( [this] { DeviceLayer::SystemLayer().CancelTimer(HandleAdvertisingTimeout, this); }); } @@ -338,89 +344,73 @@ void BLEManagerImpl::AdvertisingStateChangedCb(int result, bt_advertiser_h adver } // ====== Private Functions. -void BLEManagerImpl::NotifyBLEPeripheralGATTServerRegisterComplete(bool aIsSuccess, void * apAppstate) + +void BLEManagerImpl::NotifyBLEPeripheralGATTServerRegisterComplete(CHIP_ERROR error) { - ChipDeviceEvent event; - event.Type = DeviceEventType::kPlatformTizenBLEPeripheralGATTServerRegisterComplete; - event.Platform.BLEPeripheralGATTServerRegisterComplete.mIsSuccess = aIsSuccess; - event.Platform.BLEPeripheralGATTServerRegisterComplete.mpAppstate = apAppstate; + ChipDeviceEvent event{ .Type = DeviceEventType::kPlatformTizenBLEPeripheralGATTServerRegisterComplete, + .Platform = { .BLEPeripheralGATTServerRegisterComplete = { .mError = error } } }; PlatformMgr().PostEventOrDie(&event); } -void BLEManagerImpl::NotifyBLEPeripheralAdvConfiguredComplete(bool aIsSuccess, void * apAppstate) +void BLEManagerImpl::NotifyBLEPeripheralAdvConfiguredComplete(CHIP_ERROR error) { - ChipDeviceEvent event; - event.Type = DeviceEventType::kPlatformTizenBLEPeripheralAdvConfiguredComplete; - event.Platform.BLEPeripheralAdvConfiguredComplete.mIsSuccess = aIsSuccess; - event.Platform.BLEPeripheralAdvConfiguredComplete.mpAppstate = apAppstate; + ChipDeviceEvent event{ .Type = DeviceEventType::kPlatformTizenBLEPeripheralAdvConfiguredComplete, + .Platform = { .BLEPeripheralAdvConfiguredComplete = { .mError = error } } }; PlatformMgr().PostEventOrDie(&event); } -void BLEManagerImpl::NotifyBLEPeripheralAdvStartComplete(bool aIsSuccess, void * apAppstate) +void BLEManagerImpl::NotifyBLEPeripheralAdvStartComplete(CHIP_ERROR error) { - ChipDeviceEvent event; - event.Type = DeviceEventType::kPlatformTizenBLEPeripheralAdvStartComplete; - event.Platform.BLEPeripheralAdvStartComplete.mIsSuccess = aIsSuccess; - event.Platform.BLEPeripheralAdvStartComplete.mpAppstate = apAppstate; + ChipDeviceEvent event{ .Type = DeviceEventType::kPlatformTizenBLEPeripheralAdvStartComplete, + .Platform = { .BLEPeripheralAdvStartComplete = { .mError = error } } }; PlatformMgr().PostEventOrDie(&event); } -void BLEManagerImpl::NotifyBLEPeripheralAdvStopComplete(bool aIsSuccess, void * apAppstate) +void BLEManagerImpl::NotifyBLEPeripheralAdvStopComplete(CHIP_ERROR error) { - ChipDeviceEvent event; - event.Type = DeviceEventType::kPlatformTizenBLEPeripheralAdvStopComplete; - event.Platform.BLEPeripheralAdvStopComplete.mIsSuccess = aIsSuccess; - event.Platform.BLEPeripheralAdvStopComplete.mpAppstate = apAppstate; + ChipDeviceEvent event{ .Type = DeviceEventType::kPlatformTizenBLEPeripheralAdvStopComplete, + .Platform = { .BLEPeripheralAdvStopComplete = { .mError = error } } }; PlatformMgr().PostEventOrDie(&event); } -void BLEManagerImpl::NotifyBLEWriteReceived(System::PacketBufferHandle & buf, BLE_CONNECTION_OBJECT conId) +void BLEManagerImpl::NotifyBLEWriteReceived(BLE_CONNECTION_OBJECT conId, System::PacketBufferHandle & buf) { - ChipDeviceEvent event; - event.Type = DeviceEventType::kCHIPoBLEWriteReceived; - event.CHIPoBLEWriteReceived.ConId = conId; - event.CHIPoBLEWriteReceived.Data = std::move(buf).UnsafeRelease(); + ChipDeviceEvent event{ .Type = DeviceEventType::kCHIPoBLEWriteReceived, + .CHIPoBLEWriteReceived = { .ConId = conId, .Data = std::move(buf).UnsafeRelease() } }; PlatformMgr().PostEventOrDie(&event); } -void BLEManagerImpl::NotifyBLENotificationReceived(System::PacketBufferHandle & buf, BLE_CONNECTION_OBJECT conId) +void BLEManagerImpl::NotifyBLENotificationReceived(BLE_CONNECTION_OBJECT conId, System::PacketBufferHandle & buf) { - ChipDeviceEvent event; - event.Type = DeviceEventType::kPlatformTizenBLEIndicationReceived; - event.Platform.BLEIndicationReceived.mConnection = conId; - event.Platform.BLEIndicationReceived.mData = std::move(buf).UnsafeRelease(); + ChipDeviceEvent event{ .Type = DeviceEventType::kPlatformTizenBLEIndicationReceived, + .Platform = { + .BLEIndicationReceived = { .mConnection = conId, .mData = std::move(buf).UnsafeRelease() } } }; PlatformMgr().PostEventOrDie(&event); } -void BLEManagerImpl::NotifyBLESubscribed(bool indicationsEnabled, BLE_CONNECTION_OBJECT conId) +void BLEManagerImpl::NotifyBLESubscribed(BLE_CONNECTION_OBJECT conId, bool indicationsEnabled) { - ChipDeviceEvent event; - event.Type = (indicationsEnabled) ? DeviceEventType::kCHIPoBLESubscribe : DeviceEventType::kCHIPoBLEUnsubscribe; - event.CHIPoBLESubscribe.ConId = conId; + ChipDeviceEvent event{ .Type = indicationsEnabled ? DeviceEventType::kCHIPoBLESubscribe : DeviceEventType::kCHIPoBLEUnsubscribe, + .CHIPoBLESubscribe = { .ConId = conId } }; PlatformMgr().PostEventOrDie(&event); } void BLEManagerImpl::NotifyBLEIndicationConfirmation(BLE_CONNECTION_OBJECT conId) { - ChipDeviceEvent event; - event.Type = DeviceEventType::kCHIPoBLEIndicateConfirm; - event.CHIPoBLEIndicateConfirm.ConId = conId; + ChipDeviceEvent event{ .Type = DeviceEventType::kCHIPoBLEIndicateConfirm, .CHIPoBLEIndicateConfirm = { .ConId = conId } }; PlatformMgr().PostEventOrDie(&event); } void BLEManagerImpl::NotifyBLEConnectionEstablished(BLE_CONNECTION_OBJECT conId, CHIP_ERROR error) { - ChipDeviceEvent event; - event.Type = DeviceEventType::kCHIPoBLEConnectionEstablished; + ChipDeviceEvent event{ .Type = DeviceEventType::kCHIPoBLEConnectionEstablished }; PlatformMgr().PostEventOrDie(&event); } void BLEManagerImpl::NotifyBLEDisconnection(BLE_CONNECTION_OBJECT conId, CHIP_ERROR error) { - ChipDeviceEvent event; - event.Type = DeviceEventType::kCHIPoBLEConnectionError; - event.CHIPoBLEConnectionError.ConId = conId; - event.CHIPoBLEConnectionError.Reason = error; + ChipDeviceEvent event{ .Type = DeviceEventType::kCHIPoBLEConnectionError, + .CHIPoBLEConnectionError = { .ConId = conId, .Reason = error } }; PlatformMgr().PostEventOrDie(&event); } @@ -429,9 +419,8 @@ void BLEManagerImpl::NotifyHandleConnectFailed(CHIP_ERROR error) ChipLogProgress(DeviceLayer, "Connection failed: %" CHIP_ERROR_FORMAT, error.Format()); if (mIsCentral) { - ChipDeviceEvent event; - event.Type = DeviceEventType::kPlatformTizenBLECentralConnectFailed; - event.Platform.BLECentralConnectFailed.mError = error; + ChipDeviceEvent event{ .Type = DeviceEventType::kPlatformTizenBLECentralConnectFailed, + .Platform = { .BLECentralConnectFailed = { .mError = error } } }; PlatformMgr().PostEventOrDie(&event); } } @@ -440,27 +429,23 @@ void BLEManagerImpl::NotifyHandleNewConnection(BLE_CONNECTION_OBJECT conId) { if (mIsCentral) { - ChipDeviceEvent event; - event.Type = DeviceEventType::kPlatformTizenBLECentralConnected; - event.Platform.BLECentralConnected.mConnection = conId; + ChipDeviceEvent event{ .Type = DeviceEventType::kPlatformTizenBLECentralConnected, + .Platform = { .BLECentralConnected = { .mConnection = conId } } }; PlatformMgr().PostEventOrDie(&event); } } void BLEManagerImpl::NotifyHandleWriteComplete(BLE_CONNECTION_OBJECT conId) { - ChipDeviceEvent event; - event.Type = DeviceEventType::kPlatformTizenBLEWriteComplete; - event.Platform.BLEWriteComplete.mConnection = conId; + ChipDeviceEvent event{ .Type = DeviceEventType::kPlatformTizenBLEWriteComplete, + .Platform = { .BLEWriteComplete = { .mConnection = conId } } }; PlatformMgr().PostEventOrDie(&event); } void BLEManagerImpl::NotifySubscribeOpComplete(BLE_CONNECTION_OBJECT conId, bool isSubscribed) { - ChipDeviceEvent event; - event.Type = DeviceEventType::kPlatformTizenBLESubscribeOpComplete; - event.Platform.BLESubscribeOpComplete.mConnection = conId; - event.Platform.BLESubscribeOpComplete.mIsSubscribed = isSubscribed; + ChipDeviceEvent event{ .Type = DeviceEventType::kPlatformTizenBLESubscribeOpComplete, + .Platform = { .BLESubscribeOpComplete = { .mConnection = conId, .mIsSubscribed = isSubscribed } } }; PlatformMgr().PostEventOrDie(&event); } @@ -574,7 +559,7 @@ CHIP_ERROR BLEManagerImpl::RegisterGATTServer() VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_gatt_server_create() failed: %s", get_error_message(ret))); // Create Service (BTP Service) - ret = bt_gatt_service_create(Ble::CHIP_BLE_SERVICE_LONG_UUID_STR, BT_GATT_SERVICE_TYPE_PRIMARY, &service); + ret = bt_gatt_service_create(Ble::CHIP_BLE_SERVICE_SHORT_UUID_STR, BT_GATT_SERVICE_TYPE_PRIMARY, &service); VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_gatt_service_create() failed: %s", get_error_message(ret))); // Create 1st Characteristic (Client TX Buffer) @@ -583,7 +568,7 @@ CHIP_ERROR BLEManagerImpl::RegisterGATTServer() BT_GATT_PROPERTY_WRITE, // Write Request is not coming if we use WITHOUT_RESPONSE property. Let's use WRITE property and // consider to use WITHOUT_RESPONSE property in the future according to the CHIP Spec 4.16.3.2. BTP // GATT Service - "CHIPoBLE_C1", strlen("CHIPoBLE_C1"), &char1); + nullptr, 0, &char1); VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_gatt_characteristic_create() failed: %s", get_error_message(ret))); @@ -604,8 +589,7 @@ CHIP_ERROR BLEManagerImpl::RegisterGATTServer() // Create 2nd Characteristic (Client RX Buffer) ret = bt_gatt_characteristic_create(Ble::CHIP_BLE_CHAR_2_UUID_STR, BT_GATT_PERMISSION_READ, - BT_GATT_PROPERTY_READ | BT_GATT_PROPERTY_INDICATE, "CHIPoBLE_C2", strlen("CHIPoBLE_C2"), - &char2); + BT_GATT_PROPERTY_READ | BT_GATT_PROPERTY_INDICATE, nullptr, 0, &char2); VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_gatt_characteristic_create() failed: %s", get_error_message(ret))); @@ -618,6 +602,7 @@ CHIP_ERROR BLEManagerImpl::RegisterGATTServer() this); VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_gatt_server_set_read_value_requested_cb() failed: %s", get_error_message(ret))); + ret = bt_gatt_server_set_characteristic_notification_state_change_cb( char2, +[](bool notify, bt_gatt_server_h gattServer, bt_gatt_h charHandle, void * self) { @@ -628,13 +613,14 @@ CHIP_ERROR BLEManagerImpl::RegisterGATTServer() ChipLogError(DeviceLayer, "bt_gatt_server_set_characteristic_notification_state_change_cb() failed: %s", get_error_message(ret))); - // Create CCC Descriptor - ret = bt_gatt_descriptor_create(Ble::CHIP_BLE_DESC_SHORT_UUID_STR, BT_GATT_PERMISSION_READ | BT_GATT_PERMISSION_WRITE, + ret = bt_gatt_descriptor_create(kClientCharacteristicConfigurationUUID, BT_GATT_PERMISSION_READ | BT_GATT_PERMISSION_WRITE, desc_value, sizeof(desc_value), &desc); VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_gatt_descriptor_create() failed: %s", get_error_message(ret))); + ret = bt_gatt_characteristic_add_descriptor(char2, desc); VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_gatt_characteristic_add_descriptor() failed: %s", get_error_message(ret))); + ret = bt_gatt_service_add_characteristic(service, char2); VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_gatt_service_add_characteristic() failed: %s", get_error_message(ret))); @@ -648,8 +634,7 @@ CHIP_ERROR BLEManagerImpl::RegisterGATTServer() ret = bt_gatt_server_start(); VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_gatt_server_start() failed: %s", get_error_message(ret))); - ChipLogDetail(DeviceLayer, "NotifyBLEPeripheralGATTServerRegisterComplete Success"); - BLEManagerImpl::NotifyBLEPeripheralGATTServerRegisterComplete(true, nullptr); + BLEManagerImpl::NotifyBLEPeripheralGATTServerRegisterComplete(CHIP_NO_ERROR); // Save the Local Peripheral char1 & char2 handles mGattCharC1Handle = char1; @@ -657,8 +642,7 @@ CHIP_ERROR BLEManagerImpl::RegisterGATTServer() return CHIP_NO_ERROR; exit: - ChipLogDetail(DeviceLayer, "NotifyBLEPeripheralGATTServerRegisterComplete Failed"); - BLEManagerImpl::NotifyBLEPeripheralGATTServerRegisterComplete(false, nullptr); + BLEManagerImpl::NotifyBLEPeripheralGATTServerRegisterComplete(TizenToChipError(ret)); return TizenToChipError(ret); } @@ -727,7 +711,7 @@ CHIP_ERROR BLEManagerImpl::StartBLEAdvertising() VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_adapter_le_set_advertising_device_name() failed: %s", get_error_message(ret))); - BLEManagerImpl::NotifyBLEPeripheralAdvConfiguredComplete(true, nullptr); + BLEManagerImpl::NotifyBLEPeripheralAdvConfiguredComplete(CHIP_NO_ERROR); ret = bt_adapter_le_start_advertising_new( mAdvertiser, @@ -742,8 +726,9 @@ CHIP_ERROR BLEManagerImpl::StartBLEAdvertising() return CHIP_NO_ERROR; exit: - BLEManagerImpl::NotifyBLEPeripheralAdvStartComplete(false, nullptr); - return ret != BT_ERROR_NONE ? TizenToChipError(ret) : err; + err = ret != BT_ERROR_NONE ? TizenToChipError(ret) : err; + BLEManagerImpl::NotifyBLEPeripheralAdvStartComplete(err); + return err; } CHIP_ERROR BLEManagerImpl::StopBLEAdvertising() @@ -758,7 +743,7 @@ CHIP_ERROR BLEManagerImpl::StopBLEAdvertising() return CHIP_NO_ERROR; exit: - BLEManagerImpl::NotifyBLEPeripheralAdvStopComplete(false, nullptr); + BLEManagerImpl::NotifyBLEPeripheralAdvStopComplete(TizenToChipError(ret)); return TizenToChipError(ret); } @@ -896,7 +881,7 @@ void BLEManagerImpl::HandleC1CharWriteEvent(BLE_CONNECTION_OBJECT conId, const u // Copy the data to a packet buffer. buf = System::PacketBufferHandle::NewWithData(value, len); VerifyOrExit(!buf.IsNull(), err = CHIP_ERROR_NO_MEMORY); - NotifyBLEWriteReceived(buf, conId); + NotifyBLEWriteReceived(conId, buf); return; exit: if (err != CHIP_NO_ERROR) @@ -915,7 +900,7 @@ void BLEManagerImpl::HandleRXCharChanged(BLE_CONNECTION_OBJECT conId, const uint // Copy the data to a packet buffer. buf = System::PacketBufferHandle::NewWithData(value, len); VerifyOrExit(!buf.IsNull(), err = CHIP_ERROR_NO_MEMORY); - NotifyBLENotificationReceived(buf, conId); + NotifyBLENotificationReceived(conId, buf); return; exit: if (err != CHIP_NO_ERROR) diff --git a/src/platform/Tizen/BLEManagerImpl.h b/src/platform/Tizen/BLEManagerImpl.h index ed30b92aa958b7..5dfee7fba75c83 100644 --- a/src/platform/Tizen/BLEManagerImpl.h +++ b/src/platform/Tizen/BLEManagerImpl.h @@ -196,13 +196,13 @@ class BLEManagerImpl final : public BLEManager, bool IsDeviceChipPeripheral(BLE_CONNECTION_OBJECT conId); // ==== BLE Adv & GATT Server. - void NotifyBLEPeripheralGATTServerRegisterComplete(bool aIsSuccess, void * apAppstate); - void NotifyBLEPeripheralAdvConfiguredComplete(bool aIsSuccess, void * apAppstate); - void NotifyBLEPeripheralAdvStartComplete(bool aIsSuccess, void * apAppstate); - void NotifyBLEPeripheralAdvStopComplete(bool aIsSuccess, void * apAppstate); - void NotifyBLESubscribed(bool indicationsEnabled, BLE_CONNECTION_OBJECT conId); + void NotifyBLEPeripheralGATTServerRegisterComplete(CHIP_ERROR error); + void NotifyBLEPeripheralAdvConfiguredComplete(CHIP_ERROR error); + void NotifyBLEPeripheralAdvStartComplete(CHIP_ERROR error); + void NotifyBLEPeripheralAdvStopComplete(CHIP_ERROR error); + void NotifyBLESubscribed(BLE_CONNECTION_OBJECT conId, bool indicationsEnabled); void NotifyBLEIndicationConfirmation(BLE_CONNECTION_OBJECT conId); - void NotifyBLEWriteReceived(System::PacketBufferHandle & buf, BLE_CONNECTION_OBJECT conId); + void NotifyBLEWriteReceived(BLE_CONNECTION_OBJECT conId, System::PacketBufferHandle & buf); static void HandleAdvertisingTimeout(chip::System::Layer *, void * appState); AdvertisingIntervals GetAdvertisingIntervals() const; @@ -214,7 +214,7 @@ class BLEManagerImpl final : public BLEManager, void NotifyHandleConnectFailed(CHIP_ERROR error); void NotifyHandleWriteComplete(BLE_CONNECTION_OBJECT conId); void NotifySubscribeOpComplete(BLE_CONNECTION_OBJECT conId, bool isSubscribed); - void NotifyBLENotificationReceived(System::PacketBufferHandle & buf, BLE_CONNECTION_OBJECT conId); + void NotifyBLENotificationReceived(BLE_CONNECTION_OBJECT conId, System::PacketBufferHandle & buf); CHIP_ERROR RegisterGATTServer(); CHIP_ERROR StartBLEAdvertising(); diff --git a/src/platform/Tizen/CHIPDevicePlatformEvent.h b/src/platform/Tizen/CHIPDevicePlatformEvent.h index 2145b18b448c8f..ce606fd7f576fd 100644 --- a/src/platform/Tizen/CHIPDevicePlatformEvent.h +++ b/src/platform/Tizen/CHIPDevicePlatformEvent.h @@ -23,6 +23,7 @@ #pragma once +#include #include #include @@ -67,23 +68,19 @@ struct ChipDevicePlatformEvent { struct { - bool mIsSuccess; - void * mpAppstate; + CHIP_ERROR mError; } BLEPeripheralGATTServerRegisterComplete; struct { - bool mIsSuccess; - void * mpAppstate; + CHIP_ERROR mError; } BLEPeripheralAdvConfiguredComplete; struct { - bool mIsSuccess; - void * mpAppstate; + CHIP_ERROR mError; } BLEPeripheralAdvStartComplete; struct { - bool mIsSuccess; - void * mpAppstate; + CHIP_ERROR mError; } BLEPeripheralAdvStopComplete; struct { From 4ec2035f2cb5f20eec8d3623d765924db050e6c9 Mon Sep 17 00:00:00 2001 From: C Freeman Date: Wed, 5 Jun 2024 09:20:39 -0400 Subject: [PATCH 13/15] Python wheels: move template into its own gni (#33739) This will let us re-use the template later for wheels not in src/controller/python. Nothing within the template has been changed - this is just a move. Test: ran build_python.sh, it's fine still. --- build/chip/python_wheel.gni | 88 ++++++++++++++++++++++++++++++++++ src/controller/python/BUILD.gn | 70 +-------------------------- 2 files changed, 89 insertions(+), 69 deletions(-) create mode 100644 build/chip/python_wheel.gni diff --git a/build/chip/python_wheel.gni b/build/chip/python_wheel.gni new file mode 100644 index 00000000000000..ac00fe140456cc --- /dev/null +++ b/build/chip/python_wheel.gni @@ -0,0 +1,88 @@ +# Copyright (c) 2024 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/chip.gni") +import("//build_overrides/pigweed.gni") + +import("$dir_pw_build/python.gni") +import("${chip_root}/src/system/system.gni") + +declare_args() { + chip_python_version = "0.0" + chip_python_package_prefix = "chip" + chip_python_supports_stack_locking = chip_system_config_locking != "none" +} + +template("chip_python_wheel_action") { + _dist_dir = "${root_out_dir}/controller/python" + + _py_manifest_file = "${target_gen_dir}/${target_name}.py_manifest.json" + + pw_python_action(target_name) { + script = "build-chip-wheel.py" + forward_variables_from(invoker, "*") + + _py_manifest_files_rebased = [] + foreach(_manifest_entry, py_manifest_files) { + inputs += _manifest_entry.sources + _py_manifest_files_rebased += [ + { + src_dir = rebase_path(_manifest_entry.src_dir, + get_path_info(_py_manifest_file, "dir")) + sources = + rebase_path(_manifest_entry.sources, _manifest_entry.src_dir) + }, + ] + } + + if (defined(invoker.py_scripts)) { + _py_scripts = invoker.py_scripts + } else { + _py_scripts = [] + } + + _py_manifest = { + files = _py_manifest_files_rebased + packages = py_packages + scripts = _py_scripts + package_reqs = py_package_reqs + } + + write_file(_py_manifest_file, _py_manifest, "json") + + args = [ + "--package_name", + py_package_name, + "--build_number", + chip_python_version, + "--build_dir", + rebase_path("${target_gen_dir}/${target_name}.py_build", root_build_dir), + "--dist_dir", + rebase_path(_dist_dir, root_build_dir), + "--manifest", + rebase_path(_py_manifest_file, root_build_dir), + "--plat-name", + py_platform_tag, + ] + + if (defined(invoker.lib_name)) { + args += [ + "--lib-name", + lib_name, + ] + } + + outputs = [ "${_dist_dir}/$output_name" ] + } +} diff --git a/src/controller/python/BUILD.gn b/src/controller/python/BUILD.gn index 9adda770125317..747aa522504ca6 100644 --- a/src/controller/python/BUILD.gn +++ b/src/controller/python/BUILD.gn @@ -18,6 +18,7 @@ import("//build_overrides/pigweed.gni") import("$dir_pw_build/python.gni") +import("${chip_root}/build/chip/python_wheel.gni") import("${chip_root}/build/chip/tools.gni") import("${chip_root}/src/platform/python.gni") import("${chip_root}/src/system/system.gni") @@ -31,12 +32,6 @@ config("controller_wno_deprecate") { cflags = [ "-Wno-deprecated-declarations" ] } -declare_args() { - chip_python_version = "0.0" - chip_python_package_prefix = "chip" - chip_python_supports_stack_locking = chip_system_config_locking != "none" -} - shared_library("ChipDeviceCtrl") { if (chip_controller) { output_name = "_ChipDeviceCtrl" @@ -157,69 +152,6 @@ shared_library("ChipDeviceCtrl") { configs += [ ":controller_wno_deprecate" ] } -template("chip_python_wheel_action") { - _dist_dir = "${root_out_dir}/controller/python" - - _py_manifest_file = "${target_gen_dir}/${target_name}.py_manifest.json" - - pw_python_action(target_name) { - script = "build-chip-wheel.py" - forward_variables_from(invoker, "*") - - _py_manifest_files_rebased = [] - foreach(_manifest_entry, py_manifest_files) { - inputs += _manifest_entry.sources - _py_manifest_files_rebased += [ - { - src_dir = rebase_path(_manifest_entry.src_dir, - get_path_info(_py_manifest_file, "dir")) - sources = - rebase_path(_manifest_entry.sources, _manifest_entry.src_dir) - }, - ] - } - - if (defined(invoker.py_scripts)) { - _py_scripts = invoker.py_scripts - } else { - _py_scripts = [] - } - - _py_manifest = { - files = _py_manifest_files_rebased - packages = py_packages - scripts = _py_scripts - package_reqs = py_package_reqs - } - - write_file(_py_manifest_file, _py_manifest, "json") - - args = [ - "--package_name", - py_package_name, - "--build_number", - chip_python_version, - "--build_dir", - rebase_path("${target_gen_dir}/${target_name}.py_build", root_build_dir), - "--dist_dir", - rebase_path(_dist_dir, root_build_dir), - "--manifest", - rebase_path(_py_manifest_file, root_build_dir), - "--plat-name", - py_platform_tag, - ] - - if (defined(invoker.lib_name)) { - args += [ - "--lib-name", - lib_name, - ] - } - - outputs = [ "${_dist_dir}/$output_name" ] - } -} - chip_python_wheel_action("chip-core") { py_manifest_files = [ { From 6092e8a764f45371d8c48da9b254fe83f917d388 Mon Sep 17 00:00:00 2001 From: Stefan Agner Date: Wed, 5 Jun 2024 16:06:15 +0200 Subject: [PATCH 14/15] [Python] Drop network lock (#33720) The network lock is not needed in the Python controller, as all calls to the SDK are made by posting to the Matter SDK event loop through ScheduleWork(), hence are guaranteed to be serialized. From how I understand ScheduleWork() works, it pushes the work to the event loop through PostEvent() which at least on POSIX is using the thread safe device queue (see GenericPlatformManagerImpl_POSIX.cpp). --- src/controller/python/chip/ChipStack.py | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/src/controller/python/chip/ChipStack.py b/src/controller/python/chip/ChipStack.py index 06afff3ef3c380..b47c4639825da8 100644 --- a/src/controller/python/chip/ChipStack.py +++ b/src/controller/python/chip/ChipStack.py @@ -144,8 +144,6 @@ class ChipStack(object): def __init__(self, persistentStoragePath: str, enableServerInteractions=True): builtins.enableDebugMode = False - # TODO: Probably no longer necessary, see https://github.com/project-chip/connectedhomeip/issues/33321. - self.networkLock = Lock() self.completeEvent = Event() self.commissioningCompleteEvent = Event() self._ChipStackLib = None @@ -212,7 +210,6 @@ def Shutdown(self): # #20437 tracks consolidating these. # self._ChipStackLib.pychip_CommonStackShutdown() - self.networkLock = None self.completeEvent = None self._ChipStackLib = None self._chipDLLPath = None @@ -226,10 +223,7 @@ def Call(self, callFunct, timeoutMs: int = None): This function is a wrapper of PostTaskOnChipThread, which includes some handling of application specific logics. Calling this function on CHIP on CHIP mainloop thread will cause deadlock. ''' - # TODO: Lock probably no longer necessary, see https://github.com/project-chip/connectedhomeip/issues/33321. - with self.networkLock: - res = self.PostTaskOnChipThread(callFunct).Wait(timeoutMs) - return res + return self.PostTaskOnChipThread(callFunct).Wait(timeoutMs) async def CallAsync(self, callFunct, timeoutMs: int = None): '''Run a Python function on CHIP stack, and wait for the response. @@ -256,9 +250,7 @@ def CallAsyncWithCompleteCallback(self, callFunct): # throw error if op in progress self.callbackRes = None self.completeEvent.clear() - # TODO: Lock probably no longer necessary, see https://github.com/project-chip/connectedhomeip/issues/33321. - with self.networkLock: - res = self.PostTaskOnChipThread(callFunct).Wait() + res = self.PostTaskOnChipThread(callFunct).Wait() if not res.is_success: self.completeEvent.set() From 92a322d391511a9fda840a72cbe571c7c6ad7c0e Mon Sep 17 00:00:00 2001 From: shripad621git <79364691+shripad621git@users.noreply.github.com> Date: Wed, 5 Jun 2024 22:32:05 +0530 Subject: [PATCH 15/15] Adding few logs related to event ids for ESP32 platform specific events (#33751) --- src/platform/ESP32/PlatformManagerImpl.cpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/platform/ESP32/PlatformManagerImpl.cpp b/src/platform/ESP32/PlatformManagerImpl.cpp index ed9f6aca7128c9..d5ad12352dbf3a 100644 --- a/src/platform/ESP32/PlatformManagerImpl.cpp +++ b/src/platform/ESP32/PlatformManagerImpl.cpp @@ -119,6 +119,7 @@ void PlatformManagerImpl::HandleESPSystemEvent(void * arg, esp_event_base_t even event.Platform.ESPSystemEvent.Id = eventId; if (eventBase == IP_EVENT) { + ChipLogProgress(DeviceLayer, "Posting ESPSystemEvent: IP Event with eventId : %ld", eventId); switch (eventId) { case IP_EVENT_STA_GOT_IP: @@ -138,6 +139,7 @@ void PlatformManagerImpl::HandleESPSystemEvent(void * arg, esp_event_base_t even #if CHIP_DEVICE_CONFIG_ENABLE_WIFI else if (eventBase == WIFI_EVENT) { + ChipLogProgress(DeviceLayer, "Posting ESPSystemEvent: Wifi Event with eventId : %ld", eventId); switch (eventId) { case WIFI_EVENT_SCAN_DONE: @@ -181,7 +183,10 @@ void PlatformManagerImpl::HandleESPSystemEvent(void * arg, esp_event_base_t even } } #endif // CHIP_DEVICE_CONFIG_ENABLE_WIFI - + else + { + ChipLogProgress(DeviceLayer, "Posting ESPSystemEvent with eventId : %ld", eventId); + } sInstance.PostEventOrDie(&event); }