3 * Copyright (c) 2021 Project CHIP Authors
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
18 #include "AdapterIterator.h"
20 #if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE
22 #include <support/CodeUtils.h>
23 #include <support/logging/CHIPLogging.h>
26 namespace DeviceLayer {
29 AdapterIterator::~AdapterIterator()
31 if (mManager != nullptr)
33 g_object_unref(mManager);
36 if (mObjectList != nullptr)
38 g_list_free_full(mObjectList, g_object_unref);
41 if (mCurrent.adapter != nullptr)
43 g_object_unref(mCurrent.adapter);
44 mCurrent.adapter = nullptr;
48 void AdapterIterator::Initialize()
50 GError * error = nullptr;
52 mManager = g_dbus_object_manager_client_new_for_bus_sync(G_BUS_TYPE_SYSTEM, G_DBUS_OBJECT_MANAGER_CLIENT_FLAGS_NONE,
53 BLUEZ_INTERFACE, "/", bluez_object_manager_client_get_proxy_type,
54 nullptr /* unused user data in the Proxy Type Func */,
55 nullptr /*destroy notify */, nullptr /* cancellable */, &error);
57 VerifyOrExit(mManager != nullptr, ChipLogError(DeviceLayer, "Failed to get DBUS object manager for listing adapters."));
59 mObjectList = g_dbus_object_manager_get_objects(mManager);
60 mCurrentListItem = mObjectList;
65 ChipLogError(DeviceLayer, "DBus error: %s", error->message);
70 bool AdapterIterator::Advance()
72 if (mCurrentListItem == nullptr)
77 while (mCurrentListItem != nullptr)
79 BluezAdapter1 * adapter = bluez_object_get_adapter1(BLUEZ_OBJECT(mCurrentListItem->data));
80 if (adapter == nullptr)
82 mCurrentListItem = mCurrentListItem->next;
86 // PATH is of the for BLUEZ_PATH / hci<nr>, i.e. like
88 // Index represents the number after hci
89 const char * path = g_dbus_proxy_get_object_path(G_DBUS_PROXY(adapter));
92 if (sscanf(path, BLUEZ_PATH "/hci%u", &index) != 1)
94 ChipLogError(DeviceLayer, "Failed to extract HCI index from '%s'", path);
98 if (mCurrent.adapter != nullptr)
100 g_object_unref(mCurrent.adapter);
101 mCurrent.adapter = nullptr;
104 mCurrent.index = index;
105 mCurrent.address = bluez_adapter1_get_address(adapter);
106 mCurrent.alias = bluez_adapter1_get_alias(adapter);
107 mCurrent.name = bluez_adapter1_get_name(adapter);
108 mCurrent.powered = bluez_adapter1_get_powered(adapter);
109 mCurrent.adapter = adapter;
111 mCurrentListItem = mCurrentListItem->next;
119 bool AdapterIterator::Next()
121 if (mManager == nullptr)
129 } // namespace Internal
130 } // namespace DeviceLayer