1 /*
2 * Copyright (C) 2021-2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 #include "bluetooth_ble_central_manager.h"
16 #include "bluetooth_ble_central_manager_callback_stub.h"
17 #include "bluetooth_def.h"
18 #include "bluetooth_errorcode.h"
19 #include "bluetooth_host.h"
20 #include "bluetooth_log.h"
21 #include "bluetooth_observer_list.h"
22 #include "bluetooth_utils.h"
23 #include "i_bluetooth_ble_central_manager.h"
24 #include "iservice_registry.h"
25 #include "system_ability_definition.h"
26
27 namespace OHOS {
28 namespace Bluetooth {
29 std::mutex g_bleManagerProxyMutex;
30 struct BleCentralManager::impl {
31 impl();
32 ~impl();
33
34 bool MatchesScanFilters(const BluetoothBleScanResult &result);
35 bool MatchesScanFilter(const BluetoothBleScanFilter &filter, const BluetoothBleScanResult &result);
36 bool MatchesAddrAndName(const BluetoothBleScanFilter &filter, const BluetoothBleScanResult &result);
37 bool MatchesServiceUuids(const BluetoothBleScanFilter &filter, const BluetoothBleScanResult &result);
38 bool MatchesUuid(bluetooth::Uuid filterUuid, bluetooth::Uuid uuid, bluetooth::Uuid uuidMask);
39 bool MatchesManufacturerDatas(const BluetoothBleScanFilter &filter, const BluetoothBleScanResult &result);
40 bool MatchesServiceDatas(const BluetoothBleScanFilter &filter, const BluetoothBleScanResult &result);
41 std::string ParseServiceData(bluetooth::Uuid uuid, std::string data);
42 bool MatchesData(std::vector<uint8_t> fData, std::string rData, std::vector<uint8_t> dataMask);
43 bool InitBleCentralManagerProxy(void);
44 void ConvertBleScanSetting(const BleScanSettings &inSettings, BluetoothBleScanSettings &outSetting);
45 void ConvertBleScanFilter(const std::vector<BleScanFilter> &filters,
46 std::vector<BluetoothBleScanFilter> &bluetoothBleScanFilters);
47 void ConvertAdvertiserSetting(const BleAdvertiserSettings &inSettings, BluetoothBleAdvertiserSettings &outSettings);
48 void ConvertActiveDeviceInfo(const std::vector<BleActiveDeviceInfo> &inDeviceInfos,
49 std::vector<BluetoothActiveDeviceInfo> &outDeviceInfos);
50
51 class BluetoothBleCentralManagerCallbackImp : public BluetoothBleCentralManagerCallBackStub {
52 public:
BluetoothBleCentralManagerCallbackImp(BleCentralManager::impl & bleCentralManger)53 explicit BluetoothBleCentralManagerCallbackImp(BleCentralManager::impl &bleCentralManger)
54 : bleCentralManger_(bleCentralManger){};
55 ~BluetoothBleCentralManagerCallbackImp() override = default;
OnScanCallback(const BluetoothBleScanResult & result)56 void OnScanCallback(const BluetoothBleScanResult &result) override
57 {
58 {
59 std::lock_guard<std::mutex> lock(bleCentralManger_.blesCanFiltersMutex_);
60 if (!bleCentralManger_.bleScanFilters_.empty() && bleCentralManger_.IsNeedFilterMatches_ &&
61 !bleCentralManger_.MatchesScanFilters(result)) {
62 return;
63 }
64 }
65
66 bleCentralManger_.callbacks_.ForEach([&result](std::shared_ptr<BleCentralManagerCallback> observer) {
67 BluetoothBleScanResult tempResult(result);
68 BleScanResult scanResult;
69 for (auto &manufacturerData : tempResult.GetManufacturerData()) {
70 scanResult.AddManufacturerData(manufacturerData.first, manufacturerData.second);
71 }
72
73 for (auto &serviceUuidData : tempResult.GetServiceUuids()) {
74 UUID uuid = UUID::ConvertFrom128Bits(serviceUuidData.ConvertTo128Bits());
75 scanResult.AddServiceUuid(uuid);
76 }
77
78 for (auto &serviceData : tempResult.GetServiceData()) {
79 UUID uuid = UUID::ConvertFrom128Bits(serviceData.first.ConvertTo128Bits());
80 scanResult.AddServiceData(uuid, serviceData.second);
81 }
82
83 scanResult.SetAdvertiseFlag(tempResult.GetAdvertiseFlag());
84 scanResult.SetRssi(tempResult.GetRssi());
85 scanResult.SetConnectable(tempResult.IsConnectable());
86 BluetoothRemoteDevice device(tempResult.GetPeripheralDevice().GetAddress(), BT_TRANSPORT_BLE);
87 scanResult.SetPeripheralDevice(device);
88 scanResult.SetPayload(tempResult.GetPayload());
89 scanResult.SetName(tempResult.GetName());
90
91 observer->OnScanCallback(scanResult);
92 });
93 }
OnBleBatchScanResultsEvent(std::vector<BluetoothBleScanResult> & results)94 void OnBleBatchScanResultsEvent(std::vector<BluetoothBleScanResult> &results) override
95 {
96 HILOGI("enter");
97 bleCentralManger_.callbacks_.ForEach([&results](std::shared_ptr<BleCentralManagerCallback> observer) {
98 std::vector<BleScanResult> scanResults;
99 for (auto &result : results) {
100 BleScanResult scanResult;
101 for (auto &manufacturerData : result.GetManufacturerData()) {
102 scanResult.AddManufacturerData(manufacturerData.first, manufacturerData.second);
103 }
104
105 for (auto &serviceData : result.GetServiceData()) {
106 UUID uuid = UUID::ConvertFrom128Bits(serviceData.first.ConvertTo128Bits());
107 scanResult.AddServiceData(uuid, serviceData.second);
108 }
109
110 for (auto &serviceUuidData : result.GetServiceUuids()) {
111 UUID uuid = UUID::ConvertFrom128Bits(serviceUuidData.ConvertTo128Bits());
112 scanResult.AddServiceUuid(uuid);
113 }
114
115 scanResult.SetAdvertiseFlag(result.GetAdvertiseFlag());
116 scanResult.SetConnectable(result.IsConnectable());
117 scanResult.SetRssi(result.GetRssi());
118 BluetoothRemoteDevice device(result.GetPeripheralDevice().GetAddress(), BT_TRANSPORT_BLE);
119 scanResult.SetPeripheralDevice(device);
120 scanResult.SetPayload(result.GetPayload());
121
122 scanResults.push_back(scanResult);
123 }
124
125 observer->OnBleBatchScanResultsEvent(scanResults);
126 });
127 }
128
OnStartOrStopScanEvent(int resultCode,bool isStartScan)129 void OnStartOrStopScanEvent(int resultCode, bool isStartScan) override
130 {
131 HILOGD("resultCode: %{public}d, isStartScan: %{public}d", resultCode, isStartScan);
132 bleCentralManger_.callbacks_.ForEach(
133 [resultCode, isStartScan](std::shared_ptr<BleCentralManagerCallback> observer) {
134 observer->OnStartOrStopScanEvent(resultCode, isStartScan);
135 });
136 }
137
OnNotifyMsgReportFromLpDevice(const bluetooth::Uuid & uuid,int msgType,const std::vector<uint8_t> & value)138 void OnNotifyMsgReportFromLpDevice(const bluetooth::Uuid &uuid, int msgType,
139 const std::vector<uint8_t> &value) override
140 {
141 bleCentralManger_.callbacks_.ForEach(
142 [uuid, msgType, value](std::shared_ptr<BleCentralManagerCallback> observer) {
143 UUID btUuid = UUID::ConvertFrom128Bits(uuid.ConvertTo128Bits());
144 observer->OnNotifyMsgReportFromLpDevice(btUuid, msgType, value);
145 });
146 }
147
148 private:
149 BleCentralManager::impl &bleCentralManger_;
150 BLUETOOTH_DISALLOW_COPY_AND_ASSIGN(BluetoothBleCentralManagerCallbackImp);
151 };
152 sptr<BluetoothBleCentralManagerCallbackImp> callbackImp_ = nullptr;
153
154 sptr<IBluetoothBleCentralManager> proxy_ = nullptr;
155 BluetoothObserverList<BleCentralManagerCallback> callbacks_;
156
157 std::vector<BluetoothBleScanFilter> bleScanFilters_;
158 bool IsNeedFilterMatches_ = true;
159 std::mutex blesCanFiltersMutex_;
160
161 class BleCentralManagerDeathRecipient;
162 sptr<BleCentralManagerDeathRecipient> deathRecipient_ = nullptr;
163
164 int32_t scannerId_ = BLE_SCAN_INVALID_ID;
165 bool enableRandomAddrMode_ = true;
166 };
167
168 class BleCentralManager::impl::BleCentralManagerDeathRecipient final : public IRemoteObject::DeathRecipient {
169 public:
BleCentralManagerDeathRecipient(BleCentralManager::impl & impl)170 explicit BleCentralManagerDeathRecipient(BleCentralManager::impl &impl) : owner_(impl) {};
171 ~BleCentralManagerDeathRecipient() final = default;
172 BLUETOOTH_DISALLOW_COPY_AND_ASSIGN(BleCentralManagerDeathRecipient);
173
OnRemoteDied(const wptr<IRemoteObject> & remote)174 void OnRemoteDied(const wptr<IRemoteObject> &remote) final
175 {
176 HILOGI("enter");
177 std::lock_guard<std::mutex> lock(g_bleManagerProxyMutex);
178 if (!owner_.proxy_) {
179 return;
180 }
181 owner_.scannerId_ = BLE_SCAN_INVALID_ID;
182 owner_.proxy_ = nullptr;
183 }
184
185 private:
186 BleCentralManager::impl &owner_;
187 };
188
InitBleCentralManagerProxy(void)189 bool BleCentralManager::impl::InitBleCentralManagerProxy(void)
190 {
191 std::lock_guard<std::mutex> lock(g_bleManagerProxyMutex);
192 if (proxy_) {
193 return true;
194 }
195 HILOGI("enter");
196 proxy_ = GetRemoteProxy<IBluetoothBleCentralManager>(BLE_CENTRAL_MANAGER_SERVER);
197 if (!proxy_) {
198 HILOGE("get bleCentralManager proxy_ failed");
199 return false;
200 }
201 callbackImp_ = new BluetoothBleCentralManagerCallbackImp(*this);
202 proxy_->RegisterBleCentralManagerCallback(scannerId_, enableRandomAddrMode_, callbackImp_);
203 HILOGI("RegisterBleCentralManagerCallback, scannerId: %{public}d", scannerId_);
204
205 deathRecipient_ = new BleCentralManagerDeathRecipient(*this);
206 proxy_->AsObject()->AddDeathRecipient(deathRecipient_);
207 return true;
208 }
209
impl()210 BleCentralManager::impl::impl()
211 {}
212
MatchesScanFilters(const BluetoothBleScanResult & result)213 bool BleCentralManager::impl::MatchesScanFilters(const BluetoothBleScanResult &result)
214 {
215 for (const auto &filter : bleScanFilters_) {
216 if (!MatchesScanFilter(filter, result)) {
217 continue;
218 }
219 return true;
220 }
221 return false;
222 }
223
MatchesScanFilter(const BluetoothBleScanFilter & filter,const BluetoothBleScanResult & result)224 bool BleCentralManager::impl::MatchesScanFilter(const BluetoothBleScanFilter &filter,
225 const BluetoothBleScanResult &result)
226 {
227 if (!MatchesAddrAndName(filter, result)) {
228 return false;
229 }
230
231 if (filter.HasServiceUuid() && !MatchesServiceUuids(filter, result)) {
232 return false;
233 }
234
235 if (!MatchesManufacturerDatas(filter, result)) {
236 return false;
237 }
238
239 if (!MatchesServiceDatas(filter, result)) {
240 return false;
241 }
242
243 return true;
244 }
245
MatchesAddrAndName(const BluetoothBleScanFilter & filter,const BluetoothBleScanResult & result)246 bool BleCentralManager::impl::MatchesAddrAndName(const BluetoothBleScanFilter &filter,
247 const BluetoothBleScanResult &result)
248 {
249 std::string address = result.GetPeripheralDevice().GetAddress();
250 if (address.empty()) {
251 return false;
252 }
253
254 std::string deviceId = filter.GetDeviceId();
255 if (!deviceId.empty() && deviceId != address) {
256 return false;
257 }
258
259 std::string name = filter.GetName();
260 if (!name.empty()) {
261 std::string rName = result.GetName();
262 if (rName.empty() || rName != name) {
263 return false;
264 }
265 }
266
267 return true;
268 }
269
MatchesServiceUuids(const BluetoothBleScanFilter & filter,const BluetoothBleScanResult & result)270 bool BleCentralManager::impl::MatchesServiceUuids(const BluetoothBleScanFilter &filter,
271 const BluetoothBleScanResult &result)
272 {
273 std::vector<bluetooth::Uuid> rUuids = result.GetServiceUuids();
274 if (rUuids.empty()) {
275 return false;
276 }
277
278 bluetooth::Uuid filterUuid = filter.GetServiceUuid();
279 bool hasUuidMask = filter.HasServiceUuidMask();
280
281 for (auto &uuid : rUuids) {
282 if (!hasUuidMask) {
283 if (filterUuid.operator==(uuid)) {
284 return true;
285 }
286 } else {
287 bluetooth::Uuid uuidMask = filter.GetServiceUuidMask();
288 if (MatchesUuid(filterUuid, uuid, uuidMask)) {
289 return true;
290 }
291 }
292 }
293 return false;
294 }
295
MatchesUuid(bluetooth::Uuid filterUuid,bluetooth::Uuid uuid,bluetooth::Uuid uuidMask)296 bool BleCentralManager::impl::MatchesUuid(bluetooth::Uuid filterUuid, bluetooth::Uuid uuid, bluetooth::Uuid uuidMask)
297 {
298 HILOGI("enter");
299 uint8_t uuid128[bluetooth::Uuid::UUID128_BYTES_TYPE];
300 uint8_t uuidMask128[bluetooth::Uuid::UUID128_BYTES_TYPE];
301 uint8_t resultUuid128[bluetooth::Uuid::UUID128_BYTES_TYPE];
302 if (!filterUuid.ConvertToBytesLE(uuid128)) {
303 HILOGE("Convert filter uuid faild.");
304 return false;
305 }
306 if (!uuidMask.ConvertToBytesLE(uuidMask128)) {
307 HILOGE("Convert uuid mask faild.");
308 return false;
309 }
310 if (!uuid.ConvertToBytesLE(resultUuid128)) {
311 HILOGE("Convert result uuid faild.");
312 return false;
313 }
314 size_t maskLength = sizeof(uuidMask128);
315 if (maskLength <= 0) {
316 return false;
317 }
318
319 for (size_t i = 0; i < maskLength; i++) {
320 if ((uuid128[i] & uuidMask128[i]) != (resultUuid128[i] & uuidMask128[i])) {
321 return false;
322 }
323 }
324
325 return true;
326 }
327
MatchesManufacturerDatas(const BluetoothBleScanFilter & filter,const BluetoothBleScanResult & result)328 bool BleCentralManager::impl::MatchesManufacturerDatas(const BluetoothBleScanFilter &filter,
329 const BluetoothBleScanResult &result)
330 {
331 uint16_t manufacturerId = filter.GetManufacturerId();
332 std::vector<uint8_t> data = filter.GetManufactureData();
333 if (data.size() == 0) {
334 return true;
335 }
336
337 std::vector<uint8_t> dataMask = filter.GetManufactureDataMask();
338
339 for (auto &manufacturerData : result.GetManufacturerData()) {
340 if (manufacturerId != manufacturerData.first) {
341 continue;
342 }
343
344 if (MatchesData(data, manufacturerData.second, dataMask)) {
345 return true;
346 }
347 }
348 return false;
349 }
350
MatchesServiceDatas(const BluetoothBleScanFilter & filter,const BluetoothBleScanResult & result)351 bool BleCentralManager::impl::MatchesServiceDatas(const BluetoothBleScanFilter &filter,
352 const BluetoothBleScanResult &result)
353 {
354 std::vector<uint8_t> data = filter.GetServiceData();
355 if (data.size() == 0) {
356 return true;
357 }
358
359 std::vector<uint8_t> dataMask = filter.GetServiceDataMask();
360
361 for (auto &serviceData : result.GetServiceData()) {
362 std::string rSData = ParseServiceData(serviceData.first, serviceData.second);
363 if (MatchesData(data, rSData, dataMask)) {
364 return true;
365 }
366 }
367 return false;
368 }
369
ParseServiceData(bluetooth::Uuid uuid,std::string data)370 std::string BleCentralManager::impl::ParseServiceData(bluetooth::Uuid uuid, std::string data)
371 {
372 std::string tmpServcieData;
373 int uuidType = uuid.GetUuidType();
374 switch (uuidType) {
375 case bluetooth::Uuid::UUID16_BYTES_TYPE: {
376 uint16_t uuid16 = uuid.ConvertTo16Bits();
377 tmpServcieData = std::string(reinterpret_cast<char *>(&uuid16), BLE_UUID_LEN_16);
378 break;
379 }
380 case bluetooth::Uuid::UUID32_BYTES_TYPE: {
381 uint32_t uuid32 = uuid.ConvertTo32Bits();
382 tmpServcieData = std::string(reinterpret_cast<char *>(&uuid32), BLE_UUID_LEN_32);
383 break;
384 }
385 case bluetooth::Uuid::UUID128_BYTES_TYPE: {
386 uint8_t uuid128[bluetooth::Uuid::UUID128_BYTES_TYPE];
387 if (!uuid.ConvertToBytesLE(uuid128)) {
388 HILOGE("Convert filter uuid faild.");
389 }
390 tmpServcieData = std::string(reinterpret_cast<char *>(&uuid128), BLE_UUID_LEN_128);
391 break;
392 }
393 default:
394 break;
395 }
396 return tmpServcieData + data;
397 }
398
MatchesData(std::vector<uint8_t> fData,std::string rData,std::vector<uint8_t> dataMask)399 bool BleCentralManager::impl::MatchesData(std::vector<uint8_t> fData, std::string rData, std::vector<uint8_t> dataMask)
400 {
401 if (rData.empty()) {
402 return false;
403 }
404
405 size_t length = fData.size();
406 std::vector<uint8_t> vec(rData.begin(), rData.end());
407 if (vec.size() < length) {
408 return false;
409 }
410
411 if (dataMask.empty() || dataMask.size() != length) {
412 for (size_t i = 0; i < length; i++) {
413 if (fData[i] != vec[i]) {
414 return false;
415 }
416 }
417 return true;
418 }
419 for (size_t i = 0; i < length; i++) {
420 if ((fData[i] & dataMask[i]) != (vec[i] & dataMask[i])) {
421 return false;
422 }
423 }
424 return true;
425 }
426
ConvertBleScanSetting(const BleScanSettings & inSettings,BluetoothBleScanSettings & outSetting)427 void BleCentralManager::impl::ConvertBleScanSetting(const BleScanSettings &inSettings,
428 BluetoothBleScanSettings &outSetting)
429 {
430 outSetting.SetReportDelay(0);
431 outSetting.SetScanMode(inSettings.GetScanMode());
432 outSetting.SetLegacy(inSettings.GetLegacy());
433 outSetting.SetPhy(inSettings.GetPhy());
434 }
435
ConvertBleScanFilter(const std::vector<BleScanFilter> & filters,std::vector<BluetoothBleScanFilter> & bluetoothBleScanFilters)436 void BleCentralManager::impl::ConvertBleScanFilter(const std::vector<BleScanFilter> &filters,
437 std::vector<BluetoothBleScanFilter> &bluetoothBleScanFilters)
438 {
439 for (auto filter : filters) {
440 BluetoothBleScanFilter scanFilter;
441 scanFilter.SetDeviceId(filter.GetDeviceId());
442 scanFilter.SetName(filter.GetName());
443 if (filter.HasServiceUuid()) {
444 scanFilter.SetServiceUuid(bluetooth::Uuid::ConvertFromString(
445 filter.GetServiceUuid().ToString()));
446 }
447 if (filter.HasServiceUuidMask()) {
448 scanFilter.SetServiceUuidMask(bluetooth::Uuid::ConvertFromString(
449 filter.GetServiceUuidMask().ToString()));
450 }
451 if (filter.HasSolicitationUuid()) {
452 scanFilter.SetServiceSolicitationUuid(bluetooth::Uuid::ConvertFromString(
453 filter.GetServiceSolicitationUuid().ToString()));
454 }
455 if (filter.HasSolicitationUuidMask()) {
456 scanFilter.SetServiceSolicitationUuidMask(bluetooth::Uuid::ConvertFromString(
457 filter.GetServiceSolicitationUuidMask().ToString()));
458 }
459 scanFilter.SetServiceData(filter.GetServiceData());
460 scanFilter.SetServiceDataMask(filter.GetServiceDataMask());
461 scanFilter.SetManufacturerId(filter.GetManufacturerId());
462 scanFilter.SetManufactureData(filter.GetManufactureData());
463 scanFilter.SetManufactureDataMask(filter.GetManufactureDataMask());
464 bluetoothBleScanFilters.push_back(scanFilter);
465 }
466 }
467
ConvertAdvertiserSetting(const BleAdvertiserSettings & inSettings,BluetoothBleAdvertiserSettings & outSettings)468 void BleCentralManager::impl::ConvertAdvertiserSetting(const BleAdvertiserSettings &inSettings,
469 BluetoothBleAdvertiserSettings &outSettings)
470 {
471 outSettings.SetConnectable(inSettings.IsConnectable());
472 outSettings.SetInterval(inSettings.GetInterval());
473 outSettings.SetLegacyMode(inSettings.IsLegacyMode());
474 outSettings.SetTxPower(inSettings.GetTxPower());
475 }
476
ConvertActiveDeviceInfo(const std::vector<BleActiveDeviceInfo> & inDeviceInfos,std::vector<BluetoothActiveDeviceInfo> & outDeviceInfos)477 void BleCentralManager::impl::ConvertActiveDeviceInfo(const std::vector<BleActiveDeviceInfo> &inDeviceInfos,
478 std::vector<BluetoothActiveDeviceInfo> &outDeviceInfos)
479 {
480 for (auto info : inDeviceInfos) {
481 BluetoothActiveDeviceInfo deviceInfo;
482 deviceInfo.deviceId = info.deviceId;
483 deviceInfo.status = info.status;
484 deviceInfo.timeOut = info.timeOut;
485 outDeviceInfos.push_back(deviceInfo);
486 }
487 }
488
~impl()489 BleCentralManager::impl::~impl()
490 {
491 if (proxy_) {
492 proxy_->DeregisterBleCentralManagerCallback(scannerId_, callbackImp_);
493 proxy_->AsObject()->RemoveDeathRecipient(deathRecipient_);
494 }
495 }
496
497
BleCentralManager(BleCentralManagerCallback & callback)498 BleCentralManager::BleCentralManager(BleCentralManagerCallback &callback) : pimpl(nullptr)
499 {
500 if (pimpl == nullptr) {
501 pimpl = std::make_unique<impl>();
502 if (pimpl == nullptr) {
503 HILOGE("failed, no pimpl");
504 }
505 }
506
507 HILOGI("successful");
508 std::shared_ptr<BleCentralManagerCallback> pointer(&callback, [](BleCentralManagerCallback *) {});
509 bool ret = pimpl->callbacks_.Register(pointer);
510 if (ret)
511 return;
512 }
513
BleCentralManager(std::shared_ptr<BleCentralManagerCallback> callback,bool enableRandomAddrMode)514 BleCentralManager::BleCentralManager(std::shared_ptr<BleCentralManagerCallback> callback, bool enableRandomAddrMode)
515 : pimpl(nullptr)
516 {
517 if (pimpl == nullptr) {
518 pimpl = std::make_unique<impl>();
519 if (pimpl == nullptr) {
520 HILOGE("failed, no pimpl");
521 }
522 }
523 HILOGI("successful");
524 pimpl->enableRandomAddrMode_ = enableRandomAddrMode;
525 pimpl->callbacks_.Register(callback);
526 }
527
~BleCentralManager()528 BleCentralManager::~BleCentralManager()
529 {
530 }
531
StartScan()532 int BleCentralManager::StartScan()
533 {
534 if (!IS_BLE_ENABLED()) {
535 HILOGE("bluetooth is off.");
536 return BT_ERR_INVALID_STATE;
537 }
538
539 if (pimpl == nullptr || !pimpl->InitBleCentralManagerProxy()) {
540 HILOGE("pimpl or ble central manager proxy is nullptr");
541 return BT_ERR_INTERNAL_ERROR;
542 }
543 if (pimpl->scannerId_ == BLE_SCAN_INVALID_ID) {
544 HILOGE("scannerId is invalid");
545 return BT_ERR_INTERNAL_ERROR;
546 }
547
548 HILOGI("StartScan without param, scannerId: %{public}d", pimpl->scannerId_);
549 return pimpl->proxy_->StartScan(pimpl->scannerId_);
550 }
551
StartScan(const BleScanSettings & settings)552 int BleCentralManager::StartScan(const BleScanSettings &settings)
553 {
554 if (!IS_BLE_ENABLED()) {
555 HILOGE("bluetooth is off.");
556 return BT_ERR_INVALID_STATE;
557 }
558
559 if (pimpl == nullptr || !pimpl->InitBleCentralManagerProxy()) {
560 HILOGE("pimpl or ble central manager proxy is nullptr");
561 return BT_ERR_INTERNAL_ERROR;
562 }
563 if (pimpl->scannerId_ == BLE_SCAN_INVALID_ID) {
564 HILOGE("scannerId is invalid");
565 return BT_ERR_INTERNAL_ERROR;
566 }
567
568 HILOGI("StartScan with params, scannerId: %{public}d", pimpl->scannerId_);
569 BluetoothBleScanSettings setting;
570 // not use report delay scan. settings.GetReportDelayMillisValue()
571 setting.SetReportDelay(0);
572 setting.SetScanMode(settings.GetScanMode());
573 setting.SetLegacy(settings.GetLegacy());
574 setting.SetPhy(settings.GetPhy());
575 return pimpl->proxy_->StartScan(pimpl->scannerId_, setting);
576 }
577
StopScan()578 int BleCentralManager::StopScan()
579 {
580 if (!IS_BLE_ENABLED()) {
581 HILOGE("bluetooth is off.");
582 return BT_ERR_INVALID_STATE;
583 }
584
585 if (pimpl == nullptr || !pimpl->InitBleCentralManagerProxy()) {
586 HILOGE("pimpl or ble central manager proxy is nullptr");
587 return BT_ERR_INTERNAL_ERROR;
588 }
589 if (pimpl->scannerId_ == BLE_SCAN_INVALID_ID) {
590 HILOGE("scannerId is invalid");
591 return BT_ERR_INTERNAL_ERROR;
592 }
593
594 HILOGI("scannerId_: %{public}d", pimpl->scannerId_);
595 std::lock_guard<std::mutex> lock(pimpl->blesCanFiltersMutex_);
596
597 int ret = pimpl->proxy_->StopScan(pimpl->scannerId_);
598 pimpl->proxy_->RemoveScanFilter(pimpl->scannerId_);
599 pimpl->bleScanFilters_.clear();
600 pimpl->IsNeedFilterMatches_ = true;
601 return ret;
602 }
603
ConfigScanFilter(const std::vector<BleScanFilter> & filters)604 int BleCentralManager::ConfigScanFilter(const std::vector<BleScanFilter> &filters)
605 {
606 if (!IS_BLE_ENABLED()) {
607 HILOGE("bluetooth is off.");
608 return BT_ERR_INVALID_STATE;
609 }
610
611 if (pimpl == nullptr || !pimpl->InitBleCentralManagerProxy() || pimpl->scannerId_ == BLE_SCAN_INVALID_ID) {
612 HILOGE("pimpl or ble central manager proxy is nullptr");
613 return BT_ERR_INTERNAL_ERROR;
614 }
615
616 std::lock_guard<std::mutex> lock(pimpl->blesCanFiltersMutex_);
617 std::vector<BluetoothBleScanFilter> bluetoothBleScanFilters;
618 for (auto filter : filters) {
619 BluetoothBleScanFilter scanFilter;
620 scanFilter.SetDeviceId(filter.GetDeviceId());
621 scanFilter.SetName(filter.GetName());
622 if (filter.HasServiceUuid()) {
623 scanFilter.SetServiceUuid(bluetooth::Uuid::ConvertFromString(
624 filter.GetServiceUuid().ToString()));
625 }
626 if (filter.HasServiceUuidMask()) {
627 scanFilter.SetServiceUuidMask(bluetooth::Uuid::ConvertFromString(
628 filter.GetServiceUuidMask().ToString()));
629 }
630 if (filter.HasSolicitationUuid()) {
631 scanFilter.SetServiceSolicitationUuid(bluetooth::Uuid::ConvertFromString(
632 filter.GetServiceSolicitationUuid().ToString()));
633 }
634 if (filter.HasSolicitationUuidMask()) {
635 scanFilter.SetServiceSolicitationUuidMask(bluetooth::Uuid::ConvertFromString(
636 filter.GetServiceSolicitationUuidMask().ToString()));
637 }
638 scanFilter.SetServiceData(filter.GetServiceData());
639 scanFilter.SetServiceDataMask(filter.GetServiceDataMask());
640 scanFilter.SetManufacturerId(filter.GetManufacturerId());
641 scanFilter.SetManufactureData(filter.GetManufactureData());
642 scanFilter.SetManufactureDataMask(filter.GetManufactureDataMask());
643 bluetoothBleScanFilters.push_back(scanFilter);
644 pimpl->bleScanFilters_.push_back(scanFilter);
645 }
646 int ret = pimpl->proxy_->ConfigScanFilter(pimpl->scannerId_, bluetoothBleScanFilters);
647 if (ret != BT_NO_ERROR) {
648 HILOGE("failed.");
649 return ret;
650 }
651
652 if (filters.empty()) {
653 HILOGI("filters is empty can not config");
654 pimpl->IsNeedFilterMatches_ = false;
655 }
656 return ret;
657 }
658
SetLpDeviceAdvParam(int duration,int maxExtAdvEvents,int window,int interval,int advHandle)659 int BleCentralManager::SetLpDeviceAdvParam(int duration, int maxExtAdvEvents, int window, int interval, int advHandle)
660 {
661 if (!IS_BLE_ENABLED()) {
662 HILOGE("bluetooth is off.");
663 return BT_ERR_INTERNAL_ERROR;
664 }
665
666 if (pimpl == nullptr || !pimpl->InitBleCentralManagerProxy()) {
667 HILOGE("pimpl or ble central manager proxy is nullptr");
668 return BT_ERR_INTERNAL_ERROR;
669 }
670 return pimpl->proxy_->SetLpDeviceAdvParam(duration, maxExtAdvEvents, window, interval, advHandle);
671 }
672
SetScanReportChannelToLpDevice(bool enable)673 int BleCentralManager::SetScanReportChannelToLpDevice(bool enable)
674 {
675 if (!IS_BLE_ENABLED()) {
676 HILOGE("bluetooth is off.");
677 return BT_ERR_INTERNAL_ERROR;
678 }
679
680 if (pimpl == nullptr || !pimpl->InitBleCentralManagerProxy()) {
681 HILOGE("pimpl or ble central manager proxy is nullptr");
682 return BT_ERR_INTERNAL_ERROR;
683 }
684
685 // need start scan first
686 if (pimpl->scannerId_ == BLE_SCAN_INVALID_ID) {
687 HILOGE("failed, scannerId invalid.");
688 return BT_ERR_INTERNAL_ERROR;
689 }
690 return pimpl->proxy_->SetScanReportChannelToLpDevice(pimpl->scannerId_, enable);
691 }
692
EnableSyncDataToLpDevice()693 int BleCentralManager::EnableSyncDataToLpDevice()
694 {
695 if (!IS_BLE_ENABLED()) {
696 HILOGE("bluetooth is off.");
697 return BT_ERR_INTERNAL_ERROR;
698 }
699
700 if (pimpl == nullptr || !pimpl->InitBleCentralManagerProxy()) {
701 HILOGE("pimpl or ble central manager proxy is nullptr");
702 return BT_ERR_INTERNAL_ERROR;
703 }
704 return pimpl->proxy_->EnableSyncDataToLpDevice();
705 }
706
DisableSyncDataToLpDevice()707 int BleCentralManager::DisableSyncDataToLpDevice()
708 {
709 if (!IS_BLE_ENABLED()) {
710 HILOGE("bluetooth is off.");
711 return BT_ERR_INTERNAL_ERROR;
712 }
713
714 if (pimpl == nullptr || !pimpl->InitBleCentralManagerProxy()) {
715 HILOGE("pimpl or ble central manager proxy is nullptr");
716 return BT_ERR_INTERNAL_ERROR;
717 }
718 return pimpl->proxy_->DisableSyncDataToLpDevice();
719 }
720
SendParamsToLpDevice(const std::vector<uint8_t> & dataValue,int32_t type)721 int BleCentralManager::SendParamsToLpDevice(const std::vector<uint8_t> &dataValue, int32_t type)
722 {
723 if (!IS_BLE_ENABLED()) {
724 HILOGE("bluetooth is off.");
725 return BT_ERR_INTERNAL_ERROR;
726 }
727
728 if (pimpl == nullptr || !pimpl->InitBleCentralManagerProxy()) {
729 HILOGE("pimpl or ble central manager proxy is nullptr");
730 return BT_ERR_INTERNAL_ERROR;
731 }
732 return pimpl->proxy_->SendParamsToLpDevice(dataValue, type);
733 }
734
IsLpDeviceAvailable()735 bool BleCentralManager::IsLpDeviceAvailable()
736 {
737 if (!IS_BLE_ENABLED()) {
738 HILOGE("bluetooth is off.");
739 return BT_ERR_INTERNAL_ERROR;
740 }
741
742 if (pimpl == nullptr || !pimpl->InitBleCentralManagerProxy()) {
743 HILOGE("pimpl or ble central manager proxy is nullptr");
744 return BT_ERR_INTERNAL_ERROR;
745 }
746 return pimpl->proxy_->IsLpDeviceAvailable();
747 }
748
SetLpDeviceParam(const BleLpDeviceParamSet & lpDeviceParamSet)749 int BleCentralManager::SetLpDeviceParam(const BleLpDeviceParamSet &lpDeviceParamSet)
750 {
751 if (!IS_BLE_ENABLED()) {
752 HILOGE("bluetooth is off.");
753 return BT_ERR_INTERNAL_ERROR;
754 }
755
756 if (pimpl == nullptr || !pimpl->InitBleCentralManagerProxy()) {
757 HILOGE("pimpl or ble central manager proxy is nullptr");
758 return BT_ERR_INTERNAL_ERROR;
759 }
760
761 BluetoothLpDeviceParamSet paramSet;
762 if ((lpDeviceParamSet.fieldValidFlagBit & BLE_LPDEVICE_SCAN_SETTING_VALID_BIT) != 0) {
763 pimpl->ConvertBleScanSetting(lpDeviceParamSet.scanSettings, paramSet.btScanSettings);
764 }
765
766 if ((lpDeviceParamSet.fieldValidFlagBit & BLE_LPDEVICE_SCAN_FILTER_VALID_BIT) != 0) {
767 pimpl->ConvertBleScanFilter(lpDeviceParamSet.scanFilters, paramSet.btScanFilters);
768 }
769
770 if ((lpDeviceParamSet.fieldValidFlagBit & BLE_LPDEVICE_ADV_SETTING_VALID_BIT) != 0) {
771 pimpl->ConvertAdvertiserSetting(lpDeviceParamSet.advSettings, paramSet.btAdvSettings);
772 }
773
774 if ((lpDeviceParamSet.fieldValidFlagBit & BLE_LPDEVICE_ADVDATA_VALID_BIT) != 0) {
775 paramSet.btAdvData.SetPayload(std::string(lpDeviceParamSet.advData.begin(),
776 lpDeviceParamSet.advData.end()));
777 }
778
779 if ((lpDeviceParamSet.fieldValidFlagBit & BLE_LPDEVICE_RESPDATA_VALID_BIT) != 0) {
780 paramSet.btRespData.SetPayload(std::string(lpDeviceParamSet.respData.begin(),
781 lpDeviceParamSet.respData.end()));
782 }
783
784 if ((lpDeviceParamSet.fieldValidFlagBit & BLE_LPDEVICE_ADV_DEVICEINFO_VALID_BIT) != 0) {
785 pimpl->ConvertActiveDeviceInfo(lpDeviceParamSet.activeDeviceInfos, paramSet.activeDeviceInfos);
786 }
787 paramSet.fieldValidFlagBit = lpDeviceParamSet.fieldValidFlagBit;
788 paramSet.uuid = bluetooth::Uuid::ConvertFromString(lpDeviceParamSet.uuid.ToString());
789 paramSet.advHandle = lpDeviceParamSet.advHandle;
790 paramSet.deliveryMode = lpDeviceParamSet.deliveryMode;
791 paramSet.duration = lpDeviceParamSet.duration;
792
793 return pimpl->proxy_->SetLpDeviceParam(paramSet);
794 }
795
RemoveLpDeviceParam(const UUID & uuid)796 int BleCentralManager::RemoveLpDeviceParam(const UUID &uuid)
797 {
798 if (!IS_BLE_ENABLED()) {
799 HILOGE("bluetooth is off.");
800 return BT_ERR_INTERNAL_ERROR;
801 }
802
803 if (pimpl == nullptr || !pimpl->proxy_) {
804 HILOGE("pimpl or ble central manager proxy is nullptr");
805 return BT_ERR_INTERNAL_ERROR;
806 }
807 bluetooth::Uuid btUuid = bluetooth::Uuid::ConvertFromString(uuid.ToString());
808 return pimpl->proxy_->RemoveLpDeviceParam(btUuid);
809 }
810
BleScanResult()811 BleScanResult::BleScanResult()
812 {}
813
~BleScanResult()814 BleScanResult::~BleScanResult()
815 {}
816
GetServiceUuids() const817 std::vector<UUID> BleScanResult::GetServiceUuids() const
818 {
819 return serviceUuids_;
820 }
821
GetManufacturerData() const822 std::map<uint16_t, std::string> BleScanResult::GetManufacturerData() const
823 {
824 return manufacturerSpecificData_;
825 }
826
GetServiceData() const827 std::map<UUID, std::string> BleScanResult::GetServiceData() const
828 {
829 return serviceData_;
830 }
831
GetPeripheralDevice() const832 BluetoothRemoteDevice BleScanResult::GetPeripheralDevice() const
833 {
834 return peripheralDevice_;
835 }
836
GetRssi() const837 int8_t BleScanResult::GetRssi() const
838 {
839 return rssi_;
840 }
841
IsConnectable() const842 bool BleScanResult::IsConnectable() const
843 {
844 return connectable_;
845 }
846
GetAdvertiseFlag() const847 uint8_t BleScanResult::GetAdvertiseFlag() const
848 {
849 return advertiseFlag_;
850 }
851
GetPayload() const852 std::vector<uint8_t> BleScanResult::GetPayload() const
853 {
854 return payload_;
855 }
856
AddManufacturerData(uint16_t manufacturerId,const std::string & data)857 void BleScanResult::AddManufacturerData(uint16_t manufacturerId, const std::string &data)
858 {
859 manufacturerSpecificData_.insert(std::make_pair(manufacturerId, data));
860 }
861
AddServiceData(const UUID & uuid,const std::string & data)862 void BleScanResult::AddServiceData(const UUID &uuid, const std::string &data)
863 {
864 serviceData_.insert(std::make_pair(uuid, data));
865 }
866
AddServiceUuid(const UUID & serviceUuid)867 void BleScanResult::AddServiceUuid(const UUID &serviceUuid)
868 {
869 serviceUuids_.push_back(serviceUuid);
870 }
871
SetPayload(std::string payload)872 void BleScanResult::SetPayload(std::string payload)
873 {
874 payload_.assign(payload.begin(), payload.end());
875 }
876
SetPeripheralDevice(const BluetoothRemoteDevice & device)877 void BleScanResult::SetPeripheralDevice(const BluetoothRemoteDevice &device)
878 {
879 peripheralDevice_ = device;
880 }
881
SetRssi(int8_t rssi)882 void BleScanResult::SetRssi(int8_t rssi)
883 {
884 rssi_ = rssi;
885 }
886
SetConnectable(bool connectable)887 void BleScanResult::SetConnectable(bool connectable)
888 {
889 connectable_ = connectable;
890 }
891
SetAdvertiseFlag(uint8_t flag)892 void BleScanResult::SetAdvertiseFlag(uint8_t flag)
893 {
894 advertiseFlag_ = flag;
895 }
896
SetName(const std::string & name)897 void BleScanResult::SetName(const std::string &name)
898 {
899 name_ = name;
900 }
GetName(void)901 std::string BleScanResult::GetName(void)
902 {
903 return name_;
904 }
905
BleScanSettings()906 BleScanSettings::BleScanSettings()
907 {}
908
~BleScanSettings()909 BleScanSettings::~BleScanSettings()
910 {}
911
SetReportDelay(long reportDelayMillis)912 void BleScanSettings::SetReportDelay(long reportDelayMillis)
913 {
914 reportDelayMillis_ = reportDelayMillis;
915 }
916
GetReportDelayMillisValue() const917 long BleScanSettings::GetReportDelayMillisValue() const
918 {
919 return reportDelayMillis_;
920 }
921
SetScanMode(int scanMode)922 int BleScanSettings::SetScanMode(int scanMode)
923 {
924 if (scanMode < SCAN_MODE_LOW_POWER || scanMode >= SCAN_MODE_INVALID) {
925 return RET_BAD_PARAM;
926 }
927
928 scanMode_ = scanMode;
929 return RET_NO_ERROR;
930 }
931
GetScanMode() const932 int BleScanSettings::GetScanMode() const
933 {
934 return scanMode_;
935 }
936
SetLegacy(bool legacy)937 void BleScanSettings::SetLegacy(bool legacy)
938 {
939 legacy_ = legacy;
940 }
941
GetLegacy() const942 bool BleScanSettings::GetLegacy() const
943 {
944 return legacy_;
945 }
946
SetPhy(int phy)947 void BleScanSettings::SetPhy(int phy)
948 {
949 phy_ = phy;
950 }
951
GetPhy() const952 int BleScanSettings::GetPhy() const
953 {
954 return phy_;
955 }
956
BleScanFilter()957 BleScanFilter::BleScanFilter()
958 {}
959
~BleScanFilter()960 BleScanFilter::~BleScanFilter()
961 {}
962
SetDeviceId(std::string deviceId)963 void BleScanFilter::SetDeviceId(std::string deviceId)
964 {
965 deviceId_ = deviceId;
966 }
967
GetDeviceId() const968 std::string BleScanFilter::GetDeviceId() const
969 {
970 return deviceId_;
971 }
972
SetName(std::string name)973 void BleScanFilter::SetName(std::string name)
974 {
975 name_ = name;
976 }
977
GetName() const978 std::string BleScanFilter::GetName() const
979 {
980 return name_;
981 }
982
SetServiceUuid(const UUID & uuid)983 void BleScanFilter::SetServiceUuid(const UUID &uuid)
984 {
985 serviceUuid_ = uuid;
986 hasServiceUuid_ = true;
987 }
988
HasServiceUuid()989 bool BleScanFilter::HasServiceUuid()
990 {
991 return hasServiceUuid_;
992 }
993
GetServiceUuid() const994 UUID BleScanFilter::GetServiceUuid() const
995 {
996 return serviceUuid_;
997 }
998
SetServiceUuidMask(const UUID & serviceUuidMask)999 void BleScanFilter::SetServiceUuidMask(const UUID &serviceUuidMask)
1000 {
1001 serviceUuidMask_ = serviceUuidMask;
1002 hasServiceUuidMask_ = true;
1003 }
1004
HasServiceUuidMask()1005 bool BleScanFilter::HasServiceUuidMask()
1006 {
1007 return hasServiceUuidMask_;
1008 }
1009
GetServiceUuidMask() const1010 UUID BleScanFilter::GetServiceUuidMask() const
1011 {
1012 return serviceUuidMask_;
1013 }
1014
SetServiceSolicitationUuid(const UUID & serviceSolicitationUuid)1015 void BleScanFilter::SetServiceSolicitationUuid(const UUID &serviceSolicitationUuid)
1016 {
1017 serviceSolicitationUuid_ = serviceSolicitationUuid;
1018 hasSolicitationUuid_ = true;
1019 }
1020
HasSolicitationUuid()1021 bool BleScanFilter::HasSolicitationUuid()
1022 {
1023 return hasSolicitationUuid_;
1024 }
1025
GetServiceSolicitationUuid() const1026 UUID BleScanFilter::GetServiceSolicitationUuid() const
1027 {
1028 return serviceSolicitationUuid_;
1029 }
1030
SetServiceSolicitationUuidMask(const UUID & serviceSolicitationUuidMask)1031 void BleScanFilter::SetServiceSolicitationUuidMask(const UUID &serviceSolicitationUuidMask)
1032 {
1033 serviceSolicitationUuidMask_ = serviceSolicitationUuidMask;
1034 hasSolicitationUuidMask_ = true;
1035 }
1036
HasSolicitationUuidMask()1037 bool BleScanFilter::HasSolicitationUuidMask()
1038 {
1039 return hasSolicitationUuidMask_;
1040 }
1041
GetServiceSolicitationUuidMask() const1042 UUID BleScanFilter::GetServiceSolicitationUuidMask() const
1043 {
1044 return serviceSolicitationUuidMask_;
1045 }
1046
SetServiceData(std::vector<uint8_t> serviceData)1047 void BleScanFilter::SetServiceData(std::vector<uint8_t> serviceData)
1048
1049 {
1050 serviceData_ = serviceData;
1051 }
1052
GetServiceData() const1053 std::vector<uint8_t> BleScanFilter::GetServiceData() const
1054 {
1055 return serviceData_;
1056 }
1057
SetServiceDataMask(std::vector<uint8_t> serviceDataMask)1058 void BleScanFilter::SetServiceDataMask(std::vector<uint8_t> serviceDataMask)
1059 {
1060 serviceDataMask_ = serviceDataMask;
1061 }
1062
GetServiceDataMask() const1063 std::vector<uint8_t> BleScanFilter::GetServiceDataMask() const
1064 {
1065 return serviceDataMask_;
1066 }
1067
SetManufacturerId(uint16_t manufacturerId)1068 void BleScanFilter::SetManufacturerId(uint16_t manufacturerId)
1069 {
1070 manufacturerId_ = manufacturerId;
1071 }
1072
GetManufacturerId() const1073 uint16_t BleScanFilter::GetManufacturerId() const
1074 {
1075 return manufacturerId_;
1076 }
1077
SetManufactureData(std::vector<uint8_t> manufactureData)1078 void BleScanFilter::SetManufactureData(std::vector<uint8_t> manufactureData)
1079 {
1080 manufactureData_ = manufactureData;
1081 }
1082
GetManufactureData() const1083 std::vector<uint8_t> BleScanFilter::GetManufactureData() const
1084 {
1085 return manufactureData_;
1086 }
1087
SetManufactureDataMask(std::vector<uint8_t> manufactureDataMask)1088 void BleScanFilter::SetManufactureDataMask(std::vector<uint8_t> manufactureDataMask)
1089 {
1090 manufactureDataMask_ = manufactureDataMask;
1091 }
1092
GetManufactureDataMask() const1093 std::vector<uint8_t> BleScanFilter::GetManufactureDataMask() const
1094 {
1095 return manufactureDataMask_;
1096 }
1097 } // namespace Bluetooth
1098 } // namespace OHOS
1099