1/****************************************************************************
2**
3** Copyright (C) 2017 The Qt Company Ltd.
4** Contact: https://www.qt.io/licensing/
5**
6** This file is part of the QtBluetooth module of the Qt Toolkit.
7**
8** $QT_BEGIN_LICENSE:LGPL$
9** Commercial License Usage
10** Licensees holding valid commercial Qt licenses may use this file in
11** accordance with the commercial license agreement provided with the
12** Software or, alternatively, in accordance with the terms contained in
13** a written agreement between you and The Qt Company. For licensing terms
14** and conditions see https://www.qt.io/terms-conditions. For further
15** information use the contact form at https://www.qt.io/contact-us.
16**
17** GNU Lesser General Public License Usage
18** Alternatively, this file may be used under the terms of the GNU Lesser
19** General Public License version 3 as published by the Free Software
20** Foundation and appearing in the file LICENSE.LGPL3 included in the
21** packaging of this file. Please review the following information to
22** ensure the GNU Lesser General Public License version 3 requirements
23** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
24**
25** GNU General Public License Usage
26** Alternatively, this file may be used under the terms of the GNU
27** General Public License version 2.0 or (at your option) the GNU General
28** Public license version 3 or any later version approved by the KDE Free
29** Qt Foundation. The licenses are as published by the Free Software
30** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
31** included in the packaging of this file. Please review the following
32** information to ensure the GNU General Public License requirements will
33** be met: https://www.gnu.org/licenses/gpl-2.0.html and
34** https://www.gnu.org/licenses/gpl-3.0.html.
35**
36** $QT_END_LICENSE$
37**
38****************************************************************************/
39
40#include "qlowenergycontrollerbase_p.h"
41
42#include <QtCore/QLoggingCategory>
43
44#include <QtBluetooth/QBluetoothLocalDevice>
45#include <QtBluetooth/QLowEnergyCharacteristicData>
46#include <QtBluetooth/QLowEnergyDescriptorData>
47#include <QtBluetooth/QLowEnergyServiceData>
48
49QT_BEGIN_NAMESPACE
50
51Q_DECLARE_LOGGING_CATEGORY(QT_BT)
52
53QLowEnergyControllerPrivate::QLowEnergyControllerPrivate()
54 : QObject()
55{
56}
57
58QLowEnergyControllerPrivate::~QLowEnergyControllerPrivate()
59{
60}
61
62bool QLowEnergyControllerPrivate::isValidLocalAdapter()
63{
64#if defined(QT_WINRT_BLUETOOTH) || defined(Q_OS_DARWIN)
65 return true;
66#endif
67 if (localAdapter.isNull())
68 return false;
69
70 const QList<QBluetoothHostInfo> foundAdapters = QBluetoothLocalDevice::allDevices();
71 bool adapterFound = false;
72
73 for (const QBluetoothHostInfo &info : foundAdapters) {
74 if (info.address() == localAdapter) {
75 adapterFound = true;
76 break;
77 }
78 }
79
80 return adapterFound;
81}
82
83
84void QLowEnergyControllerPrivate::setError(
85 QLowEnergyController::Error newError)
86{
87 Q_Q(QLowEnergyController);
88 error = newError;
89
90 switch (newError) {
91 case QLowEnergyController::UnknownRemoteDeviceError:
92 errorString = QLowEnergyController::tr("Remote device cannot be found");
93 break;
94 case QLowEnergyController::InvalidBluetoothAdapterError:
95 errorString = QLowEnergyController::tr("Cannot find local adapter");
96 break;
97 case QLowEnergyController::NetworkError:
98 errorString = QLowEnergyController::tr("Error occurred during connection I/O");
99 break;
100 case QLowEnergyController::ConnectionError:
101 errorString = QLowEnergyController::tr("Error occurred trying to connect to remote device.");
102 break;
103 case QLowEnergyController::AdvertisingError:
104 errorString = QLowEnergyController::tr("Error occurred trying to start advertising");
105 break;
106 case QLowEnergyController::RemoteHostClosedError:
107 errorString = QLowEnergyController::tr("Remote device closed the connection");
108 break;
109 case QLowEnergyController::AuthorizationError:
110 errorString = QLowEnergyController::tr("Failed to authorize on the remote device");
111 break;
112 case QLowEnergyController::NoError:
113 return;
114 default:
115 case QLowEnergyController::UnknownError:
116 errorString = QLowEnergyController::tr("Unknown Error");
117 break;
118 }
119
120 emit q->error(newError);
121}
122
123void QLowEnergyControllerPrivate::setState(
124 QLowEnergyController::ControllerState newState)
125{
126 Q_Q(QLowEnergyController);
127 if (state == newState)
128 return;
129
130 state = newState;
131 if (state == QLowEnergyController::UnconnectedState
132 && role == QLowEnergyController::PeripheralRole) {
133 remoteDevice.clear();
134 }
135 emit q->stateChanged(state);
136}
137
138QSharedPointer<QLowEnergyServicePrivate> QLowEnergyControllerPrivate::serviceForHandle(
139 QLowEnergyHandle handle)
140{
141 ServiceDataMap &currentList = serviceList;
142 if (role == QLowEnergyController::PeripheralRole)
143 currentList = localServices;
144
145 const QList<QSharedPointer<QLowEnergyServicePrivate>> values = currentList.values();
146 for (auto service: values)
147 if (service->startHandle <= handle && handle <= service->endHandle)
148 return service;
149
150 return QSharedPointer<QLowEnergyServicePrivate>();
151}
152
153/*!
154 Returns a valid characteristic if the given handle is the
155 handle of the characteristic itself or one of its descriptors
156 */
157QLowEnergyCharacteristic QLowEnergyControllerPrivate::characteristicForHandle(
158 QLowEnergyHandle handle)
159{
160 QSharedPointer<QLowEnergyServicePrivate> service = serviceForHandle(handle);
161 if (service.isNull())
162 return QLowEnergyCharacteristic();
163
164 if (service->characteristicList.isEmpty())
165 return QLowEnergyCharacteristic();
166
167 // check whether it is the handle of a characteristic header
168 if (service->characteristicList.contains(handle))
169 return QLowEnergyCharacteristic(service, handle);
170
171 // check whether it is the handle of the characteristic value or its descriptors
172 QList<QLowEnergyHandle> charHandles = service->characteristicList.keys();
173 std::sort(charHandles.begin(), charHandles.end());
174 for (int i = charHandles.size() - 1; i >= 0; i--) {
175 if (charHandles.at(i) > handle)
176 continue;
177
178 return QLowEnergyCharacteristic(service, charHandles.at(i));
179 }
180
181 return QLowEnergyCharacteristic();
182}
183
184/*!
185 Returns a valid descriptor if \a handle belongs to a descriptor;
186 otherwise an invalid one.
187 */
188QLowEnergyDescriptor QLowEnergyControllerPrivate::descriptorForHandle(
189 QLowEnergyHandle handle)
190{
191 const QLowEnergyCharacteristic matchingChar = characteristicForHandle(handle);
192 if (!matchingChar.isValid())
193 return QLowEnergyDescriptor();
194
195 const QLowEnergyServicePrivate::CharData charData = matchingChar.
196 d_ptr->characteristicList[matchingChar.attributeHandle()];
197
198 if (charData.descriptorList.contains(handle))
199 return QLowEnergyDescriptor(matchingChar.d_ptr, matchingChar.attributeHandle(),
200 handle);
201
202 return QLowEnergyDescriptor();
203}
204
205/*!
206 Returns the length of the updated characteristic value.
207 */
208quint16 QLowEnergyControllerPrivate::updateValueOfCharacteristic(
209 QLowEnergyHandle charHandle,const QByteArray &value, bool appendValue)
210{
211 QSharedPointer<QLowEnergyServicePrivate> service = serviceForHandle(charHandle);
212 if (!service.isNull()) {
213 CharacteristicDataMap::iterator charIt = service->characteristicList.find(charHandle);
214 if (charIt != service->characteristicList.end()) {
215 QLowEnergyServicePrivate::CharData &charDetails = charIt.value();
216
217 if (appendValue)
218 charDetails.value += value;
219 else
220 charDetails.value = value;
221
222 return charDetails.value.size();
223 }
224 }
225
226 return 0;
227}
228
229/*!
230 Returns the length of the updated descriptor value.
231 */
232quint16 QLowEnergyControllerPrivate::updateValueOfDescriptor(
233 QLowEnergyHandle charHandle, QLowEnergyHandle descriptorHandle,
234 const QByteArray &value, bool appendValue)
235{
236 QSharedPointer<QLowEnergyServicePrivate> service = serviceForHandle(charHandle);
237 if (!service.isNull()) {
238 CharacteristicDataMap::iterator charIt = service->characteristicList.find(charHandle);
239 if (charIt != service->characteristicList.end()) {
240 QLowEnergyServicePrivate::CharData &charDetails = charIt.value();
241
242 DescriptorDataMap::iterator descIt = charDetails.descriptorList.find(descriptorHandle);
243 if (descIt != charDetails.descriptorList.end()) {
244 QLowEnergyServicePrivate::DescData &descDetails = descIt.value();
245
246 if (appendValue)
247 descDetails.value += value;
248 else
249 descDetails.value = value;
250
251 return descDetails.value.size();
252 }
253 }
254 }
255
256 return 0;
257}
258
259void QLowEnergyControllerPrivate::invalidateServices()
260{
261 for (QSharedPointer<QLowEnergyServicePrivate> service : serviceList.values())
262 service->setController(nullptr);
263
264 for (QSharedPointer<QLowEnergyServicePrivate> service : localServices.values())
265 service->setController(nullptr);
266
267 serviceList.clear();
268 localServices.clear();
269 lastLocalHandle = {};
270}
271
272QLowEnergyService *QLowEnergyControllerPrivate::addServiceHelper(
273 const QLowEnergyServiceData &service)
274{
275 // Spec says services "should" be grouped by uuid length (16-bit first, then 128-bit).
276 // Since this is not mandatory, we ignore it here and let the caller take responsibility
277 // for it.
278
279 const auto servicePrivate = QSharedPointer<QLowEnergyServicePrivate>::create();
280 servicePrivate->setController(this);
281 servicePrivate->state = QLowEnergyService::LocalService;
282 servicePrivate->uuid = service.uuid();
283 servicePrivate->type = service.type() == QLowEnergyServiceData::ServiceTypePrimary
284 ? QLowEnergyService::PrimaryService : QLowEnergyService::IncludedService;
285 const QList<QLowEnergyService *> includedServices = service.includedServices();
286 for (QLowEnergyService * const includedService : includedServices) {
287 servicePrivate->includedServices << includedService->serviceUuid();
288 includedService->d_ptr->type |= QLowEnergyService::IncludedService;
289 }
290
291 // Spec v4.2, Vol 3, Part G, Section 3.
292 const QLowEnergyHandle oldLastHandle = this->lastLocalHandle;
293 servicePrivate->startHandle = ++this->lastLocalHandle; // Service declaration.
294 this->lastLocalHandle += servicePrivate->includedServices.count(); // Include declarations.
295 const QList<QLowEnergyCharacteristicData> characteristics = service.characteristics();
296 for (const QLowEnergyCharacteristicData &cd : characteristics) {
297 const QLowEnergyHandle declHandle = ++this->lastLocalHandle;
298 QLowEnergyServicePrivate::CharData charData;
299 charData.valueHandle = ++this->lastLocalHandle;
300 charData.uuid = cd.uuid();
301 charData.properties = cd.properties();
302 charData.value = cd.value();
303 const QList<QLowEnergyDescriptorData> descriptors = cd.descriptors();
304 for (const QLowEnergyDescriptorData &dd : descriptors) {
305 QLowEnergyServicePrivate::DescData descData;
306 descData.uuid = dd.uuid();
307 descData.value = dd.value();
308 charData.descriptorList.insert(++this->lastLocalHandle, descData);
309 }
310 servicePrivate->characteristicList.insert(declHandle, charData);
311 }
312 servicePrivate->endHandle = this->lastLocalHandle;
313 const bool handleOverflow = this->lastLocalHandle <= oldLastHandle;
314 if (handleOverflow) {
315 qCWarning(QT_BT) << "Not enough attribute handles left to create this service";
316 this->lastLocalHandle = oldLastHandle;
317 return nullptr;
318 }
319
320 if (localServices.contains(servicePrivate->uuid)) {
321 qWarning() << "Overriding existing local service with uuid"
322 << servicePrivate->uuid;
323 }
324 this->localServices.insert(servicePrivate->uuid, servicePrivate);
325
326 this->addToGenericAttributeList(service, servicePrivate->startHandle);
327 return new QLowEnergyService(servicePrivate);
328}
329
330QT_END_NAMESPACE
331