From 7350209db277f6a912ceac476bb14ab10ee0c7f1 Mon Sep 17 00:00:00 2001 From: Arkadiusz Bokowy Date: Thu, 10 Aug 2023 20:54:39 +0200 Subject: [PATCH] [Linux] C++ version of autoptr for glib objects (#28304) * Remove CHIPOBLE ifdefs in files included by GN * Pass arguments as const if possible * Fix typo in enum name * Get rid of excessive casting * Fix memory leak on new CHIP device scanned * Free memory returned by g_variant_lookup_value * Move glib deleter helpers to lib/support * Define GAutoPtr for glib objects memory management * Build break fix * Fix build break without WPA * Add missing include * Move GLibTypeDeleter.h to src/platform --- src/controller/python/chip/ble/LinuxImpl.cpp | 4 +- .../GlibTypeDeleter.h => GLibTypeDeleter.h} | 51 ++++++ src/platform/Linux/BLEManagerImpl.cpp | 30 ++-- src/platform/Linux/BLEManagerImpl.h | 12 +- src/platform/Linux/BUILD.gn | 13 +- .../Linux/ConnectivityManagerImpl.cpp | 55 ++++--- src/platform/Linux/ThreadStackManagerImpl.cpp | 66 ++++---- src/platform/Linux/ThreadStackManagerImpl.h | 11 +- src/platform/Linux/bluez/AdapterIterator.cpp | 4 - src/platform/Linux/bluez/AdapterIterator.h | 8 +- .../Linux/bluez/ChipDeviceScanner.cpp | 59 +++---- src/platform/Linux/bluez/ChipDeviceScanner.h | 12 +- src/platform/Linux/bluez/Helper.cpp | 150 ++++++++---------- src/platform/Linux/bluez/Helper.h | 12 +- src/platform/webos/BLEManagerImpl.h | 6 +- src/platform/webos/BUILD.gn | 2 +- src/platform/webos/GlibTypeDeleter.h | 71 --------- src/platform/webos/ThreadStackManagerImpl.h | 2 +- 18 files changed, 268 insertions(+), 300 deletions(-) rename src/platform/{Linux/GlibTypeDeleter.h => GLibTypeDeleter.h} (70%) delete mode 100644 src/platform/webos/GlibTypeDeleter.h diff --git a/src/controller/python/chip/ble/LinuxImpl.cpp b/src/controller/python/chip/ble/LinuxImpl.cpp index 41e589e3c62944..c33dddd1325dcc 100644 --- a/src/controller/python/chip/ble/LinuxImpl.cpp +++ b/src/controller/python/chip/ble/LinuxImpl.cpp @@ -78,11 +78,11 @@ class ScannerDelegateImpl : public ChipDeviceScannerDelegate void SetScanner(std::unique_ptr scanner) { mScanner = std::move(scanner); } - void OnDeviceScanned(BluezDevice1 * device, const chip::Ble::ChipBLEDeviceIdentificationInfo & info) override + void OnDeviceScanned(BluezDevice1 & device, const chip::Ble::ChipBLEDeviceIdentificationInfo & info) override { if (mScanCallback) { - mScanCallback(mContext, bluez_device1_get_address(device), info.GetDeviceDiscriminator(), info.GetProductId(), + mScanCallback(mContext, bluez_device1_get_address(&device), info.GetDeviceDiscriminator(), info.GetProductId(), info.GetVendorId()); } } diff --git a/src/platform/Linux/GlibTypeDeleter.h b/src/platform/GLibTypeDeleter.h similarity index 70% rename from src/platform/Linux/GlibTypeDeleter.h rename to src/platform/GLibTypeDeleter.h index 476a00a9ae5c50..bd93be76203cd2 100644 --- a/src/platform/Linux/GlibTypeDeleter.h +++ b/src/platform/GLibTypeDeleter.h @@ -17,7 +17,12 @@ #pragma once +#include + #include +#include + +namespace chip { template class UniquePointerReceiver @@ -69,3 +74,49 @@ struct GBytesDeleter { void operator()(GBytes * object) { g_bytes_unref(object); } }; + +template +struct GAutoPtrDeleter +{ +}; + +template <> +struct GAutoPtrDeleter +{ + using deleter = GFree; +}; + +template <> +struct GAutoPtrDeleter +{ + using deleter = GBytesDeleter; +}; + +template <> +struct GAutoPtrDeleter +{ + using deleter = GObjectDeleter; +}; + +template <> +struct GAutoPtrDeleter +{ + using deleter = GErrorDeleter; +}; + +template <> +struct GAutoPtrDeleter +{ + using deleter = GVariantDeleter; +}; + +template <> +struct GAutoPtrDeleter +{ + using deleter = GVariantIterDeleter; +}; + +template +using GAutoPtr = std::unique_ptr::deleter>; + +} // namespace chip diff --git a/src/platform/Linux/BLEManagerImpl.cpp b/src/platform/Linux/BLEManagerImpl.cpp index 07ea5d6170d8c4..deab037321dd27 100644 --- a/src/platform/Linux/BLEManagerImpl.cpp +++ b/src/platform/Linux/BLEManagerImpl.cpp @@ -21,20 +21,26 @@ * Provides an implementation of the BLEManager singleton object * for Linux platforms. */ -#include -#include -#include -#include -#include -#include -#include +/** + * Note: BLEManager requires ConnectivityManager to be defined beforehand, + * otherwise we will face circular dependency between them. */ +#include + +/** + * Note: Use public include for BLEManager which includes our local + * platform//BLEManagerImpl.h after defining interface class. */ +#include "platform/internal/BLEManager.h" #include #include #include -#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE +#include +#include +#include +#include +#include #include "bluez/Helper.h" @@ -773,9 +779,9 @@ void BLEManagerImpl::NotifyBLEPeripheralAdvStopComplete(bool aIsSuccess, void * PlatformMgr().PostEventOrDie(&event); } -void BLEManagerImpl::OnDeviceScanned(BluezDevice1 * device, const chip::Ble::ChipBLEDeviceIdentificationInfo & info) +void BLEManagerImpl::OnDeviceScanned(BluezDevice1 & device, const chip::Ble::ChipBLEDeviceIdentificationInfo & info) { - ChipLogProgress(Ble, "New device scanned: %s", bluez_device1_get_address(device)); + ChipLogProgress(Ble, "New device scanned: %s", bluez_device1_get_address(&device)); if (mBLEScanConfig.mBleScanState == BleScanState::kScanForDiscriminator) { @@ -787,7 +793,7 @@ void BLEManagerImpl::OnDeviceScanned(BluezDevice1 * device, const chip::Ble::Chi } else if (mBLEScanConfig.mBleScanState == BleScanState::kScanForAddress) { - if (strcmp(bluez_device1_get_address(device), mBLEScanConfig.mAddress.c_str()) != 0) + if (strcmp(bluez_device1_get_address(&device), mBLEScanConfig.mAddress.c_str()) != 0) { return; } @@ -837,5 +843,3 @@ void BLEManagerImpl::OnScanError(CHIP_ERROR err) } // namespace Internal } // namespace DeviceLayer } // namespace chip - -#endif // CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE diff --git a/src/platform/Linux/BLEManagerImpl.h b/src/platform/Linux/BLEManagerImpl.h index 319b4b3468e0ff..23e182f2281b31 100644 --- a/src/platform/Linux/BLEManagerImpl.h +++ b/src/platform/Linux/BLEManagerImpl.h @@ -26,8 +26,6 @@ #include #include -#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE - #include "bluez/ChipDeviceScanner.h" #include "bluez/Types.h" @@ -154,7 +152,7 @@ class BLEManagerImpl final : public BLEManager, CHIP_ERROR CancelConnection() override; // ===== Members that implement virtual methods on ChipDeviceScannerDelegate - void OnDeviceScanned(BluezDevice1 * device, const chip::Ble::ChipBLEDeviceIdentificationInfo & info) override; + void OnDeviceScanned(BluezDevice1 & device, const chip::Ble::ChipBLEDeviceIdentificationInfo & info) override; void OnScanComplete() override; // ===== Members for internal use by the following friends. @@ -181,9 +179,9 @@ class BLEManagerImpl final : public BLEManager, enum { - kMaxConnections = 1, // TODO: right max connection - kMaxDeviceNameLength = 20, // TODO: right-size this - kMaxAdvertismentDataSetSize = 31 // TODO: verify this + kMaxConnections = 1, // TODO: right max connection + kMaxDeviceNameLength = 20, // TODO: right-size this + kMaxAdvertisementDataSetSize = 31 // TODO: verify this }; CHIP_ERROR StartBLEAdvertising(); @@ -246,5 +244,3 @@ inline bool BLEManagerImpl::_IsAdvertising() } // namespace Internal } // namespace DeviceLayer } // namespace chip - -#endif // CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE diff --git a/src/platform/Linux/BUILD.gn b/src/platform/Linux/BUILD.gn index 69d0289254d063..56324ff5c4a494 100644 --- a/src/platform/Linux/BUILD.gn +++ b/src/platform/Linux/BUILD.gn @@ -41,10 +41,8 @@ static_library("Linux") { sources = [ "../DeviceSafeQueue.cpp", "../DeviceSafeQueue.h", + "../GLibTypeDeleter.h", "../SingletonConfigurationManager.cpp", - "BLEManagerImpl.cpp", - "BLEManagerImpl.h", - "BlePlatformConfig.h", "CHIPDevicePlatformConfig.h", "CHIPDevicePlatformEvent.h", "CHIPLinuxStorage.cpp", @@ -85,6 +83,9 @@ static_library("Linux") { if (chip_enable_ble) { sources += [ + "BLEManagerImpl.cpp", + "BLEManagerImpl.h", + "BlePlatformConfig.h", "bluez/AdapterIterator.cpp", "bluez/AdapterIterator.h", "bluez/ChipDeviceScanner.cpp", @@ -125,7 +126,6 @@ static_library("Linux") { if (chip_enable_openthread) { sources += [ - "GlibTypeDeleter.h", "ThreadStackManagerImpl.cpp", "ThreadStackManagerImpl.h", ] @@ -138,10 +138,7 @@ static_library("Linux") { } if (chip_enable_wifi) { - sources += [ - "GlibTypeDeleter.h", - "NetworkCommissioningWiFiDriver.cpp", - ] + sources += [ "NetworkCommissioningWiFiDriver.cpp" ] public_deps += [ "dbus/wpa" ] } diff --git a/src/platform/Linux/ConnectivityManagerImpl.cpp b/src/platform/Linux/ConnectivityManagerImpl.cpp index d393008102bbb4..b9686d8ce104f8 100644 --- a/src/platform/Linux/ConnectivityManagerImpl.cpp +++ b/src/platform/Linux/ConnectivityManagerImpl.cpp @@ -58,7 +58,7 @@ #endif #if CHIP_DEVICE_CONFIG_ENABLE_WPA -#include +#include #include #endif @@ -76,6 +76,23 @@ using namespace ::chip::app::Clusters::WiFiNetworkDiagnostics; using namespace ::chip::DeviceLayer::NetworkCommissioning; namespace chip { + +#if CHIP_DEVICE_CONFIG_ENABLE_WPA + +template <> +struct GAutoPtrDeleter +{ + using deleter = GObjectDeleter; +}; + +template <> +struct GAutoPtrDeleter +{ + using deleter = GObjectDeleter; +}; + +#endif // CHIP_DEVICE_CONFIG_ENABLE_WPA + namespace DeviceLayer { ConnectivityManagerImpl ConnectivityManagerImpl::sInstance; @@ -1070,8 +1087,7 @@ ConnectivityManagerImpl::ConnectWiFiNetworkAsync(ByteSpan ssid, ByteSpan credent void ConnectivityManagerImpl::_ConnectWiFiNetworkAsyncCallback(GObject * source_object, GAsyncResult * res, gpointer user_data) { ConnectivityManagerImpl * this_ = reinterpret_cast(user_data); - std::unique_ptr attachRes; - std::unique_ptr err; + GAutoPtr err; std::lock_guard lock(mWpaSupplicantMutex); @@ -1159,7 +1175,7 @@ void ConnectivityManagerImpl::PostNetworkConnect() CHIP_ERROR ConnectivityManagerImpl::CommitConfig() { gboolean result; - std::unique_ptr err; + GAutoPtr err; std::lock_guard lock(mWpaSupplicantMutex); @@ -1290,7 +1306,7 @@ CHIP_ERROR ConnectivityManagerImpl::GetWiFiVersion(WiFiVersionEnum & wiFiVersion int32_t ConnectivityManagerImpl::GetDisconnectReason() { std::lock_guard lock(mWpaSupplicantMutex); - std::unique_ptr err; + GAutoPtr err; gint errorValue = wpa_fi_w1_wpa_supplicant1_interface_get_disconnect_reason(mWpaSupplicant.iface); // wpa_supplicant DBus API: DisconnectReason: The most recent IEEE 802.11 reason code for disconnect. Negative value @@ -1306,7 +1322,7 @@ CHIP_ERROR ConnectivityManagerImpl::GetConfiguredNetwork(NetworkCommissioning::N // with the proxy object. std::lock_guard lock(mWpaSupplicantMutex); - std::unique_ptr err; + GAutoPtr err; if (mWpaSupplicant.iface == nullptr) { @@ -1322,10 +1338,9 @@ CHIP_ERROR ConnectivityManagerImpl::GetConfiguredNetwork(NetworkCommissioning::N return CHIP_ERROR_KEY_NOT_FOUND; } - std::unique_ptr 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())); + 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())); if (networkInfo == nullptr) { return CHIP_ERROR_INTERNAL; @@ -1333,9 +1348,9 @@ CHIP_ERROR ConnectivityManagerImpl::GetConfiguredNetwork(NetworkCommissioning::N network.connected = wpa_fi_w1_wpa_supplicant1_network_get_enabled(networkInfo.get()); GVariant * properties = wpa_fi_w1_wpa_supplicant1_network_get_properties(networkInfo.get()); - GVariant * ssid = g_variant_lookup_value(properties, "ssid", nullptr); + GAutoPtr ssid(g_variant_lookup_value(properties, "ssid", nullptr)); gsize length; - const gchar * ssidStr = g_variant_get_string(ssid, &length); + const gchar * ssidStr = g_variant_get_string(ssid.get(), &length); // TODO: wpa_supplicant will return ssid with quotes! We should have a better way to get the actual ssid in bytes. gsize length_actual = length - 2; VerifyOrReturnError(length_actual <= sizeof(network.networkID), CHIP_ERROR_INTERNAL); @@ -1350,7 +1365,7 @@ CHIP_ERROR ConnectivityManagerImpl::StopAutoScan() std::lock_guard lock(mWpaSupplicantMutex); VerifyOrReturnError(mWpaSupplicant.iface != nullptr, CHIP_ERROR_INCORRECT_STATE); - std::unique_ptr err; + GAutoPtr err; gboolean result; ChipLogDetail(DeviceLayer, "wpa_supplicant: disabling auto scan"); @@ -1407,6 +1422,7 @@ CHIP_ERROR ConnectivityManagerImpl::StartWiFiScan(ByteSpan ssid, WiFiDriver::Sca } namespace { + // wpa_supplicant's scan results don't contains the channel infomation, so we need this lookup table for resolving the band and // channel infomation. std::pair GetBandAndChannelFromFrequency(uint32_t freq) @@ -1505,6 +1521,7 @@ std::pair GetBandAndChannelFromFrequency(uint32_t freq) } return ret; } + } // namespace bool ConnectivityManagerImpl::_GetBssInfo(const gchar * bssPath, NetworkCommissioning::WiFiScanResponse & result) @@ -1514,8 +1531,8 @@ bool ConnectivityManagerImpl::_GetBssInfo(const gchar * bssPath, NetworkCommissi // completed before this function returns. Also, no external callbacks are registered // with the proxy object. - std::unique_ptr err; - std::unique_ptr bss( + 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())); @@ -1526,8 +1543,8 @@ bool ConnectivityManagerImpl::_GetBssInfo(const gchar * bssPath, NetworkCommissi WpaFiW1Wpa_supplicant1BSSProxy * bssProxy = WPA_FI_W1_WPA_SUPPLICANT1_BSS_PROXY(bss.get()); - std::unique_ptr ssid(g_dbus_proxy_get_cached_property(G_DBUS_PROXY(bssProxy), "SSID")); - std::unique_ptr bssid(g_dbus_proxy_get_cached_property(G_DBUS_PROXY(bssProxy), "BSSID")); + GAutoPtr ssid(g_dbus_proxy_get_cached_property(G_DBUS_PROXY(bssProxy), "SSID")); + GAutoPtr bssid(g_dbus_proxy_get_cached_property(G_DBUS_PROXY(bssProxy), "BSSID")); // Network scan is performed in the background, so the BSS // may be gone when we try to get the properties. @@ -1635,8 +1652,8 @@ bool ConnectivityManagerImpl::_GetBssInfo(const gchar * bssPath, NetworkCommissi return res; }; auto GetNetworkSecurityType = [IsNetworkWPAPSK, IsNetworkWPA2PSK](WpaFiW1Wpa_supplicant1BSSProxy * proxy) -> uint8_t { - std::unique_ptr wpa(g_dbus_proxy_get_cached_property(G_DBUS_PROXY(proxy), "WPA")); - std::unique_ptr rsn(g_dbus_proxy_get_cached_property(G_DBUS_PROXY(proxy), "RSN")); + GAutoPtr wpa(g_dbus_proxy_get_cached_property(G_DBUS_PROXY(proxy), "WPA")); + GAutoPtr rsn(g_dbus_proxy_get_cached_property(G_DBUS_PROXY(proxy), "RSN")); uint8_t res = IsNetworkWPAPSK(wpa.get()) | IsNetworkWPA2PSK(rsn.get()); if (res == 0) diff --git a/src/platform/Linux/ThreadStackManagerImpl.cpp b/src/platform/Linux/ThreadStackManagerImpl.cpp index 8e27a9fece2b0f..dfaee5297f6f11 100755 --- a/src/platform/Linux/ThreadStackManagerImpl.cpp +++ b/src/platform/Linux/ThreadStackManagerImpl.cpp @@ -21,6 +21,7 @@ #include #include #include +#include #include #include #include @@ -65,10 +66,10 @@ CHIP_ERROR GLibMatterContextSetActiveDataset(SetActiveDatasetContext * context) // all D-Bus signals will be delivered to the GLib global default main context. VerifyOrDie(g_main_context_get_thread_default() != nullptr); - std::unique_ptr bytes(g_bytes_new(context->netInfo.data(), context->netInfo.size())); + GAutoPtr bytes(g_bytes_new(context->netInfo.data(), context->netInfo.size())); if (!bytes) return CHIP_ERROR_NO_MEMORY; - std::unique_ptr value(g_variant_new_from_bytes(G_VARIANT_TYPE_BYTESTRING, bytes.release(), true)); + GAutoPtr value(g_variant_new_from_bytes(G_VARIANT_TYPE_BYTESTRING, bytes.release(), true)); if (!value) return CHIP_ERROR_NO_MEMORY; openthread_io_openthread_border_router_set_active_dataset_tlvs(context->proxy, value.release()); @@ -85,7 +86,7 @@ CHIP_ERROR ThreadStackManagerImpl::GLibMatterContextInitThreadStack(ThreadStackM // all D-Bus signals will be delivered to the GLib global default main context. VerifyOrDie(g_main_context_get_thread_default() != nullptr); - std::unique_ptr err; + 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())); @@ -107,7 +108,7 @@ CHIP_ERROR ThreadStackManagerImpl::_InitThreadStack() // If get property is called inside dbus thread (we are going to make it so), XXX_get_XXX can be used instead of XXX_dup_XXX // which is a little bit faster and the returned object doesn't need to be freed. Same for all following get properties. - std::unique_ptr role(openthread_io_openthread_border_router_dup_device_role(mProxy.get())); + GAutoPtr role(openthread_io_openthread_border_router_dup_device_role(mProxy.get())); if (role) { ThreadDeviceRoleChangedHandler(role.get()); @@ -125,7 +126,7 @@ void ThreadStackManagerImpl::OnDbusPropertiesChanged(OpenthreadIoOpenthreadBorde const gchar * key; GVariant * value; - std::unique_ptr iter; + GAutoPtr iter; g_variant_get(changed_properties, "a{sv}", &MakeUniquePointerReceiver(iter).Get()); if (!iter) return; @@ -189,13 +190,13 @@ bool ThreadStackManagerImpl::_HaveRouteToAddress(const Inet::IPAddress & destAdd return true; } - std::unique_ptr routes(openthread_io_openthread_border_router_dup_external_routes(mProxy.get())); + GAutoPtr routes(openthread_io_openthread_border_router_dup_external_routes(mProxy.get())); if (!routes) return false; if (g_variant_n_children(routes.get()) > 0) { - std::unique_ptr iter; + GAutoPtr iter; g_variant_get(routes.get(), "av", &MakeUniquePointerReceiver(iter).Get()); if (!iter) return false; @@ -205,7 +206,7 @@ bool ThreadStackManagerImpl::_HaveRouteToAddress(const Inet::IPAddress & destAdd { if (route == nullptr) continue; - std::unique_ptr prefix; + GAutoPtr prefix; guint16 rloc16; guchar preference; gboolean stable; @@ -215,7 +216,7 @@ bool ThreadStackManagerImpl::_HaveRouteToAddress(const Inet::IPAddress & destAdd if (!prefix) continue; - std::unique_ptr address; + GAutoPtr address; guchar prefixLength; g_variant_get(prefix.get(), "(&vy)", &MakeUniquePointerReceiver(address).Get(), &prefixLength); if (!address) @@ -273,12 +274,11 @@ CHIP_ERROR ThreadStackManagerImpl::_GetThreadProvision(Thread::OperationalDatase VerifyOrReturnError(mProxy, CHIP_ERROR_INCORRECT_STATE); { - std::unique_ptr err; - - std::unique_ptr 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())); + 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())); if (err) { @@ -293,14 +293,14 @@ CHIP_ERROR ThreadStackManagerImpl::_GetThreadProvision(Thread::OperationalDatase return CHIP_ERROR_KEY_NOT_FOUND; } - std::unique_ptr tupleContent(g_variant_get_child_value(response.get(), 0)); + GAutoPtr tupleContent(g_variant_get_child_value(response.get(), 0)); if (tupleContent == nullptr) { return CHIP_ERROR_KEY_NOT_FOUND; } - std::unique_ptr value(g_variant_get_variant(tupleContent.get())); + GAutoPtr value(g_variant_get_variant(tupleContent.get())); if (value == nullptr) { @@ -331,12 +331,10 @@ bool ThreadStackManagerImpl::_IsThreadEnabled() { VerifyOrReturnError(mProxy, false); - std::unique_ptr err; - - std::unique_ptr 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())); + 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())); if (err) { @@ -349,14 +347,14 @@ bool ThreadStackManagerImpl::_IsThreadEnabled() return false; } - std::unique_ptr tupleContent(g_variant_get_child_value(response.get(), 0)); + GAutoPtr tupleContent(g_variant_get_child_value(response.get(), 0)); if (tupleContent == nullptr) { return false; } - std::unique_ptr value(g_variant_get_variant(tupleContent.get())); + GAutoPtr value(g_variant_get_variant(tupleContent.get())); if (value == nullptr) { @@ -395,7 +393,7 @@ CHIP_ERROR ThreadStackManagerImpl::_SetThreadEnabled(bool val) } else { - std::unique_ptr err; + GAutoPtr err; gboolean result = openthread_io_openthread_border_router_call_reset_sync(mProxy.get(), nullptr, &MakeUniquePointerReceiver(err).Get()); if (err) @@ -416,8 +414,8 @@ CHIP_ERROR ThreadStackManagerImpl::_SetThreadEnabled(bool val) void ThreadStackManagerImpl::_OnThreadBrAttachFinished(GObject * source_object, GAsyncResult * res, gpointer user_data) { ThreadStackManagerImpl * this_ = reinterpret_cast(user_data); - std::unique_ptr attachRes; - std::unique_ptr err; + GAutoPtr attachRes; + GAutoPtr err; { gboolean result = openthread_io_openthread_border_router_call_attach_finish(this_->mProxy.get(), res, &MakeUniquePointerReceiver(err).Get()); @@ -457,7 +455,7 @@ ConnectivityManager::ThreadDeviceType ThreadStackManagerImpl::_GetThreadDeviceTy return ConnectivityManager::ThreadDeviceType::kThreadDeviceType_NotSupported; } - std::unique_ptr role(openthread_io_openthread_border_router_dup_device_role(mProxy.get())); + GAutoPtr role(openthread_io_openthread_border_router_dup_device_role(mProxy.get())); if (!role) return ConnectivityManager::ThreadDeviceType::kThreadDeviceType_NotSupported; if (strcmp(role.get(), kOpenthreadDeviceRoleDetached) == 0 || strcmp(role.get(), kOpenthreadDeviceRoleDisabled) == 0) @@ -466,7 +464,7 @@ ConnectivityManager::ThreadDeviceType ThreadStackManagerImpl::_GetThreadDeviceTy } if (strcmp(role.get(), kOpenthreadDeviceRoleChild) == 0) { - std::unique_ptr linkMode(openthread_io_openthread_border_router_dup_link_mode(mProxy.get())); + GAutoPtr linkMode(openthread_io_openthread_border_router_dup_link_mode(mProxy.get())); if (!linkMode) return ConnectivityManager::ThreadDeviceType::kThreadDeviceType_NotSupported; gboolean rx_on_when_idle; @@ -511,7 +509,7 @@ CHIP_ERROR ThreadStackManagerImpl::_SetThreadDeviceType(ConnectivityManager::Thr if (!network_data) { - std::unique_ptr linkMode(g_variant_new("(bbb)", rx_on_when_idle, device_type, network_data)); + GAutoPtr linkMode(g_variant_new("(bbb)", rx_on_when_idle, device_type, network_data)); if (!linkMode) return CHIP_ERROR_NO_MEMORY; openthread_io_openthread_border_router_set_link_mode(mProxy.get(), linkMode.release()); @@ -646,8 +644,8 @@ void ThreadStackManagerImpl::_OnNetworkScanFinished(GObject * source_object, GAs void ThreadStackManagerImpl::_OnNetworkScanFinished(GAsyncResult * res) { - std::unique_ptr scan_result; - std::unique_ptr err; + 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()); @@ -671,7 +669,7 @@ void ThreadStackManagerImpl::_OnNetworkScanFinished(GAsyncResult * res) if (g_variant_n_children(scan_result.get()) > 0) { - std::unique_ptr iter; + GAutoPtr iter; g_variant_get(scan_result.get(), "a(tstayqqyyyybb)", &MakeUniquePointerReceiver(iter).Get()); if (!iter) { diff --git a/src/platform/Linux/ThreadStackManagerImpl.h b/src/platform/Linux/ThreadStackManagerImpl.h index 3914c04524b14c..22bbc7f5191924 100755 --- a/src/platform/Linux/ThreadStackManagerImpl.h +++ b/src/platform/Linux/ThreadStackManagerImpl.h @@ -22,13 +22,20 @@ #include #include -#include +#include #include #include #include #include namespace chip { + +template <> +struct GAutoPtrDeleter +{ + using deleter = GObjectDeleter; +}; + namespace DeviceLayer { class ThreadStackManagerImpl : public ThreadStackManager @@ -148,7 +155,7 @@ class ThreadStackManagerImpl : public ThreadStackManager uint8_t lqi; }; - std::unique_ptr mProxy; + GAutoPtr mProxy; static CHIP_ERROR GLibMatterContextInitThreadStack(ThreadStackManagerImpl * self); static CHIP_ERROR GLibMatterContextCallAttach(ThreadStackManagerImpl * self); diff --git a/src/platform/Linux/bluez/AdapterIterator.cpp b/src/platform/Linux/bluez/AdapterIterator.cpp index bc892247ac8986..868671e405eaf3 100644 --- a/src/platform/Linux/bluez/AdapterIterator.cpp +++ b/src/platform/Linux/bluez/AdapterIterator.cpp @@ -17,8 +17,6 @@ #include "AdapterIterator.h" -#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE - #include #include #include @@ -139,5 +137,3 @@ bool AdapterIterator::Next() } // namespace Internal } // namespace DeviceLayer } // namespace chip - -#endif diff --git a/src/platform/Linux/bluez/AdapterIterator.h b/src/platform/Linux/bluez/AdapterIterator.h index c06ea8cb97a73f..2908c7a28e51d3 100644 --- a/src/platform/Linux/bluez/AdapterIterator.h +++ b/src/platform/Linux/bluez/AdapterIterator.h @@ -17,12 +17,14 @@ #pragma once +#include + +#include + #include "lib/core/CHIPError.h" #include "Types.h" -#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE - namespace chip { namespace DeviceLayer { namespace Internal { @@ -92,5 +94,3 @@ class AdapterIterator } // namespace Internal } // namespace DeviceLayer } // namespace chip - -#endif // CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE diff --git a/src/platform/Linux/bluez/ChipDeviceScanner.cpp b/src/platform/Linux/bluez/ChipDeviceScanner.cpp index 26543fe6a78f77..fec7ff519b2425 100644 --- a/src/platform/Linux/bluez/ChipDeviceScanner.cpp +++ b/src/platform/Linux/bluez/ChipDeviceScanner.cpp @@ -17,14 +17,12 @@ #include "ChipDeviceScanner.h" -#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE - #include #include #include #include -#include +#include #include "BluezObjectList.h" #include "Types.h" @@ -61,7 +59,7 @@ CHIP_ERROR MainLoopCreateObjectManager(GDBusCreateObjectManagerContext * context // all D-Bus signals will be delivered to the GLib global default main context. VerifyOrDie(g_main_context_get_thread_default() != nullptr); - std::unique_ptr err; + GAutoPtr err; context->object = 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 */, @@ -78,11 +76,11 @@ bool BluezGetChipDeviceInfo(BluezDevice1 & aDevice, chip::Ble::ChipBLEDeviceIden GVariant * serviceData = bluez_device1_get_service_data(&aDevice); VerifyOrReturnError(serviceData != nullptr, false); - GVariant * dataValue = g_variant_lookup_value(serviceData, CHIP_BLE_UUID_SERVICE_STRING, nullptr); + GAutoPtr dataValue(g_variant_lookup_value(serviceData, CHIP_BLE_UUID_SERVICE_STRING, nullptr)); VerifyOrReturnError(dataValue != nullptr, false); size_t dataLen = 0; - const void * dataBytes = g_variant_get_fixed_array(dataValue, &dataLen, sizeof(uint8_t)); + const void * dataBytes = g_variant_get_fixed_array(dataValue.get(), &dataLen, sizeof(uint8_t)); VerifyOrReturnError(dataBytes != nullptr && dataLen >= sizeof(aDeviceInfo), false); memcpy(&aDeviceInfo, dataBytes, sizeof(aDeviceInfo)); @@ -225,59 +223,59 @@ CHIP_ERROR ChipDeviceScanner::MainLoopStopScan(ChipDeviceScanner * self) void ChipDeviceScanner::SignalObjectAdded(GDBusObjectManager * manager, GDBusObject * object, ChipDeviceScanner * self) { - self->ReportDevice(bluez_object_get_device1(BLUEZ_OBJECT(object))); + BluezDevice1 * device = bluez_object_get_device1(BLUEZ_OBJECT(object)); + VerifyOrReturn(device != nullptr); + + self->ReportDevice(*device); + + g_object_unref(device); } void ChipDeviceScanner::SignalInterfaceChanged(GDBusObjectManagerClient * manager, GDBusObjectProxy * object, GDBusProxy * aInterface, GVariant * aChangedProperties, const gchar * const * aInvalidatedProps, ChipDeviceScanner * self) { - self->ReportDevice(bluez_object_get_device1(BLUEZ_OBJECT(object))); + BluezDevice1 * device = bluez_object_get_device1(BLUEZ_OBJECT(object)); + VerifyOrReturn(device != nullptr); + + self->ReportDevice(*device); + + g_object_unref(device); } -void ChipDeviceScanner::ReportDevice(BluezDevice1 * device) +void ChipDeviceScanner::ReportDevice(BluezDevice1 & device) { - if (device == nullptr) - { - return; - } - - if (strcmp(bluez_device1_get_adapter(device), g_dbus_proxy_get_object_path(G_DBUS_PROXY(mAdapter))) != 0) + if (strcmp(bluez_device1_get_adapter(&device), g_dbus_proxy_get_object_path(G_DBUS_PROXY(mAdapter))) != 0) { return; } chip::Ble::ChipBLEDeviceIdentificationInfo deviceInfo; - if (!BluezGetChipDeviceInfo(*device, deviceInfo)) + if (!BluezGetChipDeviceInfo(device, deviceInfo)) { - ChipLogDetail(Ble, "Device %s does not look like a CHIP device.", bluez_device1_get_address(device)); + ChipLogDetail(Ble, "Device %s does not look like a CHIP device.", bluez_device1_get_address(&device)); return; } mDelegate->OnDeviceScanned(device, deviceInfo); } -void ChipDeviceScanner::RemoveDevice(BluezDevice1 * device) +void ChipDeviceScanner::RemoveDevice(BluezDevice1 & device) { - if (device == nullptr) - { - return; - } - - if (strcmp(bluez_device1_get_adapter(device), g_dbus_proxy_get_object_path(G_DBUS_PROXY(mAdapter))) != 0) + if (strcmp(bluez_device1_get_adapter(&device), g_dbus_proxy_get_object_path(G_DBUS_PROXY(mAdapter))) != 0) { return; } chip::Ble::ChipBLEDeviceIdentificationInfo deviceInfo; - if (!BluezGetChipDeviceInfo(*device, deviceInfo)) + if (!BluezGetChipDeviceInfo(device, deviceInfo)) { return; } - const auto devicePath = g_dbus_proxy_get_object_path(G_DBUS_PROXY(device)); + const auto devicePath = g_dbus_proxy_get_object_path(G_DBUS_PROXY(&device)); GError * error = nullptr; if (!bluez_adapter1_call_remove_device_sync(mAdapter, devicePath, nullptr, &error)) @@ -298,7 +296,12 @@ CHIP_ERROR ChipDeviceScanner::MainLoopStartScan(ChipDeviceScanner * self) ChipLogProgress(Ble, "BLE removing known devices."); for (BluezObject & object : BluezObjectList(self->mManager)) { - self->RemoveDevice(bluez_object_get_device1(&object)); + BluezDevice1 * device = bluez_object_get_device1(&object); + if (device != nullptr) + { + self->RemoveDevice(*device); + g_object_unref(device); + } } // Search for LE only. @@ -335,5 +338,3 @@ CHIP_ERROR ChipDeviceScanner::MainLoopStartScan(ChipDeviceScanner * self) } // namespace Internal } // namespace DeviceLayer } // namespace chip - -#endif // CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE diff --git a/src/platform/Linux/bluez/ChipDeviceScanner.h b/src/platform/Linux/bluez/ChipDeviceScanner.h index 2c8c9763b2d6b4..f07606b2ae3b29 100644 --- a/src/platform/Linux/bluez/ChipDeviceScanner.h +++ b/src/platform/Linux/bluez/ChipDeviceScanner.h @@ -19,8 +19,6 @@ #include -#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE - #include #include @@ -40,7 +38,7 @@ class ChipDeviceScannerDelegate virtual ~ChipDeviceScannerDelegate() {} // Called when a CHIP device was found - virtual void OnDeviceScanned(BluezDevice1 * device, const chip::Ble::ChipBLEDeviceIdentificationInfo & info) = 0; + virtual void OnDeviceScanned(BluezDevice1 & device, const chip::Ble::ChipBLEDeviceIdentificationInfo & info) = 0; // Called when a scan was completed (stopped or timed out) virtual void OnScanComplete() = 0; @@ -93,11 +91,11 @@ class ChipDeviceScanner ChipDeviceScanner * self); /// Check if a given device is a CHIP device and if yes, report it as discovered - void ReportDevice(BluezDevice1 * device); + void ReportDevice(BluezDevice1 & device); /// Check if a given device is a CHIP device and if yes, remove it from the adapter /// so that it can be re-discovered if it's still advertising. - void RemoveDevice(BluezDevice1 * device); + void RemoveDevice(BluezDevice1 & device); GDBusObjectManager * mManager = nullptr; BluezAdapter1 * mAdapter = nullptr; @@ -107,12 +105,10 @@ class ChipDeviceScanner gulong mInterfaceChangedSignal = 0; bool mIsScanning = false; bool mIsStopping = false; - /// Used to track if timer has alread expired and doesn't need to be canceled. + /// Used to track if timer has already expired and doesn't need to be canceled. bool mTimerExpired = false; }; } // namespace Internal } // namespace DeviceLayer } // namespace chip - -#endif // CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE diff --git a/src/platform/Linux/bluez/Helper.cpp b/src/platform/Linux/bluez/Helper.cpp index d071f3b304acb3..19d008a88cc2cb 100644 --- a/src/platform/Linux/bluez/Helper.cpp +++ b/src/platform/Linux/bluez/Helper.cpp @@ -47,29 +47,31 @@ * @file * Provides Bluez dbus implementation for BLE */ -#include -#include -#include -#include -#include -#include -#include -#include -#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE #include #include -#include #include #include #include #include #include +#include +#include +#include + +#include +#include +#include +#include +#include #include #include #include +#include #include +#include +#include #include #include "BluezObjectIterator.h" @@ -992,11 +994,10 @@ static void BluezSignalOnObjectRemoved(GDBusObjectManager * aManager, GDBusObjec // for Characteristic1, or GattService -- handle here via calling otPlatTobleHandleDisconnected, or ignore. } -static BluezGattService1 * BluezServiceCreate(gpointer apClosure) +static BluezGattService1 * BluezServiceCreate(BluezEndpoint * endpoint) { BluezObjectSkeleton * object; BluezGattService1 * service; - BluezEndpoint * endpoint = static_cast(apClosure); endpoint->mpServicePath = g_strdup_printf("%s/service", endpoint->mpRootPath); ChipLogDetail(DeviceLayer, "CREATE service object at %s", endpoint->mpServicePath); @@ -1156,7 +1157,7 @@ static BluezConnection * BluezCharacteristicGetBluezConnection(BluezGattCharacte } #endif // CHIP_BLUEZ_CENTRAL_SUPPORT -void EndpointCleanup(BluezEndpoint * apEndpoint) +static void EndpointCleanup(BluezEndpoint * apEndpoint) { if (apEndpoint != nullptr) { @@ -1262,24 +1263,23 @@ static void UpdateAdditionalDataCharacteristic(BluezGattCharacteristic1 * charac } #endif -static void BluezPeripheralObjectsSetup(gpointer apClosure) +static void BluezPeripheralObjectsSetup(BluezEndpoint * endpoint) { static const char * const c1_flags[] = { "write", nullptr }; static const char * const c2_flags[] = { "read", "indicate", nullptr }; +#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING static const char * const c3_flags[] = { "read", nullptr }; +#endif - BluezEndpoint * endpoint = static_cast(apClosure); - VerifyOrExit(endpoint != nullptr, ChipLogError(DeviceLayer, "endpoint is NULL in %s", __func__)); - - endpoint->mpService = BluezServiceCreate(apClosure); + endpoint->mpService = BluezServiceCreate(endpoint); // C1 characteristic endpoint->mpC1 = BluezCharacteristicCreate(endpoint->mpService, "c1", CHIP_PLAT_BLE_UUID_C1_STRING, endpoint->mpRoot); bluez_gatt_characteristic1_set_flags(endpoint->mpC1, c1_flags); - g_signal_connect(endpoint->mpC1, "handle-read-value", G_CALLBACK(BluezCharacteristicReadValue), apClosure); + g_signal_connect(endpoint->mpC1, "handle-read-value", G_CALLBACK(BluezCharacteristicReadValue), endpoint); g_signal_connect(endpoint->mpC1, "handle-write-value", G_CALLBACK(BluezCharacteristicWriteValueError), nullptr); - g_signal_connect(endpoint->mpC1, "handle-acquire-write", G_CALLBACK(BluezCharacteristicAcquireWrite), apClosure); + g_signal_connect(endpoint->mpC1, "handle-acquire-write", G_CALLBACK(BluezCharacteristicAcquireWrite), endpoint); g_signal_connect(endpoint->mpC1, "handle-acquire-notify", G_CALLBACK(BluezCharacteristicAcquireNotifyError), nullptr); g_signal_connect(endpoint->mpC1, "handle-start-notify", G_CALLBACK(BluezCharacteristicStartNotifyError), nullptr); g_signal_connect(endpoint->mpC1, "handle-stop-notify", G_CALLBACK(BluezCharacteristicStopNotifyError), nullptr); @@ -1287,13 +1287,13 @@ static void BluezPeripheralObjectsSetup(gpointer apClosure) endpoint->mpC2 = BluezCharacteristicCreate(endpoint->mpService, "c2", CHIP_PLAT_BLE_UUID_C2_STRING, endpoint->mpRoot); bluez_gatt_characteristic1_set_flags(endpoint->mpC2, c2_flags); - g_signal_connect(endpoint->mpC2, "handle-read-value", G_CALLBACK(BluezCharacteristicReadValue), apClosure); + g_signal_connect(endpoint->mpC2, "handle-read-value", G_CALLBACK(BluezCharacteristicReadValue), endpoint); g_signal_connect(endpoint->mpC2, "handle-write-value", G_CALLBACK(BluezCharacteristicWriteValueError), nullptr); g_signal_connect(endpoint->mpC2, "handle-acquire-write", G_CALLBACK(BluezCharacteristicAcquireWriteError), nullptr); - g_signal_connect(endpoint->mpC2, "handle-acquire-notify", G_CALLBACK(BluezCharacteristicAcquireNotify), apClosure); - g_signal_connect(endpoint->mpC2, "handle-start-notify", G_CALLBACK(BluezCharacteristicStartNotify), apClosure); - g_signal_connect(endpoint->mpC2, "handle-stop-notify", G_CALLBACK(BluezCharacteristicStopNotify), apClosure); - g_signal_connect(endpoint->mpC2, "handle-confirm", G_CALLBACK(BluezCharacteristicConfirm), apClosure); + g_signal_connect(endpoint->mpC2, "handle-acquire-notify", G_CALLBACK(BluezCharacteristicAcquireNotify), endpoint); + g_signal_connect(endpoint->mpC2, "handle-start-notify", G_CALLBACK(BluezCharacteristicStartNotify), endpoint); + g_signal_connect(endpoint->mpC2, "handle-stop-notify", G_CALLBACK(BluezCharacteristicStopNotify), endpoint); + g_signal_connect(endpoint->mpC2, "handle-confirm", G_CALLBACK(BluezCharacteristicConfirm), endpoint); ChipLogDetail(DeviceLayer, "CHIP BTP C1 %s", bluez_gatt_characteristic1_get_service(endpoint->mpC1)); ChipLogDetail(DeviceLayer, "CHIP BTP C2 %s", bluez_gatt_characteristic1_get_service(endpoint->mpC2)); @@ -1303,23 +1303,19 @@ static void BluezPeripheralObjectsSetup(gpointer apClosure) // Additional data characteristics endpoint->mpC3 = BluezCharacteristicCreate(endpoint->mpService, "c3", CHIP_PLAT_BLE_UUID_C3_STRING, endpoint->mpRoot); bluez_gatt_characteristic1_set_flags(endpoint->mpC3, c3_flags); - g_signal_connect(endpoint->mpC3, "handle-read-value", G_CALLBACK(BluezCharacteristicReadValue), apClosure); + g_signal_connect(endpoint->mpC3, "handle-read-value", G_CALLBACK(BluezCharacteristicReadValue), endpoint); g_signal_connect(endpoint->mpC3, "handle-write-value", G_CALLBACK(BluezCharacteristicWriteValueError), nullptr); g_signal_connect(endpoint->mpC3, "handle-acquire-write", G_CALLBACK(BluezCharacteristicAcquireWriteError), nullptr); - g_signal_connect(endpoint->mpC3, "handle-acquire-notify", G_CALLBACK(BluezCharacteristicAcquireNotify), apClosure); - g_signal_connect(endpoint->mpC3, "handle-start-notify", G_CALLBACK(BluezCharacteristicStartNotify), apClosure); - g_signal_connect(endpoint->mpC3, "handle-stop-notify", G_CALLBACK(BluezCharacteristicStopNotify), apClosure); - g_signal_connect(endpoint->mpC3, "handle-confirm", G_CALLBACK(BluezCharacteristicConfirm), apClosure); + g_signal_connect(endpoint->mpC3, "handle-acquire-notify", G_CALLBACK(BluezCharacteristicAcquireNotify), endpoint); + g_signal_connect(endpoint->mpC3, "handle-start-notify", G_CALLBACK(BluezCharacteristicStartNotify), endpoint); + g_signal_connect(endpoint->mpC3, "handle-stop-notify", G_CALLBACK(BluezCharacteristicStopNotify), endpoint); + g_signal_connect(endpoint->mpC3, "handle-confirm", G_CALLBACK(BluezCharacteristicConfirm), endpoint); // update the characteristic value UpdateAdditionalDataCharacteristic(endpoint->mpC3); ChipLogDetail(DeviceLayer, "CHIP BTP C3 %s", bluez_gatt_characteristic1_get_service(endpoint->mpC3)); #else ChipLogDetail(DeviceLayer, "CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING is FALSE"); - (void) c3_flags; #endif - -exit: - return; } static void BluezOnBusAcquired(GDBusConnection * aConn, const gchar * aName, gpointer apClosure) @@ -1335,7 +1331,7 @@ static void BluezOnBusAcquired(GDBusConnection * aConn, const gchar * aName, gpo endpoint->mpRoot = g_dbus_object_manager_server_new(endpoint->mpRootPath); g_dbus_object_manager_server_set_connection(endpoint->mpRoot, aConn); - BluezPeripheralObjectsSetup(apClosure); + BluezPeripheralObjectsSetup(endpoint); } exit: @@ -1356,39 +1352,35 @@ static void BluezOnNameLost(GDBusConnection * aConn, const gchar * aName, gpoint static CHIP_ERROR StartupEndpointBindings(BluezEndpoint * endpoint) { - GDBusObjectManager * manager; - GError * error = nullptr; - GDBusConnection * conn = nullptr; - VerifyOrExit(endpoint != nullptr, ChipLogError(DeviceLayer, "endpoint is NULL in %s", __func__)); + VerifyOrReturnError(endpoint != nullptr, CHIP_ERROR_INVALID_ARGUMENT, + ChipLogError(DeviceLayer, "endpoint is NULL in %s", __func__)); - conn = g_bus_get_sync(G_BUS_TYPE_SYSTEM, nullptr, &error); - VerifyOrExit(conn != nullptr, ChipLogError(DeviceLayer, "FAIL: get bus sync in %s, error: %s", __func__, error->message)); + GAutoPtr err; + GAutoPtr conn(g_bus_get_sync(G_BUS_TYPE_SYSTEM, nullptr, &MakeUniquePointerReceiver(err).Get())); + VerifyOrReturnError(conn != nullptr, CHIP_ERROR_INTERNAL, + ChipLogError(DeviceLayer, "FAIL: get bus sync in %s, error: %s", __func__, err->message)); if (endpoint->mpAdapterName != nullptr) endpoint->mpOwningName = g_strdup_printf("%s", endpoint->mpAdapterName); else endpoint->mpOwningName = g_strdup_printf("C-%04x", getpid() & 0xffff); - BluezOnBusAcquired(conn, endpoint->mpOwningName, endpoint); + BluezOnBusAcquired(conn.get(), endpoint->mpOwningName, endpoint); - manager = g_dbus_object_manager_client_new_sync( - conn, 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 */, &error); - - VerifyOrExit(manager != nullptr, ChipLogError(DeviceLayer, "FAIL: Error getting object manager client: %s", error->message)); + GDBusObjectManager * manager = 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()); + VerifyOrReturnError(manager != nullptr, CHIP_ERROR_INTERNAL, + ChipLogError(DeviceLayer, "FAIL: Error getting object manager client: %s", err->message)); endpoint->mpObjMgr = manager; - bluezObjectsSetup(endpoint); g_signal_connect(manager, "object-added", G_CALLBACK(BluezSignalOnObjectAdded), endpoint); g_signal_connect(manager, "object-removed", G_CALLBACK(BluezSignalOnObjectRemoved), endpoint); g_signal_connect(manager, "interface-proxy-properties-changed", G_CALLBACK(BluezSignalInterfacePropertiesChanged), endpoint); -exit: - if (error != nullptr) - g_error_free(error); - return CHIP_NO_ERROR; } @@ -1454,10 +1446,9 @@ CHIP_ERROR SendBluezIndication(BLE_CONNECTION_OBJECT apConn, chip::System::Packe return PlatformMgrImpl().GLibMatterContextInvokeSync(BluezC2Indicate, MakeConnectionDataBundle(apConn, apBuf)); } -static CHIP_ERROR BluezDisconnect(void * apClosure) +static CHIP_ERROR BluezDisconnect(BluezConnection * conn) { - BluezConnection * conn = static_cast(apClosure); - GError * error = nullptr; + GError * error = nullptr; gboolean success; VerifyOrExit(conn != nullptr, ChipLogError(DeviceLayer, "conn is NULL in %s", __func__)); @@ -1474,14 +1465,9 @@ static CHIP_ERROR BluezDisconnect(void * apClosure) return CHIP_NO_ERROR; } -static CHIP_ERROR CloseBleconnectionCB(void * apAppState) -{ - return BluezDisconnect(apAppState); -} - CHIP_ERROR CloseBluezConnection(BLE_CONNECTION_OBJECT apConn) { - return PlatformMgrImpl().GLibMatterContextInvokeSync(CloseBleconnectionCB, apConn); + return PlatformMgrImpl().GLibMatterContextInvokeSync(BluezDisconnect, static_cast(apConn)); } CHIP_ERROR StartBluezAdv(BluezEndpoint * apEndpoint) @@ -1516,12 +1502,12 @@ CHIP_ERROR BluezGattsAppRegister(BluezEndpoint * apEndpoint) return err; } -CHIP_ERROR ConfigureBluezAdv(BLEAdvConfig & aBleAdvConfig, BluezEndpoint * apEndpoint) +static CHIP_ERROR ConfigureBluezAdv(const BLEAdvConfig & aBleAdvConfig, BluezEndpoint * apEndpoint) { const char * msg = nullptr; CHIP_ERROR err = CHIP_NO_ERROR; VerifyOrExit(aBleAdvConfig.mpBleName != nullptr, msg = "FAIL: BLE name is NULL"); - VerifyOrExit(aBleAdvConfig.mpAdvertisingUUID != nullptr, msg = "FAIL: BLE mpAdvertisingUUID is NULL in %s"); + VerifyOrExit(aBleAdvConfig.mpAdvertisingUUID != nullptr, msg = "FAIL: BLE mpAdvertisingUUID is NULL"); apEndpoint->mpAdapterName = g_strdup(aBleAdvConfig.mpBleName); apEndpoint->mpAdvertisingUUID = g_strdup(aBleAdvConfig.mpAdvertisingUUID); @@ -1546,20 +1532,14 @@ CHIP_ERROR ConfigureBluezAdv(BLEAdvConfig & aBleAdvConfig, BluezEndpoint * apEnd return err; } -CHIP_ERROR InitBluezBleLayer(bool aIsCentral, char * apBleAddr, BLEAdvConfig & aBleAdvConfig, BluezEndpoint *& apEndpoint) +CHIP_ERROR InitBluezBleLayer(bool aIsCentral, const char * apBleAddr, const BLEAdvConfig & aBleAdvConfig, + BluezEndpoint *& apEndpoint) { + BluezEndpoint * endpoint = g_new0(BluezEndpoint, 1); CHIP_ERROR err = CHIP_NO_ERROR; - bool retval = false; - BluezEndpoint * endpoint = nullptr; - - // initialize server endpoint - endpoint = g_new0(BluezEndpoint, 1); - VerifyOrExit(endpoint != nullptr, ChipLogError(DeviceLayer, "FAIL: memory allocation in %s", __func__)); if (apBleAddr != nullptr) endpoint->mpAdapterAddr = g_strdup(apBleAddr); - else - endpoint->mpAdapterAddr = nullptr; endpoint->mpConnMap = g_hash_table_new(g_str_hash, g_str_equal); endpoint->mIsCentral = aIsCentral; @@ -1578,10 +1558,8 @@ CHIP_ERROR InitBluezBleLayer(bool aIsCentral, char * apBleAddr, BLEAdvConfig & a err = PlatformMgrImpl().GLibMatterContextInvokeSync(StartupEndpointBindings, endpoint); VerifyOrExit(err == CHIP_NO_ERROR, ChipLogError(DeviceLayer, "Failed to schedule endpoint initialization")); - retval = TRUE; - exit: - if (retval) + if (err == CHIP_NO_ERROR) { apEndpoint = endpoint; ChipLogDetail(DeviceLayer, "PlatformBlueZInit init success"); @@ -1651,12 +1629,12 @@ static void OnCharacteristicChanged(GDBusProxy * aInterface, GVariant * aChanged gpointer apConnection) { BLE_CONNECTION_OBJECT connection = static_cast(apConnection); - GVariant * value = g_variant_lookup_value(aChangedProperties, "Value", G_VARIANT_TYPE_BYTESTRING); - VerifyOrReturn(value != nullptr); + GAutoPtr dataValue(g_variant_lookup_value(aChangedProperties, "Value", G_VARIANT_TYPE_BYTESTRING)); + VerifyOrReturn(dataValue != nullptr); size_t bufferLen; - auto buffer = g_variant_get_fixed_array(value, &bufferLen, sizeof(uint8_t)); - VerifyOrReturn(value != nullptr, ChipLogError(DeviceLayer, "Characteristic value has unexpected type")); + auto buffer = g_variant_get_fixed_array(dataValue.get(), &bufferLen, sizeof(uint8_t)); + VerifyOrReturn(buffer != nullptr, ChipLogError(DeviceLayer, "Characteristic value has unexpected type")); BLEManagerImpl::HandleTXCharChanged(connection, static_cast(buffer), bufferLen); } @@ -1735,7 +1713,10 @@ CHIP_ERROR BluezUnsubscribeCharacteristic(BLE_CONNECTION_OBJECT apConn) struct ConnectParams { - ConnectParams(BluezDevice1 * device, BluezEndpoint * endpoint) : mDevice(device), mEndpoint(endpoint), mNumRetries(0) {} + ConnectParams(BluezDevice1 * device, BluezEndpoint * endpoint) : + mDevice(reinterpret_cast(g_object_ref(device))), mEndpoint(endpoint), mNumRetries(0) + {} + ~ConnectParams() { g_object_unref(mDevice); } BluezDevice1 * mDevice; BluezEndpoint * mEndpoint; uint16_t mNumRetries; @@ -1793,20 +1774,16 @@ static CHIP_ERROR ConnectDeviceImpl(ConnectParams * apParams) g_cancellable_reset(endpoint->mpConnectCancellable); bluez_device1_call_connect(device, endpoint->mpConnectCancellable, ConnectDeviceDone, apParams); - g_object_unref(device); return CHIP_NO_ERROR; } -CHIP_ERROR ConnectDevice(BluezDevice1 * apDevice, BluezEndpoint * apEndpoint) +CHIP_ERROR ConnectDevice(BluezDevice1 & aDevice, BluezEndpoint * apEndpoint) { - auto params = chip::Platform::New(apDevice, apEndpoint); - g_object_ref(apDevice); - + auto params = chip::Platform::New(&aDevice, apEndpoint); if (PlatformMgrImpl().GLibMatterContextInvokeSync(ConnectDeviceImpl, params) != CHIP_NO_ERROR) { ChipLogError(Ble, "Failed to schedule ConnectDeviceImpl() on CHIPoBluez thread"); - g_object_unref(apDevice); chip::Platform::Delete(params); return CHIP_ERROR_INCORRECT_STATE; } @@ -1823,4 +1800,3 @@ void CancelConnect(BluezEndpoint * apEndpoint) } // namespace Internal } // namespace DeviceLayer } // namespace chip -#endif // CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE diff --git a/src/platform/Linux/bluez/Helper.h b/src/platform/Linux/bluez/Helper.h index d2576e019751ba..687e9a166c4b72 100644 --- a/src/platform/Linux/bluez/Helper.h +++ b/src/platform/Linux/bluez/Helper.h @@ -50,15 +50,17 @@ #pragma once -#include "Types.h" +#include +#include -#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE +#include "Types.h" namespace chip { namespace DeviceLayer { namespace Internal { -CHIP_ERROR InitBluezBleLayer(bool aIsCentral, char * apBleAddr, BLEAdvConfig & aBleAdvConfig, BluezEndpoint *& apEndpoint); +CHIP_ERROR InitBluezBleLayer(bool aIsCentral, const char * apBleAddr, const BLEAdvConfig & aBleAdvConfig, + BluezEndpoint *& apEndpoint); CHIP_ERROR ShutdownBluezBleLayer(BluezEndpoint * apEndpoint); CHIP_ERROR SendBluezIndication(BLE_CONNECTION_OBJECT apConn, chip::System::PacketBufferHandle apBuf); CHIP_ERROR CloseBluezConnection(BLE_CONNECTION_OBJECT apConn); @@ -74,11 +76,9 @@ CHIP_ERROR BluezSubscribeCharacteristic(BLE_CONNECTION_OBJECT apConn); /// Unsubscribe from the CHIP TX characteristic on the remote peripheral device CHIP_ERROR BluezUnsubscribeCharacteristic(BLE_CONNECTION_OBJECT apConn); -CHIP_ERROR ConnectDevice(BluezDevice1 * apDevice, BluezEndpoint * apEndpoint); +CHIP_ERROR ConnectDevice(BluezDevice1 & aDevice, BluezEndpoint * apEndpoint); void CancelConnect(BluezEndpoint * apEndpoint); } // namespace Internal } // namespace DeviceLayer } // namespace chip - -#endif // CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE diff --git a/src/platform/webos/BLEManagerImpl.h b/src/platform/webos/BLEManagerImpl.h index eb26e9d498819a..4780bbe661227a 100644 --- a/src/platform/webos/BLEManagerImpl.h +++ b/src/platform/webos/BLEManagerImpl.h @@ -163,9 +163,9 @@ class BLEManagerImpl final : public BLEManager, enum { - kMaxConnections = 1, // TODO: right max connection - kMaxDeviceNameLength = 20, // TODO: right-size this - kMaxAdvertismentDataSetSize = 31 // TODO: verify this + kMaxConnections = 1, // TODO: right max connection + kMaxDeviceNameLength = 20, // TODO: right-size this + kMaxAdvertisementDataSetSize = 31 // TODO: verify this }; struct BLEConnection diff --git a/src/platform/webos/BUILD.gn b/src/platform/webos/BUILD.gn index 7ab184f2442a84..719f3c70254b2c 100644 --- a/src/platform/webos/BUILD.gn +++ b/src/platform/webos/BUILD.gn @@ -59,6 +59,7 @@ static_library("webos") { sources = [ "../DeviceSafeQueue.cpp", "../DeviceSafeQueue.h", + "../GLibTypeDeleter.h", "../SingletonConfigurationManager.cpp", "BLEManagerImpl.cpp", "BLEManagerImpl.h", @@ -126,7 +127,6 @@ static_library("webos") { if (chip_enable_openthread) { sources += [ - "GlibTypeDeleter.h", "ThreadStackManagerImpl.cpp", "ThreadStackManagerImpl.h", ] diff --git a/src/platform/webos/GlibTypeDeleter.h b/src/platform/webos/GlibTypeDeleter.h deleted file mode 100644 index 476a00a9ae5c50..00000000000000 --- a/src/platform/webos/GlibTypeDeleter.h +++ /dev/null @@ -1,71 +0,0 @@ -/* - * - * Copyright (c) 2020 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include - -template -class UniquePointerReceiver -{ -public: - UniquePointerReceiver(std::unique_ptr & target) : mTarget(target) {} - - ~UniquePointerReceiver() { mTarget.reset(mValue); } - - T *& Get() { return mValue; } - -private: - std::unique_ptr & mTarget; - T * mValue = nullptr; -}; - -template -UniquePointerReceiver MakeUniquePointerReceiver(std::unique_ptr & target) -{ - return UniquePointerReceiver(target); -} - -struct GFree -{ - void operator()(gpointer object) { g_free(object); } -}; - -struct GObjectDeleter -{ - void operator()(gpointer object) { g_object_unref(object); } -}; - -struct GErrorDeleter -{ - void operator()(GError * object) { g_error_free(object); } -}; - -struct GVariantDeleter -{ - void operator()(GVariant * object) { g_variant_unref(object); } -}; - -struct GVariantIterDeleter -{ - void operator()(GVariantIter * object) { g_variant_iter_free(object); } -}; - -struct GBytesDeleter -{ - void operator()(GBytes * object) { g_bytes_unref(object); } -}; diff --git a/src/platform/webos/ThreadStackManagerImpl.h b/src/platform/webos/ThreadStackManagerImpl.h index e2391dffd78aba..b70910878c08d0 100644 --- a/src/platform/webos/ThreadStackManagerImpl.h +++ b/src/platform/webos/ThreadStackManagerImpl.h @@ -22,10 +22,10 @@ #include #include +#include #include #include #include -#include #include namespace chip {