forked from project-chip/connectedhomeip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ChipDeviceScanner.cpp
318 lines (256 loc) · 10.3 KB
/
ChipDeviceScanner.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
/*
*
* Copyright (c) 2021-2022 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 "ChipDeviceScanner.h"
#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE
#include <errno.h>
#include <pthread.h>
#include <lib/support/logging/CHIPLogging.h>
#include <platform/CHIPDeviceLayer.h>
#include "BluezObjectList.h"
#include "Types.h"
namespace chip {
namespace DeviceLayer {
namespace Internal {
namespace {
struct GObjectUnref
{
template <typename T>
void operator()(T * value)
{
g_object_unref(value);
}
};
using GCancellableUniquePtr = std::unique_ptr<GCancellable, GObjectUnref>;
using GDBusObjectManagerUniquePtr = std::unique_ptr<GDBusObjectManager, GObjectUnref>;
/// Retrieve CHIP device identification info from the device advertising data
bool BluezGetChipDeviceInfo(BluezDevice1 & aDevice, chip::Ble::ChipBLEDeviceIdentificationInfo & aDeviceInfo)
{
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);
VerifyOrReturnError(dataValue != nullptr, false);
size_t dataLen = 0;
const void * dataBytes = g_variant_get_fixed_array(dataValue, &dataLen, sizeof(uint8_t));
VerifyOrReturnError(dataBytes != nullptr && dataLen >= sizeof(aDeviceInfo), false);
memcpy(&aDeviceInfo, dataBytes, sizeof(aDeviceInfo));
return true;
}
} // namespace
ChipDeviceScanner::ChipDeviceScanner(GDBusObjectManager * manager, BluezAdapter1 * adapter, GCancellable * cancellable,
ChipDeviceScannerDelegate * delegate) :
mManager(manager),
mAdapter(adapter), mCancellable(cancellable), mDelegate(delegate)
{
g_object_ref(mAdapter);
g_object_ref(mCancellable);
g_object_ref(mManager);
}
ChipDeviceScanner::~ChipDeviceScanner()
{
StopScan();
// In case the timeout timer is still active
chip::DeviceLayer::SystemLayer().CancelTimer(TimerExpiredCallback, this);
g_object_unref(mManager);
g_object_unref(mCancellable);
g_object_unref(mAdapter);
mManager = nullptr;
mAdapter = nullptr;
mCancellable = nullptr;
mDelegate = nullptr;
}
std::unique_ptr<ChipDeviceScanner> ChipDeviceScanner::Create(BluezAdapter1 * adapter, ChipDeviceScannerDelegate * delegate)
{
GError * error = nullptr;
GCancellableUniquePtr cancellable(g_cancellable_new(), GObjectUnref());
if (!cancellable)
{
return std::unique_ptr<ChipDeviceScanner>();
}
GDBusObjectManagerUniquePtr manager(
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 */, cancellable.get(), &error),
GObjectUnref());
if (!manager)
{
ChipLogError(Ble, "Failed to get DBUS object manager for device scanning: %s", error->message);
g_error_free(error);
return std::unique_ptr<ChipDeviceScanner>();
}
return std::make_unique<ChipDeviceScanner>(manager.get(), adapter, cancellable.get(), delegate);
}
CHIP_ERROR ChipDeviceScanner::StartScan(System::Clock::Timeout timeout)
{
ReturnErrorCodeIf(mIsScanning, CHIP_ERROR_INCORRECT_STATE);
mIsScanning = true; // optimistic, to allow all callbacks to check this
if (PlatformMgrImpl().ScheduleOnGLibMainLoopThread(MainLoopStartScan, this, true) != CHIP_NO_ERROR)
{
ChipLogError(Ble, "Failed to schedule BLE scan start.");
mIsScanning = false;
return CHIP_ERROR_INTERNAL;
}
if (!mIsScanning)
{
ChipLogError(Ble, "Failed to start BLE scan.");
return CHIP_ERROR_INTERNAL;
}
CHIP_ERROR err = chip::DeviceLayer::SystemLayer().StartTimer(timeout, TimerExpiredCallback, static_cast<void *>(this));
if (err != CHIP_NO_ERROR)
{
ChipLogError(Ble, "Failed to schedule scan timeout.");
StopScan();
return err;
}
return CHIP_NO_ERROR;
}
void ChipDeviceScanner::TimerExpiredCallback(chip::System::Layer * layer, void * appState)
{
ChipDeviceScanner * chipDeviceScanner = static_cast<ChipDeviceScanner *>(appState);
chipDeviceScanner->mDelegate->OnScanError(CHIP_ERROR_TIMEOUT);
chipDeviceScanner->StopScan();
}
CHIP_ERROR ChipDeviceScanner::StopScan()
{
ReturnErrorCodeIf(!mIsScanning, CHIP_NO_ERROR);
ReturnErrorCodeIf(mIsStopping, CHIP_NO_ERROR);
mIsStopping = true;
g_cancellable_cancel(mCancellable); // in case we are currently running a scan
if (mObjectAddedSignal)
{
g_signal_handler_disconnect(mManager, mObjectAddedSignal);
mObjectAddedSignal = 0;
}
if (mInterfaceChangedSignal)
{
g_signal_handler_disconnect(mManager, mInterfaceChangedSignal);
mInterfaceChangedSignal = 0;
}
if (PlatformMgrImpl().ScheduleOnGLibMainLoopThread(MainLoopStopScan, this, true) != CHIP_NO_ERROR)
{
ChipLogError(Ble, "Failed to schedule BLE scan stop.");
return CHIP_ERROR_INTERNAL;
}
return CHIP_NO_ERROR;
}
int ChipDeviceScanner::MainLoopStopScan(ChipDeviceScanner * self)
{
GError * error = nullptr;
if (!bluez_adapter1_call_stop_discovery_sync(self->mAdapter, nullptr /* not cancellable */, &error))
{
ChipLogError(Ble, "Failed to stop discovery %s", error->message);
g_error_free(error);
}
ChipDeviceScannerDelegate * delegate = self->mDelegate;
self->mIsScanning = false;
// callback is explicitly allowed to delete the scanner (hence no more
// references to 'self' here)
delegate->OnScanComplete();
return 0;
}
void ChipDeviceScanner::SignalObjectAdded(GDBusObjectManager * manager, GDBusObject * object, ChipDeviceScanner * self)
{
self->ReportDevice(bluez_object_get_device1(BLUEZ_OBJECT(object)));
}
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)));
}
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)
{
return;
}
chip::Ble::ChipBLEDeviceIdentificationInfo deviceInfo;
if (!BluezGetChipDeviceInfo(*device, deviceInfo))
{
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)
{
if (device == nullptr)
{
return;
}
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))
{
return;
}
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))
{
ChipLogDetail(Ble, "Failed to remove device %s: %s", StringOrNullMarker(devicePath), error->message);
g_error_free(error);
}
}
int ChipDeviceScanner::MainLoopStartScan(ChipDeviceScanner * self)
{
GError * error = nullptr;
self->mObjectAddedSignal = g_signal_connect(self->mManager, "object-added", G_CALLBACK(SignalObjectAdded), self);
self->mInterfaceChangedSignal =
g_signal_connect(self->mManager, "interface-proxy-properties-changed", G_CALLBACK(SignalInterfaceChanged), self);
ChipLogProgress(Ble, "BLE removing known devices.");
for (BluezObject & object : BluezObjectList(self->mManager))
{
self->RemoveDevice(bluez_object_get_device1(&object));
}
// Search for LE only.
// Do NOT add filtering by UUID as it is done by the following kernel function:
// https://github.com/torvalds/linux/blob/bdb575f872175ed0ecf2638369da1cb7a6e86a14/net/bluetooth/mgmt.c#L9258.
// The function requires that devices advertise its services' UUIDs in UUID16/32/128 fields
// while the Matter specification requires only FLAGS (0x01) and SERVICE_DATA_16 (0x16) fields
// in the advertisement packets.
GVariantBuilder filterBuilder;
g_variant_builder_init(&filterBuilder, G_VARIANT_TYPE("a{sv}"));
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, &error))
{
// Not critical: ignore if fails
ChipLogError(Ble, "Failed to set discovery filters: %s", error->message);
g_clear_error(&error);
}
ChipLogProgress(Ble, "BLE initiating scan.");
if (!bluez_adapter1_call_start_discovery_sync(self->mAdapter, self->mCancellable, &error))
{
ChipLogError(Ble, "Failed to start discovery: %s", error->message);
g_error_free(error);
self->mIsScanning = false;
self->mDelegate->OnScanComplete();
}
return 0;
}
} // namespace Internal
} // namespace DeviceLayer
} // namespace chip
#endif // CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE