From 6350333131ef0fb95d469a6987a34f0bbcc95b7e Mon Sep 17 00:00:00 2001 From: Junior Martinez <67972863+jmartinez-silabs@users.noreply.github.com> Date: Tue, 20 Feb 2024 16:10:07 -0500 Subject: [PATCH 01/13] [THREAD] Bring clear all Srp Client host and Services to the GenericThreadStackManagerImpl (#32215) * Bring the functionality to clear all Srp Client host and Services to the GenericThreadStackManagerImpl * Fix Tizen build * Update src/platform/Tizen/ThreadStackManagerImpl.cpp Co-authored-by: Arkadiusz Bokowy * Add method documentation and address comments * Restyled by whitespace --------- Co-authored-by: Arkadiusz Bokowy Co-authored-by: Restyled.io --- src/include/platform/ThreadStackManager.h | 35 +++++++++++++ src/platform/ESP32/ThreadStackManagerImpl.cpp | 24 +++++++++ src/platform/ESP32/ThreadStackManagerImpl.h | 11 ++++ .../GenericThreadStackManagerImpl_FreeRTOS.h | 8 +++ ...GenericThreadStackManagerImpl_FreeRTOS.hpp | 26 ++++++++++ .../CYW30739/ThreadStackManagerImpl.cpp | 23 ++++++++ .../CYW30739/ThreadStackManagerImpl.h | 8 +++ src/platform/Linux/ThreadStackManagerImpl.h | 5 ++ ...GenericThreadStackManagerImpl_OpenThread.h | 3 ++ ...nericThreadStackManagerImpl_OpenThread.hpp | 35 +++++++++++++ src/platform/Tizen/ThreadStackManagerImpl.cpp | 10 ++++ src/platform/Tizen/ThreadStackManagerImpl.h | 6 +++ .../Zephyr/ThreadStackManagerImpl.cpp | 16 ++++++ src/platform/Zephyr/ThreadStackManagerImpl.h | 8 +++ .../silabs/ConfigurationManagerImpl.cpp | 2 +- src/platform/silabs/ThreadStackManagerImpl.h | 11 ---- .../silabs/efr32/ThreadStackManagerImpl.cpp | 52 ------------------- .../telink/ThreadStackManagerImpl.cpp | 16 ++++++ src/platform/telink/ThreadStackManagerImpl.h | 8 +++ src/platform/webos/ThreadStackManagerImpl.h | 5 ++ 20 files changed, 248 insertions(+), 64 deletions(-) diff --git a/src/include/platform/ThreadStackManager.h b/src/include/platform/ThreadStackManager.h index 86d895ec1cfe52..cda3c7acdccbd5 100644 --- a/src/include/platform/ThreadStackManager.h +++ b/src/include/platform/ThreadStackManager.h @@ -121,6 +121,26 @@ class ThreadStackManager CHIP_ERROR RemoveSrpService(const char * aInstanceName, const char * aName); CHIP_ERROR InvalidateAllSrpServices(); ///< Mark all SRP services as invalid CHIP_ERROR RemoveInvalidSrpServices(); ///< Remove SRP services marked as invalid + + /* + * @brief Utility function to clear all thread SRP host and services established between the SRP server and client. + * It is expected that a transaction is done between the SRP server and client so the clear request is applied on both ends + * + * A generic implementation is provided in `GenericThreadStackManagerImpl_OpenThread` with the SoC OT stack + */ + CHIP_ERROR ClearAllSrpHostAndServices(); + + /* + * @brief Used to synchronize on the SRP server response confirming the clearing of the host and service entries + * Should be called in ClearAllSrpHostAndServices once the request is sent. + */ + void WaitOnSrpClearAllComplete(); + + /* + * @brief Notify that the SRP server confirmed the clearing of the host and service entries + * Should be called in the SRP Client set callback in the removal confirmation. + */ + void NotifySrpClearAllComplete(); CHIP_ERROR SetupSrpHost(const char * aHostName); CHIP_ERROR ClearSrpHost(const char * aHostName); CHIP_ERROR SetSrpDnsCallbacks(DnsAsyncReturnCallback aInitCallback, DnsAsyncReturnCallback aErrorCallback, void * aContext); @@ -289,6 +309,21 @@ inline CHIP_ERROR ThreadStackManager::RemoveInvalidSrpServices() return static_cast(this)->_RemoveInvalidSrpServices(); } +inline CHIP_ERROR ThreadStackManager::ClearAllSrpHostAndServices() +{ + return static_cast(this)->_ClearAllSrpHostAndServices(); +} + +inline void ThreadStackManager::WaitOnSrpClearAllComplete() +{ + return static_cast(this)->_WaitOnSrpClearAllComplete(); +} + +inline void ThreadStackManager::NotifySrpClearAllComplete() +{ + return static_cast(this)->_NotifySrpClearAllComplete(); +} + inline CHIP_ERROR ThreadStackManager::SetupSrpHost(const char * aHostName) { return static_cast(this)->_SetupSrpHost(aHostName); diff --git a/src/platform/ESP32/ThreadStackManagerImpl.cpp b/src/platform/ESP32/ThreadStackManagerImpl.cpp index eed07af6d68af1..0449607999668b 100644 --- a/src/platform/ESP32/ThreadStackManagerImpl.cpp +++ b/src/platform/ESP32/ThreadStackManagerImpl.cpp @@ -77,6 +77,30 @@ void ThreadStackManagerImpl::_UnlockThreadStack() esp_openthread_lock_release(); } +#if CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT +void ThreadStackManagerImpl::_WaitOnSrpClearAllComplete() +{ + // Only 1 task can be blocked on a srpClearAll request + if (mSrpClearAllRequester == nullptr) + { + mSrpClearAllRequester = xTaskGetCurrentTaskHandle(); + // Wait on OnSrpClientNotification which confirms the clearing is done. + // It will notify this current task with NotifySrpClearAllComplete. + // However, we won't wait more than 2s. + ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(2000)); + mSrpClearAllRequester = nullptr; + } +} + +void ThreadStackManagerImpl::_NotifySrpClearAllComplete() +{ + if (mSrpClearAllRequester) + { + xTaskNotifyGive(mSrpClearAllRequester); + } +} +#endif // CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT + void ThreadStackManagerImpl::_ProcessThreadActivity() { // Intentionally empty. diff --git a/src/platform/ESP32/ThreadStackManagerImpl.h b/src/platform/ESP32/ThreadStackManagerImpl.h index 46795d658d6535..1287e7a5f3a1ba 100644 --- a/src/platform/ESP32/ThreadStackManagerImpl.h +++ b/src/platform/ESP32/ThreadStackManagerImpl.h @@ -68,10 +68,21 @@ class ThreadStackManagerImpl final : public ThreadStackManager, void _OnCHIPoBLEAdvertisingStart(); void _OnCHIPoBLEAdvertisingStop(); +#if CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT + void _WaitOnSrpClearAllComplete(); + void _NotifySrpClearAllComplete(); +#endif // CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT + // ===== Methods that override the GenericThreadStackMa + private: friend ThreadStackManager & ::chip::DeviceLayer::ThreadStackMgr(void); friend ThreadStackManagerImpl & ::chip::DeviceLayer::ThreadStackMgrImpl(void); static ThreadStackManagerImpl sInstance; + +#if CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT + TaskHandle_t mSrpClearAllRequester = nullptr; +#endif + ThreadStackManagerImpl() = default; }; diff --git a/src/platform/FreeRTOS/GenericThreadStackManagerImpl_FreeRTOS.h b/src/platform/FreeRTOS/GenericThreadStackManagerImpl_FreeRTOS.h index 870fcf2ed80657..059b701f6bda05 100644 --- a/src/platform/FreeRTOS/GenericThreadStackManagerImpl_FreeRTOS.h +++ b/src/platform/FreeRTOS/GenericThreadStackManagerImpl_FreeRTOS.h @@ -64,6 +64,10 @@ class GenericThreadStackManagerImpl_FreeRTOS bool _TryLockThreadStack(void); void _UnlockThreadStack(void); +#if CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT + void _WaitOnSrpClearAllComplete(); + void _NotifySrpClearAllComplete(); +#endif // CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT // ===== Members available to the implementation subclass. SemaphoreHandle_t mThreadStackLock; @@ -88,6 +92,10 @@ class GenericThreadStackManagerImpl_FreeRTOS #if defined(CHIP_CONFIG_FREERTOS_USE_STATIC_SEMAPHORE) && CHIP_CONFIG_FREERTOS_USE_STATIC_SEMAPHORE StaticSemaphore_t mThreadStackLockMutex; #endif + +#if CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT + TaskHandle_t mSrpClearAllRequester = nullptr; +#endif }; // Instruct the compiler to instantiate the template only when explicitly told to do so. diff --git a/src/platform/FreeRTOS/GenericThreadStackManagerImpl_FreeRTOS.hpp b/src/platform/FreeRTOS/GenericThreadStackManagerImpl_FreeRTOS.hpp index 4dbee81b23af01..9008258989375e 100644 --- a/src/platform/FreeRTOS/GenericThreadStackManagerImpl_FreeRTOS.hpp +++ b/src/platform/FreeRTOS/GenericThreadStackManagerImpl_FreeRTOS.hpp @@ -101,6 +101,32 @@ void GenericThreadStackManagerImpl_FreeRTOS::_UnlockThreadStack(void) xSemaphoreGive(mThreadStackLock); } +#if CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT +template +void GenericThreadStackManagerImpl_FreeRTOS::_WaitOnSrpClearAllComplete() +{ + // Only 1 task can be blocked on a srpClearAll request + if (mSrpClearAllRequester == nullptr) + { + mSrpClearAllRequester = xTaskGetCurrentTaskHandle(); + // Wait on OnSrpClientNotification which confirms the slearing is done. + // It will notify this current task with NotifySrpClearAllComplete. + // However, we won't wait more than 2s. + ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(2000)); + mSrpClearAllRequester = nullptr; + } +} + +template +void GenericThreadStackManagerImpl_FreeRTOS::_NotifySrpClearAllComplete() +{ + if (mSrpClearAllRequester) + { + xTaskNotifyGive(mSrpClearAllRequester); + } +} +#endif // CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT + template void GenericThreadStackManagerImpl_FreeRTOS::SignalThreadActivityPending() { diff --git a/src/platform/Infineon/CYW30739/ThreadStackManagerImpl.cpp b/src/platform/Infineon/CYW30739/ThreadStackManagerImpl.cpp index f0393a795ef63a..21297d75cf5252 100644 --- a/src/platform/Infineon/CYW30739/ThreadStackManagerImpl.cpp +++ b/src/platform/Infineon/CYW30739/ThreadStackManagerImpl.cpp @@ -54,6 +54,14 @@ CHIP_ERROR ThreadStackManagerImpl::_InitThreadStack() VerifyOrExit(result == WICED_SUCCESS, err = CHIP_ERROR_INTERNAL); otSysInit(0, NULL); +#if CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT + mSrpClearAllSemaphore = wiced_rtos_create_mutex(); + VerifyOrExit(mSrpClearAllSemaphore != nullptr, err = CHIP_ERROR_NO_MEMORY); + + result = wiced_rtos_init_mutex(mSrpClearAllSemaphore); + VerifyOrExit(result == WICED_SUCCESS, err = CHIP_ERROR_INTERNAL); +#endif // CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT + err = GenericThreadStackManagerImpl_OpenThread::DoInit(NULL); exit: @@ -95,6 +103,21 @@ void ThreadStackManagerImpl::_UnlockThreadStack() VerifyOrReturn(result == WICED_SUCCESS || result == WICED_NOT_OWNED, ChipLogError(DeviceLayer, "%s %x", __func__, result)); } +#if CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT +void ThreadStackManagerImpl::_WaitOnSrpClearAllComplete() +{ + const wiced_result_t result = wiced_rtos_lock_mutex(mSrpClearAllSemaphore); + VerifyOrReturn(result == WICED_SUCCESS, ChipLogError(DeviceLayer, "%s %x", __func__, result)); +} + +void ThreadStackManagerImpl::_NotifySrpClearAllComplete() +{ + const wiced_result_t result = wiced_rtos_unlock_mutex(mSrpClearAllSemaphore); + VerifyOrReturn(result == WICED_SUCCESS || result == WICED_NOT_OWNED, ChipLogError(DeviceLayer, "%s %x", __func__, result)); +} +#endif // CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT +// ===== Methods that override the GenericThreadStackMa + void ThreadStackManagerImpl::ThreadTaskMain(void) { while (true) diff --git a/src/platform/Infineon/CYW30739/ThreadStackManagerImpl.h b/src/platform/Infineon/CYW30739/ThreadStackManagerImpl.h index cdb2cb8ee65fdc..5cd3fef1c60239 100644 --- a/src/platform/Infineon/CYW30739/ThreadStackManagerImpl.h +++ b/src/platform/Infineon/CYW30739/ThreadStackManagerImpl.h @@ -58,6 +58,11 @@ class ThreadStackManagerImpl final : public ThreadStackManager, bool _TryLockThreadStack(); void _UnlockThreadStack(); +#if CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT + void _WaitOnSrpClearAllComplete(); + void _NotifySrpClearAllComplete(); +#endif // CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT + // ===== Methods that override the GenericThreadStackMa private: // ===== Members for internal use by the following friends. @@ -67,6 +72,9 @@ class ThreadStackManagerImpl final : public ThreadStackManager, wiced_thread_t * mThread; EventFlags mEventFlags; wiced_mutex_t * mMutex; +#if CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT + wiced_mutex_t * mSrpClearAllSemaphore; +#endif // CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT static ThreadStackManagerImpl sInstance; // ===== Private members for use by this class only. diff --git a/src/platform/Linux/ThreadStackManagerImpl.h b/src/platform/Linux/ThreadStackManagerImpl.h index 977c6b94d0027f..e262837dd84c76 100755 --- a/src/platform/Linux/ThreadStackManagerImpl.h +++ b/src/platform/Linux/ThreadStackManagerImpl.h @@ -57,6 +57,11 @@ class ThreadStackManagerImpl : public ThreadStackManager bool _TryLockThreadStack() { return false; } // Intentionally left blank void _UnlockThreadStack() {} // Intentionally left blank +#if CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT + void _WaitOnSrpClearAllComplete() {} + void _NotifySrpClearAllComplete() {} +#endif // CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT + bool _HaveRouteToAddress(const Inet::IPAddress & destAddr); void _OnPlatformEvent(const ChipDeviceEvent * event); diff --git a/src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread.h b/src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread.h index 161c2b202a8310..8ce0805182dcaa 100644 --- a/src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread.h +++ b/src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread.h @@ -121,6 +121,7 @@ class GenericThreadStackManagerImpl_OpenThread CHIP_ERROR _RemoveSrpService(const char * aInstanceName, const char * aName); CHIP_ERROR _InvalidateAllSrpServices(); CHIP_ERROR _RemoveInvalidSrpServices(); + CHIP_ERROR _ClearAllSrpHostAndServices(); CHIP_ERROR _SetupSrpHost(const char * aHostName); CHIP_ERROR _ClearSrpHost(const char * aHostName); @@ -203,6 +204,8 @@ class GenericThreadStackManagerImpl_OpenThread SrpClient mSrpClient; + bool mIsSrpClearAllRequested = false; + static void OnSrpClientNotification(otError aError, const otSrpClientHostInfo * aHostInfo, const otSrpClientService * aServices, const otSrpClientService * aRemovedServices, void * aContext); static void OnSrpClientStateChange(const otSockAddr * aServerSockAddr, void * aContext); diff --git a/src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread.hpp b/src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread.hpp index acc0c78d0c8eb7..21c44dd00279e3 100644 --- a/src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread.hpp +++ b/src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread.hpp @@ -1307,6 +1307,12 @@ void GenericThreadStackManagerImpl_OpenThread::OnSrpClientNotificatio ThreadStackMgrImpl().mSrpClient.mIsInitialized = true; ThreadStackMgrImpl().mSrpClient.mInitializedCallback(ThreadStackMgrImpl().mSrpClient.mCallbackContext, CHIP_NO_ERROR); + + if (ThreadStackMgrImpl().mIsSrpClearAllRequested) + { + ThreadStackMgrImpl().NotifySrpClearAllComplete(); + ThreadStackMgrImpl().mIsSrpClearAllRequested = false; + } } } @@ -1618,6 +1624,35 @@ CHIP_ERROR GenericThreadStackManagerImpl_OpenThread::_RemoveInvalidSr return error; } +/* + * @brief This is a utility function to remove all Thread client srp host and services + * established between the device and the srp server (in most cases the OTBR). + * The calling task is blocked until OnSrpClientNotification which confims the client received the request. + * The blocking mechanism is defined by the platform implementation of `WaitOnSrpClearAllComplete` and `NotifySrpClearAllComplete` + * + * Note: This function is meant to be used during the factory reset sequence. + * + */ +template +CHIP_ERROR GenericThreadStackManagerImpl_OpenThread::_ClearAllSrpHostAndServices() +{ + CHIP_ERROR error = CHIP_NO_ERROR; + Impl()->LockThreadStack(); + if (!mIsSrpClearAllRequested) + { + error = + MapOpenThreadError(otSrpClientRemoveHostAndServices(mOTInst, true /*aRemoveKeyLease*/, true /*aSendUnregToServer*/)); + mIsSrpClearAllRequested = true; + Impl()->UnlockThreadStack(); + Impl()->WaitOnSrpClearAllComplete(); + } + else + { + Impl()->UnlockThreadStack(); + } + return error; +} + template CHIP_ERROR GenericThreadStackManagerImpl_OpenThread::_SetupSrpHost(const char * aHostName) { diff --git a/src/platform/Tizen/ThreadStackManagerImpl.cpp b/src/platform/Tizen/ThreadStackManagerImpl.cpp index 47a4548507e332..e6252d92926190 100644 --- a/src/platform/Tizen/ThreadStackManagerImpl.cpp +++ b/src/platform/Tizen/ThreadStackManagerImpl.cpp @@ -646,6 +646,16 @@ CHIP_ERROR ThreadStackManagerImpl::_RemoveInvalidSrpServices() return CHIP_NO_ERROR; } +CHIP_ERROR ThreadStackManagerImpl::_ClearAllSrpHostAndServices() +{ + for (auto it = mSrpClientServices.begin(); it != mSrpClientServices.end();) + { + ReturnErrorOnFailure(_RemoveSrpService(it->mInstanceName, it->mName)); + it = mSrpClientServices.erase(it); + } + return CHIP_NO_ERROR; +} + void ThreadStackManagerImpl::_ThreadIpAddressCb(int index, char * ipAddr, thread_ipaddr_type_e ipAddrType, void * userData) { VerifyOrReturn(ipAddr != nullptr, ChipLogError(DeviceLayer, "FAIL: Invalid argument: Thread ipAddr not found")); diff --git a/src/platform/Tizen/ThreadStackManagerImpl.h b/src/platform/Tizen/ThreadStackManagerImpl.h index 05b300f574114b..07092f43b320eb 100644 --- a/src/platform/Tizen/ThreadStackManagerImpl.h +++ b/src/platform/Tizen/ThreadStackManagerImpl.h @@ -57,6 +57,11 @@ class ThreadStackManagerImpl : public ThreadStackManager bool _TryLockThreadStack() { return false; } // Intentionally left blank void _UnlockThreadStack() {} // Intentionally left blank +#if CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT + void _WaitOnSrpClearAllComplete() {} + void _NotifySrpClearAllComplete() {} +#endif // CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT + bool _HaveRouteToAddress(const Inet::IPAddress & destAddr); void _OnPlatformEvent(const ChipDeviceEvent * event); @@ -115,6 +120,7 @@ class ThreadStackManagerImpl : public ThreadStackManager CHIP_ERROR _RemoveSrpService(const char * aInstanceName, const char * aName); CHIP_ERROR _InvalidateAllSrpServices(); CHIP_ERROR _RemoveInvalidSrpServices(); + CHIP_ERROR _ClearAllSrpHostAndServices(); CHIP_ERROR _SetupSrpHost(const char * aHostName); CHIP_ERROR _ClearSrpHost(const char * aHostName); CHIP_ERROR _SetSrpDnsCallbacks(DnsAsyncReturnCallback aInitCallback, DnsAsyncReturnCallback aErrorCallback, void * aContext); diff --git a/src/platform/Zephyr/ThreadStackManagerImpl.cpp b/src/platform/Zephyr/ThreadStackManagerImpl.cpp index 3cfcfe3b7888b2..95bdfc8ea7044a 100644 --- a/src/platform/Zephyr/ThreadStackManagerImpl.cpp +++ b/src/platform/Zephyr/ThreadStackManagerImpl.cpp @@ -66,6 +66,10 @@ CHIP_ERROR ThreadStackManagerImpl::_InitThreadStack() return MapOpenThreadError(otError); }); +#if CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT + k_sem_init(&mSrpClearAllSemaphore, 0, 1); +#endif // CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT + return CHIP_NO_ERROR; } @@ -85,5 +89,17 @@ void ThreadStackManagerImpl::_UnlockThreadStack() openthread_api_mutex_unlock(openthread_get_default_context()); } +#if CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT +void ThreadStackManagerImpl::_WaitOnSrpClearAllComplete() +{ + k_sem_take(&mSrpClearAllSemaphore, K_SECONDS(2)); +} + +void ThreadStackManagerImpl::_NotifySrpClearAllComplete() +{ + k_sem_give(&mSrpClearAllSemaphore); +} +#endif // CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT + } // namespace DeviceLayer } // namespace chip diff --git a/src/platform/Zephyr/ThreadStackManagerImpl.h b/src/platform/Zephyr/ThreadStackManagerImpl.h index c0c66b492c6b1d..ec9feb8b121d3e 100644 --- a/src/platform/Zephyr/ThreadStackManagerImpl.h +++ b/src/platform/Zephyr/ThreadStackManagerImpl.h @@ -71,6 +71,10 @@ class ThreadStackManagerImpl final : public ThreadStackManager, bool _TryLockThreadStack(); void _UnlockThreadStack(); +#if CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT + void _WaitOnSrpClearAllComplete(); + void _NotifySrpClearAllComplete(); +#endif // CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT // ===== Methods that override the GenericThreadStackManagerImpl_OpenThread abstract interface. void _ProcessThreadActivity() {} @@ -83,6 +87,10 @@ class ThreadStackManagerImpl final : public ThreadStackManager, friend ThreadStackManager & ::chip::DeviceLayer::ThreadStackMgr(void); friend ThreadStackManagerImpl & ::chip::DeviceLayer::ThreadStackMgrImpl(void); +#if CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT + k_sem mSrpClearAllSemaphore; +#endif // CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT + static ThreadStackManagerImpl sInstance; // ===== Private members for use by this class only. diff --git a/src/platform/silabs/ConfigurationManagerImpl.cpp b/src/platform/silabs/ConfigurationManagerImpl.cpp index a3e1778c11ac3f..8412075de3a914 100644 --- a/src/platform/silabs/ConfigurationManagerImpl.cpp +++ b/src/platform/silabs/ConfigurationManagerImpl.cpp @@ -272,7 +272,7 @@ void ConfigurationManagerImpl::DoFactoryReset(intptr_t arg) #if CHIP_DEVICE_CONFIG_ENABLE_THREAD #if CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT - ThreadStackMgrImpl().RemoveAllSrpServices(); + ThreadStackMgr().ClearAllSrpHostAndServices(); #endif // CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT ChipLogProgress(DeviceLayer, "Clearing Thread provision"); ThreadStackMgr().ErasePersistentInfo(); diff --git a/src/platform/silabs/ThreadStackManagerImpl.h b/src/platform/silabs/ThreadStackManagerImpl.h index b1436b3b75b27e..c56990fb0d3712 100644 --- a/src/platform/silabs/ThreadStackManagerImpl.h +++ b/src/platform/silabs/ThreadStackManagerImpl.h @@ -72,19 +72,11 @@ class ThreadStackManagerImpl final : public ThreadStackManager, using ThreadStackManager::InitThreadStack; CHIP_ERROR InitThreadStack(otInstance * otInst); -#if CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT - void RemoveAllSrpServices(); -#endif private: // ===== Methods that implement the ThreadStackManager abstract interface. CHIP_ERROR _InitThreadStack(void); -#if CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT - static void OnSrpClientRemoveCallback(otError aError, const otSrpClientHostInfo * aHostInfo, - const otSrpClientService * aServices, const otSrpClientService * aRemovedServices, - void * aContext); -#endif // ===== Members for internal use by the following friends. friend ThreadStackManager & ::chip::DeviceLayer::ThreadStackMgr(void); @@ -94,9 +86,6 @@ class ThreadStackManagerImpl final : public ThreadStackManager, static ThreadStackManagerImpl sInstance; static bool IsInitialized(); -#if CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT - TaskHandle_t srpRemoveRequester = nullptr; -#endif // ===== Private members for use by this class only. diff --git a/src/platform/silabs/efr32/ThreadStackManagerImpl.cpp b/src/platform/silabs/efr32/ThreadStackManagerImpl.cpp index c4556036034e78..83767f9a0e1fb8 100644 --- a/src/platform/silabs/efr32/ThreadStackManagerImpl.cpp +++ b/src/platform/silabs/efr32/ThreadStackManagerImpl.cpp @@ -66,58 +66,6 @@ bool ThreadStackManagerImpl::IsInitialized() return sInstance.mThreadStackLock != NULL; } -#if CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT -/* - * @brief Notifies `RemoveAllSrpServices` that the Srp Client removal has completed - * and unblock the calling task. - * - * No data is processed. - */ -void ThreadStackManagerImpl::OnSrpClientRemoveCallback(otError aError, const otSrpClientHostInfo * aHostInfo, - const otSrpClientService * aServices, - const otSrpClientService * aRemovedServices, void * aContext) -{ - if (ThreadStackMgrImpl().srpRemoveRequester) - { - xTaskNotifyGive(ThreadStackMgrImpl().srpRemoveRequester); - } -} - -/* - * @brief This is a utility function to remove all Thread client Srp services - * established between the device and the srp server (in most cases the OTBR). - * The calling task is blocked until OnSrpClientRemoveCallback. - * - * Note: This function is meant to be used during the factory reset sequence. - * It overrides the generic SrpClient callback `OnSrpClientNotification` with - * OnSrpClientRemoveCallback which doesn't process any of the callback data. - * - * If there is a usecase where this function would be needed in a non-Factory reset context, - * OnSrpClientRemoveCallback should be extended and tied back with the GenericThreadStackManagerImpl_OpenThread - * management of the srp clients. - */ -void ThreadStackManagerImpl::RemoveAllSrpServices() -{ - // This check ensure that only one srp services removal is running - if (ThreadStackMgrImpl().srpRemoveRequester == nullptr) - { - srpRemoveRequester = xTaskGetCurrentTaskHandle(); - otSrpClientSetCallback(OTInstance(), &OnSrpClientRemoveCallback, nullptr); - InvalidateAllSrpServices(); - if (RemoveInvalidSrpServices() == CHIP_NO_ERROR) - { - // Wait for the OnSrpClientRemoveCallback. - ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(2000)); - } - else - { - ChipLogError(DeviceLayer, "Failed to remove srp services"); - } - ThreadStackMgrImpl().srpRemoveRequester = nullptr; - } -} -#endif // CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT - } // namespace DeviceLayer } // namespace chip diff --git a/src/platform/telink/ThreadStackManagerImpl.cpp b/src/platform/telink/ThreadStackManagerImpl.cpp index e66735b1de68f2..13ba8be424563b 100644 --- a/src/platform/telink/ThreadStackManagerImpl.cpp +++ b/src/platform/telink/ThreadStackManagerImpl.cpp @@ -68,6 +68,10 @@ CHIP_ERROR ThreadStackManagerImpl::_InitThreadStack() return MapOpenThreadError(otError); }); +#if CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT + k_sem_init(&mSrpClearAllSemaphore, 0, 1); +#endif // CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT + return CHIP_NO_ERROR; } @@ -87,6 +91,18 @@ void ThreadStackManagerImpl::_UnlockThreadStack() openthread_api_mutex_unlock(openthread_get_default_context()); } +#if CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT +void ThreadStackManagerImpl::_WaitOnSrpClearAllComplete() +{ + k_sem_take(&mSrpClearAllSemaphore, K_SECONDS(2)); +} + +void ThreadStackManagerImpl::_NotifySrpClearAllComplete() +{ + k_sem_give(&mSrpClearAllSemaphore); +} +#endif // CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT + CHIP_ERROR ThreadStackManagerImpl::_AttachToThreadNetwork(const Thread::OperationalDataset & dataset, NetworkCommissioning::Internal::WirelessDriver::ConnectCallback * callback) diff --git a/src/platform/telink/ThreadStackManagerImpl.h b/src/platform/telink/ThreadStackManagerImpl.h index d1040542f3c616..21db9972f62dec 100644 --- a/src/platform/telink/ThreadStackManagerImpl.h +++ b/src/platform/telink/ThreadStackManagerImpl.h @@ -74,6 +74,10 @@ class ThreadStackManagerImpl final : public ThreadStackManager, bool _TryLockThreadStack(); void _UnlockThreadStack(); +#if CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT + void _WaitOnSrpClearAllComplete(); + void _NotifySrpClearAllComplete(); +#endif // CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT // ===== Methods that override the GenericThreadStackManagerImpl_OpenThread abstract interface. void _ProcessThreadActivity() {} @@ -95,6 +99,10 @@ class ThreadStackManagerImpl final : public ThreadStackManager, bool mRadioBlocked; bool mReadyToAttach; +#if CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT + k_sem mSrpClearAllSemaphore; +#endif // CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT + NetworkCommissioning::ThreadDriver::ScanCallback * mpScanCallback; }; diff --git a/src/platform/webos/ThreadStackManagerImpl.h b/src/platform/webos/ThreadStackManagerImpl.h index 876c339cceb6ae..a21d4cbf551251 100644 --- a/src/platform/webos/ThreadStackManagerImpl.h +++ b/src/platform/webos/ThreadStackManagerImpl.h @@ -50,6 +50,11 @@ class ThreadStackManagerImpl : public ThreadStackManager bool _TryLockThreadStack() { return false; } // Intentionally left blank void _UnlockThreadStack() {} // Intentionally left blank +#if CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT + void _WaitOnSrpClearAllComplete() {} + void _NotifySrpClearAllComplete() {} +#endif // CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT + bool _HaveRouteToAddress(const Inet::IPAddress & destAddr); void _OnPlatformEvent(const ChipDeviceEvent * event); From b8de5cc5ea9b103fc2b1f9c4ac42cf41d7416e72 Mon Sep 17 00:00:00 2001 From: David Rempel <63119829+drempelg@users.noreply.github.com> Date: Tue, 20 Feb 2024 15:16:02 -0800 Subject: [PATCH 02/13] Feature/energypreferences (#30244) * Adding the Energy Preferences XML * Added just the xml and regenerated. No implementations yet as requested. * regen * put the cluster back into all-clusters after merge. * Apply suggestions from code review Added suggestions for ARRAY vs array Co-authored-by: Boris Zbarsky * regenerate * Finished up impl for energy-preferences * Added some error checking for features, and constraint checking. Also turned on the features in the all-clusters-app * Restyled by whitespace * Restyled by clang-format * Fixed copy paste bug * Removed some unecessary changes and a comment. * initialize the delegate pointer * Put the cluster back in the all-clusters app after the merge * Fixed minor issues from review * Restyled by whitespace * Addressing some review concerns * Some more comments resolved * Better documentation, a set of braces I missed last time around, and added an extra header include. * fix build error after merge * Restyled by whitespace * Restyled by clang-format * Update src/app/clusters/energy-preference-server/energy-preference-server.cpp Co-authored-by: Boris Zbarsky * Implement proposed API changes with clearer delineation of storage * Restyled by clang-format * Typo * Regen zap, update code to reflect the updated return from Feature::Get * ZAP regen, to fix merge errors * Apply suggestions from code review Co-authored-by: Boris Zbarsky * Address suggestion re: optionality conversion * Fix one more omission * another small fix * Fix up copyright headers * Restyled by clang-format * Reinitialize storage objects on every iteration * fix typo * Restyled by clang-format * Apply suggestions from code review Co-authored-by: Boris Zbarsky --------- Co-authored-by: Boris Zbarsky Co-authored-by: Restyled.io Co-authored-by: Robert Szewczyk --- .../all-clusters-app.matter | 48 ++++ .../all-clusters-common/all-clusters-app.zap | 186 ++++++++++++++ .../src/energy-preference-delegate.cpp | 137 ++++++++++ .../all-clusters-app/ameba/chip_main.cmake | 1 + .../esp32/main/CMakeLists.txt | 5 +- examples/all-clusters-app/linux/BUILD.gn | 1 + .../energy-preference-server.cpp | 235 ++++++++++++++++++ .../energy-preference-server.h | 107 ++++++++ src/app/common/templates/config-data.yaml | 1 + .../chip/energy-preference-cluster.xml | 1 + src/app/zap_cluster_list.json | 2 +- .../data_model/controller-clusters.matter | 2 +- 12 files changed, 723 insertions(+), 3 deletions(-) create mode 100644 examples/all-clusters-app/all-clusters-common/src/energy-preference-delegate.cpp create mode 100644 src/app/clusters/energy-preference-server/energy-preference-server.cpp create mode 100644 src/app/clusters/energy-preference-server/energy-preference-server.h 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 62dc0d7d84c3fa..5a7b510b05b0c8 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 @@ -4455,6 +4455,40 @@ provisional cluster EnergyEvse = 153 { timed command ClearTargets(): DefaultSuccess = 7; } +/** This cluster provides an interface to specify preferences for how devices should consume energy. */ +provisional cluster EnergyPreference = 155 { + revision 1; + + enum EnergyPriorityEnum : enum8 { + kComfort = 0; + kSpeed = 1; + kEfficiency = 2; + kWaterConsumption = 3; + } + + bitmap Feature : bitmap32 { + kEnergyBalance = 0x1; + kLowPowerModeSensitivity = 0x2; + } + + struct BalanceStruct { + percent step = 0; + optional char_string<64> label = 1; + } + + readonly attribute optional BalanceStruct energyBalances[] = 0; + attribute optional int8u currentEnergyBalance = 1; + readonly attribute optional EnergyPriorityEnum energyPriorities[] = 2; + readonly attribute optional BalanceStruct lowPowerModeSensitivities[] = 3; + attribute optional int8u currentLowPowerModeSensitivity = 4; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; +} + /** The Power Topology Cluster provides a mechanism for expressing how power is flowing between endpoints. */ provisional cluster PowerTopology = 156 { revision 1; @@ -8361,6 +8395,20 @@ endpoint 1 { handle command ClearTargets; } + server cluster EnergyPreference { + callback attribute energyBalances; + ram attribute currentEnergyBalance; + callback attribute energyPriorities; + callback attribute lowPowerModeSensitivities; + ram attribute currentLowPowerModeSensitivity; + callback attribute generatedCommandList; + callback attribute acceptedCommandList; + callback attribute eventList; + callback attribute attributeList; + ram attribute featureMap default = 3; + ram attribute clusterRevision default = 1; + } + server cluster PowerTopology { callback attribute availableEndpoints; callback attribute activeEndpoints; 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 0a2a3faf1b37e8..21bcfee37b5e0d 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 @@ -14692,6 +14692,192 @@ } ] }, + { + "name": "Energy Preference", + "code": 155, + "mfgCode": null, + "define": "ENERGY_PREFERENCE_CLUSTER", + "side": "server", + "enabled": 1, + "attributes": [ + { + "name": "EnergyBalances", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "CurrentEnergyBalance", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "int8u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "EnergyPriorities", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "LowPowerModeSensitivities", + "code": 3, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "CurrentLowPowerModeSensitivity", + "code": 4, + "mfgCode": null, + "side": "server", + "type": "int8u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "GeneratedCommandList", + "code": 65528, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AcceptedCommandList", + "code": 65529, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "EventList", + "code": 65530, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AttributeList", + "code": 65531, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "3", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "1", + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + } + ] + }, { "name": "Window Covering", "code": 258, diff --git a/examples/all-clusters-app/all-clusters-common/src/energy-preference-delegate.cpp b/examples/all-clusters-app/all-clusters-common/src/energy-preference-delegate.cpp new file mode 100644 index 00000000000000..cd9b47dd7979e6 --- /dev/null +++ b/examples/all-clusters-app/all-clusters-common/src/energy-preference-delegate.cpp @@ -0,0 +1,137 @@ +/* + * + * 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 + +using namespace chip; +using namespace chip::app::Clusters::EnergyPreference; +using namespace chip::app::Clusters::EnergyPreference::Structs; + +static BalanceStruct::Type gsEnergyBalances[] = { + { .step = 0, .label = Optional("Efficient"_span) }, + { .step = 50, .label = Optional() }, + { .step = 100, .label = Optional("Comfort"_span) }, +}; + +static BalanceStruct::Type gsPowerBalances[] = { + { .step = 0, .label = Optional("1 Minute"_span) }, + { .step = 12, .label = Optional("5 Minutes"_span) }, + { .step = 24, .label = Optional("10 Minutes"_span) }, + { .step = 36, .label = Optional("15 Minutes"_span) }, + { .step = 48, .label = Optional("20 Minutes"_span) }, + { .step = 60, .label = Optional("25 Minutes"_span) }, + { .step = 70, .label = Optional("30 Minutes"_span) }, + { .step = 80, .label = Optional("60 Minutes"_span) }, + { .step = 90, .label = Optional("120 Minutes"_span) }, + { .step = 100, .label = Optional("Never"_span) }, +}; + +// assumes it'll be the only delegate for it's lifetime. +struct EPrefDelegate : public Delegate +{ + EPrefDelegate(); + virtual ~EPrefDelegate(); + + CHIP_ERROR GetEnergyBalanceAtIndex(chip::EndpointId aEndpoint, size_t aIndex, chip::Percent & aOutStep, + chip::Optional & aOutLabel) override; + CHIP_ERROR GetEnergyPriorityAtIndex(chip::EndpointId aEndpoint, size_t aIndex, EnergyPriorityEnum & priority) override; + CHIP_ERROR GetLowPowerModeSensitivityAtIndex(chip::EndpointId aEndpoint, size_t aIndex, chip::Percent & aOutStep, + chip::Optional & aOutLabel) override; + + size_t GetNumEnergyBalances(chip::EndpointId aEndpoint) override; + size_t GetNumLowPowerModeSensitivities(chip::EndpointId aEndpoint) override; +}; + +EPrefDelegate::EPrefDelegate() : Delegate() +{ + VerifyOrDie(GetDelegate() == nullptr); + SetDelegate(this); +} + +EPrefDelegate::~EPrefDelegate() +{ + VerifyOrDie(GetDelegate() == this); + SetDelegate(nullptr); +} + +size_t EPrefDelegate::GetNumEnergyBalances(chip::EndpointId aEndpoint) +{ + return (ArraySize(gsEnergyBalances)); +} + +size_t EPrefDelegate::GetNumLowPowerModeSensitivities(chip::EndpointId aEndpoint) +{ + return (ArraySize(gsEnergyBalances)); +} + +CHIP_ERROR +EPrefDelegate::GetEnergyBalanceAtIndex(chip::EndpointId aEndpoint, size_t aIndex, chip::Percent & aOutStep, + chip::Optional & aOutLabel) +{ + if (aIndex < GetNumEnergyBalances(aEndpoint)) + { + aOutStep = gsEnergyBalances[aIndex].step; + if (gsEnergyBalances[aIndex].label.HasValue()) + { + chip::CopyCharSpanToMutableCharSpan(gsEnergyBalances[aIndex].label.Value(), aOutLabel.Value()); + } + else + { + aOutLabel.ClearValue(); + } + return CHIP_NO_ERROR; + } + return CHIP_ERROR_NOT_FOUND; +} + +CHIP_ERROR +EPrefDelegate::GetEnergyPriorityAtIndex(chip::EndpointId aEndpoint, size_t aIndex, EnergyPriorityEnum & priority) +{ + static EnergyPriorityEnum priorities[] = { EnergyPriorityEnum::kEfficiency, EnergyPriorityEnum::kComfort }; + + if (aIndex < ArraySize(priorities)) + { + priority = priorities[aIndex]; + return CHIP_NO_ERROR; + } + + return CHIP_ERROR_NOT_FOUND; +} + +CHIP_ERROR +EPrefDelegate::GetLowPowerModeSensitivityAtIndex(chip::EndpointId aEndpoint, size_t aIndex, chip::Percent & aOutStep, + chip::Optional & aOutLabel) +{ + if (aIndex < GetNumLowPowerModeSensitivities(aEndpoint)) + { + aOutStep = gsPowerBalances[aIndex].step; + if (gsPowerBalances[aIndex].label.HasValue()) + { + chip::CopyCharSpanToMutableCharSpan(gsPowerBalances[aIndex].label.Value(), aOutLabel.Value()); + } + else + { + aOutLabel.ClearValue(); + } + return CHIP_NO_ERROR; + } + + return CHIP_ERROR_NOT_FOUND; +} + +static EPrefDelegate gsDelegate; diff --git a/examples/all-clusters-app/ameba/chip_main.cmake b/examples/all-clusters-app/ameba/chip_main.cmake index 0d8b99c117716e..c4572063508ac0 100755 --- a/examples/all-clusters-app/ameba/chip_main.cmake +++ b/examples/all-clusters-app/ameba/chip_main.cmake @@ -158,6 +158,7 @@ list( ${chip_dir}/examples/all-clusters-app/all-clusters-common/src/concentration-measurement-instances.cpp ${chip_dir}/examples/all-clusters-app/all-clusters-common/src/device-energy-management-stub.cpp ${chip_dir}/examples/all-clusters-app/all-clusters-common/src/energy-evse-stub.cpp + ${chip_dir}/examples/all-clusters-app/all-clusters-common/src/energy-preference-delegate.cpp ${chip_dir}/examples/all-clusters-app/all-clusters-common/src/fan-stub.cpp ${chip_dir}/examples/all-clusters-app/all-clusters-common/src/oven-modes.cpp ${chip_dir}/examples/all-clusters-app/all-clusters-common/src/laundry-washer-controls-delegate-impl.cpp diff --git a/examples/all-clusters-app/esp32/main/CMakeLists.txt b/examples/all-clusters-app/esp32/main/CMakeLists.txt index 238f0e899c340d..63851b1deeb611 100644 --- a/examples/all-clusters-app/esp32/main/CMakeLists.txt +++ b/examples/all-clusters-app/esp32/main/CMakeLists.txt @@ -96,8 +96,11 @@ set(SRC_DIRS_LIST "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/time-synchronization-server" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/valve-configuration-and-control-server" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/dishwasher-alarm-server" - "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/laundry-washer-controls-server" + "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/laundry-washer-controls-server" + "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/laundry-washer-controls-server" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/laundry-dryer-controls-server" + "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/all-clusters-app/all-clusters-common/src" + "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/energy-preference-server" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/electrical-energy-measurement-server" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/electrical-power-measurement-server" ) diff --git a/examples/all-clusters-app/linux/BUILD.gn b/examples/all-clusters-app/linux/BUILD.gn index 998f98a19cd3de..3d52ef748de90d 100644 --- a/examples/all-clusters-app/linux/BUILD.gn +++ b/examples/all-clusters-app/linux/BUILD.gn @@ -40,6 +40,7 @@ source_set("chip-all-clusters-common") { "${chip_root}/examples/all-clusters-app/all-clusters-common/src/electrical-energy-measurement-stub.cpp", "${chip_root}/examples/all-clusters-app/all-clusters-common/src/electrical-power-measurement-stub.cpp", "${chip_root}/examples/all-clusters-app/all-clusters-common/src/energy-evse-stub.cpp", + "${chip_root}/examples/all-clusters-app/all-clusters-common/src/energy-preference-delegate.cpp", "${chip_root}/examples/all-clusters-app/all-clusters-common/src/fan-stub.cpp", "${chip_root}/examples/all-clusters-app/all-clusters-common/src/laundry-dryer-controls-delegate-impl.cpp", "${chip_root}/examples/all-clusters-app/all-clusters-common/src/laundry-washer-controls-delegate-impl.cpp", diff --git a/src/app/clusters/energy-preference-server/energy-preference-server.cpp b/src/app/clusters/energy-preference-server/energy-preference-server.cpp new file mode 100644 index 00000000000000..7cb377a7221ba1 --- /dev/null +++ b/src/app/clusters/energy-preference-server/energy-preference-server.cpp @@ -0,0 +1,235 @@ +/** + * + * Copyright (c) 2024 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "energy-preference-server.h" + +#include // Needed for registerAttributeAccessOverride + +#include +#include +#include +#include +#include +#include +#include + +using namespace chip; +using namespace chip::app; +using namespace chip::app::Clusters; +using namespace chip::app::Clusters::EnergyPreference; +using namespace chip::app::Clusters::EnergyPreference::Structs; +using namespace chip::app::Clusters::EnergyPreference::Attributes; + +using Status = Protocols::InteractionModel::Status; + +namespace { + +class EnergyPrefAttrAccess : public AttributeAccessInterface +{ +public: + EnergyPrefAttrAccess() : AttributeAccessInterface(Optional::Missing(), EnergyPreference::Id) {} + + CHIP_ERROR Read(const ConcreteReadAttributePath & aPath, AttributeValueEncoder & aEncoder) override; +}; + +EnergyPrefAttrAccess gEnergyPrefAttrAccess; +Delegate * gsDelegate = nullptr; + +CHIP_ERROR EnergyPrefAttrAccess::Read(const ConcreteReadAttributePath & aPath, AttributeValueEncoder & aEncoder) +{ + VerifyOrDie(aPath.mClusterId == EnergyPreference::Id); + EndpointId endpoint = aPath.mEndpointId; + uint32_t ourFeatureMap = 0; + const bool featureMapIsGood = FeatureMap::Get(aPath.mEndpointId, &ourFeatureMap) == Status::Success; + const bool balanceSupported = featureMapIsGood && ((ourFeatureMap & to_underlying(Feature::kEnergyBalance)) != 0); + const bool lowPowerSupported = featureMapIsGood && ((ourFeatureMap & to_underlying(Feature::kLowPowerModeSensitivity)) != 0); + + switch (aPath.mAttributeId) + { + case EnergyBalances::Id: + if (!balanceSupported) + { + return CHIP_IM_GLOBAL_STATUS(UnsupportedAttribute); + } + + if (gsDelegate != nullptr) + { + return aEncoder.EncodeList([endpoint](const auto & encoder) -> CHIP_ERROR { + size_t index = 0; + CHIP_ERROR err = CHIP_NO_ERROR; + do + { + Percent step; + char buffer[64]; + Optional label{ MutableCharSpan(buffer) }; + if ((err = gsDelegate->GetEnergyBalanceAtIndex(endpoint, index, step, label)) == CHIP_NO_ERROR) + { + BalanceStruct::Type balance = { step, + label.HasValue() ? Optional(label.Value()) + : Optional() }; + ReturnErrorOnFailure(encoder.Encode(balance)); + index++; + } + } while (err == CHIP_NO_ERROR); + + if (err == CHIP_ERROR_NOT_FOUND) + { + return CHIP_NO_ERROR; + } + return err; + }); + } + return CHIP_ERROR_INCORRECT_STATE; + case EnergyPriorities::Id: + if (balanceSupported == false) + { + return CHIP_IM_GLOBAL_STATUS(UnsupportedAttribute); + } + + if (gsDelegate != nullptr) + { + return aEncoder.EncodeList([endpoint](const auto & encoder) -> CHIP_ERROR { + EnergyPriorityEnum priority; + size_t index = 0; + CHIP_ERROR err = CHIP_NO_ERROR; + while ((err = gsDelegate->GetEnergyPriorityAtIndex(endpoint, index, priority)) == CHIP_NO_ERROR) + { + ReturnErrorOnFailure(encoder.Encode(priority)); + index++; + } + if (err == CHIP_ERROR_NOT_FOUND) + { + return CHIP_NO_ERROR; + } + return err; + }); + } + return CHIP_ERROR_INCORRECT_STATE; + case LowPowerModeSensitivities::Id: + if (lowPowerSupported == false) + { + return CHIP_IM_GLOBAL_STATUS(UnsupportedAttribute); + } + + if (gsDelegate != nullptr) + { + return aEncoder.EncodeList([endpoint](const auto & encoder) -> CHIP_ERROR { + size_t index = 0; + CHIP_ERROR err = CHIP_NO_ERROR; + do + { + Percent step; + char buffer[64]; + Optional label{ MutableCharSpan(buffer) }; + if ((err = gsDelegate->GetLowPowerModeSensitivityAtIndex(endpoint, index, step, label)) == CHIP_NO_ERROR) + { + BalanceStruct::Type balance = { step, + label.HasValue() ? Optional(label.Value()) + : Optional() }; + ReturnErrorOnFailure(encoder.Encode(balance)); + index++; + } + } while (err == CHIP_NO_ERROR); + if (err == CHIP_ERROR_NOT_FOUND) + { + return CHIP_NO_ERROR; + } + return err; + }); + } + return CHIP_ERROR_INCORRECT_STATE; + default: // return CHIP_NO_ERROR and just read from the attribute store in default + break; + } + + return CHIP_NO_ERROR; +} + +} // anonymous namespace + +namespace chip::app::Clusters::EnergyPreference { + +void SetDelegate(Delegate * aDelegate) +{ + gsDelegate = aDelegate; +} + +Delegate * GetDelegate() +{ + return gsDelegate; +} + +} // namespace chip::app::Clusters::EnergyPreference + +Status MatterEnergyPreferenceClusterServerPreAttributeChangedCallback(const ConcreteAttributePath & attributePath, + EmberAfAttributeType attributeType, uint16_t size, + uint8_t * value) +{ + EndpointId endpoint = attributePath.mEndpointId; + Delegate * delegate = GetDelegate(); + uint32_t ourFeatureMap; + const bool featureMapIsGood = FeatureMap::Get(attributePath.mEndpointId, &ourFeatureMap) == Status::Success; + const bool balanceSupported = featureMapIsGood && ((ourFeatureMap & to_underlying(Feature::kEnergyBalance)) != 0); + const bool lowPowerSupported = featureMapIsGood && ((ourFeatureMap & to_underlying(Feature::kLowPowerModeSensitivity)) != 0); + + if (delegate == nullptr) + { + return Status::UnsupportedWrite; + } + + switch (attributePath.mAttributeId) + { + case CurrentEnergyBalance::Id: { + if (balanceSupported == false) + { + return Status::UnsupportedAttribute; + } + + uint8_t index = Encoding::Get8(value); + size_t arraySize = delegate->GetNumEnergyBalances(endpoint); + if (index >= arraySize) + { + return Status::ConstraintError; + } + + return Status::Success; + } + + case CurrentLowPowerModeSensitivity::Id: { + if (lowPowerSupported == false) + { + return Status::UnsupportedAttribute; + } + + uint8_t index = Encoding::Get8(value); + size_t arraySize = delegate->GetNumLowPowerModeSensitivities(endpoint); + if (index >= arraySize) + { + return Status::ConstraintError; + } + + return Status::Success; + } + default: + return Status::Success; + } +} + +void MatterEnergyPreferencePluginServerInitCallback() +{ + registerAttributeAccessOverride(&gEnergyPrefAttrAccess); +} diff --git a/src/app/clusters/energy-preference-server/energy-preference-server.h b/src/app/clusters/energy-preference-server/energy-preference-server.h new file mode 100644 index 00000000000000..771057847e372a --- /dev/null +++ b/src/app/clusters/energy-preference-server/energy-preference-server.h @@ -0,0 +1,107 @@ +/** + * + * Copyright (c) 2024 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include + +#include +#include +#include +#include + +namespace chip::app::Clusters::EnergyPreference { + +struct Delegate +{ + // Note: This delegate does not handle the "Current Active" indexes attributes storage. + // eg: Current Energy Balance and Current Low Power Mode Sensitivity. These can be handled using + // ember built in storage, or via the external callbacks as desired by the implementer. + + virtual ~Delegate() {} + + /** + * Get an Energy Balance. + * + * The delegate method is called by the cluster to fill out the + * values for the list in EnergyBalances attribute. Storage for + * both aOutStep and aOutLabel is provided by the caller. + * + * @param aEndpoint The endpoint to query. + * @param aIndex The index of the balance, with 0 representing the first one. + * @param aOutStep The Step value from BalanceStruct + * + * @param aOutLabel The Label value from BalanceStruct. Storage is + * provided by the caller, and is large enough to accomodate the + * longest label (64 chars), on successful return the size of the span must be + * adjusted to reflect the length of the value, or ClearValue() called on the Optional to indicate there is no label. + * + * @return CHIP_ERROR_NOT_FOUND if the index is out of range. + */ + virtual CHIP_ERROR GetEnergyBalanceAtIndex(chip::EndpointId aEndpoint, size_t aIndex, chip::Percent & aOutStep, + chip::Optional & aOutLabel) = 0; + + /** + * Get an Energy Priority. + * @param aEndpoint The endpoint to query. + * @param aIndex The index of the priority, with 0 representing the first one. + * @param aOutPriority The EnergyPriorityEnum to copy the data into. + * @return CHIP_ERROR_NOT_FOUND if the index is out of range. + */ + virtual CHIP_ERROR GetEnergyPriorityAtIndex(chip::EndpointId aEndpoint, size_t aIndex, + chip::app::Clusters::EnergyPreference::EnergyPriorityEnum & aOutPriority) = 0; + + /** + * Get a Power Sensitity Balance Struct data at the specified index. + * + * The delegate method is called by the cluster to fill out the + * values for the list in LowPowerSensitivities attribute. Storage for + * both aOutStep and aOutLabel is provided by the caller. + * + * @param aEndpoint The endpoint to query. + * @param aIndex The index of the priority, with 0 representing the first one. + * @param aOutStep The Step value from BalanceStruct + * + * @param aOutLabel The Label value from BalanceStruct. Storage is + * provided by the caller, and is large enough to accomodate the + * longest label (64 chars), on successful return the size of the span must be + * adjusted to reflect the length of the value, or ClearValue() called on the Optional to indicate there is no label. + * + * @return CHIP_ERROR_NOT_FOUND if the index is out of range. + */ + virtual CHIP_ERROR GetLowPowerModeSensitivityAtIndex(chip::EndpointId aEndpoint, size_t aIndex, chip::Percent & aOutStep, + chip::Optional & aOutLabel) = 0; + + /** + * Get the number of energy balances this endpoint has. + * @param aEndpoint The endpoint to query. + * @return the number of balance structs in the list. + */ + virtual size_t GetNumEnergyBalances(chip::EndpointId aEndpoint) = 0; + + /** + * Get the number of low power mode sensitivities this endpoint has. + * @param aEndpoint The endpoint to query. + * @return the number of balance structs in the list. + */ + virtual size_t GetNumLowPowerModeSensitivities(chip::EndpointId aEndpoint) = 0; +}; + +void SetDelegate(Delegate * aDelegate); +Delegate * GetDelegate(); + +} // namespace chip::app::Clusters::EnergyPreference diff --git a/src/app/common/templates/config-data.yaml b/src/app/common/templates/config-data.yaml index 20677184632c6c..875cdbcdbd1514 100644 --- a/src/app/common/templates/config-data.yaml +++ b/src/app/common/templates/config-data.yaml @@ -84,5 +84,6 @@ ClustersWithPreAttributeChangeFunctions: - Mode Select - Fan Control - Thermostat + - Energy Preference - Laundry Washer Controls - Laundry Dryer Controls diff --git a/src/app/zap-templates/zcl/data-model/chip/energy-preference-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/energy-preference-cluster.xml index ceff9846978e63..32893bd82a68e9 100644 --- a/src/app/zap-templates/zcl/data-model/chip/energy-preference-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/energy-preference-cluster.xml @@ -22,6 +22,7 @@ limitations under the License. true This cluster provides an interface to specify preferences for how devices should consume energy. + EnergyBalances diff --git a/src/app/zap_cluster_list.json b/src/app/zap_cluster_list.json index 56adf0a1126f95..2edfb272ad23e1 100644 --- a/src/app/zap_cluster_list.json +++ b/src/app/zap_cluster_list.json @@ -192,7 +192,7 @@ "ETHERNET_NETWORK_DIAGNOSTICS_CLUSTER": [ "ethernet-network-diagnostics-server" ], - "ENERGY_PREFERENCE_CLUSTER": [""], + "ENERGY_PREFERENCE_CLUSTER": ["energy-preference-server"], "FAN_CONTROL_CLUSTER": ["fan-control-server"], "FAULT_INJECTION_CLUSTER": ["fault-injection-server"], "FIXED_LABEL_CLUSTER": ["fixed-label-server"], diff --git a/src/controller/data_model/controller-clusters.matter b/src/controller/data_model/controller-clusters.matter index 89864630b8e85e..235366f4206e78 100644 --- a/src/controller/data_model/controller-clusters.matter +++ b/src/controller/data_model/controller-clusters.matter @@ -4978,7 +4978,7 @@ provisional cluster EnergyEvse = 153 { /** This cluster provides an interface to specify preferences for how devices should consume energy. */ provisional cluster EnergyPreference = 155 { - revision 1; // NOTE: Default/not specifically set + revision 1; enum EnergyPriorityEnum : enum8 { kComfort = 0; From 0c3f012c71cf3466ad5fe6d236b47e2bce914c7b Mon Sep 17 00:00:00 2001 From: Karsten Sperling <113487422+ksperling-apple@users.noreply.github.com> Date: Thu, 22 Feb 2024 01:58:17 +1300 Subject: [PATCH 03/13] Disable WiFi PDC support by default for 1.3 (#32234) Fixes #32169 --- src/platform/Darwin/CHIPDevicePlatformConfig.h | 1 - src/platform/Linux/CHIPDevicePlatformConfig.h | 1 - src/platform/Linux/NetworkCommissioningWiFiDriver.cpp | 2 +- 3 files changed, 1 insertion(+), 3 deletions(-) diff --git a/src/platform/Darwin/CHIPDevicePlatformConfig.h b/src/platform/Darwin/CHIPDevicePlatformConfig.h index 15fdaa476e3645..7a5140494c22dd 100644 --- a/src/platform/Darwin/CHIPDevicePlatformConfig.h +++ b/src/platform/Darwin/CHIPDevicePlatformConfig.h @@ -25,7 +25,6 @@ // ==================== Platform Adaptations ==================== -#define CHIP_DEVICE_CONFIG_ENABLE_WIFI_PDC 1 #define CHIP_DEVICE_CONFIG_ENABLE_WIFI_STATION 0 #define CHIP_DEVICE_CONFIG_ENABLE_WIFI_AP 0 diff --git a/src/platform/Linux/CHIPDevicePlatformConfig.h b/src/platform/Linux/CHIPDevicePlatformConfig.h index 70ed39d62899d5..530e2716308842 100644 --- a/src/platform/Linux/CHIPDevicePlatformConfig.h +++ b/src/platform/Linux/CHIPDevicePlatformConfig.h @@ -26,7 +26,6 @@ // ==================== Platform Adaptations ==================== #if CHIP_DEVICE_CONFIG_ENABLE_WIFI -#define CHIP_DEVICE_CONFIG_ENABLE_WIFI_PDC 1 #define CHIP_DEVICE_CONFIG_ENABLE_WIFI_STATION 1 #define CHIP_DEVICE_CONFIG_ENABLE_WIFI_AP 0 #else diff --git a/src/platform/Linux/NetworkCommissioningWiFiDriver.cpp b/src/platform/Linux/NetworkCommissioningWiFiDriver.cpp index 4b5b3c0b6b5e7d..16e4b7f0d7fbde 100644 --- a/src/platform/Linux/NetworkCommissioningWiFiDriver.cpp +++ b/src/platform/Linux/NetworkCommissioningWiFiDriver.cpp @@ -44,12 +44,12 @@ constexpr char kWiFiCredentialsKeyName[] = "wifi-pass"; constexpr char kWifiNetworkIdentityKeyName[] = "wifi-ni"; constexpr char kWifiClientIdentityKeyName[] = "wifi-ci"; constexpr char kWifiClientIdentityKeypairKeyName[] = "wifi-cik"; +#endif // CHIP_DEVICE_CONFIG_ENABLE_WIFI_PDC inline CHIP_ERROR IgnoreNotFound(CHIP_ERROR err) { return (err == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND) ? CHIP_NO_ERROR : err; } -#endif // CHIP_DEVICE_CONFIG_ENABLE_WIFI_PDC } // namespace // NOTE: For WiFiDriver, we uses two network configs, one is mSavedNetwork, and another is mStagingNetwork, during init, it will From a64773a912e09f65cfe00f527dd8d85123c69c83 Mon Sep 17 00:00:00 2001 From: Matthew Swartwout Date: Wed, 21 Feb 2024 05:52:25 -0800 Subject: [PATCH 04/13] Initialize scalar members in TLVReader (#32129) * Initialize scalar members in TLVReader The documented return values for multiple TLVReader functions do match the actual return value for the uninitialize case. Explicitly initialize members with null/0 values to match the documentation. * Restyled by clang-format * Don't inline constructor * Restyled by clang-format --------- Co-authored-by: Restyled.io --- src/lib/core/TLVReader.cpp | 6 ++++++ src/lib/core/TLVReader.h | 2 ++ src/lib/core/tests/TestTLV.cpp | 23 +++++++++++++++++++++++ 3 files changed, 31 insertions(+) diff --git a/src/lib/core/TLVReader.cpp b/src/lib/core/TLVReader.cpp index abef9af1636ca5..8368b9fb0fac04 100644 --- a/src/lib/core/TLVReader.cpp +++ b/src/lib/core/TLVReader.cpp @@ -49,6 +49,12 @@ using namespace chip::Encoding; static const uint8_t sTagSizes[] = { 0, 1, 2, 4, 2, 4, 6, 8 }; +TLVReader::TLVReader() : + ImplicitProfileId(kProfileIdNotSpecified), AppData(nullptr), mElemLenOrVal(0), mBackingStore(nullptr), mReadPoint(nullptr), + mBufEnd(nullptr), mLenRead(0), mMaxLen(0), mContainerType(kTLVType_NotSpecified), mControlByte(kTLVControlByte_NotSpecified), + mContainerOpen(false) +{} + void TLVReader::Init(const uint8_t * data, size_t dataLen) { // TODO: Maybe we can just make mMaxLen and mLenRead size_t instead? diff --git a/src/lib/core/TLVReader.h b/src/lib/core/TLVReader.h index bfb6b47f14d3f4..e86812cc2dc16b 100644 --- a/src/lib/core/TLVReader.h +++ b/src/lib/core/TLVReader.h @@ -86,6 +86,8 @@ class DLL_EXPORT TLVReader friend class TLVUpdater; public: + TLVReader(); + /** * Initializes a TLVReader object from another TLVReader object. * diff --git a/src/lib/core/tests/TestTLV.cpp b/src/lib/core/tests/TestTLV.cpp index fce0a5d17ae484..f71bce13fbd70b 100644 --- a/src/lib/core/tests/TestTLV.cpp +++ b/src/lib/core/tests/TestTLV.cpp @@ -3832,6 +3832,27 @@ void TestTLVReader_SkipOverContainer(nlTestSuite * inSuite) ForEachElement(inSuite, reader, nullptr, TestTLVReader_SkipOverContainer_ProcessElement); } +/** + * Tests using an uninitialized TLVReader. + */ +void TestTLVReaderUninitialized(nlTestSuite * inSuite) +{ + TLVReader reader; + + NL_TEST_ASSERT(inSuite, reader.GetType() == kTLVType_NotSpecified); + NL_TEST_ASSERT(inSuite, reader.GetLength() == 0); + NL_TEST_ASSERT(inSuite, reader.GetControlByte() == kTLVControlByte_NotSpecified); + NL_TEST_ASSERT(inSuite, reader.GetContainerType() == kTLVType_NotSpecified); + NL_TEST_ASSERT(inSuite, reader.GetLengthRead() == 0); + NL_TEST_ASSERT(inSuite, reader.GetRemainingLength() == 0); + NL_TEST_ASSERT(inSuite, reader.GetTotalLength() == 0); + NL_TEST_ASSERT(inSuite, reader.GetBackingStore() == nullptr); + NL_TEST_ASSERT(inSuite, reader.IsElementDouble() == false); + NL_TEST_ASSERT(inSuite, reader.GetReadPoint() == nullptr); + NL_TEST_ASSERT(inSuite, reader.ImplicitProfileId == kProfileIdNotSpecified); + NL_TEST_ASSERT(inSuite, reader.AppData == nullptr); +} + /** * Test CHIP TLV Reader */ @@ -3852,6 +3873,8 @@ void CheckTLVReader(nlTestSuite * inSuite, void * inContext) TestTLVReader_NextOverContainer(inSuite); TestTLVReader_SkipOverContainer(inSuite); + + TestTLVReaderUninitialized(inSuite); } /** From e1a4a01ca6c5715153381449b6d73bece6995756 Mon Sep 17 00:00:00 2001 From: Arkadiusz Bokowy Date: Wed, 21 Feb 2024 17:35:34 +0100 Subject: [PATCH 05/13] Extend GAutoPtr to conventionally get receiver (#32115) * Extend GAutoPtr to conventionally get receiver * Replace explicit use of MakeUniquePointerReceiver with GetReceiver() * Replace g_clear_error with .reset() * Add missing GLibTypeDeleter.h dependency to Tizen platform --- src/platform/GLibTypeDeleter.h | 12 +++- .../Linux/ConnectivityManagerImpl.cpp | 55 ++++++++----------- src/platform/Linux/ThreadStackManagerImpl.cpp | 28 ++++------ src/platform/Linux/bluez/AdapterIterator.cpp | 2 +- .../Linux/bluez/BluezAdvertisement.cpp | 8 +-- src/platform/Linux/bluez/BluezConnection.cpp | 10 ++-- src/platform/Linux/bluez/BluezEndpoint.cpp | 15 +++-- .../Linux/bluez/ChipDeviceScanner.cpp | 15 ++--- src/platform/Tizen/BLEManagerImpl.cpp | 12 ++-- src/platform/Tizen/BUILD.gn | 1 + src/platform/Tizen/DnssdImpl.cpp | 10 ++-- src/platform/Tizen/WiFiManager.cpp | 10 ++-- 12 files changed, 84 insertions(+), 94 deletions(-) diff --git a/src/platform/GLibTypeDeleter.h b/src/platform/GLibTypeDeleter.h index e6d9bfd0d2c1ed..f217d559e9cc66 100644 --- a/src/platform/GLibTypeDeleter.h +++ b/src/platform/GLibTypeDeleter.h @@ -29,10 +29,10 @@ class UniquePointerReceiver { public: UniquePointerReceiver(std::unique_ptr & target) : mTarget(target) {} - ~UniquePointerReceiver() { mTarget.reset(mValue); } T *& Get() { return mValue; } + T ** operator&() { return &mValue; } private: std::unique_ptr & mTarget; @@ -151,6 +151,14 @@ struct GAutoPtrDeleter }; template -using GAutoPtr = std::unique_ptr::deleter>; +class GAutoPtr : public std::unique_ptr::deleter> +{ +public: + using deleter = typename GAutoPtrDeleter::deleter; + using std::unique_ptr::unique_ptr; + + // Convenience method to get a UniquePointerReceiver for this object. + UniquePointerReceiver GetReceiver() { return MakeUniquePointerReceiver(*this); } +}; } // namespace chip diff --git a/src/platform/Linux/ConnectivityManagerImpl.cpp b/src/platform/Linux/ConnectivityManagerImpl.cpp index eef7ce883f0042..2a57a99d507976 100644 --- a/src/platform/Linux/ConnectivityManagerImpl.cpp +++ b/src/platform/Linux/ConnectivityManagerImpl.cpp @@ -266,8 +266,7 @@ void ConnectivityManagerImpl::_ClearWiFiStationProvision() if (mWiFiStationMode != kWiFiStationMode_ApplicationControlled) { GAutoPtr err; - wpa_fi_w1_wpa_supplicant1_interface_call_remove_all_networks_sync(mWpaSupplicant.iface, nullptr, - &MakeUniquePointerReceiver(err).Get()); + wpa_fi_w1_wpa_supplicant1_interface_call_remove_all_networks_sync(mWpaSupplicant.iface, nullptr, &err.GetReceiver()); if (err != nullptr) { @@ -388,7 +387,7 @@ void ConnectivityManagerImpl::_OnWpaPropertiesChanged(WpaFiW1Wpa_supplicant1Inte WiFiDiagnosticsDelegate * delegate = GetDiagnosticDataProvider().GetWiFiDiagnosticsDelegate(); - g_variant_get(changedProperties, "a{sv}", &MakeUniquePointerReceiver(iter).Get()); + g_variant_get(changedProperties, "a{sv}", &iter.GetReceiver()); while (g_variant_iter_loop(iter.get(), "{&sv}", &key, &value)) { @@ -497,8 +496,7 @@ void ConnectivityManagerImpl::_OnWpaInterfaceProxyReady(GObject * sourceObject, std::lock_guard lock(mWpaSupplicantMutex); - WpaFiW1Wpa_supplicant1Interface * iface = - wpa_fi_w1_wpa_supplicant1_interface_proxy_new_for_bus_finish(res, &MakeUniquePointerReceiver(err).Get()); + WpaFiW1Wpa_supplicant1Interface * iface = wpa_fi_w1_wpa_supplicant1_interface_proxy_new_for_bus_finish(res, &err.GetReceiver()); if (mWpaSupplicant.iface) { @@ -552,8 +550,7 @@ void ConnectivityManagerImpl::_OnWpaBssProxyReady(GObject * sourceObject, GAsync std::lock_guard lock(mWpaSupplicantMutex); - WpaFiW1Wpa_supplicant1BSS * bss = - wpa_fi_w1_wpa_supplicant1_bss_proxy_new_for_bus_finish(res, &MakeUniquePointerReceiver(err).Get()); + WpaFiW1Wpa_supplicant1BSS * bss = wpa_fi_w1_wpa_supplicant1_bss_proxy_new_for_bus_finish(res, &err.GetReceiver()); if (mWpaSupplicant.bss) { @@ -584,7 +581,7 @@ void ConnectivityManagerImpl::_OnWpaInterfaceReady(GObject * sourceObject, GAsyn std::lock_guard lock(mWpaSupplicantMutex); gboolean result = wpa_fi_w1_wpa_supplicant1_call_get_interface_finish(mWpaSupplicant.proxy, &mWpaSupplicant.interfacePath, res, - &MakeUniquePointerReceiver(err).Get()); + &err.GetReceiver()); if (result) { mWpaSupplicant.state = GDBusWpaSupplicant::WPA_GOT_INTERFACE_PATH; @@ -622,7 +619,7 @@ void ConnectivityManagerImpl::_OnWpaInterfaceReady(GObject * sourceObject, GAsyn args = g_variant_builder_end(&builder); result = wpa_fi_w1_wpa_supplicant1_call_create_interface_sync(mWpaSupplicant.proxy, args, &mWpaSupplicant.interfacePath, - nullptr, &MakeUniquePointerReceiver(error).Get()); + nullptr, &error.GetReceiver()); if (result) { @@ -747,7 +744,7 @@ void ConnectivityManagerImpl::_OnWpaProxyReady(GObject * sourceObject, GAsyncRes std::lock_guard lock(mWpaSupplicantMutex); - mWpaSupplicant.proxy = wpa_fi_w1_wpa_supplicant1_proxy_new_for_bus_finish(res, &MakeUniquePointerReceiver(err).Get()); + mWpaSupplicant.proxy = wpa_fi_w1_wpa_supplicant1_proxy_new_for_bus_finish(res, &err.GetReceiver()); if (mWpaSupplicant.proxy != nullptr && err.get() == nullptr) { mWpaSupplicant.state = GDBusWpaSupplicant::WPA_CONNECTED; @@ -898,7 +895,7 @@ void ConnectivityManagerImpl::DriveAPState() GAutoPtr error(nullptr); gboolean result = wpa_fi_w1_wpa_supplicant1_interface_call_remove_network_sync( - mWpaSupplicant.iface, mWpaSupplicant.networkPath, nullptr, &MakeUniquePointerReceiver(error).Get()); + mWpaSupplicant.iface, mWpaSupplicant.networkPath, nullptr, &error.GetReceiver()); if (result) { @@ -963,7 +960,7 @@ CHIP_ERROR ConnectivityManagerImpl::ConfigureWiFiAP() args = g_variant_builder_end(&builder); gboolean result = wpa_fi_w1_wpa_supplicant1_interface_call_add_network_sync( - mWpaSupplicant.iface, args, &mWpaSupplicant.networkPath, nullptr, &MakeUniquePointerReceiver(err).Get()); + mWpaSupplicant.iface, args, &mWpaSupplicant.networkPath, nullptr, &err.GetReceiver()); if (result) { @@ -972,7 +969,7 @@ CHIP_ERROR ConnectivityManagerImpl::ConfigureWiFiAP() ChipLogProgress(DeviceLayer, "wpa_supplicant: added network: SSID: %s: %s", ssid, mWpaSupplicant.networkPath); result = wpa_fi_w1_wpa_supplicant1_interface_call_select_network_sync(mWpaSupplicant.iface, mWpaSupplicant.networkPath, - nullptr, &MakeUniquePointerReceiver(error).Get()); + nullptr, &error.GetReceiver()); if (result) { ChipLogProgress(DeviceLayer, "wpa_supplicant: succeeded to start softAP: SSID: %s", ssid); @@ -1033,7 +1030,7 @@ ConnectivityManagerImpl::_ConnectWiFiNetworkAsync(GVariant * args, GAutoPtr error; result = wpa_fi_w1_wpa_supplicant1_interface_call_remove_network_sync(mWpaSupplicant.iface, networkPath, nullptr, - &MakeUniquePointerReceiver(error).Get()); + &error.GetReceiver()); if (result) { @@ -1055,7 +1052,7 @@ ConnectivityManagerImpl::_ConnectWiFiNetworkAsync(GVariant * args, } result = wpa_fi_w1_wpa_supplicant1_interface_call_add_network_sync(mWpaSupplicant.iface, args, &mWpaSupplicant.networkPath, - nullptr, &MakeUniquePointerReceiver(err).Get()); + nullptr, &err.GetReceiver()); if (result) { @@ -1127,7 +1124,7 @@ static CHIP_ERROR AddOrReplaceBlob(WpaFiW1Wpa_supplicant1Interface * iface, cons const char * name = (strncmp(nameOrRef, refPrefix.data(), refPrefix.size()) == 0) ? nameOrRef + refPrefix.size() : nameOrRef; GAutoPtr err; - if (!wpa_fi_w1_wpa_supplicant1_interface_call_remove_blob_sync(iface, name, nullptr, &MakeUniquePointerReceiver(err).Get())) + if (!wpa_fi_w1_wpa_supplicant1_interface_call_remove_blob_sync(iface, name, nullptr, &err.GetReceiver())) { GAutoPtr remoteError(g_dbus_error_get_remote_error(err.get())); if (!(remoteError && strcmp(remoteError.get(), kWpaSupplicantBlobUnknown) == 0)) @@ -1138,8 +1135,7 @@ static CHIP_ERROR AddOrReplaceBlob(WpaFiW1Wpa_supplicant1Interface * iface, cons err.reset(); } if (!wpa_fi_w1_wpa_supplicant1_interface_call_add_blob_sync( - iface, name, g_variant_new_fixed_array(G_VARIANT_TYPE_BYTE, data.data(), data.size(), 1), nullptr, - &MakeUniquePointerReceiver(err).Get())) + iface, name, g_variant_new_fixed_array(G_VARIANT_TYPE_BYTE, data.data(), data.size(), 1), nullptr, &err.GetReceiver())) { ChipLogError(DeviceLayer, "wpa_supplicant: failed to add blob: %s", err ? err->message : "unknown error"); return CHIP_ERROR_INTERNAL; @@ -1239,8 +1235,8 @@ void ConnectivityManagerImpl::_ConnectWiFiNetworkAsyncCallback(GObject * sourceO std::lock_guard lock(mWpaSupplicantMutex); { - gboolean result = wpa_fi_w1_wpa_supplicant1_interface_call_select_network_finish(mWpaSupplicant.iface, res, - &MakeUniquePointerReceiver(err).Get()); + gboolean result = + wpa_fi_w1_wpa_supplicant1_interface_call_select_network_finish(mWpaSupplicant.iface, res, &err.GetReceiver()); if (!result) { ChipLogError(DeviceLayer, "Failed to perform connect network: %s", err == nullptr ? "unknown error" : err->message); @@ -1257,8 +1253,7 @@ void ConnectivityManagerImpl::_ConnectWiFiNetworkAsyncCallback(GObject * sourceO return; } - result = wpa_fi_w1_wpa_supplicant1_interface_call_save_config_sync(mWpaSupplicant.iface, nullptr, - &MakeUniquePointerReceiver(err).Get()); + result = wpa_fi_w1_wpa_supplicant1_interface_call_save_config_sync(mWpaSupplicant.iface, nullptr, &err.GetReceiver()); if (result) { ChipLogProgress(DeviceLayer, "wpa_supplicant: save config succeeded!"); @@ -1335,8 +1330,7 @@ CHIP_ERROR ConnectivityManagerImpl::CommitConfig() ChipLogProgress(DeviceLayer, "wpa_supplicant: save config"); - result = wpa_fi_w1_wpa_supplicant1_interface_call_save_config_sync(mWpaSupplicant.iface, nullptr, - &MakeUniquePointerReceiver(err).Get()); + result = wpa_fi_w1_wpa_supplicant1_interface_call_save_config_sync(mWpaSupplicant.iface, nullptr, &err.GetReceiver()); if (!result) { @@ -1486,8 +1480,7 @@ CHIP_ERROR ConnectivityManagerImpl::GetConfiguredNetwork(NetworkCommissioning::N } GAutoPtr networkInfo(wpa_fi_w1_wpa_supplicant1_network_proxy_new_for_bus_sync( - G_BUS_TYPE_SYSTEM, G_DBUS_PROXY_FLAGS_NONE, kWpaSupplicantServiceName, networkPath, nullptr, - &MakeUniquePointerReceiver(err).Get())); + G_BUS_TYPE_SYSTEM, G_DBUS_PROXY_FLAGS_NONE, kWpaSupplicantServiceName, networkPath, nullptr, &err.GetReceiver())); if (networkInfo == nullptr) { return CHIP_ERROR_INTERNAL; @@ -1518,7 +1511,7 @@ CHIP_ERROR ConnectivityManagerImpl::StopAutoScan() ChipLogDetail(DeviceLayer, "wpa_supplicant: disabling auto scan"); result = wpa_fi_w1_wpa_supplicant1_interface_call_auto_scan_sync( - mWpaSupplicant.iface, "" /* empty string means disabling auto scan */, nullptr, &MakeUniquePointerReceiver(err).Get()); + mWpaSupplicant.iface, "" /* empty string means disabling auto scan */, nullptr, &err.GetReceiver()); if (!result) { ChipLogError(DeviceLayer, "wpa_supplicant: Failed to stop auto network scan: %s", err ? err->message : "unknown"); @@ -1548,8 +1541,7 @@ CHIP_ERROR ConnectivityManagerImpl::StartWiFiScan(ByteSpan ssid, WiFiDriver::Sca g_variant_builder_add(&builder, "{sv}", "Type", g_variant_new_string("active")); args = g_variant_builder_end(&builder); - result = wpa_fi_w1_wpa_supplicant1_interface_call_scan_sync(mWpaSupplicant.iface, args, nullptr, - &MakeUniquePointerReceiver(err).Get()); + result = wpa_fi_w1_wpa_supplicant1_interface_call_scan_sync(mWpaSupplicant.iface, args, nullptr, &err.GetReceiver()); if (result) { @@ -1676,9 +1668,8 @@ bool ConnectivityManagerImpl::_GetBssInfo(const gchar * bssPath, NetworkCommissi // with the proxy object. GAutoPtr err; - GAutoPtr bss( - wpa_fi_w1_wpa_supplicant1_bss_proxy_new_for_bus_sync(G_BUS_TYPE_SYSTEM, G_DBUS_PROXY_FLAGS_NONE, kWpaSupplicantServiceName, - bssPath, nullptr, &MakeUniquePointerReceiver(err).Get())); + GAutoPtr bss(wpa_fi_w1_wpa_supplicant1_bss_proxy_new_for_bus_sync( + G_BUS_TYPE_SYSTEM, G_DBUS_PROXY_FLAGS_NONE, kWpaSupplicantServiceName, bssPath, nullptr, &err.GetReceiver())); if (bss == nullptr) { diff --git a/src/platform/Linux/ThreadStackManagerImpl.cpp b/src/platform/Linux/ThreadStackManagerImpl.cpp index a8f6c23f1e5a24..5fd865df5485ad 100644 --- a/src/platform/Linux/ThreadStackManagerImpl.cpp +++ b/src/platform/Linux/ThreadStackManagerImpl.cpp @@ -85,7 +85,7 @@ CHIP_ERROR ThreadStackManagerImpl::GLibMatterContextInitThreadStack(ThreadStackM GAutoPtr err; self->mProxy.reset(openthread_io_openthread_border_router_proxy_new_for_bus_sync( G_BUS_TYPE_SYSTEM, G_DBUS_PROXY_FLAGS_NONE, kDBusOpenThreadService, kDBusOpenThreadObjectPath, nullptr, - &MakeUniquePointerReceiver(err).Get())); + &err.GetReceiver())); VerifyOrReturnError( self->mProxy != nullptr, CHIP_ERROR_INTERNAL, ChipLogError(DeviceLayer, "openthread: failed to create openthread dbus proxy %s", err ? err->message : "unknown error")); @@ -123,7 +123,7 @@ void ThreadStackManagerImpl::OnDbusPropertiesChanged(OpenthreadIoOpenthreadBorde GVariant * value; GAutoPtr iter; - g_variant_get(changed_properties, "a{sv}", &MakeUniquePointerReceiver(iter).Get()); + g_variant_get(changed_properties, "a{sv}", &iter.GetReceiver()); if (!iter) return; while (g_variant_iter_loop(iter.get(), "{&sv}", &key, &value)) @@ -193,7 +193,7 @@ bool ThreadStackManagerImpl::_HaveRouteToAddress(const Inet::IPAddress & destAdd if (g_variant_n_children(routes.get()) > 0) { GAutoPtr iter; - g_variant_get(routes.get(), "av", &MakeUniquePointerReceiver(iter).Get()); + g_variant_get(routes.get(), "av", &iter.GetReceiver()); if (!iter) return false; @@ -207,14 +207,13 @@ bool ThreadStackManagerImpl::_HaveRouteToAddress(const Inet::IPAddress & destAdd guchar preference; gboolean stable; gboolean nextHopIsThisDevice; - g_variant_get(route, "(&vqybb)", &MakeUniquePointerReceiver(prefix).Get(), &rloc16, &preference, &stable, - &nextHopIsThisDevice); + g_variant_get(route, "(&vqybb)", &prefix.GetReceiver(), &rloc16, &preference, &stable, &nextHopIsThisDevice); if (!prefix) continue; GAutoPtr address; guchar prefixLength; - g_variant_get(prefix.get(), "(&vy)", &MakeUniquePointerReceiver(address).Get(), &prefixLength); + g_variant_get(prefix.get(), "(&vy)", &address.GetReceiver(), &prefixLength); if (!address) continue; @@ -273,8 +272,7 @@ CHIP_ERROR ThreadStackManagerImpl::_GetThreadProvision(Thread::OperationalDatase GAutoPtr err; GAutoPtr response(g_dbus_proxy_call_sync(G_DBUS_PROXY(mProxy.get()), "org.freedesktop.DBus.Properties.Get", g_variant_new("(ss)", "io.openthread.BorderRouter", "ActiveDatasetTlvs"), - G_DBUS_CALL_FLAGS_NONE, -1, nullptr, - &MakeUniquePointerReceiver(err).Get())); + G_DBUS_CALL_FLAGS_NONE, -1, nullptr, &err.GetReceiver())); if (err) { @@ -330,7 +328,7 @@ bool ThreadStackManagerImpl::_IsThreadEnabled() GAutoPtr err; GAutoPtr response(g_dbus_proxy_call_sync(G_DBUS_PROXY(mProxy.get()), "org.freedesktop.DBus.Properties.Get", g_variant_new("(ss)", "io.openthread.BorderRouter", "DeviceRole"), - G_DBUS_CALL_FLAGS_NONE, -1, nullptr, &MakeUniquePointerReceiver(err).Get())); + G_DBUS_CALL_FLAGS_NONE, -1, nullptr, &err.GetReceiver())); if (err) { @@ -390,8 +388,7 @@ CHIP_ERROR ThreadStackManagerImpl::_SetThreadEnabled(bool val) else { GAutoPtr err; - gboolean result = - openthread_io_openthread_border_router_call_reset_sync(mProxy.get(), nullptr, &MakeUniquePointerReceiver(err).Get()); + gboolean result = openthread_io_openthread_border_router_call_reset_sync(mProxy.get(), nullptr, &err.GetReceiver()); if (err) { ChipLogError(DeviceLayer, "openthread: _SetThreadEnabled calling %s failed: %s", "Reset", err->message); @@ -413,8 +410,7 @@ void ThreadStackManagerImpl::_OnThreadBrAttachFinished(GObject * source_object, GAutoPtr attachRes; GAutoPtr err; { - gboolean result = openthread_io_openthread_border_router_call_attach_finish(this_->mProxy.get(), res, - &MakeUniquePointerReceiver(err).Get()); + gboolean result = openthread_io_openthread_border_router_call_attach_finish(this_->mProxy.get(), res, &err.GetReceiver()); if (!result) { ChipLogError(DeviceLayer, "Failed to perform finish Thread network scan: %s", @@ -612,8 +608,8 @@ void ThreadStackManagerImpl::_OnNetworkScanFinished(GAsyncResult * res) GAutoPtr scan_result; GAutoPtr err; { - gboolean result = openthread_io_openthread_border_router_call_scan_finish( - mProxy.get(), &MakeUniquePointerReceiver(scan_result).Get(), res, &MakeUniquePointerReceiver(err).Get()); + gboolean result = openthread_io_openthread_border_router_call_scan_finish(mProxy.get(), &scan_result.GetReceiver(), res, + &err.GetReceiver()); if (!result) { ChipLogError(DeviceLayer, "Failed to perform finish Thread network scan: %s", @@ -635,7 +631,7 @@ void ThreadStackManagerImpl::_OnNetworkScanFinished(GAsyncResult * res) if (g_variant_n_children(scan_result.get()) > 0) { GAutoPtr iter; - g_variant_get(scan_result.get(), "a(tstayqqynyybb)", &MakeUniquePointerReceiver(iter).Get()); + g_variant_get(scan_result.get(), "a(tstayqqynyybb)", &iter.GetReceiver()); if (!iter) { delete scanResult; diff --git a/src/platform/Linux/bluez/AdapterIterator.cpp b/src/platform/Linux/bluez/AdapterIterator.cpp index 3197be4e73e175..e69c473f52bbfe 100644 --- a/src/platform/Linux/bluez/AdapterIterator.cpp +++ b/src/platform/Linux/bluez/AdapterIterator.cpp @@ -57,7 +57,7 @@ CHIP_ERROR AdapterIterator::Initialize(AdapterIterator * self) self->mManager = g_dbus_object_manager_client_new_for_bus_sync( G_BUS_TYPE_SYSTEM, G_DBUS_OBJECT_MANAGER_CLIENT_FLAGS_NONE, BLUEZ_INTERFACE, "/", bluez_object_manager_client_get_proxy_type, nullptr /* unused user data in the Proxy Type Func */, - nullptr /*destroy notify */, nullptr /* cancellable */, &MakeUniquePointerReceiver(error).Get()); + nullptr /* destroy notify */, nullptr /* cancellable */, &error.GetReceiver()); VerifyOrExit(self->mManager != nullptr, ChipLogError(DeviceLayer, "Failed to get DBUS object manager for listing adapters."); err = CHIP_ERROR_INTERNAL); diff --git a/src/platform/Linux/bluez/BluezAdvertisement.cpp b/src/platform/Linux/bluez/BluezAdvertisement.cpp index 1b95aae41a4f11..196529816b59ab 100644 --- a/src/platform/Linux/bluez/BluezAdvertisement.cpp +++ b/src/platform/Linux/bluez/BluezAdvertisement.cpp @@ -118,7 +118,7 @@ CHIP_ERROR BluezAdvertisement::Init(const BluezEndpoint & aEndpoint, const char mpRoot = reinterpret_cast(g_object_ref(aEndpoint.GetGattApplicationObjectManager())); mpAdapter = reinterpret_cast(g_object_ref(aEndpoint.GetAdapter())); - g_object_get(G_OBJECT(mpRoot), "object-path", &MakeUniquePointerReceiver(rootPath).Get(), nullptr); + g_object_get(G_OBJECT(mpRoot), "object-path", &rootPath.GetReceiver(), nullptr); mpAdvPath = g_strdup_printf("%s/advertising", rootPath.get()); mpAdvUUID = g_strdup(aAdvUUID); @@ -241,8 +241,7 @@ void BluezAdvertisement::StartDone(GObject * aObject, GAsyncResult * aResult) GAutoPtr error; gboolean success = FALSE; - success = - bluez_leadvertising_manager1_call_register_advertisement_finish(advMgr, aResult, &MakeUniquePointerReceiver(error).Get()); + success = bluez_leadvertising_manager1_call_register_advertisement_finish(advMgr, aResult, &error.GetReceiver()); if (success == FALSE) { g_dbus_object_manager_server_unexport(mpRoot, mpAdvPath); @@ -304,8 +303,7 @@ void BluezAdvertisement::StopDone(GObject * aObject, GAsyncResult * aResult) GAutoPtr error; gboolean success = FALSE; - success = - bluez_leadvertising_manager1_call_unregister_advertisement_finish(advMgr, aResult, &MakeUniquePointerReceiver(error).Get()); + success = bluez_leadvertising_manager1_call_unregister_advertisement_finish(advMgr, aResult, &error.GetReceiver()); if (success == FALSE) { diff --git a/src/platform/Linux/bluez/BluezConnection.cpp b/src/platform/Linux/bluez/BluezConnection.cpp index 39b5bb0bdb8ba6..d2d5745a4c37c2 100644 --- a/src/platform/Linux/bluez/BluezConnection.cpp +++ b/src/platform/Linux/bluez/BluezConnection.cpp @@ -180,7 +180,7 @@ CHIP_ERROR BluezConnection::BluezDisconnect(BluezConnection * conn) ChipLogDetail(DeviceLayer, "%s peer=%s", __func__, conn->GetPeerAddress()); - success = bluez_device1_call_disconnect_sync(conn->mpDevice, nullptr, &MakeUniquePointerReceiver(error).Get()); + success = bluez_device1_call_disconnect_sync(conn->mpDevice, nullptr, &error.GetReceiver()); VerifyOrExit(success == TRUE, ChipLogError(DeviceLayer, "FAIL: Disconnect: %s", error->message)); exit: @@ -284,7 +284,7 @@ CHIP_ERROR BluezConnection::SendIndicationImpl(ConnectionDataBundle * data) VerifyOrExit(len <= static_cast(std::numeric_limits::max()), ChipLogError(DeviceLayer, "FAIL: buffer too large in %s", __func__)); auto status = g_io_channel_write_chars(data->mConn.mC2Channel.mChannel.get(), buf, static_cast(len), &written, - &MakeUniquePointerReceiver(error).Get()); + &error.GetReceiver()); VerifyOrExit(status == G_IO_STATUS_NORMAL, ChipLogError(DeviceLayer, "FAIL: C2 Indicate: %s", error->message)); } else @@ -311,7 +311,7 @@ void BluezConnection::SendWriteRequestDone(GObject * aObject, GAsyncResult * aRe { BluezGattCharacteristic1 * c1 = BLUEZ_GATT_CHARACTERISTIC1(aObject); GAutoPtr error; - gboolean success = bluez_gatt_characteristic1_call_write_value_finish(c1, aResult, &MakeUniquePointerReceiver(error).Get()); + gboolean success = bluez_gatt_characteristic1_call_write_value_finish(c1, aResult, &error.GetReceiver()); VerifyOrReturn(success == TRUE, ChipLogError(DeviceLayer, "FAIL: SendWriteRequest : %s", error->message)); BLEManagerImpl::HandleWriteComplete(static_cast(apConnection)); @@ -360,7 +360,7 @@ void BluezConnection::SubscribeCharacteristicDone(GObject * aObject, GAsyncResul { BluezGattCharacteristic1 * c2 = BLUEZ_GATT_CHARACTERISTIC1(aObject); GAutoPtr error; - gboolean success = bluez_gatt_characteristic1_call_write_value_finish(c2, aResult, &MakeUniquePointerReceiver(error).Get()); + gboolean success = bluez_gatt_characteristic1_call_write_value_finish(c2, aResult, &error.GetReceiver()); VerifyOrReturn(success == TRUE, ChipLogError(DeviceLayer, "FAIL: SubscribeCharacteristic : %s", error->message)); @@ -392,7 +392,7 @@ void BluezConnection::UnsubscribeCharacteristicDone(GObject * aObject, GAsyncRes { BluezGattCharacteristic1 * c2 = BLUEZ_GATT_CHARACTERISTIC1(aObject); GAutoPtr error; - gboolean success = bluez_gatt_characteristic1_call_write_value_finish(c2, aResult, &MakeUniquePointerReceiver(error).Get()); + gboolean success = bluez_gatt_characteristic1_call_write_value_finish(c2, aResult, &error.GetReceiver()); VerifyOrReturn(success == TRUE, ChipLogError(DeviceLayer, "FAIL: UnsubscribeCharacteristic : %s", error->message)); diff --git a/src/platform/Linux/bluez/BluezEndpoint.cpp b/src/platform/Linux/bluez/BluezEndpoint.cpp index 3baca7d127f20a..e68b28b8f421a8 100644 --- a/src/platform/Linux/bluez/BluezEndpoint.cpp +++ b/src/platform/Linux/bluez/BluezEndpoint.cpp @@ -264,8 +264,7 @@ void BluezEndpoint::RegisterGattApplicationDone(GObject * aObject, GAsyncResult GAutoPtr error; BluezGattManager1 * gattMgr = BLUEZ_GATT_MANAGER1(aObject); - gboolean success = - bluez_gatt_manager1_call_register_application_finish(gattMgr, aResult, &MakeUniquePointerReceiver(error).Get()); + gboolean success = bluez_gatt_manager1_call_register_application_finish(gattMgr, aResult, &error.GetReceiver()); VerifyOrReturn(success == TRUE, { ChipLogError(DeviceLayer, "FAIL: RegisterApplication : %s", error->message); @@ -614,16 +613,16 @@ void BluezEndpoint::SetupGattServer(GDBusConnection * aConn) CHIP_ERROR BluezEndpoint::StartupEndpointBindings() { GAutoPtr err; - GAutoPtr conn(g_bus_get_sync(G_BUS_TYPE_SYSTEM, nullptr, &MakeUniquePointerReceiver(err).Get())); + GAutoPtr conn(g_bus_get_sync(G_BUS_TYPE_SYSTEM, nullptr, &err.GetReceiver())); VerifyOrReturnError(conn != nullptr, CHIP_ERROR_INTERNAL, ChipLogError(DeviceLayer, "FAIL: get bus sync in %s, error: %s", __func__, err->message)); SetupGattServer(conn.get()); - mpObjMgr = g_dbus_object_manager_client_new_sync( - conn.get(), G_DBUS_OBJECT_MANAGER_CLIENT_FLAGS_NONE, BLUEZ_INTERFACE, "/", bluez_object_manager_client_get_proxy_type, - nullptr /* unused user data in the Proxy Type Func */, nullptr /*destroy notify */, nullptr /* cancellable */, - &MakeUniquePointerReceiver(err).Get()); + mpObjMgr = g_dbus_object_manager_client_new_sync(conn.get(), G_DBUS_OBJECT_MANAGER_CLIENT_FLAGS_NONE, BLUEZ_INTERFACE, "/", + bluez_object_manager_client_get_proxy_type, + nullptr /* unused user data in the Proxy Type Func */, + nullptr /*destroy notify */, nullptr /* cancellable */, &err.GetReceiver()); VerifyOrReturnError(mpObjMgr != nullptr, CHIP_ERROR_INTERNAL, ChipLogError(DeviceLayer, "FAIL: Error getting object manager client: %s", err->message)); @@ -729,7 +728,7 @@ CHIP_ERROR BluezEndpoint::ConnectDeviceImpl(BluezDevice1 & aDevice) for (uint16_t i = 0; i < kMaxConnectRetries; i++) { GAutoPtr error; - if (bluez_device1_call_connect_sync(&aDevice, mConnectCancellable.get(), &MakeUniquePointerReceiver(error).Get())) + if (bluez_device1_call_connect_sync(&aDevice, mConnectCancellable.get(), &error.GetReceiver())) { ChipLogDetail(DeviceLayer, "ConnectDevice complete"); return CHIP_NO_ERROR; diff --git a/src/platform/Linux/bluez/ChipDeviceScanner.cpp b/src/platform/Linux/bluez/ChipDeviceScanner.cpp index 5d9cbf25c9028b..03b26aa08e3dc7 100644 --- a/src/platform/Linux/bluez/ChipDeviceScanner.cpp +++ b/src/platform/Linux/bluez/ChipDeviceScanner.cpp @@ -72,7 +72,7 @@ CHIP_ERROR ChipDeviceScanner::Init(BluezAdapter1 * adapter, ChipDeviceScannerDel self->mManager = g_dbus_object_manager_client_new_for_bus_sync( G_BUS_TYPE_SYSTEM, G_DBUS_OBJECT_MANAGER_CLIENT_FLAGS_NONE, BLUEZ_INTERFACE, "/", bluez_object_manager_client_get_proxy_type, nullptr /* unused user data in the Proxy Type Func */, - nullptr /* destroy notify */, nullptr /* cancellable */, &MakeUniquePointerReceiver(err).Get()); + nullptr /* destroy notify */, nullptr /* cancellable */, &err.GetReceiver()); VerifyOrReturnError(self->mManager != nullptr, CHIP_ERROR_INTERNAL, ChipLogError(Ble, "Failed to get D-Bus object manager for device scanning: %s", err->message)); return CHIP_NO_ERROR; @@ -205,8 +205,7 @@ CHIP_ERROR ChipDeviceScanner::MainLoopStopScan(ChipDeviceScanner * self) self->mInterfaceChangedSignal = 0; } - if (!bluez_adapter1_call_stop_discovery_sync(self->mAdapter, nullptr /* not cancellable */, - &MakeUniquePointerReceiver(error).Get())) + if (!bluez_adapter1_call_stop_discovery_sync(self->mAdapter, nullptr /* not cancellable */, &error.GetReceiver())) { ChipLogError(Ble, "Failed to stop discovery %s", error->message); return CHIP_ERROR_INTERNAL; @@ -268,7 +267,7 @@ void ChipDeviceScanner::RemoveDevice(BluezDevice1 & device) const auto devicePath = g_dbus_proxy_get_object_path(G_DBUS_PROXY(&device)); GAutoPtr error; - if (!bluez_adapter1_call_remove_device_sync(mAdapter, devicePath, nullptr, &MakeUniquePointerReceiver(error).Get())) + if (!bluez_adapter1_call_remove_device_sync(mAdapter, devicePath, nullptr, &error.GetReceiver())) { ChipLogDetail(Ble, "Failed to remove device %s: %s", StringOrNullMarker(devicePath), error->message); } @@ -303,17 +302,15 @@ CHIP_ERROR ChipDeviceScanner::MainLoopStartScan(ChipDeviceScanner * self) g_variant_builder_add(&filterBuilder, "{sv}", "Transport", g_variant_new_string("le")); GVariant * filter = g_variant_builder_end(&filterBuilder); - if (!bluez_adapter1_call_set_discovery_filter_sync(self->mAdapter, filter, self->mCancellable.get(), - &MakeUniquePointerReceiver(error).Get())) + if (!bluez_adapter1_call_set_discovery_filter_sync(self->mAdapter, filter, self->mCancellable.get(), &error.GetReceiver())) { // Not critical: ignore if fails ChipLogError(Ble, "Failed to set discovery filters: %s", error->message); - g_clear_error(&MakeUniquePointerReceiver(error).Get()); + error.reset(); } ChipLogProgress(Ble, "BLE initiating scan."); - if (!bluez_adapter1_call_start_discovery_sync(self->mAdapter, self->mCancellable.get(), - &MakeUniquePointerReceiver(error).Get())) + if (!bluez_adapter1_call_start_discovery_sync(self->mAdapter, self->mCancellable.get(), &error.GetReceiver())) { ChipLogError(Ble, "Failed to start discovery: %s", error->message); return CHIP_ERROR_INTERNAL; diff --git a/src/platform/Tizen/BLEManagerImpl.cpp b/src/platform/Tizen/BLEManagerImpl.cpp index 0a1a9468d00b06..4d4c3e77316fc7 100644 --- a/src/platform/Tizen/BLEManagerImpl.cpp +++ b/src/platform/Tizen/BLEManagerImpl.cpp @@ -208,11 +208,11 @@ void BLEManagerImpl::ReadValueRequestedCb(const char * remoteAddress, int reques GAutoPtr uuid; GAutoPtr value; - VerifyOrReturn(__GetAttInfo(gattHandle, &MakeUniquePointerReceiver(uuid).Get(), &type) == BT_ERROR_NONE, + VerifyOrReturn(__GetAttInfo(gattHandle, &uuid.GetReceiver(), &type) == BT_ERROR_NONE, ChipLogError(DeviceLayer, "Failed to fetch GATT Attribute from GATT handle")); ChipLogProgress(DeviceLayer, "Gatt read requested on %s: uuid=%s", __ConvertAttTypeToStr(type), StringOrNullMarker(uuid.get())); - ret = bt_gatt_get_value(gattHandle, &MakeUniquePointerReceiver(value).Get(), &len); + ret = bt_gatt_get_value(gattHandle, &value.GetReceiver(), &len); VerifyOrReturn(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_gatt_get_value() failed: %s", get_error_message(ret))); ChipLogByteSpan(DeviceLayer, ByteSpan(Uint8::from_const_char(value.get()), len)); @@ -233,7 +233,7 @@ void BLEManagerImpl::WriteValueRequestedCb(const char * remoteAddress, int reque conn = static_cast(g_hash_table_lookup(mConnectionMap, remoteAddress)); VerifyOrReturn(conn != nullptr, ChipLogError(DeviceLayer, "Failed to find connection info")); - VerifyOrReturn(__GetAttInfo(gattHandle, &MakeUniquePointerReceiver(uuid).Get(), &type) == BT_ERROR_NONE, + VerifyOrReturn(__GetAttInfo(gattHandle, &uuid.GetReceiver(), &type) == BT_ERROR_NONE, ChipLogError(DeviceLayer, "Failed to fetch GATT Attribute from GATT handle")); ChipLogProgress(DeviceLayer, "Gatt write requested on %s: uuid=%s len=%d", __ConvertAttTypeToStr(type), StringOrNullMarker(uuid.get()), len); @@ -268,7 +268,7 @@ void BLEManagerImpl::NotificationStateChangedCb(bool notify, bt_gatt_server_h se VerifyOrReturn(conn != nullptr, ChipLogError(DeviceLayer, "Failed to find connection info")); - int ret = __GetAttInfo(charHandle, &MakeUniquePointerReceiver(uuid).Get(), &type); + int ret = __GetAttInfo(charHandle, &uuid.GetReceiver(), &type); VerifyOrReturn(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "Failed to fetch GATT Attribute from CHAR handle: %s", get_error_message(ret))); @@ -776,7 +776,7 @@ static bool __GattClientForeachCharCb(int total, int index, bt_gatt_h charHandle GAutoPtr uuid; auto conn = static_cast(data); - int ret = __GetAttInfo(charHandle, &MakeUniquePointerReceiver(uuid).Get(), &type); + int ret = __GetAttInfo(charHandle, &uuid.GetReceiver(), &type); VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "Failed to fetch GATT Attribute from CHAR handle: %s", get_error_message(ret))); @@ -803,7 +803,7 @@ static bool __GattClientForeachServiceCb(int total, int index, bt_gatt_h svcHand auto conn = static_cast(data); ChipLogProgress(DeviceLayer, "__GattClientForeachServiceCb"); - int ret = __GetAttInfo(svcHandle, &MakeUniquePointerReceiver(uuid).Get(), &type); + int ret = __GetAttInfo(svcHandle, &uuid.GetReceiver(), &type); VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "Failed to fetch GATT Attribute from SVC handle: %s", get_error_message(ret))); diff --git a/src/platform/Tizen/BUILD.gn b/src/platform/Tizen/BUILD.gn index 0d0f329be1bd5e..f2f972635a054d 100644 --- a/src/platform/Tizen/BUILD.gn +++ b/src/platform/Tizen/BUILD.gn @@ -31,6 +31,7 @@ static_library("Tizen") { sources = [ "../DeviceSafeQueue.cpp", "../DeviceSafeQueue.h", + "../GLibTypeDeleter.h", "../SingletonConfigurationManager.cpp", "AppPreference.cpp", "AppPreference.h", diff --git a/src/platform/Tizen/DnssdImpl.cpp b/src/platform/Tizen/DnssdImpl.cpp index 8d383ac48f5d13..cc3e5a1e8f76a6 100644 --- a/src/platform/Tizen/DnssdImpl.cpp +++ b/src/platform/Tizen/DnssdImpl.cpp @@ -181,13 +181,13 @@ void OnBrowse(dnssd_service_state_e state, dnssd_service_h service, void * data) chip::GAutoPtr ifaceName; uint32_t interfaceId = 0; - ret = dnssd_service_get_type(service, &MakeUniquePointerReceiver(type).Get()); + ret = dnssd_service_get_type(service, &type.GetReceiver()); VerifyOrExit(ret == DNSSD_ERROR_NONE, ChipLogError(DeviceLayer, "dnssd_service_get_type() failed: %s", get_error_message(ret))); - ret = dnssd_service_get_name(service, &MakeUniquePointerReceiver(name).Get()); + ret = dnssd_service_get_name(service, &name.GetReceiver()); VerifyOrExit(ret == DNSSD_ERROR_NONE, ChipLogError(DeviceLayer, "dnssd_service_get_name() failed: %s", get_error_message(ret))); - ret = dnssd_service_get_interface(service, &MakeUniquePointerReceiver(ifaceName).Get()); + ret = dnssd_service_get_interface(service, &ifaceName.GetReceiver()); VerifyOrExit(ret == DNSSD_ERROR_NONE, ChipLogError(DeviceLayer, "dnssd_service_get_interface() failed: %s", get_error_message(ret))); @@ -305,12 +305,12 @@ void OnResolve(dnssd_error_e result, dnssd_service_h service, void * userData) chip::Inet::IPAddress ipAddr; CHIP_ERROR err = CHIP_NO_ERROR; - int ret = dnssd_service_get_name(service, &MakeUniquePointerReceiver(name).Get()); + int ret = dnssd_service_get_name(service, &name.GetReceiver()); VerifyOrExit(ret == DNSSD_ERROR_NONE, ChipLogError(DeviceLayer, "dnssd_service_get_name() failed: %s", get_error_message(ret))); chip::Platform::CopyString(rCtx->mResult.mName, name.get()); - ret = dnssd_service_get_ip(service, &MakeUniquePointerReceiver(ipv4).Get(), &MakeUniquePointerReceiver(ipv6).Get()); + ret = dnssd_service_get_ip(service, &ipv4.GetReceiver(), &ipv6.GetReceiver()); VerifyOrExit(ret == DNSSD_ERROR_NONE, ChipLogError(DeviceLayer, "dnssd_service_get_ip() failed: %s", get_error_message(ret))); // If both IPv4 and IPv6 are set, IPv6 address has higher priority. diff --git a/src/platform/Tizen/WiFiManager.cpp b/src/platform/Tizen/WiFiManager.cpp index ed43377e5e0142..50e8b9206401d7 100644 --- a/src/platform/Tizen/WiFiManager.cpp +++ b/src/platform/Tizen/WiFiManager.cpp @@ -400,14 +400,14 @@ bool WiFiManager::_FoundAPOnScanCb(wifi_manager_ap_h ap, void * userData) wifi_manager_security_type_e type; WiFiScanResponse scannedAP; - wifiErr = wifi_manager_ap_get_essid(ap, &MakeUniquePointerReceiver(essid).Get()); + wifiErr = wifi_manager_ap_get_essid(ap, &essid.GetReceiver()); VerifyOrExit(wifiErr == WIFI_MANAGER_ERROR_NONE, ChipLogError(DeviceLayer, "FAIL: get AP essid [%s]", get_error_message(wifiErr))); ChipLogProgress(DeviceLayer, "Essid Found: %s\n", essid.get()); scannedAP.ssidLen = static_cast(std::min(strlen(essid.get()), sizeof(scannedAP.ssid))); memcpy(scannedAP.ssid, essid.get(), scannedAP.ssidLen); - wifiErr = wifi_manager_ap_get_bssid(ap, &MakeUniquePointerReceiver(bssid).Get()); + wifiErr = wifi_manager_ap_get_bssid(ap, &bssid.GetReceiver()); VerifyOrExit(wifiErr == WIFI_MANAGER_ERROR_NONE, ChipLogError(DeviceLayer, "Fail: get AP bssid [%s]", get_error_message(wifiErr))); memcpy(scannedAP.bssid, bssid.get(), std::min(strlen(bssid.get()), sizeof(scannedAP.bssid))); @@ -443,7 +443,7 @@ bool WiFiManager::_FoundAPCb(wifi_manager_ap_h ap, void * userData) bool isPassphraseRequired = false; auto clonedAp = reinterpret_cast(userData); - wifiErr = wifi_manager_ap_get_essid(ap, &MakeUniquePointerReceiver(essid).Get()); + wifiErr = wifi_manager_ap_get_essid(ap, &essid.GetReceiver()); VerifyOrExit(wifiErr == WIFI_MANAGER_ERROR_NONE, ChipLogError(DeviceLayer, "FAIL: get AP essid [%s]", get_error_message(wifiErr))); @@ -503,7 +503,7 @@ bool WiFiManager::_ConfigListCb(const wifi_manager_config_h config, void * userD GAutoPtr name; wifi_manager_security_type_e securityType = WIFI_MANAGER_SECURITY_TYPE_NONE; - wifi_manager_config_get_name(config, &MakeUniquePointerReceiver(name).Get()); + wifi_manager_config_get_name(config, &name.GetReceiver()); wifi_manager_config_get_security_type(config, &securityType); wifiErr = wifi_manager_config_remove(sInstance.mWiFiManagerHandle, config); @@ -1155,7 +1155,7 @@ CHIP_ERROR WiFiManager::GetConfiguredNetwork(NetworkCommissioning::Network & net return CHIP_ERROR_INCORRECT_STATE; } GAutoPtr essid; - int wifiErr = wifi_manager_ap_get_essid(connectedAp, &MakeUniquePointerReceiver(essid).Get()); + int wifiErr = wifi_manager_ap_get_essid(connectedAp, &essid.GetReceiver()); VerifyOrReturnError(wifiErr == WIFI_MANAGER_ERROR_NONE, CHIP_ERROR_INTERNAL, ChipLogError(DeviceLayer, "FAIL: get essid [%s]", get_error_message(wifiErr))); network.networkIDLen = static_cast(std::min(strlen(essid.get()), sizeof(network.networkID))); From e8cf8f0c6053ca93bf08b53b8fe194de17ea2831 Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Wed, 21 Feb 2024 11:54:39 -0500 Subject: [PATCH 06/13] Mark ServerEndpoint Darwin objects as Sendable in Swift. (#32088) These are allowed to be accessed concurrently from multiple threads, so are Sendable. --- src/darwin/Framework/CHIP/ServerEndpoint/MTRAccessGrant.h | 1 + src/darwin/Framework/CHIP/ServerEndpoint/MTRDeviceTypeRevision.h | 1 + src/darwin/Framework/CHIP/ServerEndpoint/MTRServerAttribute.h | 1 + src/darwin/Framework/CHIP/ServerEndpoint/MTRServerCluster.h | 1 + src/darwin/Framework/CHIP/ServerEndpoint/MTRServerEndpoint.h | 1 + 5 files changed, 5 insertions(+) diff --git a/src/darwin/Framework/CHIP/ServerEndpoint/MTRAccessGrant.h b/src/darwin/Framework/CHIP/ServerEndpoint/MTRAccessGrant.h index e0b25449755f16..e0dc4bd052f0f4 100644 --- a/src/darwin/Framework/CHIP/ServerEndpoint/MTRAccessGrant.h +++ b/src/darwin/Framework/CHIP/ServerEndpoint/MTRAccessGrant.h @@ -24,6 +24,7 @@ NS_ASSUME_NONNULL_BEGIN * An access grant, which can be represented as an entry in the Matter Access * Control cluster. */ +NS_SWIFT_SENDABLE MTR_NEWLY_AVAILABLE @interface MTRAccessGrant : NSObject diff --git a/src/darwin/Framework/CHIP/ServerEndpoint/MTRDeviceTypeRevision.h b/src/darwin/Framework/CHIP/ServerEndpoint/MTRDeviceTypeRevision.h index 7f4f88b0cfd643..dc95ddcddaeaeb 100644 --- a/src/darwin/Framework/CHIP/ServerEndpoint/MTRDeviceTypeRevision.h +++ b/src/darwin/Framework/CHIP/ServerEndpoint/MTRDeviceTypeRevision.h @@ -23,6 +23,7 @@ NS_ASSUME_NONNULL_BEGIN * A representation of a "device type revision" in the sense used in the Matter * specification. This has an identifier and a version number. */ +NS_SWIFT_SENDABLE MTR_NEWLY_AVAILABLE @interface MTRDeviceTypeRevision : NSObject diff --git a/src/darwin/Framework/CHIP/ServerEndpoint/MTRServerAttribute.h b/src/darwin/Framework/CHIP/ServerEndpoint/MTRServerAttribute.h index 46e95bfb39a7bd..7d8c27b74b55d3 100644 --- a/src/darwin/Framework/CHIP/ServerEndpoint/MTRServerAttribute.h +++ b/src/darwin/Framework/CHIP/ServerEndpoint/MTRServerAttribute.h @@ -25,6 +25,7 @@ NS_ASSUME_NONNULL_BEGIN * MTRDeviceController. An attribute has an identifier and a value, and may or * may not be writable. */ +NS_SWIFT_SENDABLE MTR_NEWLY_AVAILABLE @interface MTRServerAttribute : NSObject diff --git a/src/darwin/Framework/CHIP/ServerEndpoint/MTRServerCluster.h b/src/darwin/Framework/CHIP/ServerEndpoint/MTRServerCluster.h index 48604dd2a76797..02b0f4b274374d 100644 --- a/src/darwin/Framework/CHIP/ServerEndpoint/MTRServerCluster.h +++ b/src/darwin/Framework/CHIP/ServerEndpoint/MTRServerCluster.h @@ -24,6 +24,7 @@ NS_ASSUME_NONNULL_BEGIN /** * A representation of a server cluster implemented by an MTRDeviceController. */ +NS_SWIFT_SENDABLE MTR_NEWLY_AVAILABLE @interface MTRServerCluster : NSObject diff --git a/src/darwin/Framework/CHIP/ServerEndpoint/MTRServerEndpoint.h b/src/darwin/Framework/CHIP/ServerEndpoint/MTRServerEndpoint.h index 13dbe8454d759e..9716692ea8895d 100644 --- a/src/darwin/Framework/CHIP/ServerEndpoint/MTRServerEndpoint.h +++ b/src/darwin/Framework/CHIP/ServerEndpoint/MTRServerEndpoint.h @@ -25,6 +25,7 @@ NS_ASSUME_NONNULL_BEGIN /** * A representation of an endpoint implemented by an MTRDeviceController. */ +NS_SWIFT_SENDABLE MTR_NEWLY_AVAILABLE @interface MTRServerEndpoint : NSObject From 7be1b2e418e0063d8117b0ea31163703c2972105 Mon Sep 17 00:00:00 2001 From: Jean-Francois Penven <67962328+jepenven-silabs@users.noreply.github.com> Date: Wed, 21 Feb 2024 12:01:26 -0500 Subject: [PATCH 07/13] [Silabs] Silabs fix app error (#32238) * fix main * Fix app errorr --- examples/platform/silabs/main.cpp | 10 ++++++---- examples/platform/silabs/silabs_utils.cpp | 2 +- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/examples/platform/silabs/main.cpp b/examples/platform/silabs/main.cpp index 3c9829edd1954f..a3155194e8d1dd 100644 --- a/examples/platform/silabs/main.cpp +++ b/examples/platform/silabs/main.cpp @@ -71,8 +71,9 @@ int main(void) void application_start(void * unused) { - if (SilabsMatterConfig::InitMatter(BLE_DEV_NAME) != CHIP_NO_ERROR) - appError(CHIP_ERROR_INTERNAL); + CHIP_ERROR err = SilabsMatterConfig::InitMatter(BLE_DEV_NAME); + if (err != CHIP_NO_ERROR) + appError(err); gExampleDeviceInfoProvider.SetStorageDelegate(&chip::Server::GetInstance().GetPersistentStorage()); chip::DeviceLayer::SetDeviceInfoProvider(&gExampleDeviceInfoProvider); @@ -83,8 +84,9 @@ void application_start(void * unused) chip::DeviceLayer::PlatformMgr().UnlockChipStack(); SILABS_LOG("Starting App Task"); - if (AppTask::GetAppTask().StartAppTask() != CHIP_NO_ERROR) - appError(CHIP_ERROR_INTERNAL); + err = AppTask::GetAppTask().StartAppTask(); + if (err != CHIP_NO_ERROR) + appError(err); vTaskDelete(main_Task); } diff --git a/examples/platform/silabs/silabs_utils.cpp b/examples/platform/silabs/silabs_utils.cpp index 7231836c15bf7e..c8a068a328955c 100644 --- a/examples/platform/silabs/silabs_utils.cpp +++ b/examples/platform/silabs/silabs_utils.cpp @@ -27,7 +27,7 @@ void appError(int err) snprintf(faultMessage, sizeof faultMessage, "App Critical Error:%d", err); SILABS_LOG("!!!!!!!!!!!! %s !!!!!!!!!!!", faultMessage); chip::DeviceLayer::Silabs::OnSoftwareFaultEventHandler(faultMessage); - vTaskDelay(pdMS_TO_TICKS(1000)); + vTaskSuspendAll(); /* Force an assert. */ chipAbort(); } From 40fc3ea8e9da0a76371bd8bf2050efa69a7efe9e Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Wed, 21 Feb 2024 13:03:41 -0500 Subject: [PATCH 08/13] Improve "need a custom toolchain" message to log more information. (#32239) Logging what gn thinks is going on for the host/target OS and cpu can help diagnose why we didn't find toolchain in the big if cascade. --- build/config/BUILDCONFIG.gn | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/build/config/BUILDCONFIG.gn b/build/config/BUILDCONFIG.gn index 9d2f17d1acf86e..01626726e0b9af 100644 --- a/build/config/BUILDCONFIG.gn +++ b/build/config/BUILDCONFIG.gn @@ -127,7 +127,9 @@ if (_chip_defaults.custom_toolchain != "") { "Unsupported target_cpu: ${current_cpu}. Shall be arm for webOS") } } else { - assert(false, "No toolchain specified, please specify custom_toolchain") + assert( + false, + "No toolchain specified, please specify custom_toolchain for host_os='${host_os}', target_os='${target_os}', host_cpu='${host_cpu}', target_cpu='${target_cpu}'") } set_default_toolchain(_default_toolchain) From f72008cb8a283093245517797fcc21cb0fb3a317 Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Wed, 21 Feb 2024 13:21:36 -0500 Subject: [PATCH 09/13] Correctly annotate things that are unused when logging is disabled. (#32141) We don't seem to have very good CI coverage for the logging-disabled configurations. Also removes UNUSED_VAR and UNUSED_PARAMETER use in favor of the standard [[maybe_unused]]. Fixes https://github.com/project-chip/connectedhomeip/issues/32113 --- .../bridge-app/asr/subdevice/SubDeviceManager.cpp | 7 +++---- examples/bridge-app/esp32/main/main.cpp | 7 +++---- examples/bridge-app/linux/main.cpp | 7 +++---- examples/bridge-app/telink/src/AppTask.cpp | 7 +++---- examples/chip-tool/commands/common/DeviceScanner.cpp | 2 +- .../discover/DiscoverCommissionersCommand.cpp | 2 +- examples/common/websocket-server/WebSocketServer.cpp | 6 +++--- examples/light-switch-app/genio/src/main.cpp | 2 -- examples/lighting-app/genio/src/AppTask.cpp | 2 -- examples/lighting-app/genio/src/main.cpp | 2 -- examples/lock-app/genio/src/AppTask.cpp | 2 -- examples/lock-app/genio/src/main.cpp | 2 -- examples/ota-requestor-app/genio/src/AppTask.cpp | 2 -- examples/ota-requestor-app/genio/src/main.cpp | 2 -- .../silabs/efr32/rs911x/hal/efx32_ncp_host.c | 12 ++++-------- examples/platform/silabs/efr32/rs911x/hal/efx_spi.c | 5 +---- examples/thermostat/genio/src/main.cpp | 2 -- examples/tv-casting-app/linux/CastingUtils.cpp | 4 ++-- .../tv-casting-common/core/CastingPlayer.cpp | 2 +- .../tv-casting-common/src/CastingServer.cpp | 2 +- .../tv-casting-common/src/ZCLCallbacks.cpp | 4 ++-- src/app/app-platform/ContentAppPlatform.cpp | 9 ++++----- src/app/server/DefaultAclStorage.cpp | 2 +- src/app/util/types_stub.h | 6 ------ src/controller/tests/data_model/TestRead.cpp | 2 +- src/crypto/tests/TestChipCryptoPAL.cpp | 2 +- 26 files changed, 35 insertions(+), 69 deletions(-) diff --git a/examples/bridge-app/asr/subdevice/SubDeviceManager.cpp b/examples/bridge-app/asr/subdevice/SubDeviceManager.cpp index ab0f2ef3b707a1..9d4eda96e98438 100644 --- a/examples/bridge-app/asr/subdevice/SubDeviceManager.cpp +++ b/examples/bridge-app/asr/subdevice/SubDeviceManager.cpp @@ -91,12 +91,11 @@ CHIP_ERROR RemoveDeviceEndpoint(SubDevice * dev) { if (gSubDevices[index] == dev) { - EndpointId ep = emberAfClearDynamicEndpoint(index); - gSubDevices[index] = NULL; - ChipLogProgress(DeviceLayer, "Removed device %s from dynamic endpoint %d (index=%d)", dev->GetName(), ep, index); // Silence complaints about unused ep when progress logging // disabled. - UNUSED_VAR(ep); + [[maybe_unused]] EndpointId ep = emberAfClearDynamicEndpoint(index); + gSubDevices[index] = NULL; + ChipLogProgress(DeviceLayer, "Removed device %s from dynamic endpoint %d (index=%d)", dev->GetName(), ep, index); return CHIP_NO_ERROR; } } diff --git a/examples/bridge-app/esp32/main/main.cpp b/examples/bridge-app/esp32/main/main.cpp index 27cdb3c5e2dab5..07db2ba94a534f 100644 --- a/examples/bridge-app/esp32/main/main.cpp +++ b/examples/bridge-app/esp32/main/main.cpp @@ -201,12 +201,11 @@ CHIP_ERROR RemoveDeviceEndpoint(Device * dev) { if (gDevices[index] == dev) { - EndpointId ep = emberAfClearDynamicEndpoint(index); - gDevices[index] = NULL; - ChipLogProgress(DeviceLayer, "Removed device %s from dynamic endpoint %d (index=%d)", dev->GetName(), ep, index); // Silence complaints about unused ep when progress logging // disabled. - UNUSED_VAR(ep); + [[maybe_unused]] EndpointId ep = emberAfClearDynamicEndpoint(index); + gDevices[index] = NULL; + ChipLogProgress(DeviceLayer, "Removed device %s from dynamic endpoint %d (index=%d)", dev->GetName(), ep, index); return CHIP_NO_ERROR; } } diff --git a/examples/bridge-app/linux/main.cpp b/examples/bridge-app/linux/main.cpp index 80c8b17b7fbed5..c569e7c06e8b45 100644 --- a/examples/bridge-app/linux/main.cpp +++ b/examples/bridge-app/linux/main.cpp @@ -300,12 +300,11 @@ int RemoveDeviceEndpoint(Device * dev) { // Todo: Update this to schedule the work rather than use this lock DeviceLayer::StackLock lock; - EndpointId ep = emberAfClearDynamicEndpoint(index); - gDevices[index] = nullptr; - ChipLogProgress(DeviceLayer, "Removed device %s from dynamic endpoint %d (index=%d)", dev->GetName(), ep, index); // Silence complaints about unused ep when progress logging // disabled. - UNUSED_VAR(ep); + [[maybe_unused]] EndpointId ep = emberAfClearDynamicEndpoint(index); + gDevices[index] = nullptr; + ChipLogProgress(DeviceLayer, "Removed device %s from dynamic endpoint %d (index=%d)", dev->GetName(), ep, index); return index; } index++; diff --git a/examples/bridge-app/telink/src/AppTask.cpp b/examples/bridge-app/telink/src/AppTask.cpp index d21897bd2d36b6..72a997c91e9511 100644 --- a/examples/bridge-app/telink/src/AppTask.cpp +++ b/examples/bridge-app/telink/src/AppTask.cpp @@ -224,12 +224,11 @@ CHIP_ERROR RemoveDeviceEndpoint(Device * dev) { if (gDevices[index] == dev) { - EndpointId ep = emberAfClearDynamicEndpoint(index); - gDevices[index] = NULL; - ChipLogProgress(DeviceLayer, "Removed device %s from dynamic endpoint %d (index=%d)", dev->GetName(), ep, index); // Silence complaints about unused ep when progress logging // disabled. - UNUSED_VAR(ep); + [[maybe_unused]] EndpointId ep = emberAfClearDynamicEndpoint(index); + gDevices[index] = NULL; + ChipLogProgress(DeviceLayer, "Removed device %s from dynamic endpoint %d (index=%d)", dev->GetName(), ep, index); return CHIP_NO_ERROR; } } diff --git a/examples/chip-tool/commands/common/DeviceScanner.cpp b/examples/chip-tool/commands/common/DeviceScanner.cpp index 29d31c1fc80565..35d74bd06c844f 100644 --- a/examples/chip-tool/commands/common/DeviceScanner.cpp +++ b/examples/chip-tool/commands/common/DeviceScanner.cpp @@ -218,7 +218,7 @@ void DeviceScanner::Log() const auto resultsCount = mDiscoveredResults.size(); VerifyOrReturn(resultsCount > 0, ChipLogProgress(chipTool, "No device discovered.")); - uint16_t index = 0; + [[maybe_unused]] uint16_t index = 0; for (auto & instance : mDiscoveredResults) { ChipLogProgress(chipTool, "Instance Name: %s ", instance.first.c_str()); diff --git a/examples/chip-tool/commands/discover/DiscoverCommissionersCommand.cpp b/examples/chip-tool/commands/discover/DiscoverCommissionersCommand.cpp index 0d1c9a032de02c..57c7574c4ea2e3 100644 --- a/examples/chip-tool/commands/discover/DiscoverCommissionersCommand.cpp +++ b/examples/chip-tool/commands/discover/DiscoverCommissionersCommand.cpp @@ -29,7 +29,7 @@ CHIP_ERROR DiscoverCommissionersCommand::RunCommand() void DiscoverCommissionersCommand::Shutdown() { - int commissionerCount = 0; + [[maybe_unused]] int commissionerCount = 0; for (int i = 0; i < CHIP_DEVICE_CONFIG_MAX_DISCOVERED_NODES; i++) { const Dnssd::DiscoveredNodeData * commissioner = mCommissionableNodeController.GetDiscoveredCommissioner(i); diff --git a/examples/common/websocket-server/WebSocketServer.cpp b/examples/common/websocket-server/WebSocketServer.cpp index 623dda3dc47527..2dba035601ea0e 100644 --- a/examples/common/websocket-server/WebSocketServer.cpp +++ b/examples/common/websocket-server/WebSocketServer.cpp @@ -24,9 +24,9 @@ #include #include -constexpr uint16_t kDefaultWebSocketServerPort = 9002; -constexpr uint16_t kMaxMessageBufferLen = 8192; -constexpr char kWebSocketServerReadyMessage[] = "== WebSocket Server Ready"; +constexpr uint16_t kDefaultWebSocketServerPort = 9002; +constexpr uint16_t kMaxMessageBufferLen = 8192; +[[maybe_unused]] constexpr char kWebSocketServerReadyMessage[] = "== WebSocket Server Ready"; namespace { lws * gWebSocketInstance = nullptr; diff --git a/examples/light-switch-app/genio/src/main.cpp b/examples/light-switch-app/genio/src/main.cpp index 93bb82a21b0735..d545409c706913 100644 --- a/examples/light-switch-app/genio/src/main.cpp +++ b/examples/light-switch-app/genio/src/main.cpp @@ -51,8 +51,6 @@ using namespace ::chip; using namespace ::chip::Inet; using namespace ::chip::DeviceLayer; -#define UNUSED_PARAMETER(a) (a = a) - volatile int apperror_cnt; /*************************************************************************** diff --git a/examples/lighting-app/genio/src/AppTask.cpp b/examples/lighting-app/genio/src/AppTask.cpp index 6a121673a002a6..d948087833c4dd 100644 --- a/examples/lighting-app/genio/src/AppTask.cpp +++ b/examples/lighting-app/genio/src/AppTask.cpp @@ -66,8 +66,6 @@ #error "Must have portYIELD_FROM_ISR or portEND_SWITCHING_ISR" #endif -#define UNUSED_PARAMETER(a) (a = a) - #if defined(ENABLE_CHIP_SHELL) using chip::Shell::Engine; using chip::Shell::PrintCommandHelp; diff --git a/examples/lighting-app/genio/src/main.cpp b/examples/lighting-app/genio/src/main.cpp index ab578f3f2c75bd..22f654eb5f2f50 100644 --- a/examples/lighting-app/genio/src/main.cpp +++ b/examples/lighting-app/genio/src/main.cpp @@ -51,8 +51,6 @@ using namespace ::chip; using namespace ::chip::Inet; using namespace ::chip::DeviceLayer; -#define UNUSED_PARAMETER(a) (a = a) - volatile int apperror_cnt; /*************************************************************************** diff --git a/examples/lock-app/genio/src/AppTask.cpp b/examples/lock-app/genio/src/AppTask.cpp index 7a438dd4974d3d..1c2f0719790196 100644 --- a/examples/lock-app/genio/src/AppTask.cpp +++ b/examples/lock-app/genio/src/AppTask.cpp @@ -60,8 +60,6 @@ #error "Must have portYIELD_FROM_ISR or portEND_SWITCHING_ISR" #endif -#define UNUSED_PARAMETER(a) (a = a) - namespace { TimerHandle_t sFunctionTimer; // FreeRTOS app sw timer. diff --git a/examples/lock-app/genio/src/main.cpp b/examples/lock-app/genio/src/main.cpp index 416c81c53436d7..92b16a39663ee4 100644 --- a/examples/lock-app/genio/src/main.cpp +++ b/examples/lock-app/genio/src/main.cpp @@ -51,8 +51,6 @@ using namespace ::chip; using namespace ::chip::Inet; using namespace ::chip::DeviceLayer; -#define UNUSED_PARAMETER(a) (a = a) - volatile int apperror_cnt; /*************************************************************************** diff --git a/examples/ota-requestor-app/genio/src/AppTask.cpp b/examples/ota-requestor-app/genio/src/AppTask.cpp index 43c92cf26adeeb..50d1d080a5b7b4 100644 --- a/examples/ota-requestor-app/genio/src/AppTask.cpp +++ b/examples/ota-requestor-app/genio/src/AppTask.cpp @@ -53,8 +53,6 @@ #error "Must have portYIELD_FROM_ISR or portEND_SWITCHING_ISR" #endif -#define UNUSED_PARAMETER(a) (a = a) - namespace { TaskHandle_t sAppTaskHandle; diff --git a/examples/ota-requestor-app/genio/src/main.cpp b/examples/ota-requestor-app/genio/src/main.cpp index dcd85fbb920859..e3676c5c9eacbd 100644 --- a/examples/ota-requestor-app/genio/src/main.cpp +++ b/examples/ota-requestor-app/genio/src/main.cpp @@ -53,8 +53,6 @@ using namespace ::chip; using namespace ::chip::Inet; using namespace ::chip::DeviceLayer; -#define UNUSED_PARAMETER(a) (a = a) - volatile int apperror_cnt; static void OTAEventsHandler(const DeviceLayer::ChipDeviceEvent * event, intptr_t arg) diff --git a/examples/platform/silabs/efr32/rs911x/hal/efx32_ncp_host.c b/examples/platform/silabs/efr32/rs911x/hal/efx32_ncp_host.c index 82976deb6a3b09..9f07d3f8f22c16 100644 --- a/examples/platform/silabs/efr32/rs911x/hal/efx32_ncp_host.c +++ b/examples/platform/silabs/efr32/rs911x/hal/efx32_ncp_host.c @@ -57,11 +57,9 @@ LDMA_TransferCfg_t ldmaRXConfig; static osSemaphoreId_t transfer_done_semaphore = NULL; -static bool dma_callback(unsigned int channel, unsigned int sequenceNo, void * userParam) +static bool dma_callback([[maybe_unused]] unsigned int channel, [[maybe_unused]] unsigned int sequenceNo, + [[maybe_unused]] void * userParam) { - UNUSED_PARAMETER(channel); - UNUSED_PARAMETER(sequenceNo); - UNUSED_PARAMETER(userParam); #if defined(SL_CATLOG_POWER_MANAGER_PRESENT) sl_power_manager_remove_em_requirement(SL_POWER_MANAGER_EM1); #endif @@ -69,10 +67,8 @@ static bool dma_callback(unsigned int channel, unsigned int sequenceNo, void * u return false; } -static void gpio_interrupt(uint8_t interrupt_number) +static void gpio_interrupt([[maybe_unused]] uint8_t interrupt_number) { - UNUSED_PARAMETER(interrupt_number); - if (NULL != init_config.rx_irq) { init_config.rx_irq(); @@ -312,4 +308,4 @@ void sl_si91x_host_disable_bus_interrupt(void) bool sl_si91x_host_is_in_irq_context(void) { return (SCB->ICSR & SCB_ICSR_VECTACTIVE_Msk) != 0U; -} \ No newline at end of file +} diff --git a/examples/platform/silabs/efr32/rs911x/hal/efx_spi.c b/examples/platform/silabs/efr32/rs911x/hal/efx_spi.c index ad6b5ed5e3418d..9097177b73a585 100644 --- a/examples/platform/silabs/efr32/rs911x/hal/efx_spi.c +++ b/examples/platform/silabs/efr32/rs911x/hal/efx_spi.c @@ -171,10 +171,7 @@ void sl_wfx_host_reset_chip(void) vTaskDelay(pdMS_TO_TICKS(3)); } -void gpio_interrupt(uint8_t interrupt_number) -{ - UNUSED_PARAMETER(interrupt_number); -} +void gpio_interrupt([[maybe_unused]] uint8_t interrupt_number) {} /***************************************************************** * @fn void rsi_hal_board_init(void) diff --git a/examples/thermostat/genio/src/main.cpp b/examples/thermostat/genio/src/main.cpp index 93bb82a21b0735..d545409c706913 100644 --- a/examples/thermostat/genio/src/main.cpp +++ b/examples/thermostat/genio/src/main.cpp @@ -51,8 +51,6 @@ using namespace ::chip; using namespace ::chip::Inet; using namespace ::chip::DeviceLayer; -#define UNUSED_PARAMETER(a) (a = a) - volatile int apperror_cnt; /*************************************************************************** diff --git a/examples/tv-casting-app/linux/CastingUtils.cpp b/examples/tv-casting-app/linux/CastingUtils.cpp index 02b9467d884614..d4d71b5dd2c0ae 100644 --- a/examples/tv-casting-app/linux/CastingUtils.cpp +++ b/examples/tv-casting-app/linux/CastingUtils.cpp @@ -105,7 +105,7 @@ void InitCommissioningFlow(intptr_t commandArg) commissioner->LogDetail(); if (associatedConnectableVideoPlayer.HasValue()) { - TargetVideoPlayerInfo * targetVideoPlayerInfo = associatedConnectableVideoPlayer.Value(); + [[maybe_unused]] TargetVideoPlayerInfo * targetVideoPlayerInfo = associatedConnectableVideoPlayer.Value(); ChipLogProgress(AppServer, "Previously connected with nodeId 0x" ChipLogFormatX64 " fabricIndex: %d", ChipLogValueX64(targetVideoPlayerInfo->GetNodeId()), targetVideoPlayerInfo->GetFabricIndex()); } @@ -305,7 +305,7 @@ void PrintFabrics() ChipLogError(AppServer, " -- Not initialized"); continue; } - NodeId myNodeId = fb.GetNodeId(); + [[maybe_unused]] NodeId myNodeId = fb.GetNodeId(); ChipLogProgress(NotSpecified, "---- Current Fabric nodeId=0x" ChipLogFormatX64 " fabricId=0x" ChipLogFormatX64 " fabricIndex=%d", ChipLogValueX64(myNodeId), ChipLogValueX64(fb.GetFabricId()), fabricIndex); diff --git a/examples/tv-casting-app/tv-casting-common/core/CastingPlayer.cpp b/examples/tv-casting-app/tv-casting-common/core/CastingPlayer.cpp index 41d9feb52977eb..f34b6b2ef16c34 100644 --- a/examples/tv-casting-app/tv-casting-common/core/CastingPlayer.cpp +++ b/examples/tv-casting-app/tv-casting-common/core/CastingPlayer.cpp @@ -257,7 +257,7 @@ void CastingPlayer::LogDetail() const { for (unsigned j = 0; j < mAttributes.numIPs; j++) { - char * ipAddressOut = mAttributes.ipAddresses[j].ToString(buf); + [[maybe_unused]] char * ipAddressOut = mAttributes.ipAddresses[j].ToString(buf); ChipLogDetail(AppServer, "\tIP Address #%d: %s", j + 1, ipAddressOut); } } diff --git a/examples/tv-casting-app/tv-casting-common/src/CastingServer.cpp b/examples/tv-casting-app/tv-casting-common/src/CastingServer.cpp index 98f6b197a59e33..a3de0a263c3efe 100644 --- a/examples/tv-casting-app/tv-casting-common/src/CastingServer.cpp +++ b/examples/tv-casting-app/tv-casting-common/src/CastingServer.cpp @@ -695,7 +695,7 @@ void CastingServer::SetDefaultFabricIndex(std::functionGetEndpointId(); - EndpointId ep = emberAfClearDynamicEndpoint(index); - mContentApps[index] = nullptr; - ChipLogProgress(DeviceLayer, "Removed device %d from dynamic endpoint %d (index=%d)", - app->GetApplicationBasicDelegate()->HandleGetVendorId(), ep, index); // Silence complaints about unused ep when progress logging // disabled. - UNUSED_VAR(ep); + /*[[maybe_unused]]*/ EndpointId ep = emberAfClearDynamicEndpoint(index); + mContentApps[index] = nullptr; + ChipLogProgress(DeviceLayer, "Removed device %d from dynamic endpoint %d (index=%d)", + app->GetApplicationBasicDelegate()->HandleGetVendorId(), ep, index); if (curEndpoint == mCurrentAppEndpointId) { mCurrentAppEndpointId = kNoCurrentEndpointId; diff --git a/src/app/server/DefaultAclStorage.cpp b/src/app/server/DefaultAclStorage.cpp index 58d0d18feedda6..6f40cce2599893 100644 --- a/src/app/server/DefaultAclStorage.cpp +++ b/src/app/server/DefaultAclStorage.cpp @@ -138,7 +138,7 @@ CHIP_ERROR DefaultAclStorage::Init(PersistentStorageDelegate & persistentStorage CHIP_ERROR err; - size_t count = 0; + [[maybe_unused]] size_t count = 0; for (auto it = first; it != last; ++it) { diff --git a/src/app/util/types_stub.h b/src/app/util/types_stub.h index ac26684f850cd7..dbd1ea184169e1 100644 --- a/src/app/util/types_stub.h +++ b/src/app/util/types_stub.h @@ -166,12 +166,6 @@ typedef struct } EmberEventControl; -/** - * @description Useful macro for avoiding compiler warnings related to unused - * function arguments or unused variables. - */ -#define UNUSED_VAR(x) (void) (x) - /** * @brief Returns the value of the bitmask \c bits within * the register or byte \c reg. diff --git a/src/controller/tests/data_model/TestRead.cpp b/src/controller/tests/data_model/TestRead.cpp index 917c3a1251e344..fc2cfaf516524b 100644 --- a/src/controller/tests/data_model/TestRead.cpp +++ b/src/controller/tests/data_model/TestRead.cpp @@ -475,7 +475,7 @@ void TestReadInteraction::TestReadSubscribeAttributeResponseWithCache(nlTestSuit // app::InteractionModelEngine::GetInstance()->RegisterReadHandlerAppCallback(&gTestReadInteraction); - int testId = 0; + [[maybe_unused]] int testId = 0; // Read of E2C3A1(dedup), E*C3A1(E1C3A1 not exit, E2C3A1 exist), E2C3A* (5 supported attributes) // Expect no versions would be cached. diff --git a/src/crypto/tests/TestChipCryptoPAL.cpp b/src/crypto/tests/TestChipCryptoPAL.cpp index b2e12568b7c222..db5ee6b74480cd 100644 --- a/src/crypto/tests/TestChipCryptoPAL.cpp +++ b/src/crypto/tests/TestChipCryptoPAL.cpp @@ -2715,7 +2715,7 @@ static void TestVIDPID_StringExtraction(nlTestSuite * inSuite, void * inContext) }; // clang-format on - int caseIdx = 0; + [[maybe_unused]] int caseIdx = 0; for (const auto & testCase : kTestCases) { AttestationCertVidPid vidpid; From 9aeff06a884f352de973192575a44524a7da6290 Mon Sep 17 00:00:00 2001 From: arun-silabs <141724790+arun-silabs@users.noreply.github.com> Date: Thu, 22 Feb 2024 00:15:42 +0530 Subject: [PATCH 10/13] [Silabs] [WiFi] Modified logs in which AP's password is printed. (#32166) * Modified logs in which AP's password is printed. * Restyled by clang-format --------- Co-authored-by: Restyled.io --- examples/platform/silabs/SiWx917/SiWx917/sl_wifi_if.c | 3 +-- examples/platform/silabs/SiWx917/SiWx917/wfx_rsi_host.c | 2 +- examples/platform/silabs/efr32/rs911x/rsi_if.c | 6 ++---- examples/platform/silabs/efr32/rs911x/wfx_rsi_host.c | 2 +- 4 files changed, 5 insertions(+), 8 deletions(-) diff --git a/examples/platform/silabs/SiWx917/SiWx917/sl_wifi_if.c b/examples/platform/silabs/SiWx917/SiWx917/sl_wifi_if.c index f78539d9817170..6dcfcfaf46aaac 100644 --- a/examples/platform/silabs/SiWx917/SiWx917/sl_wifi_if.c +++ b/examples/platform/silabs/SiWx917/SiWx917/sl_wifi_if.c @@ -569,8 +569,7 @@ static sl_status_t wfx_rsi_do_join(void) } else { - SILABS_LOG("%s: WLAN: connecting to %s==%s, sec=%d", __func__, &wfx_rsi.sec.ssid[0], &wfx_rsi.sec.passkey[0], - wfx_rsi.sec.security); + SILABS_LOG("%s: WLAN: connecting to %s, sec=%d", __func__, &wfx_rsi.sec.ssid[0], wfx_rsi.sec.security); /* * Join the network diff --git a/examples/platform/silabs/SiWx917/SiWx917/wfx_rsi_host.c b/examples/platform/silabs/SiWx917/SiWx917/wfx_rsi_host.c index 8f1f895f9683f9..0c7efc723eb049 100644 --- a/examples/platform/silabs/SiWx917/SiWx917/wfx_rsi_host.c +++ b/examples/platform/silabs/SiWx917/SiWx917/wfx_rsi_host.c @@ -178,7 +178,7 @@ sl_status_t wfx_connect_to_ap(void) { if (wfx_rsi.dev_state & WFX_RSI_ST_STA_PROVISIONED) { - SILABS_LOG("%s: connecting to access point -> SSID: %s, PSK:%s", __func__, &wfx_rsi.sec.ssid[0], &wfx_rsi.sec.passkey[0]); + SILABS_LOG("%s: connecting to access point -> SSID: %s", __func__, &wfx_rsi.sec.ssid[0]); xEventGroupSetBits(wfx_rsi.events, WFX_EVT_STA_START_JOIN); } else diff --git a/examples/platform/silabs/efr32/rs911x/rsi_if.c b/examples/platform/silabs/efr32/rs911x/rsi_if.c index c43389761dcdfc..1ba06d0e715c16 100644 --- a/examples/platform/silabs/efr32/rs911x/rsi_if.c +++ b/examples/platform/silabs/efr32/rs911x/rsi_if.c @@ -466,8 +466,7 @@ static void wfx_rsi_save_ap_info() // translation break; } - SILABS_LOG("%s: WLAN: connecting to %s==%s, sec=%d, status=%02x", __func__, &wfx_rsi.sec.ssid[0], &wfx_rsi.sec.passkey[0], - wfx_rsi.sec.security, status); + SILABS_LOG("%s: WLAN: connecting to %s, sec=%d, status=%02x", __func__, &wfx_rsi.sec.ssid[0], wfx_rsi.sec.security, status); } /******************************************************************************************** @@ -511,8 +510,7 @@ static void wfx_rsi_do_join(void) return; } - SILABS_LOG("%s: WLAN: connecting to %s==%s, sec=%d", __func__, &wfx_rsi.sec.ssid[0], &wfx_rsi.sec.passkey[0], - wfx_rsi.sec.security); + SILABS_LOG("%s: WLAN: connecting to %s, sec=%d", __func__, &wfx_rsi.sec.ssid[0], wfx_rsi.sec.security); /* * Join the network diff --git a/examples/platform/silabs/efr32/rs911x/wfx_rsi_host.c b/examples/platform/silabs/efr32/rs911x/wfx_rsi_host.c index 331895bd3e524e..15915851c11a20 100644 --- a/examples/platform/silabs/efr32/rs911x/wfx_rsi_host.c +++ b/examples/platform/silabs/efr32/rs911x/wfx_rsi_host.c @@ -180,7 +180,7 @@ sl_status_t wfx_connect_to_ap(void) { if (wfx_rsi.dev_state & WFX_RSI_ST_STA_PROVISIONED) { - SILABS_LOG("%s: connecting to access point -> SSID: %s, PSK:%s", __func__, &wfx_rsi.sec.ssid[0], &wfx_rsi.sec.passkey[0]); + SILABS_LOG("%s: connecting to access point -> SSID: %s", __func__, &wfx_rsi.sec.ssid[0]); xEventGroupSetBits(wfx_rsi.events, WFX_EVT_STA_START_JOIN); } else From 4158d55db3f936b58cc944d10fd538a8585144f3 Mon Sep 17 00:00:00 2001 From: joonhaengHeo <85541460+joonhaengHeo@users.noreply.github.com> Date: Thu, 22 Feb 2024 08:52:08 +0900 Subject: [PATCH 11/13] Add excetpion try-catch in getConnectedPointer (#32237) --- .../clusterclient/BasicClientFragment.kt | 16 ++++- .../clusterclient/GroupSettingFragment.kt | 72 ++++++++++++------- .../clusterclient/MultiAdminClientFragment.kt | 44 +++++++++--- .../clusterclient/OnOffClientFragment.kt | 48 ++++++++++--- .../clusterclient/OpCredClientFragment.kt | 16 ++++- .../OtaProviderClientFragment.kt | 56 ++++++++++++--- .../clusterclient/SensorClientFragment.kt | 16 ++++- .../clusterclient/WildcardFragment.kt | 46 ++++++++++-- .../ClusterDetailFragment.kt | 10 ++- .../ClusterInteractionFragment.kt | 9 ++- 10 files changed, 269 insertions(+), 64 deletions(-) diff --git a/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/clusterclient/BasicClientFragment.kt b/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/clusterclient/BasicClientFragment.kt index f38cacbd259073..3ef61298930268 100644 --- a/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/clusterclient/BasicClientFragment.kt +++ b/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/clusterclient/BasicClientFragment.kt @@ -139,7 +139,13 @@ class BasicClientFragment : Fragment() { val attributeId = BasicInformation.Attribute.valueOf(attributeName).id val devicePtr = - ChipClient.getConnectedDevicePointer(requireContext(), addressUpdateFragment.deviceId) + try { + ChipClient.getConnectedDevicePointer(requireContext(), addressUpdateFragment.deviceId) + } catch (e: IllegalStateException) { + Log.d(TAG, "getConnectedDevicePointer exception", e) + showMessage("Get DevicePointer fail!") + return + } ChipClient.getDeviceController(requireContext()) .readPath( @@ -182,7 +188,13 @@ class BasicClientFragment : Fragment() { private suspend fun sendWriteAttribute(attribute: BasicInformation.Attribute, tlv: ByteArray) { val clusterId = BasicInformation.ID val devicePtr = - ChipClient.getConnectedDevicePointer(requireContext(), addressUpdateFragment.deviceId) + try { + ChipClient.getConnectedDevicePointer(requireContext(), addressUpdateFragment.deviceId) + } catch (e: IllegalStateException) { + Log.d(TAG, "getConnectedDevicePointer exception", e) + showMessage("Get DevicePointer fail!") + return + } ChipClient.getDeviceController(requireContext()) .write( diff --git a/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/clusterclient/GroupSettingFragment.kt b/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/clusterclient/GroupSettingFragment.kt index 8943801c080c80..bbaacbd3c997ba 100644 --- a/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/clusterclient/GroupSettingFragment.kt +++ b/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/clusterclient/GroupSettingFragment.kt @@ -271,11 +271,16 @@ class GroupSettingFragment : Fragment() { private suspend fun sendKeySetWrite( groupKeySetStruct: GroupKeyManagementClusterGroupKeySetStruct ) { - val cluster = - ChipClusters.GroupKeyManagementCluster( - ChipClient.getConnectedDevicePointer(requireContext(), addressUpdateFragment.deviceId), - 0 - ) + val devicePtr = + try { + ChipClient.getConnectedDevicePointer(requireContext(), addressUpdateFragment.deviceId) + } catch (e: IllegalStateException) { + Log.d(TAG, "getConnectedDevicePointer exception", e) + showMessage("Get DevicePointer fail!") + return + } + val cluster = ChipClusters.GroupKeyManagementCluster(devicePtr, 0) + cluster.keySetWrite( object : ChipClusters.DefaultClusterCallback { override fun onError(e: Exception?) { @@ -311,11 +316,15 @@ class GroupSettingFragment : Fragment() { } private suspend fun writeGroupKeyMap(groupId: UInt, groupKeySetId: UInt) { - val cluster = - ChipClusters.GroupKeyManagementCluster( - ChipClient.getConnectedDevicePointer(requireContext(), addressUpdateFragment.deviceId), - 0 - ) + val devicePtr = + try { + ChipClient.getConnectedDevicePointer(requireContext(), addressUpdateFragment.deviceId) + } catch (e: IllegalStateException) { + Log.d(TAG, "getConnectedDevicePointer exception", e) + showMessage("Get DevicePointer fail!") + return + } + val cluster = ChipClusters.GroupKeyManagementCluster(devicePtr, 0) cluster.writeGroupKeyMapAttribute( object : ChipClusters.DefaultClusterCallback { override fun onError(e: Exception?) { @@ -356,11 +365,16 @@ class GroupSettingFragment : Fragment() { } private suspend fun sendAddGroup(groupId: UInt, groupName: String) { - val cluster = - ChipClusters.GroupsCluster( - ChipClient.getConnectedDevicePointer(requireContext(), addressUpdateFragment.deviceId), - 0 - ) + val devicePtr = + try { + ChipClient.getConnectedDevicePointer(requireContext(), addressUpdateFragment.deviceId) + } catch (e: IllegalStateException) { + Log.d(TAG, "getConnectedDevicePointer exception", e) + showMessage("Get DevicePointer fail!") + return + } + val cluster = ChipClusters.GroupsCluster(devicePtr, 0) + cluster.addGroup( object : ChipClusters.GroupsCluster.AddGroupResponseCallback { override fun onError(e: Exception?) { @@ -379,11 +393,15 @@ class GroupSettingFragment : Fragment() { } private suspend fun readAccessControl() { - val cluster = - ChipClusters.AccessControlCluster( - ChipClient.getConnectedDevicePointer(requireContext(), addressUpdateFragment.deviceId), - 0 - ) + val devicePtr = + try { + ChipClient.getConnectedDevicePointer(requireContext(), addressUpdateFragment.deviceId) + } catch (e: IllegalStateException) { + Log.d(TAG, "getConnectedDevicePointer exception", e) + showMessage("Get DevicePointer fail!") + return + } + val cluster = ChipClusters.AccessControlCluster(devicePtr, 0) cluster.readAclAttribute( object : ChipClusters.AccessControlCluster.AclAttributeCallback { override fun onError(e: Exception?) { @@ -437,12 +455,16 @@ class GroupSettingFragment : Fragment() { groupId: UInt, privilege: UInt ) { + val devicePtr = + try { + ChipClient.getConnectedDevicePointer(requireContext(), addressUpdateFragment.deviceId) + } catch (e: IllegalStateException) { + Log.d(TAG, "getConnectedDevicePointer exception", e) + showMessage("Get DevicePointer fail!") + return + } // If GroupID is already added to AccessControl, do not add it. - val cluster = - ChipClusters.AccessControlCluster( - ChipClient.getConnectedDevicePointer(requireContext(), addressUpdateFragment.deviceId), - 0 - ) + val cluster = ChipClusters.AccessControlCluster(devicePtr, 0) val sendEntry = ArrayList() for (entry in value) { if ( diff --git a/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/clusterclient/MultiAdminClientFragment.kt b/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/clusterclient/MultiAdminClientFragment.kt index a82f0ee60ccf35..08443d6ffb4ffc 100644 --- a/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/clusterclient/MultiAdminClientFragment.kt +++ b/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/clusterclient/MultiAdminClientFragment.kt @@ -121,8 +121,16 @@ class MultiAdminClientFragment : Fragment() { private suspend fun sendBasicCommissioningCommandClick() { val testDuration = binding.timeoutEd.text.toString().toInt() + val devicePtr = + try { + ChipClient.getConnectedDevicePointer(requireContext(), addressUpdateFragment.deviceId) + } catch (e: IllegalStateException) { + Log.d(TAG, "getConnectedDevicePointer exception", e) + showMessage("Get DevicePointer fail!") + return + } deviceController.openPairingWindowCallback( - ChipClient.getConnectedDevicePointer(requireContext(), addressUpdateFragment.deviceId), + devicePtr, testDuration, object : OpenCommissioningCallback { override fun onError(status: Int, deviceId: Long) { @@ -140,7 +148,13 @@ class MultiAdminClientFragment : Fragment() { val testDuration = binding.timeoutEd.text.toString().toInt() val testIteration = 1000 val devicePointer = - ChipClient.getConnectedDevicePointer(requireContext(), addressUpdateFragment.deviceId) + try { + ChipClient.getConnectedDevicePointer(requireContext(), addressUpdateFragment.deviceId) + } catch (e: IllegalStateException) { + Log.d(TAG, "getConnectedDevicePointer exception", e) + showMessage("Get DevicePointer fail!") + return + } var setupPinCode: Long? = null if (!binding.setupPinCodeEd.text.toString().isEmpty()) { @@ -181,6 +195,14 @@ class MultiAdminClientFragment : Fragment() { null ) + val devicePointer = + try { + ChipClient.getConnectedDevicePointer(requireContext(), addressUpdateFragment.deviceId) + } catch (e: IllegalStateException) { + Log.d(TAG, "getConnectedDevicePointer exception", e) + showMessage("Get DevicePointer fail!") + return + } deviceController.invoke( object : InvokeCallback { override fun onError(ex: Exception?) { @@ -193,7 +215,7 @@ class MultiAdminClientFragment : Fragment() { showMessage("Revoke Commissioning success") } }, - getConnectedDevicePointer(), + devicePointer, invokeElement, timedInvokeTimeout, 0 @@ -208,6 +230,16 @@ class MultiAdminClientFragment : Fragment() { val attributeId = attribute.id val attributeName = attribute.name val attributePath = ChipAttributePath.newInstance(endpointId, clusterId, attributeId) + + val devicePointer = + try { + ChipClient.getConnectedDevicePointer(requireContext(), addressUpdateFragment.deviceId) + } catch (e: IllegalStateException) { + Log.d(TAG, "getConnectedDevicePointer exception", e) + showMessage("Get DevicePointer fail!") + return + } + deviceController.readAttributePath( object : ReportCallback { override fun onReport(nodeState: NodeState?) { @@ -230,16 +262,12 @@ class MultiAdminClientFragment : Fragment() { showMessage("read $attributeName - error : ${e?.message}") } }, - getConnectedDevicePointer(), + devicePointer, listOf(attributePath), 0 ) } - private suspend fun getConnectedDevicePointer(): Long { - return ChipClient.getConnectedDevicePointer(requireContext(), addressUpdateFragment.deviceId) - } - private fun showMessage(msg: String) { requireActivity().runOnUiThread { binding.multiAdminClusterCommandStatus.text = msg } } diff --git a/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/clusterclient/OnOffClientFragment.kt b/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/clusterclient/OnOffClientFragment.kt index 7994deb2f07a13..d4b55194147fca 100644 --- a/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/clusterclient/OnOffClientFragment.kt +++ b/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/clusterclient/OnOffClientFragment.kt @@ -105,6 +105,15 @@ class OnOffClientFragment : Fragment() { val attributePath = ChipAttributePath.newInstance(endpointId, clusterId, attributeId) + val devicePointer = + try { + ChipClient.getConnectedDevicePointer(requireContext(), addressUpdateFragment.deviceId) + } catch (e: IllegalStateException) { + Log.d(TAG, "getConnectedDevicePointer exception", e) + showMessage("Get DevicePointer fail!") + return + } + ChipClient.getDeviceController(requireContext()) .readPath( object : ReportCallback { @@ -128,7 +137,7 @@ class OnOffClientFragment : Fragment() { showMessage("On/Off attribute value: $value") } }, - getConnectedDevicePointer(), + devicePointer, listOf(attributePath), null, false, @@ -181,6 +190,15 @@ class OnOffClientFragment : Fragment() { ) } + val devicePointer = + try { + ChipClient.getConnectedDevicePointer(requireContext(), addressUpdateFragment.deviceId) + } catch (e: IllegalStateException) { + Log.d(TAG, "getConnectedDevicePointer exception", e) + showMessage("Get DevicePointer fail!") + return + } + deviceController.subscribeToPath( subscriptionEstablishedCallback, resubscriptionAttemptCallback, @@ -211,7 +229,7 @@ class OnOffClientFragment : Fragment() { showReportMessage(message) } }, - getConnectedDevicePointer(), + devicePointer, listOf(attributePath), null, minInterval, @@ -265,6 +283,15 @@ class OnOffClientFragment : Fragment() { null ) + val devicePointer = + try { + ChipClient.getConnectedDevicePointer(requireContext(), addressUpdateFragment.deviceId) + } catch (e: IllegalStateException) { + Log.d(TAG, "getConnectedDevicePointer exception", e) + showMessage("Get DevicePointer fail!") + return + } + deviceController.invoke( object : InvokeCallback { override fun onError(ex: Exception?) { @@ -277,7 +304,7 @@ class OnOffClientFragment : Fragment() { showMessage("MoveToLevel command success") } }, - getConnectedDevicePointer(), + devicePointer, invokeElement, 0, 0 @@ -298,6 +325,15 @@ class OnOffClientFragment : Fragment() { null ) + val devicePointer = + try { + ChipClient.getConnectedDevicePointer(requireContext(), addressUpdateFragment.deviceId) + } catch (e: IllegalStateException) { + Log.d(TAG, "getConnectedDevicePointer exception", e) + showMessage("Get DevicePointer fail!") + return + } + deviceController.invoke( object : InvokeCallback { override fun onError(ex: Exception?) { @@ -310,17 +346,13 @@ class OnOffClientFragment : Fragment() { showMessage("${commandId.name} command success") } }, - getConnectedDevicePointer(), + devicePointer, invokeElement, 0, 0 ) } - private suspend fun getConnectedDevicePointer(): Long { - return ChipClient.getConnectedDevicePointer(requireContext(), addressUpdateFragment.deviceId) - } - private fun showMessage(msg: String) { requireActivity().runOnUiThread { binding.commandStatusTv.text = msg } } diff --git a/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/clusterclient/OpCredClientFragment.kt b/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/clusterclient/OpCredClientFragment.kt index 0314f9d82e652c..1fd8db6c97a13b 100644 --- a/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/clusterclient/OpCredClientFragment.kt +++ b/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/clusterclient/OpCredClientFragment.kt @@ -100,7 +100,13 @@ class OpCredClientFragment : Fragment() { val attributeId = attribute.id val devicePtr = - ChipClient.getConnectedDevicePointer(requireContext(), addressUpdateFragment.deviceId) + try { + ChipClient.getConnectedDevicePointer(requireContext(), addressUpdateFragment.deviceId) + } catch (e: IllegalStateException) { + Log.d(TAG, "getConnectedDevicePointer exception", e) + showMessage("Get DevicePointer fail!") + return + } ChipClient.getDeviceController(requireContext()) .readPath( @@ -137,7 +143,13 @@ class OpCredClientFragment : Fragment() { private suspend fun sendRemoveFabricsBtnClick(fabricIndex: UInt) { val devicePtr = - ChipClient.getConnectedDevicePointer(requireContext(), addressUpdateFragment.deviceId) + try { + ChipClient.getConnectedDevicePointer(requireContext(), addressUpdateFragment.deviceId) + } catch (e: IllegalStateException) { + Log.d(TAG, "getConnectedDevicePointer exception", e) + showMessage("Get DevicePointer fail!") + return + } // TODO : Need to be implement poj-to-tlv val tlvWriter = TlvWriter() tlvWriter.startStructure(AnonymousTag) diff --git a/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/clusterclient/OtaProviderClientFragment.kt b/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/clusterclient/OtaProviderClientFragment.kt index c27159193ed2dc..5d2d62ee76a690 100644 --- a/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/clusterclient/OtaProviderClientFragment.kt +++ b/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/clusterclient/OtaProviderClientFragment.kt @@ -114,6 +114,14 @@ class OtaProviderClientFragment : Fragment() { val attributeId = ClusterIDMapping.AccessControl.Attribute.Acl.id val attributePath = ChipAttributePath.newInstance(endpointId, clusterId, attributeId) + val devicePtr = + try { + ChipClient.getConnectedDevicePointer(requireContext(), addressUpdateFragment.deviceId) + } catch (e: IllegalStateException) { + Log.d(TAG, "getConnectedDevicePointer exception", e) + showMessage("Get DevicePointer fail!") + return + } deviceController.readAttributePath( object : ReportCallback { override fun onError( @@ -136,7 +144,7 @@ class OtaProviderClientFragment : Fragment() { requireActivity().runOnUiThread { showAddAccessControlDialog(tlv) } } }, - ChipClient.getConnectedDevicePointer(requireContext(), addressUpdateFragment.deviceId), + devicePtr, listOf(attributePath), 0 ) @@ -217,6 +225,15 @@ class OtaProviderClientFragment : Fragment() { newEntry.toTlv(AnonymousTag, tlvWriter) tlvWriter.endArray() + val devicePtr = + try { + ChipClient.getConnectedDevicePointer(requireContext(), addressUpdateFragment.deviceId) + } catch (e: IllegalStateException) { + Log.d(TAG, "getConnectedDevicePointer exception", e) + showMessage("Get DevicePointer fail!") + return + } + deviceController.write( object : WriteAttributesCallback { override fun onError(attributePath: ChipAttributePath?, e: Exception?) { @@ -229,7 +246,7 @@ class OtaProviderClientFragment : Fragment() { showMessage("$attributePath : Write response: $status") } }, - ChipClient.getConnectedDevicePointer(requireContext(), addressUpdateFragment.deviceId), + devicePtr, listOf( AttributeWriteRequest.newInstance( 0, @@ -249,6 +266,14 @@ class OtaProviderClientFragment : Fragment() { val clusterId = ClusterIDMapping.OtaSoftwareUpdateRequestor.ID val attributeId = attribute.id val path = ChipAttributePath.newInstance(endpointId, clusterId, attributeId) + val devicePtr = + try { + ChipClient.getConnectedDevicePointer(requireContext(), addressUpdateFragment.deviceId) + } catch (e: IllegalStateException) { + Log.d(TAG, "getConnectedDevicePointer exception", e) + showMessage("Get DevicePointer fail!") + return + } deviceController.readAttributePath( object : ReportCallback { override fun onError( @@ -279,7 +304,7 @@ class OtaProviderClientFragment : Fragment() { showMessage("OtaSoftwareUpdateRequestor ${attribute.name} value: $value") } }, - ChipClient.getConnectedDevicePointer(requireContext(), addressUpdateFragment.deviceId), + devicePtr, listOf(path), 0 ) @@ -344,6 +369,15 @@ class OtaProviderClientFragment : Fragment() { val writeRequest = AttributeWriteRequest.newInstance(endpoint, clusterId, attributeId, tlv) + val devicePtr = + try { + ChipClient.getConnectedDevicePointer(requireContext(), addressUpdateFragment.deviceId) + } catch (e: IllegalStateException) { + Log.d(TAG, "getConnectedDevicePointer exception", e) + showMessage("Get DevicePointer fail!") + return + } + deviceController.write( object : WriteAttributesCallback { override fun onError(attributePath: ChipAttributePath?, e: Exception?) { @@ -356,7 +390,7 @@ class OtaProviderClientFragment : Fragment() { showMessage("$attributePath : Write response: $status") } }, - ChipClient.getConnectedDevicePointer(requireContext(), addressUpdateFragment.deviceId), + devicePtr, listOf(writeRequest), 0, 0 @@ -461,11 +495,17 @@ class OtaProviderClientFragment : Fragment() { private suspend fun sendAnnounceOTAProviderBtnClick() { requireActivity().runOnUiThread { updateOTAStatusBtnClick() } + val devicePtr = + try { + ChipClient.getConnectedDevicePointer(requireContext(), addressUpdateFragment.deviceId) + } catch (e: IllegalStateException) { + Log.d(TAG, "getConnectedDevicePointer exception", e) + showMessage("Get DevicePointer fail!") + return + } + val otaRequestCluster = - ChipClusters.OtaSoftwareUpdateRequestorCluster( - ChipClient.getConnectedDevicePointer(requireContext(), addressUpdateFragment.deviceId), - OTA_REQUESTER_ENDPOINT_ID - ) + ChipClusters.OtaSoftwareUpdateRequestorCluster(devicePtr, OTA_REQUESTER_ENDPOINT_ID) otaRequestCluster.announceOTAProvider( object : DefaultClusterCallback { override fun onSuccess() { diff --git a/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/clusterclient/SensorClientFragment.kt b/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/clusterclient/SensorClientFragment.kt index cad12a5a54bc98..88d9ed63c4f91e 100644 --- a/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/clusterclient/SensorClientFragment.kt +++ b/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/clusterclient/SensorClientFragment.kt @@ -155,7 +155,13 @@ class SensorClientFragment : Fragment() { val clusterName = binding.clusterNameSpinner.selectedItem.toString() val clusterId = CLUSTERS[clusterName]!!["clusterId"] as Long val attributeId = CLUSTERS[clusterName]!!["attributeId"] as Long - val device = ChipClient.getConnectedDevicePointer(requireContext(), deviceId) + val device = + try { + ChipClient.getConnectedDevicePointer(requireContext(), deviceId) + } catch (e: IllegalStateException) { + Log.d(TAG, "getConnectedDevicePointer exception", e) + return + } val callback = makeReadCallback(clusterName, false) deviceController.readAttributePath( @@ -177,7 +183,13 @@ class SensorClientFragment : Fragment() { val clusterName = binding.clusterNameSpinner.selectedItem.toString() val clusterId = CLUSTERS[clusterName]!!["clusterId"] as Long val attributeId = CLUSTERS[clusterName]!!["attributeId"] as Long - val device = ChipClient.getConnectedDevicePointer(requireContext(), deviceId) + val device = + try { + ChipClient.getConnectedDevicePointer(requireContext(), deviceId) + } catch (e: IllegalStateException) { + Log.d(TAG, "getConnectedDevicePointer exception", e) + return + } val callback = makeReadCallback(clusterName, true) deviceController.subscribeToAttributePath( diff --git a/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/clusterclient/WildcardFragment.kt b/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/clusterclient/WildcardFragment.kt index af119581a7047f..5b49a6d9ab05ab 100644 --- a/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/clusterclient/WildcardFragment.kt +++ b/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/clusterclient/WildcardFragment.kt @@ -270,12 +270,18 @@ class WildcardFragment : Fragment() { "ResubscriptionAttempt terminationCause:$terminationCause, nextResubscribeIntervalMsec:$nextResubscribeIntervalMsec" ) } - + val devicePtr = + try { + ChipClient.getConnectedDevicePointer(requireContext(), addressUpdateFragment.deviceId) + } catch (e: IllegalStateException) { + Log.d(TAG, "getConnectedDevicePointer exception", e) + return + } deviceController.subscribeToPath( subscriptionEstablishedCallback, resubscriptionAttemptCallback, reportCallback, - ChipClient.getConnectedDevicePointer(requireContext(), addressUpdateFragment.deviceId), + devicePtr, attributePath.ifEmpty { null }, eventPath.ifEmpty { null }, minInterval, @@ -288,9 +294,16 @@ class WildcardFragment : Fragment() { } private suspend fun read(isFabricFiltered: Boolean, eventMin: Long?) { + val devicePtr = + try { + ChipClient.getConnectedDevicePointer(requireContext(), addressUpdateFragment.deviceId) + } catch (e: IllegalStateException) { + Log.d(TAG, "getConnectedDevicePointer exception", e) + return + } deviceController.readPath( reportCallback, - ChipClient.getConnectedDevicePointer(requireContext(), addressUpdateFragment.deviceId), + devicePtr, attributePath.ifEmpty { null }, eventPath.ifEmpty { null }, isFabricFiltered, @@ -351,10 +364,16 @@ class WildcardFragment : Fragment() { version ) } - + val devicePtr = + try { + addressUpdateFragment.getDevicePointer(requireContext()) + } catch (e: IllegalStateException) { + Log.d(TAG, "getDevicePointer exception", e) + return + } deviceController.write( writeAttributeCallback, - addressUpdateFragment.getDevicePointer(requireContext()), + devicePtr, listOf(writeRequest), timedRequestTimeoutMs, imTimeoutMs @@ -379,9 +398,16 @@ class WildcardFragment : Fragment() { } else { InvokeElement.newInstance(endpointId, clusterId, commandId, null, jsonString) } + val devicePtr = + try { + addressUpdateFragment.getDevicePointer(requireContext()) + } catch (e: IllegalStateException) { + Log.d(TAG, "getDevicePointer exception", e) + return + } deviceController.invoke( invokeCallback, - addressUpdateFragment.getDevicePointer(requireContext()), + devicePtr, invokeElement, timedRequestTimeoutMs, imTimeoutMs @@ -555,7 +581,13 @@ class WildcardFragment : Fragment() { val clusterId = 62L // OperationalCredentials val attributeId = 5L // CurrentFabricIndex val deviceId = addressUpdateFragment.deviceId - val devicePointer = ChipClient.getConnectedDevicePointer(context, deviceId) + val devicePointer = + try { + ChipClient.getConnectedDevicePointer(context, deviceId) + } catch (e: IllegalStateException) { + Log.d(TAG, "getConnectedDevicePointer exception", e) + return 0U + } return suspendCoroutine { cont -> deviceController.readAttributePath( object : ReportCallback { diff --git a/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/clusterclient/clusterinteraction/ClusterDetailFragment.kt b/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/clusterclient/clusterinteraction/ClusterDetailFragment.kt index eb14eee23770bd..09270003a41a5e 100644 --- a/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/clusterclient/clusterinteraction/ClusterDetailFragment.kt +++ b/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/clusterclient/clusterinteraction/ClusterDetailFragment.kt @@ -67,7 +67,15 @@ class ClusterDetailFragment : Fragment() { _binding = ClusterDetailFragmentBinding.inflate(inflater, container, false) scope = viewLifecycleOwner.lifecycleScope deviceId = checkNotNull(requireArguments().getLong(DEVICE_ID)) - scope.launch { devicePtr = getConnectedDevicePointer(requireContext(), deviceId) } + scope.launch { + try { + devicePtr = getConnectedDevicePointer(requireContext(), deviceId) + } catch (e: IllegalStateException) { + Log.d(TAG, "getConnectedDevicePointer exception", e) + showMessage("Get DevicePointer fail!") + return@launch + } + } endpointId = checkNotNull(requireArguments().getInt(ENDPOINT_ID_KEY)) historyCommand = requireArguments().getSerializable(HISTORY_COMMAND) as HistoryCommand? deviceController.setCompletionListener(GenericChipDeviceListener()) diff --git a/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/clusterclient/clusterinteraction/ClusterInteractionFragment.kt b/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/clusterclient/clusterinteraction/ClusterInteractionFragment.kt index d723a93b674f7f..8847da71b87271 100644 --- a/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/clusterclient/clusterinteraction/ClusterInteractionFragment.kt +++ b/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/clusterclient/clusterinteraction/ClusterInteractionFragment.kt @@ -1,6 +1,7 @@ package com.google.chip.chiptool.clusterclient.clusterinteraction import android.os.Bundle +import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup @@ -45,7 +46,13 @@ class ClusterInteractionFragment : Fragment() { binding.getEndpointListBtn.setOnClickListener { scope.launch { devicePtr = - ChipClient.getConnectedDevicePointer(requireContext(), addressUpdateFragment.deviceId) + try { + ChipClient.getConnectedDevicePointer(requireContext(), addressUpdateFragment.deviceId) + } catch (e: IllegalStateException) { + Log.d(TAG, "getConnectedDevicePointer exception", e) + showMessage("getConnectedDevicePointer fail!") + return@launch + } showMessage("Retrieving endpoints") binding.endpointList.visibility = View.VISIBLE } From c4927d453ae7d1c63c44dc3f2acc6f67f7bed539 Mon Sep 17 00:00:00 2001 From: Andrei Litvin Date: Wed, 21 Feb 2024 22:23:08 -0500 Subject: [PATCH 12/13] Pull in EventLogging into src/app:app (#32230) * Pull in EventLogging into src/app:app * Fix typo * Restyle --------- Co-authored-by: Andrei Litvin --- .github/workflows/lint.yml | 2 -- src/app/BUILD.gn | 2 ++ 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index d811fe05fa888f..66405b9e615b6d 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -100,8 +100,6 @@ jobs: --known-failure app/CompatEnumNames.h \ --known-failure app/data-model/ListLargeSystemExtensions.h \ --known-failure app/EventHeader.h \ - --known-failure app/EventLoggingDelegate.h \ - --known-failure app/EventLogging.h \ --known-failure app/EventLoggingTypes.h \ --known-failure app/InteractionModelHelper.h \ --known-failure app/ReadClient.h \ diff --git a/src/app/BUILD.gn b/src/app/BUILD.gn index 3dfbbbffe56daf..ec520e005b0d80 100644 --- a/src/app/BUILD.gn +++ b/src/app/BUILD.gn @@ -233,6 +233,8 @@ static_library("app") { "DefaultAttributePersistenceProvider.h", "DeferredAttributePersistenceProvider.cpp", "DeferredAttributePersistenceProvider.h", + "EventLogging.h", + "EventLoggingDelegate.h", "EventManagement.cpp", "EventManagement.h", "FailSafeContext.cpp", From 8fbe0a71deb96ade73282558a583386b80dbcd5a Mon Sep 17 00:00:00 2001 From: Vivien Nicolas Date: Thu, 22 Feb 2024 04:24:44 +0100 Subject: [PATCH 13/13] [CI] Add --trace_decode supports when starting an accessory from a YAML test (#32221) --- .../pseudo_clusters/clusters/accessory_server_bridge.py | 3 +++ .../pseudo_clusters/clusters/system_commands.py | 1 + 2 files changed, 4 insertions(+) diff --git a/scripts/py_matter_yamltests/matter_yamltests/pseudo_clusters/clusters/accessory_server_bridge.py b/scripts/py_matter_yamltests/matter_yamltests/pseudo_clusters/clusters/accessory_server_bridge.py index a8991deb9b7870..15ebdf46428830 100644 --- a/scripts/py_matter_yamltests/matter_yamltests/pseudo_clusters/clusters/accessory_server_bridge.py +++ b/scripts/py_matter_yamltests/matter_yamltests/pseudo_clusters/clusters/accessory_server_bridge.py @@ -77,6 +77,9 @@ def _get_start_options(request): elif name == 'crashLogPath': options.append('--crash_log') options.append(str(value)) + elif name == 'traceDecode': + options.append('--trace_decode') + options.append(str(value)) elif name == 'registerKey': pass else: diff --git a/scripts/py_matter_yamltests/matter_yamltests/pseudo_clusters/clusters/system_commands.py b/scripts/py_matter_yamltests/matter_yamltests/pseudo_clusters/clusters/system_commands.py index 77028c39d72a9a..92bab169f7e0c6 100644 --- a/scripts/py_matter_yamltests/matter_yamltests/pseudo_clusters/clusters/system_commands.py +++ b/scripts/py_matter_yamltests/matter_yamltests/pseudo_clusters/clusters/system_commands.py @@ -33,6 +33,7 @@ +