forked from project-chip/connectedhomeip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBluezConnection.cpp
397 lines (319 loc) · 15.1 KB
/
BluezConnection.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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
/*
*
* 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.
*/
#include "BluezConnection.h"
#include <cstring>
#include <limits>
#include <memory>
#include <gio/gio.h>
#include <glib.h>
#include <lib/support/CHIPMem.h>
#include <lib/support/CodeUtils.h>
#include <platform/ConnectivityManager.h>
#include <platform/GLibTypeDeleter.h>
#include <platform/Linux/dbus/bluez/DbusBluez.h>
#include <platform/PlatformManager.h>
#include <platform/internal/BLEManager.h>
#include <system/SystemPacketBuffer.h>
#include "BluezEndpoint.h"
#include "Types.h"
namespace chip {
namespace DeviceLayer {
namespace Internal {
namespace {
gboolean BluezIsServiceOnDevice(BluezGattService1 * aService, BluezDevice1 * aDevice)
{
const auto * servicePath = bluez_gatt_service1_get_device(aService);
const auto * devicePath = g_dbus_proxy_get_object_path(reinterpret_cast<GDBusProxy *>(aDevice));
return strcmp(servicePath, devicePath) == 0 ? TRUE : FALSE;
}
gboolean BluezIsCharOnService(BluezGattCharacteristic1 * aChar, BluezGattService1 * aService)
{
const auto * charPath = bluez_gatt_characteristic1_get_service(aChar);
const auto * servicePath = g_dbus_proxy_get_object_path(reinterpret_cast<GDBusProxy *>(aService));
ChipLogDetail(DeviceLayer, "Char %s on service %s", charPath, servicePath);
return strcmp(charPath, servicePath) == 0 ? TRUE : FALSE;
}
} // namespace
BluezConnection::BluezConnection(const BluezEndpoint & aEndpoint, BluezDevice1 & aDevice) :
mDevice(reinterpret_cast<BluezDevice1 *>(g_object_ref(&aDevice)))
{
Init(aEndpoint);
}
BluezConnection::IOChannel::~IOChannel()
{
if (mWatchSource != nullptr)
// Make sure the source is detached before destroying the channel.
g_source_destroy(mWatchSource.get());
}
BluezConnection::ConnectionDataBundle::ConnectionDataBundle(const BluezConnection & aConn,
const chip::System::PacketBufferHandle & aBuf) :
mConn(aConn),
mData(g_variant_new_fixed_array(G_VARIANT_TYPE_BYTE, aBuf->Start(), aBuf->DataLength(), sizeof(uint8_t)))
{}
CHIP_ERROR BluezConnection::Init(const BluezEndpoint & aEndpoint)
{
if (!aEndpoint.mIsCentral)
{
mService.reset(reinterpret_cast<BluezGattService1 *>(g_object_ref(aEndpoint.mService.get())));
mC1.reset(reinterpret_cast<BluezGattCharacteristic1 *>(g_object_ref(aEndpoint.mC1.get())));
mC2.reset(reinterpret_cast<BluezGattCharacteristic1 *>(g_object_ref(aEndpoint.mC2.get())));
}
else
{
for (BluezObject & object : aEndpoint.mObjectManager.GetObjects())
{
BluezGattService1 * service = bluez_object_get_gatt_service1(&object);
if (service != nullptr)
{
if ((BluezIsServiceOnDevice(service, mDevice.get())) == TRUE &&
(strcmp(bluez_gatt_service1_get_uuid(service), CHIP_BLE_UUID_SERVICE_STRING) == 0))
{
mService.reset(service);
break;
}
g_object_unref(service);
}
}
VerifyOrExit(mService, ChipLogError(DeviceLayer, "FAIL: NULL service in %s", __func__));
for (BluezObject & object : aEndpoint.mObjectManager.GetObjects())
{
BluezGattCharacteristic1 * char1 = bluez_object_get_gatt_characteristic1(&object);
if (char1 != nullptr)
{
if ((BluezIsCharOnService(char1, mService.get()) == TRUE) &&
(strcmp(bluez_gatt_characteristic1_get_uuid(char1), CHIP_PLAT_BLE_UUID_C1_STRING) == 0))
{
mC1.reset(char1);
}
else if ((BluezIsCharOnService(char1, mService.get()) == TRUE) &&
(strcmp(bluez_gatt_characteristic1_get_uuid(char1), CHIP_PLAT_BLE_UUID_C2_STRING) == 0))
{
mC2.reset(char1);
}
#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING
else if ((BluezIsCharOnService(char1, mService.get()) == TRUE) &&
(strcmp(bluez_gatt_characteristic1_get_uuid(char1), CHIP_PLAT_BLE_UUID_C3_STRING) == 0))
{
mC3.reset(char1);
}
#endif
else
{
g_object_unref(char1);
}
if (mC1 && mC2)
{
break;
}
}
}
VerifyOrExit(mC1, ChipLogError(DeviceLayer, "FAIL: NULL C1 in %s", __func__));
VerifyOrExit(mC2, ChipLogError(DeviceLayer, "FAIL: NULL C2 in %s", __func__));
}
exit:
return CHIP_NO_ERROR;
}
CHIP_ERROR BluezConnection::BluezDisconnect(BluezConnection * conn)
{
GAutoPtr<GError> error;
gboolean success;
ChipLogDetail(DeviceLayer, "%s peer=%s", __func__, conn->GetPeerAddress());
success = bluez_device1_call_disconnect_sync(conn->mDevice.get(), nullptr, &error.GetReceiver());
VerifyOrExit(success == TRUE, ChipLogError(DeviceLayer, "FAIL: Disconnect: %s", error->message));
exit:
return CHIP_NO_ERROR;
}
CHIP_ERROR BluezConnection::CloseConnection()
{
return PlatformMgrImpl().GLibMatterContextInvokeSync(BluezDisconnect, this);
}
const char * BluezConnection::GetPeerAddress() const
{
return bluez_device1_get_address(mDevice.get());
}
gboolean BluezConnection::WriteHandlerCallback(GIOChannel * aChannel, GIOCondition aCond, BluezConnection * apConn)
{
uint8_t buf[512 /* characteristic max size per BLE specification */];
bool isSuccess = false;
GVariant * newVal;
ssize_t len;
VerifyOrExit(!(aCond & G_IO_HUP), ChipLogError(DeviceLayer, "INFO: socket disconnected in %s", __func__));
VerifyOrExit(!(aCond & (G_IO_ERR | G_IO_NVAL)), ChipLogError(DeviceLayer, "INFO: socket error in %s", __func__));
VerifyOrExit(aCond == G_IO_IN, ChipLogError(DeviceLayer, "FAIL: error in %s", __func__));
ChipLogDetail(DeviceLayer, "C1 %s MTU: %d", __func__, apConn->GetMTU());
len = read(g_io_channel_unix_get_fd(aChannel), buf, sizeof(buf));
VerifyOrExit(len > 0, ChipLogError(DeviceLayer, "FAIL: short read in %s (%zd)", __func__, len));
// Casting len to size_t is safe, since we ensured that it's not negative.
newVal = g_variant_new_fixed_array(G_VARIANT_TYPE_BYTE, buf, static_cast<size_t>(len), sizeof(uint8_t));
bluez_gatt_characteristic1_set_value(apConn->mC1.get(), newVal);
BLEManagerImpl::HandleRXCharWrite(apConn, buf, static_cast<size_t>(len));
isSuccess = true;
exit:
return isSuccess ? G_SOURCE_CONTINUE : G_SOURCE_REMOVE;
}
void BluezConnection::SetupWriteHandler(int aSocketFd)
{
auto channel = g_io_channel_unix_new(aSocketFd);
g_io_channel_set_encoding(channel, nullptr, nullptr);
g_io_channel_set_close_on_unref(channel, TRUE);
g_io_channel_set_buffered(channel, FALSE);
auto watchSource = g_io_create_watch(channel, static_cast<GIOCondition>(G_IO_HUP | G_IO_IN | G_IO_ERR | G_IO_NVAL));
g_source_set_callback(watchSource, G_SOURCE_FUNC(WriteHandlerCallback), this, nullptr);
mC1Channel.mChannel.reset(channel);
mC1Channel.mWatchSource.reset(watchSource);
PlatformMgrImpl().GLibMatterContextAttachSource(watchSource);
}
gboolean BluezConnection::NotifyHandlerCallback(GIOChannel *, GIOCondition, BluezConnection *)
{
return G_SOURCE_REMOVE;
}
void BluezConnection::SetupNotifyHandler(int aSocketFd, bool aAdditionalAdvertising)
{
auto channel = g_io_channel_unix_new(aSocketFd);
g_io_channel_set_encoding(channel, nullptr, nullptr);
g_io_channel_set_close_on_unref(channel, TRUE);
g_io_channel_set_buffered(channel, FALSE);
auto watchSource = g_io_create_watch(channel, static_cast<GIOCondition>(G_IO_HUP | G_IO_ERR | G_IO_NVAL));
g_source_set_callback(watchSource, G_SOURCE_FUNC(NotifyHandlerCallback), this, nullptr);
#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING
if (aAdditionalAdvertising)
{
mC3Channel.mChannel.reset(channel);
mC3Channel.mWatchSource.reset(watchSource);
}
else
#endif
{
mC2Channel.mChannel.reset(channel);
mC2Channel.mWatchSource.reset(watchSource);
}
PlatformMgrImpl().GLibMatterContextAttachSource(watchSource);
}
// SendIndication callbacks
CHIP_ERROR BluezConnection::SendIndicationImpl(ConnectionDataBundle * data)
{
GAutoPtr<GError> error;
size_t len, written;
if (bluez_gatt_characteristic1_get_notify_acquired(data->mConn.mC2.get()) == TRUE)
{
auto * buf = static_cast<const char *>(g_variant_get_fixed_array(data->mData.get(), &len, sizeof(uint8_t)));
VerifyOrExit(len <= static_cast<size_t>(std::numeric_limits<gssize>::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<gssize>(len), &written,
&error.GetReceiver());
VerifyOrExit(status == G_IO_STATUS_NORMAL, ChipLogError(DeviceLayer, "FAIL: C2 Indicate: %s", error->message));
}
else
{
bluez_gatt_characteristic1_set_value(data->mConn.mC2.get(), data->mData.release());
}
exit:
return CHIP_NO_ERROR;
}
CHIP_ERROR BluezConnection::SendIndication(chip::System::PacketBufferHandle apBuf)
{
VerifyOrReturnError(!apBuf.IsNull(), CHIP_ERROR_INVALID_ARGUMENT, ChipLogError(DeviceLayer, "apBuf is NULL in %s", __func__));
VerifyOrReturnError(mC2, CHIP_ERROR_INTERNAL, ChipLogError(DeviceLayer, "C2 is NULL in %s", __func__));
ConnectionDataBundle bundle(*this, apBuf);
return PlatformMgrImpl().GLibMatterContextInvokeSync(SendIndicationImpl, &bundle);
}
// SendWriteRequest callbacks
void BluezConnection::SendWriteRequestDone(GObject * aObject, GAsyncResult * aResult, gpointer apConnection)
{
auto * pC1 = reinterpret_cast<BluezGattCharacteristic1 *>(aObject);
GAutoPtr<GError> error;
gboolean success = bluez_gatt_characteristic1_call_write_value_finish(pC1, aResult, &error.GetReceiver());
VerifyOrReturn(success == TRUE, ChipLogError(DeviceLayer, "FAIL: SendWriteRequest : %s", error->message));
BLEManagerImpl::HandleWriteComplete(static_cast<BluezConnection *>(apConnection));
}
CHIP_ERROR BluezConnection::SendWriteRequestImpl(ConnectionDataBundle * data)
{
GVariantBuilder optionsBuilder;
g_variant_builder_init(&optionsBuilder, G_VARIANT_TYPE_ARRAY);
g_variant_builder_add(&optionsBuilder, "{sv}", "type", g_variant_new_string("request"));
auto options = g_variant_builder_end(&optionsBuilder);
bluez_gatt_characteristic1_call_write_value(data->mConn.mC1.get(), data->mData.release(), options, nullptr,
SendWriteRequestDone, const_cast<BluezConnection *>(&data->mConn));
return CHIP_NO_ERROR;
}
CHIP_ERROR BluezConnection::SendWriteRequest(chip::System::PacketBufferHandle apBuf)
{
VerifyOrReturnError(!apBuf.IsNull(), CHIP_ERROR_INVALID_ARGUMENT, ChipLogError(DeviceLayer, "apBuf is NULL in %s", __func__));
VerifyOrReturnError(mC1, CHIP_ERROR_INTERNAL, ChipLogError(DeviceLayer, "C1 is NULL in %s", __func__));
ConnectionDataBundle bundle(*this, apBuf);
return PlatformMgrImpl().GLibMatterContextInvokeSync(SendWriteRequestImpl, &bundle);
}
// SubscribeCharacteristic callbacks
void BluezConnection::OnCharacteristicChanged(GDBusProxy * aInterface, GVariant * aChangedProperties,
const gchar * const * aInvalidatedProps, gpointer apConnection)
{
GAutoPtr<GVariant> dataValue(g_variant_lookup_value(aChangedProperties, "Value", G_VARIANT_TYPE_BYTESTRING));
VerifyOrReturn(dataValue != nullptr);
size_t bufferLen;
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(static_cast<BluezConnection *>(apConnection), static_cast<const uint8_t *>(buffer),
bufferLen);
}
void BluezConnection::SubscribeCharacteristicDone(GObject * aObject, GAsyncResult * aResult, gpointer apConnection)
{
auto * pC2 = reinterpret_cast<BluezGattCharacteristic1 *>(aObject);
GAutoPtr<GError> error;
gboolean success = bluez_gatt_characteristic1_call_start_notify_finish(pC2, aResult, &error.GetReceiver());
VerifyOrReturn(success == TRUE, ChipLogError(DeviceLayer, "FAIL: SubscribeCharacteristic : %s", error->message));
BLEManagerImpl::HandleSubscribeOpComplete(static_cast<BluezConnection *>(apConnection), true);
}
CHIP_ERROR BluezConnection::SubscribeCharacteristicImpl(BluezConnection * connection)
{
BluezGattCharacteristic1 * pC2 = connection->mC2.get();
VerifyOrExit(pC2 != nullptr, ChipLogError(DeviceLayer, "C2 is NULL in %s", __func__));
// Get notifications on the TX characteristic change (e.g. indication is received)
g_signal_connect(pC2, "g-properties-changed", G_CALLBACK(OnCharacteristicChanged), connection);
bluez_gatt_characteristic1_call_start_notify(pC2, nullptr, SubscribeCharacteristicDone, connection);
exit:
return CHIP_NO_ERROR;
}
CHIP_ERROR BluezConnection::SubscribeCharacteristic()
{
return PlatformMgrImpl().GLibMatterContextInvokeSync(SubscribeCharacteristicImpl, this);
}
// UnsubscribeCharacteristic callbacks
void BluezConnection::UnsubscribeCharacteristicDone(GObject * aObject, GAsyncResult * aResult, gpointer apConnection)
{
auto * pC2 = reinterpret_cast<BluezGattCharacteristic1 *>(aObject);
GAutoPtr<GError> error;
gboolean success = bluez_gatt_characteristic1_call_stop_notify_finish(pC2, aResult, &error.GetReceiver());
VerifyOrReturn(success == TRUE, ChipLogError(DeviceLayer, "FAIL: UnsubscribeCharacteristic : %s", error->message));
// Stop listening to the TX characteristic changes
g_signal_handlers_disconnect_by_data(pC2, apConnection);
BLEManagerImpl::HandleSubscribeOpComplete(static_cast<BluezConnection *>(apConnection), false);
}
CHIP_ERROR BluezConnection::UnsubscribeCharacteristicImpl(BluezConnection * connection)
{
BluezGattCharacteristic1 * pC2 = connection->mC2.get();
VerifyOrExit(pC2 != nullptr, ChipLogError(DeviceLayer, "C2 is NULL in %s", __func__));
bluez_gatt_characteristic1_call_stop_notify(pC2, nullptr, UnsubscribeCharacteristicDone, connection);
exit:
return CHIP_NO_ERROR;
}
CHIP_ERROR BluezConnection::UnsubscribeCharacteristic()
{
return PlatformMgrImpl().GLibMatterContextInvokeSync(UnsubscribeCharacteristicImpl, this);
}
} // namespace Internal
} // namespace DeviceLayer
} // namespace chip