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
16 #include "ble_adapter.h"
17
18 #include <algorithm>
19 #include <chrono>
20 #include <condition_variable>
21 #include <map>
22 #include <mutex>
23
24 #include "adapter_manager.h"
25 #include "base_observer_list.h"
26 #include "ble_feature.h"
27 #include "ble_utils.h"
28 #include "btm.h"
29 #include "btstack.h"
30 #include "class_creator.h"
31 #include "compat.h"
32 #include "interface_profile_gatt_client.h"
33 #include "interface_profile_manager.h"
34 #include "log.h"
35 #include "log_util.h"
36 #include "securec.h"
37
38 namespace OHOS {
39 namespace bluetooth {
40 struct BleAdapter::impl {
41 class GattClientCallback : public IGattClientCallback {
42 public:
GattClientCallback(BleAdapter &bleAdapter)43 explicit GattClientCallback(BleAdapter &bleAdapter) : bleAdapter_(bleAdapter)
44 {}
~GattClientCallback()45 ~GattClientCallback()
46 {}
47 void OnConnectionStateChanged(int state, int newState) override
48 {
49 LOG_DEBUG("%{public}s:%{public}d:%{public}s state:%{public}d", __FILE__, __LINE__, __FUNCTION__, newState);
50 }
51
52 void OnServicesChanged(const std::vector<Service> &services) override
53 {
54 LOG_DEBUG("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __FUNCTION__);
55 }
56
57 void OnCharacteristicRead(int ret, const Characteristic &characteristic) override
58 {
59 LOG_DEBUG("%{public}s:%{public}d:%{public}s ret : %{public}d", __FILE__, __LINE__, __FUNCTION__, ret);
60 std::lock_guard<std::mutex> lock(bleAdapter_.pimpl->mutexRemoteName_);
61 if (GattStatus::GATT_SUCCESS == ret) {
62 std::string name(characteristic.value_.get(), characteristic.value_.get() + characteristic.length_);
63 bleAdapter_.pimpl->remoteDeviceName_ = name;
64 bleAdapter_.pimpl->readCharacteristicFlag_ = true;
65 } else {
66 bleAdapter_.pimpl->readCharacteristicFlag_ = false;
67 }
68 bleAdapter_.pimpl->cvfull_.notify_all();
69 }
70
71 void OnCharacteristicWrite(int ret, const Characteristic &characteristic) override
72 {
73 LOG_DEBUG("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __FUNCTION__);
74 }
75
76 void OnCharacteristicChanged(const Characteristic &characteristic) override
77 {
78 LOG_DEBUG("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __FUNCTION__);
79 }
80
81 void OnDescriptorRead(int ret, const Descriptor &descriptor) override
82 {
83 LOG_DEBUG("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __FUNCTION__);
84 }
85
86 void OnDescriptorWrite(int ret, const Descriptor &descriptor) override
87 {
88 LOG_DEBUG("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __FUNCTION__);
89 }
90
91 void OnMtuChanged(int state, int mtu) override
92 {
93 LOG_DEBUG("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __FUNCTION__);
94 }
95
96 void OnConnectionParameterChanged(int interval, int latency, int timeout, int status) override
97 {
98 LOG_DEBUG("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __FUNCTION__);
99 }
100
101 void OnServicesDiscovered(int status) override
102 {
103 LOG_DEBUG("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __FUNCTION__);
104 }
105
106 void OnReadRemoteRssiValue(const RawAddress &addr, int rssi, int status) override
107 {
108 LOG_DEBUG("%{public}s:%{public}d:%{public}s", __FILE__, __LINE__, __FUNCTION__);
109 }
110
111 private:
112 BleAdapter &bleAdapter_;
113 };
114 impl(BleAdapter &bleAdapter);
115 impl(const impl &);
116 impl &operator=(const impl &);
117 ~impl();
118
119 std::recursive_mutex syncMutex_ {};
120 std::unique_ptr<BaseObserverList<IAdapterBleObserver>> observer_ =
121 std::make_unique<BaseObserverList<IAdapterBleObserver>>();
122 std::unique_ptr<BaseObserverList<IBlePeripheralCallback>> blePeripheralCallback_ =
123 std::make_unique<BaseObserverList<IBlePeripheralCallback>>();
124
125 std::mutex mutexRpa_ {};
126 std::mutex mutexAdvAdnScan_ {};
127 std::mutex mutexRemoteName_ {};
128 std::condition_variable cvfull_ {};
129
130 std::unique_ptr<GattClientCallback> gattClientcallback_ {};
131 IProfileGattClient *gattClientService_ {};
132 std::string remoteDeviceName_ {};
133 std::map<std::string, BlePeripheralDevice> peerConnDeviceList_ {};
134 bool btmEnableFlag_ = false;
135 bool readCharacteristicFlag_ = false;
136
137 std::unique_ptr<BleAdvertiserImpl> bleAdvertiser_ = nullptr;
138 std::unique_ptr<BleCentralManagerImpl> bleCentralManager_ = nullptr;
139 std::unique_ptr<BleSecurity> bleSecurity_ = nullptr;
140 BtmAclCallbacks btmAclCb_ {};
141 };
142
impl(BleAdapter &bleAdapter)143 BleAdapter::impl::impl(BleAdapter &bleAdapter) : gattClientcallback_(std::make_unique<GattClientCallback>(bleAdapter))
144 {}
145
~impl()146 BleAdapter::impl::~impl()
147 {}
148
BleAdapter()149 BleAdapter::BleAdapter() : utility::Context(ADAPTER_NAME_BLE, "5.0"), pimpl(std::make_unique<BleAdapter::impl>(*this))
150 {
151 LOG_DEBUG("[BleAdapter] %{public}s:Create", Name().c_str());
152 }
153
~BleAdapter()154 BleAdapter::~BleAdapter()
155 {
156 LOG_DEBUG("[BleAdapter] %{public}s:Destroy", Name().c_str());
157
158 pimpl->bleAdvertiser_ = nullptr;
159 pimpl->bleCentralManager_ = nullptr;
160 pimpl->bleSecurity_ = nullptr;
161 }
162
Enable()163 void BleAdapter::Enable()
164 {
165 LOG_DEBUG("[BleAdapter] %{public}s:%{public}s", __func__, Name().c_str());
166
167 GetDispatcher()->PostTask(std::bind(&BleAdapter::EnableTask, this));
168 }
169
EnableTask()170 bool BleAdapter::EnableTask()
171 {
172 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
173
174 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
175 bool ret = (BTM_Enable(LE_CONTROLLER) == BT_SUCCESS);
176 if (!ret) {
177 pimpl->btmEnableFlag_ = false;
178 LOG_ERROR("[BleAdapter] %{public}s:BTM enable failed!", __func__);
179 } else {
180 pimpl->btmEnableFlag_ = true;
181 LoadConfig();
182 ret = (InitBtmAndGap() == BT_SUCCESS);
183 LOG_DEBUG("[BleAdapter] %{public}s:BTM enable successfully!", __func__);
184 }
185
186 GetContext()->OnEnable(ADAPTER_NAME_BLE, ret);
187
188 return ret;
189 }
190
InitBtmAndGap()191 int BleAdapter::InitBtmAndGap()
192 {
193 int ret = RegisterCallbackToBtm();
194 if (ret != BT_SUCCESS) {
195 LOG_ERROR("[BleAdapter] %{public}s:RegisterCallbackToBtm failed!", __func__);
196 }
197
198 ret = SetLocalIrkAndIdentityAddrToBtm();
199 if (ret != BT_SUCCESS) {
200 LOG_ERROR("[BleAdapter] %{public}s:SetLocalIrkAndIdentityAddrToBtm failed!", __func__);
201 }
202
203 ret = SetRpaAddrAndTypeToBtm();
204 if (ret != BT_SUCCESS) {
205 LOG_ERROR("[BleAdapter] %{public}s:SetRpaAddrAndTypeToBtm failed!", __func__);
206 }
207
208 GAP_LeSecMode1Level level1 = static_cast<GAP_LeSecMode1Level>(BleConfig::GetInstance().GetBleModel1Level());
209 GAP_LeSecMode2Level level2 = static_cast<GAP_LeSecMode2Level>(BleConfig::GetInstance().GetBleModel2Level());
210 ret = GAPIF_LeSetSecurityMode(level1, level2);
211 if (ret == BT_NOT_SUPPORT) {
212 ret = GAPIF_LeSetSecurityMode(LE_MODE_1_LEVEL_3, level2);
213 if (ret != BT_SUCCESS) {
214 LOG_ERROR("[BleAdapter] %{public}s:GAP_LeSetSecurityMode failed!", __func__);
215 }
216 }
217
218 RegisterBleSecurityCallback(*pimpl->observer_.get());
219
220 ret = GAPIF_LeSetMinEncKeySize(GAP_ENC_KEY_MIN_SIZE);
221 if (ret != BT_SUCCESS) {
222 LOG_ERROR("[BleAdapter] %{public}s:GAP_LeSetMinEncKeySize failed!", __func__);
223 }
224
225 ret = BleProperties::GetInstance().SetBondableMode(GAP_BONDABLE_MODE);
226 if (ret != BT_SUCCESS) {
227 LOG_ERROR("[BleAdapter] %{public}s:SetBondableMode failed!", __func__);
228 }
229
230 /// Save all peer paired devices to BTM
231 std::vector<std::string> pairedAddrList = BleConfig::GetInstance().GetPairedAddrList();
232 ReadPeerDeviceInfoFromConf(pairedAddrList);
233 SavePeerDevices2BTM(pimpl->peerConnDeviceList_);
234 return ret;
235 }
236
Disable()237 void BleAdapter::Disable()
238 {
239 LOG_DEBUG("[BleAdapter] %{public}s:%{public}s", __func__, Name().c_str());
240
241 GetDispatcher()->PostTask(std::bind(&BleAdapter::DisableTask, this));
242 }
243
DisableTask()244 bool BleAdapter::DisableTask()
245 {
246 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
247
248 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
249 if (!pimpl->btmEnableFlag_) {
250 GetContext()->OnDisable(ADAPTER_NAME_BLE, pimpl->btmEnableFlag_);
251 return false;
252 }
253
254 SavePeerDeviceInfoToConf(pimpl->peerConnDeviceList_);
255 ClearPeerDeviceInfo();
256 int ret = BleProperties::GetInstance().SetBondableMode(GAP_BONDABLE_MODE_NON);
257 if (ret != BT_SUCCESS) {
258 LOG_ERROR("[BleAdapter] %{public}s:SetBondableMode failed!", __func__);
259 }
260
261 StartOrStopAdvAndScan(STOP_ADV_TYPE_ALL, STOP_SCAN_TYPE_NOR);
262 if (BleFeature::GetInstance().IsLeExtendedAdvertisingSupported()) {
263 ExAdvClearHandle();
264 }
265 ClearScanResultInfo();
266 DeregisterAllCallback();
267 ClearScannerIdInfo();
268
269 ret = (BTM_Disable(LE_CONTROLLER) == BT_SUCCESS);
270 if (!ret) {
271 LOG_ERROR("[BleAdapter] %{public}s:BTM Disable failed!", __func__);
272 } else {
273 LOG_DEBUG("[BleAdapter] %{public}s:BTM Disable successfully!", __func__);
274 }
275 GetContext()->OnDisable(ADAPTER_NAME_BLE, ret);
276 return ret;
277 }
278
NotifyAllWaitContinue() const279 void BleAdapter::NotifyAllWaitContinue() const
280 {
281 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
282
283 pimpl->cvfull_.notify_all();
284 }
285
PostEnable()286 void BleAdapter::PostEnable()
287 {
288 LOG_DEBUG("[BleAdapter] %{public}s:%{public}s", __func__, Name().c_str());
289
290 if (!pimpl->btmEnableFlag_) {
291 GetDispatcher()->PostTask(std::bind(&BleAdapter::PostEnableTask, this));
292 return;
293 }
294
295 int ret = SetBleRoles();
296 if (ret != BT_SUCCESS) {
297 LOG_ERROR("[BleAdvertiserImpl] %{public}s:Set ble roles failed!.", __func__);
298 }
299
300 GetDispatcher()->PostTask(std::bind(&BleAdapter::PostEnableTask, this));
301 }
302
PostEnableTask() const303 bool BleAdapter::PostEnableTask() const
304 {
305 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
306
307 return true;
308 }
309
StartOrStopAdvAndScan( const STOP_ALL_ADV_TYPE &stopAllAdvType, const STOP_SCAN_TYPE &scanType, bool isStartAdvAndScan) const310 void BleAdapter::StartOrStopAdvAndScan(
311 const STOP_ALL_ADV_TYPE &stopAllAdvType, const STOP_SCAN_TYPE &scanType, bool isStartAdvAndScan) const
312 {
313 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
314 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
315 if ((pimpl->bleAdvertiser_ != nullptr) &&
316 (pimpl->bleAdvertiser_->GetAdvertisingStatus() == ADVERTISE_FAILED_ALREADY_STARTED)) {
317 std::unique_lock<std::mutex> lock(pimpl->mutexAdvAdnScan_);
318 pimpl->bleAdvertiser_->StartOrStopAllAdvertising(stopAllAdvType, isStartAdvAndScan);
319 if (pimpl->cvfull_.wait_for(lock, std::chrono::seconds(BLE_THREAD_WAIT_TIMEOUT)) == std::cv_status::timeout) {
320 LOG_ERROR("[BleAdapter] %{public}s:StartOrStopAdvAndScan timeout!", __func__);
321 }
322 }
323
324 if (pimpl->bleCentralManager_ != nullptr) {
325 if (pimpl->bleCentralManager_->GetScanStatus() == SCAN_FAILED_ALREADY_STARTED) {
326 std::unique_lock<std::mutex> lock(pimpl->mutexAdvAdnScan_);
327 pimpl->bleCentralManager_->StartOrStopScan(scanType, isStartAdvAndScan);
328 if (pimpl->cvfull_.wait_for(lock, std::chrono::seconds(BLE_THREAD_WAIT_TIMEOUT)) ==
329 std::cv_status::timeout) {
330 LOG_ERROR("[BleAdapter] %{public}s:StartOrStopAdvAndScan timeout!", __func__);
331 }
332 }
333 }
334 }
335
ExAdvClearHandle() const336 void BleAdapter::ExAdvClearHandle() const
337 {
338 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
339
340 std::unique_lock<std::mutex> lock(pimpl->mutexAdvAdnScan_);
341 if (pimpl->bleAdvertiser_ != nullptr) {
342 pimpl->bleAdvertiser_->GAPExAdvClearHandle();
343 if (pimpl->cvfull_.wait_for(lock, std::chrono::seconds(BLE_THREAD_WAIT_TIMEOUT)) == std::cv_status::timeout) {
344 LOG_ERROR("[BleAdapter] %{public}s:ExAdvClearHandle timeout!", __func__);
345 }
346 }
347 }
348
LoadConfig() const349 void BleAdapter::LoadConfig() const
350 {
351 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
352
353 bool ret = BleProperties::GetInstance().LoadBleConfigInfo();
354 if (!ret) {
355 LOG_ERROR("[BleAdapter] %{public}s:LoadBleConfigInfo File failed!", __func__);
356 } else {
357 LOG_DEBUG("[BleAdapter] %{public}s:LoadBleConfigInfo File success!", __func__);
358 }
359
360 ret &= BleProperties::GetInstance().ConfigBleProperties();
361 ret &= BleProperties::GetInstance().GetAddrFromController();
362 if (ret) {
363 BTM_SetOwnAddressType(BLE_ADDR_TYPE::BLE_ADDR_TYPE_PUBLIC);
364 }
365
366 if (!ret) {
367 LOG_ERROR("[BleAdapter] %{public}s:ConfigBleProperties File failed!", __func__);
368 BleProperties::GetInstance().SaveDefaultValues();
369 } else {
370 LOG_DEBUG("[BleAdapter] %{public}s:ConfigBleProperties File success!", __func__);
371 }
372 }
373
DeregisterAllCallback() const374 int BleAdapter::DeregisterAllCallback() const
375 {
376 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
377
378 DeregisterBleSecurityCallback();
379 DeregisterBleAdvertiserCallback();
380 DeregisterBleCentralManagerCallback();
381 return DeregisterCallbackToBtm();
382 }
383
GenResPriAddrResult(uint8_t result, const uint8_t addr[BT_ADDRESS_SIZE], void *context)384 void BleAdapter::GenResPriAddrResult(uint8_t result, const uint8_t addr[BT_ADDRESS_SIZE], void *context)
385 {
386 HILOGI("ResPriAddr: %{public}s", GetEncryptAddr(RawAddress::ConvertToString(addr).GetAddress()).c_str());
387
388 auto *adapter = static_cast<BleAdapter *>(context);
389 std::unique_lock<std::mutex> lock(adapter->pimpl->mutexRpa_);
390 BtAddr btAddr;
391 (void)memcpy_s(&btAddr.addr, BT_ADDRESS_SIZE, addr, BT_ADDRESS_SIZE);
392 btAddr.type = BLE_ADDR_TYPE_RANDOM;
393 int ret = BTM_SetLeRandomAddress(&btAddr);
394 if (ret != BT_SUCCESS) {
395 LOG_ERROR("[BleAdapter] %{public}s:GenResPriAddrResult failed!", __func__);
396 }
397 BTM_SetOwnAddressType(BLE_ADDR_TYPE_RANDOM);
398
399 adapter->pimpl->cvfull_.notify_all();
400 }
401
SetRpaAddrAndTypeToBtm()402 int BleAdapter::SetRpaAddrAndTypeToBtm()
403 {
404 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
405
406 /// btm set address type and rpa address
407 int ret = BT_SUCCESS;
408 switch (BleConfig::GetInstance().GetBleAddrType()) {
409 case BLE_ADDR_TYPE_RPA: {
410 std::unique_lock<std::mutex> lock(pimpl->mutexRpa_);
411 ret = GAPIF_LeGenResPriAddr(&BleAdapter::GenResPriAddrResult, this);
412 if (ret != BT_SUCCESS) {
413 LOG_ERROR("[BleAdapter] %{public}s:GAP_LeGenResPriAddrAsync failed!", __func__);
414 }
415 if (pimpl->cvfull_.wait_for(lock, std::chrono::seconds(BLE_THREAD_WAIT_TIMEOUT)) ==
416 std::cv_status::timeout) {
417 LOG_ERROR("[BleAdapter] %{public}s:GAP_LeGenResPriAddrAsync timeout!", __func__);
418 }
419 break;
420 }
421 case BLE_ADDR_TYPE_PUBLIC:
422 default:
423 BTM_SetOwnAddressType(BleConfig::GetInstance().GetBleLocalAddrType());
424 break;
425 }
426 return ret;
427 }
428
SetLocalIrkAndIdentityAddrToBtm() const429 int BleAdapter::SetLocalIrkAndIdentityAddrToBtm() const
430 {
431 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
432
433 std::string irk = BleConfig::GetInstance().GetLocalIrk();
434 if (irk.empty()) {
435 std::vector<uint8_t> key;
436 BleUtils::Rand16hex(key);
437 BleConfig::GetInstance().SetLocalIrk(BleUtils::ConvertIntToHexString(key));
438 irk = BleUtils::ConvertIntToHexString(key);
439 }
440 std::vector<uint8_t> vec;
441 BleUtils::ConvertHexStringToInt(irk, vec);
442 BtmKey btmKey;
443 if (memcpy_s(btmKey.key, KEY_SIZE, &vec[0], vec.size()) != EOK) {
444 LOG_DEBUG("[BleAdapter] %{public}s:memcpy_s btmKey failed!", __func__);
445 return BT_OPERATION_FAILED;
446 }
447 BTM_SetLocalIdentityResolvingKey(&btmKey);
448 /// check public address
449 std::string addr = BleConfig::GetInstance().GetLocalAddress();
450 int ret = BT_SUCCESS;
451 std::string invalidMacAddress(INVALID_MAC_ADDRESS);
452 if ((addr.empty()) || (invalidMacAddress.compare(addr) == 0)) {
453 std::vector<uint8_t>().swap(vec);
454 BleUtils::GetRandomAddress(vec, false);
455 addr = RawAddress::ConvertToString(&vec[0]).GetAddress();
456 BleConfig::GetInstance().SetBleLocalAddrType(BLE_ADDR_TYPE::BLE_ADDR_TYPE_RANDOM);
457 BTM_SetOwnAddressType(BLE_ADDR_TYPE::BLE_ADDR_TYPE_RANDOM);
458 HILOGI("GAP_LeSetStaticIdentityAddr random addr = %{public}s!", GetEncryptAddr(addr).c_str());
459 ret = GAPIF_LeSetStaticIdentityAddr(&vec[0]);
460 if (ret != BT_SUCCESS) {
461 LOG_DEBUG("[BleAdapter] %{public}s:GAP_LeSetStaticIdentityAddr failed!", __func__);
462 }
463 }
464
465 if (!BleConfig::GetInstance().SetLocalIdentityAddr(addr)) {
466 LOG_DEBUG("[BleAdapter] %{public}s:SetLocalIdentityAddr failed!", __func__);
467 }
468 return ret;
469 }
470
GetLocalAddress() const471 std::string BleAdapter::GetLocalAddress() const
472 {
473 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
474
475 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
476 return BleProperties::GetInstance().GetLocalAddress();
477 }
478
GetLocalName() const479 std::string BleAdapter::GetLocalName() const
480 {
481 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
482
483 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
484 return BleProperties::GetInstance().GetLocalName();
485 }
486
SetLocalName(const std::string &name) const487 bool BleAdapter::SetLocalName(const std::string &name) const
488 {
489 LOG_DEBUG("[BleAdapter] %{public}s:SetLocalName %{public}s", __func__, name.c_str());
490
491 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
492 return BleProperties::GetInstance().SetLocalName(name);
493 }
494
GetDeviceName(const RawAddress &device) const495 std::string BleAdapter::GetDeviceName(const RawAddress &device) const
496 {
497 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
498
499 std::string remoteName = "";
500
501 if (!Compat::CompatCheck(CompatType::COMPAT_REJECT_NAME_REQUEST, device.GetAddress())) {
502 int appID = RegisterGattClientApplication(device);
503 remoteName = ReadRemoteDeviceNameByGatt(device, appID);
504 DeregisterGattClientApplication(appID);
505 }
506
507 if (!remoteName.empty()) {
508 return remoteName;
509 }
510
511 if (pimpl->bleCentralManager_ != nullptr) {
512 remoteName = pimpl->bleCentralManager_->GetDeviceName(device.GetAddress());
513 }
514
515 if (remoteName.empty()) {
516 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
517 auto it = pimpl->peerConnDeviceList_.find(device.GetAddress());
518 if (it != pimpl->peerConnDeviceList_.end()) {
519 remoteName = it->second.GetName();
520 }
521 }
522 return remoteName;
523 }
524
RegisterGattClientApplication(const RawAddress &addr) const525 int BleAdapter::RegisterGattClientApplication(const RawAddress &addr) const
526 {
527 pimpl->gattClientService_ =
528 static_cast<IProfileGattClient *>(IProfileManager::GetInstance()->GetProfileService(PROFILE_NAME_GATT_CLIENT));
529 if (pimpl->gattClientService_ != nullptr) {
530 return pimpl->gattClientService_->RegisterSharedApplication(
531 *pimpl->gattClientcallback_, addr, BTTransport::ADAPTER_BLE);
532 }
533
534 return RET_NO_SUPPORT;
535 }
536
DeregisterGattClientApplication(int appID) const537 void BleAdapter::DeregisterGattClientApplication(int appID) const
538 {
539 pimpl->gattClientService_ =
540 static_cast<IProfileGattClient *>(IProfileManager::GetInstance()->GetProfileService(PROFILE_NAME_GATT_CLIENT));
541 if (pimpl->gattClientService_ == nullptr) {
542 return;
543 }
544 pimpl->gattClientService_->DeregisterApplication(appID);
545 }
546
ReadRemoteDeviceNameByGatt(const RawAddress &addr, int appID) const547 std::string BleAdapter::ReadRemoteDeviceNameByGatt(const RawAddress &addr, int appID) const
548 {
549 std::string name = "";
550 pimpl->gattClientService_ =
551 static_cast<IProfileGattClient *>(IProfileManager::GetInstance()->GetProfileService(PROFILE_NAME_GATT_CLIENT));
552 if (pimpl->gattClientService_ == nullptr) {
553 return name;
554 }
555
556 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
557 auto it = pimpl->peerConnDeviceList_.find(addr.GetAddress());
558 if (it != pimpl->peerConnDeviceList_.end()) {
559 LOG_DEBUG("[BleAdapter] isAclConnect %{public}d ", it->second.IsAclConnected());
560 if (it->second.IsAclConnected()) {
561 std::unique_lock<std::mutex> lock(pimpl->mutexRemoteName_);
562 // Device name
563 LOG_DEBUG("Get device name from gatt. %{public}d", appID);
564 Uuid uuid = Uuid::ConvertFrom16Bits(GATT_UUID_GAP_DEVICE_NAME);
565 pimpl->gattClientService_->Connect(appID, true);
566 pimpl->gattClientService_->ReadCharacteristicByUuid(appID, uuid);
567 if (pimpl->cvfull_.wait_for(lock, std::chrono::seconds(BLE_THREAD_WAIT_TIMEOUT)) ==
568 std::cv_status::timeout) {
569 LOG_ERROR("[BleAdapter] %{public}s:ReadRemoteDeviceNameByGatt timeout!", __func__);
570 pimpl->gattClientService_->Disconnect(appID);
571 return name;
572 }
573 if (pimpl->readCharacteristicFlag_) {
574 pimpl->gattClientService_->Disconnect(appID);
575 }
576 return pimpl->remoteDeviceName_;
577 }
578 }
579 return name;
580 }
581
GetDeviceUuids(const RawAddress &device) const582 std::vector<Uuid> BleAdapter::GetDeviceUuids(const RawAddress &device) const
583 {
584 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
585
586 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
587 std::vector<Uuid> uuids;
588 auto it = pimpl->peerConnDeviceList_.find(device.GetAddress());
589 if (it != pimpl->peerConnDeviceList_.end()) {
590 uuids = it->second.GetServiceUUID();
591 }
592 return uuids;
593 }
594
GetPairedDevices() const595 std::vector<RawAddress> BleAdapter::GetPairedDevices() const
596 {
597 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
598
599 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
600 std::vector<RawAddress> pairedList;
601 for (auto it = pimpl->peerConnDeviceList_.begin(); it != pimpl->peerConnDeviceList_.end(); it++) {
602 if (BLE_PAIR_PAIRED == it->second.GetPairedStatus()) {
603 RawAddress rawAddr(it->second.GetRawAddress());
604 pairedList.push_back(rawAddr);
605 }
606 }
607 return pairedList;
608 }
609
GetConnectedDevices() const610 std::vector<RawAddress> BleAdapter::GetConnectedDevices() const
611 {
612 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
613
614 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
615 std::vector<RawAddress> pairedList;
616 for (auto it = pimpl->peerConnDeviceList_.begin(); it != pimpl->peerConnDeviceList_.end(); it++) {
617 RawAddress rawAddr(it->second.GetRawAddress());
618 pairedList.push_back(rawAddr);
619 }
620 return pairedList;
621 }
622
StartPair(const RawAddress &device)623 bool BleAdapter::StartPair(const RawAddress &device)
624 {
625 HILOGI("addr: %{public}s", GetEncryptAddr(device.GetAddress()).c_str());
626
627 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
628 if (pimpl->bleSecurity_ == nullptr) {
629 LOG_ERROR("[BleAdapter] %{public}s:failed", __func__);
630 return false;
631 }
632
633 uint8_t peerAddrType = GetPeerDeviceAddrType(RawAddress(device.GetAddress()));
634 auto it = pimpl->peerConnDeviceList_.find(device.GetAddress());
635 if (it != pimpl->peerConnDeviceList_.end()) {
636 peerAddrType = it->second.GetAddressType();
637 if (BLE_PAIR_PAIRING == it->second.GetPairedStatus()) {
638 LOG_ERROR("[BleAdapter] %{public}s:StartPair failed, because of PAIR_NONE or PAIRING!", __func__);
639 return false;
640 }
641 }
642
643 int ret = pimpl->bleSecurity_->StartPair(device, peerAddrType);
644 if (!ret) {
645 LOG_ERROR("[BleAdapter] %{public}s:failed", __func__);
646 return false;
647 }
648 LePairingStatus(device);
649 return true;
650 }
651
CancelPairing(const RawAddress &device)652 bool BleAdapter::CancelPairing(const RawAddress &device)
653 {
654 HILOGI("addr: %{public}s", GetEncryptAddr(device.GetAddress()).c_str());
655
656 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
657 auto it = pimpl->peerConnDeviceList_.find(device.GetAddress());
658 if (it != pimpl->peerConnDeviceList_.end()) {
659 int pairState = it->second.GetPairedStatus();
660 if ((BLE_PAIR_PAIRED == pairState) || (BLE_PAIR_CANCELING == pairState) || (BLE_PAIR_NONE == pairState)) {
661 HILOGE("CancelPairing failed, because of BLE_PAIR_NONE, PAIR_PAIRED or PAIR_CANCELING! %{public}d",
662 pairState);
663 return false;
664 }
665
666 if (pimpl->bleSecurity_ == nullptr) {
667 return false;
668 }
669
670 if (BT_SUCCESS == pimpl->bleSecurity_->CancelPairing(device)) {
671 it->second.SetPairedStatus(BLE_PAIR_CANCELING);
672 } else {
673 LOG_ERROR("[BleAdapter] %{public}s:CancelPairing failed, because of gap cancel pair failed!", __func__);
674 return false;
675 }
676 } else {
677 LOG_ERROR("[BleAdapter] %{public}s:CancelPairing failed, because of not find the remote device!", __func__);
678 return false;
679 }
680
681 return true;
682 }
683
RemovePairWithDisConnect(const RawAddress &device, bool isDisconnect) const684 bool BleAdapter::RemovePairWithDisConnect(const RawAddress &device, bool isDisconnect) const
685 {
686 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
687 auto it = pimpl->peerConnDeviceList_.find(device.GetAddress());
688 if ((it == pimpl->peerConnDeviceList_.end()) || (it->second.GetPairedStatus() != BLE_PAIR_PAIRED)) {
689 LOG_ERROR("[BleAdapter] %{public}s:RemovePair failed, because of not find the paired device!", __func__);
690 return false;
691 }
692
693 BleConfig::GetInstance().RemovePairedDevice(device.GetAddress());
694
695 if ((it->second.IsAclConnected()) && (isDisconnect)) {
696 int ret = BTM_AclDisconnect(it->second.GetConnectionHandle(), BTM_ACL_DISCONNECT_REASON);
697 if (ret != BT_SUCCESS) {
698 LOG_ERROR("[BleAdapter] %{public}s:BTM_AclDisconnect failed!", __func__);
699 }
700 }
701
702 // Del pair device from BTM
703 StartOrStopAdvAndScan(STOP_ADV_TYPE_RESOLVING_LIST, STOP_SCAN_TYPE_RESOLVING_LIST);
704 BtAddr btAddr;
705 (void)memset_s(&btAddr, sizeof(btAddr), 0x00, sizeof(btAddr));
706 btAddr.type = it->second.GetAddressType();
707 device.ConvertToUint8(btAddr.addr);
708 BTM_RemoveLePairedDevice(&btAddr);
709 StartOrStopAdvAndScan(STOP_ADV_TYPE_RESOLVING_LIST, STOP_SCAN_TYPE_RESOLVING_LIST, true);
710
711 if (isDisconnect) {
712 pimpl->peerConnDeviceList_.erase(device.GetAddress());
713 }
714 BleConfig::GetInstance().Save();
715
716 std::vector<RawAddress> removeDevices;
717 removeDevices.push_back(device);
718 AdapterManager::GetInstance()->OnPairDevicesRemoved(BTTransport::ADAPTER_BLE, removeDevices);
719
720 if (pimpl->blePeripheralCallback_ != nullptr) {
721 pimpl->blePeripheralCallback_->ForEach([device](IBlePeripheralCallback &observer) {
722 observer.OnPairStatusChanged(ADAPTER_BLE, device, BLE_PAIR_NONE);
723 });
724 }
725 return true;
726 }
727
RemovePair(const RawAddress &device)728 bool BleAdapter::RemovePair(const RawAddress &device)
729 {
730 HILOGI("addr: %{public}s", GetEncryptAddr(device.GetAddress()).c_str());
731
732 return RemovePairWithDisConnect(device);
733 }
734
RemoveAllPairs()735 bool BleAdapter::RemoveAllPairs()
736 {
737 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
738
739 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
740 std::vector<RawAddress> removeDevices;
741 auto it = pimpl->peerConnDeviceList_.begin();
742 while (it != pimpl->peerConnDeviceList_.end()) {
743 if (it->second.GetPairedStatus() != BLE_PAIR_PAIRED) {
744 it++;
745 continue;
746 }
747
748 std::string addr = it->second.GetRawAddress().GetAddress();
749 BleConfig::GetInstance().RemovePairedDevice(addr);
750 removeDevices.push_back(it->second.GetRawAddress());
751
752 int ret = BT_SUCCESS;
753 if (it->second.IsAclConnected()) {
754 ret = BTM_AclDisconnect(it->second.GetConnectionHandle(), BTM_ACL_DISCONNECT_REASON);
755 }
756 if (ret != BT_SUCCESS) {
757 LOG_ERROR("[BleAdapter] %{public}s:BTM_AclDisconnect failed!", __func__);
758 }
759 pimpl->peerConnDeviceList_.erase(it++);
760 }
761
762 // Del all paired devices from BTM
763 StartOrStopAdvAndScan(STOP_ADV_TYPE_RESOLVING_LIST, STOP_SCAN_TYPE_RESOLVING_LIST);
764 BTM_SetLePairedDevices(nullptr, 0);
765 StartOrStopAdvAndScan(STOP_ADV_TYPE_RESOLVING_LIST, STOP_SCAN_TYPE_RESOLVING_LIST, true);
766
767 if (!removeDevices.empty()) {
768 BleConfig::GetInstance().Save();
769 AdapterManager::GetInstance()->OnPairDevicesRemoved(BTTransport::ADAPTER_BLE, removeDevices);
770 }
771 return true;
772 }
773
IsRemovePairedDevice(const RawAddress &device) const774 bool BleAdapter::IsRemovePairedDevice(const RawAddress &device) const
775 {
776 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
777
778 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
779 auto it = pimpl->peerConnDeviceList_.find(device.GetAddress());
780 if (it != pimpl->peerConnDeviceList_.end()) {
781 return false;
782 }
783 return true;
784 }
785
IsBondedFromLocal(const RawAddress &device) const786 bool BleAdapter::IsBondedFromLocal(const RawAddress &device) const
787 {
788 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
789
790 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
791 bool isBondedFromLocal = false;
792 auto it = pimpl->peerConnDeviceList_.find(device.GetAddress());
793 if (it != pimpl->peerConnDeviceList_.end()) {
794 isBondedFromLocal = it->second.IsAclEncrypted();
795 }
796 return isBondedFromLocal;
797 }
798
SetDevicePasskey(const RawAddress &device, int passkey, bool accept) const799 bool BleAdapter::SetDevicePasskey(const RawAddress &device, int passkey, bool accept) const
800 {
801 LOG_DEBUG("[BleAdapter] %{public}s:%{public}d %{public}d", __func__, passkey, accept);
802
803 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
804 if (pimpl->bleSecurity_ == nullptr) {
805 LOG_ERROR("[BleAdapter] %{public}s:SetDevicePasskey failed!", __func__);
806 return false;
807 }
808
809 if (!BLE_INVALID_MAC_ADDRESS.compare(device.GetAddress())) {
810 LOG_ERROR("[BleAdapter] %{public}s:SetDevicePasskey failed, because of invalid bt address!", __func__);
811 return false;
812 }
813
814 auto it = pimpl->peerConnDeviceList_.find(device.GetAddress());
815 if (it == pimpl->peerConnDeviceList_.end()) {
816 LOG_ERROR("[BleAdapter] %{public}s:SetDevicePasskey failed, because of address not exist!", __func__);
817 return false;
818 }
819
820 int ret;
821 if ((BLE_PAIR_CANCELING == it->second.GetPairedStatus()) || (!accept)) {
822 ret = pimpl->bleSecurity_->SetDevicePasskey(device, passkey, GAP_NOT_ACCEPT);
823 } else {
824 ret = pimpl->bleSecurity_->SetDevicePasskey(device, passkey, GAP_ACCEPT);
825 }
826 if (BT_SUCCESS != ret) {
827 LOG_ERROR("[BleAdapter] %{public}s:SetDevicePasskey failed!", __func__);
828 return false;
829 }
830 return true;
831 }
832
PairRequestReply(const RawAddress &device, bool accept) const833 bool BleAdapter::PairRequestReply(const RawAddress &device, bool accept) const
834 {
835 LOG_DEBUG("[BleAdapter] %{public}s:%{public}d", __func__, accept);
836
837 if (pimpl->bleSecurity_ != nullptr) {
838 int addrType = GetPeerDeviceAddrType(device);
839 return pimpl->bleSecurity_->PairRequestReply(device, addrType, accept);
840 }
841 return false;
842 }
843
IsAclConnected(const RawAddress &device) const844 bool BleAdapter::IsAclConnected(const RawAddress &device) const
845 {
846 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
847
848 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
849 bool isAclConnected = false;
850 auto it = pimpl->peerConnDeviceList_.find(device.GetAddress());
851 if (it != pimpl->peerConnDeviceList_.end()) {
852 isAclConnected = it->second.IsAclConnected();
853 }
854 return isAclConnected;
855 }
856
IsAclEncrypted(const RawAddress &device) const857 bool BleAdapter::IsAclEncrypted(const RawAddress &device) const
858 {
859 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
860
861 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
862 bool isAclEncrypted = false;
863 auto it = pimpl->peerConnDeviceList_.find(device.GetAddress());
864 if (it != pimpl->peerConnDeviceList_.end()) {
865 isAclEncrypted = it->second.IsAclEncrypted();
866 }
867 return isAclEncrypted;
868 }
869
GetContext()870 utility::Context *BleAdapter::GetContext()
871 {
872 return this;
873 }
874
GetPairState(const RawAddress &device) const875 int BleAdapter::GetPairState(const RawAddress &device) const
876 {
877 HILOGI("addr: %{public}s", GetEncryptAddr(device.GetAddress()).c_str());
878
879 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
880 int pairState = BLE_PAIR_NONE;
881 auto it = pimpl->peerConnDeviceList_.find(device.GetAddress());
882 if (it == pimpl->peerConnDeviceList_.end()) {
883 return pairState;
884 } else {
885 pairState = it->second.GetPairedStatus();
886 }
887 return pairState;
888 }
889
GetBondableMode() const890 int BleAdapter::GetBondableMode() const
891 {
892 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
893
894 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
895 return BleProperties::GetInstance().GetBondableMode();
896 }
897
SetBondableMode(int mode) const898 bool BleAdapter::SetBondableMode(int mode) const
899 {
900 LOG_DEBUG("[BleAdapter] %{public}s:%{public}d", __func__, mode);
901
902 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
903 return (BleProperties::GetInstance().SetBondableMode(mode) == BT_SUCCESS);
904 }
905
SetDevicePairingConfirmation(const RawAddress &device, bool accept) const906 bool BleAdapter::SetDevicePairingConfirmation(const RawAddress &device, bool accept) const
907 {
908 HILOGI("addr: %{public}s, accept: %{public}d", GetEncryptAddr(device.GetAddress()).c_str(), accept);
909
910 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
911 if (pimpl->bleSecurity_ == nullptr) {
912 LOG_ERROR("[BleAdapter] %{public}s:failed", __func__);
913 return false;
914 }
915
916 if (BLE_INVALID_MAC_ADDRESS == device.GetAddress()) {
917 LOG_ERROR("[BleAdapter] %{public}s:failed, because of invalid bt address!", __func__);
918 return false;
919 }
920
921 auto it = pimpl->peerConnDeviceList_.find(device.GetAddress());
922 if (it == pimpl->peerConnDeviceList_.end()) {
923 LOG_ERROR("[BleAdapter] %{public}s:failed, because of address not exist!", __func__);
924 return false;
925 }
926
927 int ret;
928 if ((BLE_PAIR_CANCELING == it->second.GetPairedStatus()) || (!accept)) {
929 ret = pimpl->bleSecurity_->SetUserConfirm(device, GAP_NOT_ACCEPT);
930 } else {
931 ret = pimpl->bleSecurity_->SetUserConfirm(device, GAP_ACCEPT);
932 }
933 if (BT_SUCCESS != ret) {
934 LOG_ERROR("[BleAdapter] %{public}s:failed!", __func__);
935 return false;
936 }
937 return true;
938 }
939
GetBleMaxAdvertisingDataLength() const940 int BleAdapter::GetBleMaxAdvertisingDataLength() const
941 {
942 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
943
944 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
945 return BleFeature::GetInstance().GetBleMaximumAdvertisingDataLength();
946 }
947
GetIoCapability() const948 int BleAdapter::GetIoCapability() const
949 {
950 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
951
952 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
953 return BleProperties::GetInstance().GetIoCapability();
954 }
955
SetIoCapability(int ioCapability) const956 bool BleAdapter::SetIoCapability(int ioCapability) const
957 {
958 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
959
960 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
961 return BleProperties::GetInstance().SetIoCapability(ioCapability);
962 }
963
IsBleEnabled() const964 bool BleAdapter::IsBleEnabled() const
965 {
966 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
967
968 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
969 int status = AdapterManager::GetInstance()->GetState(BTTransport::ADAPTER_BLE);
970 return (status == BTStateID::STATE_TURN_ON);
971 }
972
IsBtDiscovering() const973 bool BleAdapter::IsBtDiscovering() const
974 {
975 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
976
977 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
978 if (pimpl->bleCentralManager_ != nullptr) {
979 return (SCAN_FAILED_ALREADY_STARTED == pimpl->bleCentralManager_->GetScanStatus());
980 }
981 return false;
982 }
983
RegisterBleAdvertiserCallback(IBleAdvertiserCallback &callback)984 void BleAdapter::RegisterBleAdvertiserCallback(IBleAdvertiserCallback &callback)
985 {
986 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
987
988 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
989 if (pimpl->bleAdvertiser_ == nullptr) {
990 pimpl->bleAdvertiser_ = std::make_unique<BleAdvertiserImpl>(callback, *this, *GetDispatcher());
991 }
992 }
993
DeregisterBleAdvertiserCallback() const994 void BleAdapter::DeregisterBleAdvertiserCallback() const
995 {
996 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
997
998 if (pimpl->bleAdvertiser_ != nullptr) {
999 pimpl->bleAdvertiser_->DeregisterCallbackToGap();
1000 }
1001 }
1002
RegisterBleCentralManagerCallback(IBleCentralManagerCallback &callback)1003 void BleAdapter::RegisterBleCentralManagerCallback(IBleCentralManagerCallback &callback)
1004 {
1005 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
1006
1007 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
1008 if (pimpl->bleCentralManager_ == nullptr) {
1009 pimpl->bleCentralManager_ = std::make_unique<BleCentralManagerImpl>(callback, *this, *GetDispatcher());
1010 }
1011 }
1012
DeregisterBleCentralManagerCallback() const1013 void BleAdapter::DeregisterBleCentralManagerCallback() const
1014 {
1015 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
1016
1017 if (pimpl->bleCentralManager_ != nullptr) {
1018 pimpl->bleCentralManager_->DeregisterCallbackToGap();
1019 }
1020 }
1021
RegisterBlePeripheralCallback(IBlePeripheralCallback &callback) const1022 void BleAdapter::RegisterBlePeripheralCallback(IBlePeripheralCallback &callback) const
1023 {
1024 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
1025
1026 if (pimpl->blePeripheralCallback_ != nullptr) {
1027 pimpl->blePeripheralCallback_->Register(callback);
1028 }
1029 }
1030
DeregisterBlePeripheralCallback(IBlePeripheralCallback &callback) const1031 void BleAdapter::DeregisterBlePeripheralCallback(IBlePeripheralCallback &callback) const
1032 {
1033 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
1034
1035 if (pimpl->blePeripheralCallback_ != nullptr) {
1036 pimpl->blePeripheralCallback_->Deregister(callback);
1037 }
1038 }
1039
RegisterBleSecurityCallback(BaseObserverList<IAdapterBleObserver> &callback)1040 void BleAdapter::RegisterBleSecurityCallback(BaseObserverList<IAdapterBleObserver> &callback)
1041 {
1042 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
1043
1044 if (pimpl->bleSecurity_ == nullptr) {
1045 pimpl->bleSecurity_ = std::make_unique<BleSecurity>(*this, *GetDispatcher(), callback);
1046 } else {
1047 pimpl->bleSecurity_->RegisterCallbackToGap();
1048 }
1049 }
1050
DeregisterBleSecurityCallback() const1051 void BleAdapter::DeregisterBleSecurityCallback() const
1052 {
1053 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
1054
1055 if (pimpl->bleSecurity_ != nullptr) {
1056 pimpl->bleSecurity_->DeregisterCallbackToGap();
1057 }
1058 }
1059
RegisterBleAdapterObserver(IAdapterBleObserver &observer) const1060 bool BleAdapter::RegisterBleAdapterObserver(IAdapterBleObserver &observer) const
1061 {
1062 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
1063
1064 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
1065 if (pimpl->observer_ != nullptr) {
1066 pimpl->observer_->Register(observer);
1067 }
1068 BleProperties::GetInstance().RegisterBleAdapterObserver(*pimpl->observer_.get());
1069 return true;
1070 }
1071
DeregisterBleAdapterObserver(IAdapterBleObserver &observer) const1072 bool BleAdapter::DeregisterBleAdapterObserver(IAdapterBleObserver &observer) const
1073 {
1074 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
1075
1076 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
1077 BleProperties::GetInstance().DeregisterBleAdapterObserver(observer);
1078 return true;
1079 }
1080
GetPeerDeviceAddrType(const RawAddress &device) const1081 int BleAdapter::GetPeerDeviceAddrType(const RawAddress &device) const
1082 {
1083 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
1084
1085 int type = BLE_ADDR_TYPE_UNKNOWN;
1086 if (pimpl->bleCentralManager_ != nullptr) {
1087 type = pimpl->bleCentralManager_->GetDeviceAddrType(device.GetAddress());
1088 }
1089 if (type == BLE_ADDR_TYPE_UNKNOWN) {
1090 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
1091 type = BLE_ADDR_TYPE_RANDOM;
1092 auto it = pimpl->peerConnDeviceList_.find(device.GetAddress());
1093 if (it != pimpl->peerConnDeviceList_.end()) {
1094 type = it->second.GetAddressType();
1095 }
1096 }
1097 return type;
1098 }
1099
ReadPeerDeviceInfoFromConf(const std::vector<std::string> &pairedAddrList) const1100 void BleAdapter::ReadPeerDeviceInfoFromConf(const std::vector<std::string> &pairedAddrList) const
1101 {
1102 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
1103
1104 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
1105 for (auto addr : pairedAddrList) {
1106 RawAddress rawAddr(addr);
1107 std::string invalidMacAddress(INVALID_MAC_ADDRESS);
1108 if ((!invalidMacAddress.compare(rawAddr.GetAddress())) || (rawAddr.GetAddress().empty())) {
1109 continue;
1110 }
1111 BlePeripheralDevice remote;
1112 remote.SetAddress(rawAddr);
1113 remote.SetAddressType(BleConfig::GetInstance().GetPeerAddressType(addr));
1114
1115 std::string name = BleConfig::GetInstance().GetPeerName(addr);
1116 remote.SetName(name);
1117
1118 int io = BleConfig::GetInstance().GetPeerDeviceIoCapability(addr);
1119 remote.SetIoCapability(io);
1120
1121 remote.SetPairedStatus(BLE_PAIR_PAIRED);
1122
1123 pimpl->peerConnDeviceList_.insert(std::make_pair(addr, remote));
1124 }
1125 }
1126
SavePeerDeviceInfoToConf(const std::map<std::string, BlePeripheralDevice> &peerConnDeviceList) const1127 bool BleAdapter::SavePeerDeviceInfoToConf(const std::map<std::string, BlePeripheralDevice> &peerConnDeviceList) const
1128 {
1129 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
1130
1131 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
1132 bool ret = false;
1133 for (auto it = peerConnDeviceList.begin(); it != peerConnDeviceList.end(); it++) {
1134 if (it->second.GetPairedStatus() != BLE_PAIR_PAIRED) {
1135 continue;
1136 }
1137 RawAddress rawAddr(it->second.GetRawAddress());
1138
1139 int addrType = it->second.GetAddressType();
1140 ret = BleConfig::GetInstance().SetPeerAddressType(rawAddr.GetAddress(), addrType);
1141
1142 ret &= BleConfig::GetInstance().SetPeerName(rawAddr.GetAddress(), it->second.GetName());
1143
1144 int deviceType = it->second.GetDeviceType();
1145 ret &= BleConfig::GetInstance().SetPeerDeviceType(rawAddr.GetAddress(), deviceType);
1146 }
1147
1148 BleConfig::GetInstance().Save();
1149 return ret;
1150 }
1151
ClearPeerDeviceInfo() const1152 void BleAdapter::ClearPeerDeviceInfo() const
1153 {
1154 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
1155
1156 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
1157 pimpl->peerConnDeviceList_.clear();
1158 }
1159
ClearScanResultInfo() const1160 void BleAdapter::ClearScanResultInfo() const
1161 {
1162 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
1163
1164 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
1165 if (pimpl->bleCentralManager_ != nullptr) {
1166 pimpl->bleCentralManager_->ClearResults();
1167 }
1168 }
1169
ClearScannerIdInfo() const1170 void BleAdapter::ClearScannerIdInfo() const
1171 {
1172 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
1173
1174 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
1175 if (pimpl->bleCentralManager_ != nullptr) {
1176 pimpl->bleCentralManager_->ClearScannerIds();
1177 }
1178 }
1179
SavePeerDevices2BTM(const std::map<std::string, BlePeripheralDevice> &peerConnDeviceList) const1180 void BleAdapter::SavePeerDevices2BTM(const std::map<std::string, BlePeripheralDevice> &peerConnDeviceList) const
1181 {
1182 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
1183
1184 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
1185 // Add pair device to BTM
1186 std::vector<BtmLePairedDevice> devices;
1187 for (auto it = peerConnDeviceList.begin(); it != peerConnDeviceList.end(); it++) {
1188 BtAddr btAddr;
1189 (void)memset_s(&btAddr, sizeof(btAddr), 0x00, sizeof(btAddr));
1190 RawAddress device(it->second.GetRawAddress());
1191 device.ConvertToUint8(btAddr.addr);
1192
1193 std::string invalidMacAddress(INVALID_MAC_ADDRESS);
1194 if ((invalidMacAddress.compare(device.GetAddress()) == 0) || (device.GetAddress().empty()) ||
1195 (BleConfig::GetInstance().GetPeerIrk(device.GetAddress()).empty()) ||
1196 (BleConfig::GetInstance().GetPeerIdentityAddr(device.GetAddress()).empty())) {
1197 continue;
1198 }
1199
1200 BtmLePairedDevice pairedDevice;
1201 (void)memset_s(&pairedDevice, sizeof(pairedDevice), 0x00, sizeof(pairedDevice));
1202 btAddr.type = it->second.GetAddressType();
1203 pairedDevice.addr = btAddr;
1204
1205 // Peer Identity Addr
1206 BtAddr peerAddr;
1207 (void)memset_s(&btAddr, sizeof(btAddr), 0x00, sizeof(btAddr));
1208 std::string addr = BleConfig::GetInstance().GetPeerIdentityAddr(device.GetAddress());
1209 RawAddress peerDevice(addr);
1210 peerAddr.type = BleConfig::GetInstance().GetPeerAddressType(device.GetAddress());
1211 peerDevice.ConvertToUint8(peerAddr.addr);
1212 pairedDevice.remoteIdentityAddress = peerAddr;
1213
1214 // IRK
1215 std::string irk = BleConfig::GetInstance().GetPeerIrk(device.GetAddress());
1216 if (!irk.empty()) {
1217 std::vector<uint8_t> vec;
1218 BleUtils::ConvertHexStringToInt(irk, vec);
1219 if (memcpy_s(pairedDevice.remoteIdentityResolvingKey.key, KEY_SIZE, &vec[0], vec.size()) != EOK) {
1220 LOG_ERROR("[BleAdapter] %{public}s:SavePeerDevices2BTM memcpy_s failed!", __func__);
1221 return;
1222 }
1223 }
1224 devices.push_back(pairedDevice);
1225 }
1226 if (!devices.empty()) {
1227 BTM_SetLePairedDevices(&devices[0], devices.size());
1228 devices.clear();
1229 }
1230 }
1231
RegisterCallbackToBtm()1232 int BleAdapter::RegisterCallbackToBtm()
1233 {
1234 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
1235
1236 pimpl->btmAclCb_.leConnectionComplete = &BleAdapter::LeConnectionComplete;
1237 pimpl->btmAclCb_.leDisconnectionComplete = &BleAdapter::LeDisconnectionComplete;
1238 pimpl->btmAclCb_.readRssiComplete = &BleAdapter::OnReadRemoteRssiEvent;
1239
1240 int ret = BTM_RegisterAclCallbacks(&pimpl->btmAclCb_, this);
1241 if (ret != BT_SUCCESS) {
1242 LOG_ERROR("[BleAdapter] %{public}s:BTM_RegisterAclCallbacks failed!", __func__);
1243 }
1244 return ret;
1245 }
1246
DeregisterCallbackToBtm() const1247 int BleAdapter::DeregisterCallbackToBtm() const
1248 {
1249 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
1250
1251 if (!pimpl->btmEnableFlag_) {
1252 return BT_OPERATION_FAILED;
1253 }
1254
1255 int ret = BTM_DeregisterAclCallbacks(&pimpl->btmAclCb_);
1256 if (ret != BT_SUCCESS) {
1257 LOG_ERROR("[BleAdapter] %{public}s:DeregisterCallbackToBtm failed!", __func__);
1258 }
1259 return ret;
1260 }
1261
LeConnectionComplete( uint8_t status, uint16_t connectionHandle, const BtAddr *addr, uint8_t role, void *context)1262 void BleAdapter::LeConnectionComplete(
1263 uint8_t status, uint16_t connectionHandle, const BtAddr *addr, uint8_t role, void *context)
1264 {
1265 HILOGI("status: %{public}u", status);
1266
1267 if (status != BT_SUCCESS) {
1268 HILOGI("status: %{public}u", status);
1269 return;
1270 }
1271
1272 auto *adapter = static_cast<BleAdapter *>(context);
1273 BtAddr address;
1274 (void)memcpy_s(&address, sizeof(BtAddr), addr, sizeof(BtAddr));
1275 adapter->GetDispatcher()->PostTask(
1276 std::bind(&BleAdapter::LeConnectionCompleteTask, adapter, status, connectionHandle, address, role));
1277 }
1278
LeConnectionCompleteTask( uint8_t status, uint16_t connectionHandle, const BtAddr &addr, uint8_t role) const1279 void BleAdapter::LeConnectionCompleteTask(
1280 uint8_t status, uint16_t connectionHandle, const BtAddr &addr, uint8_t role) const
1281 {
1282 LOG_DEBUG("[BleAdapter] %{public}s, handle is %{public}d", __func__, connectionHandle);
1283
1284 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
1285 if ((pimpl->bleAdvertiser_ != nullptr) && (!BleFeature::GetInstance().IsLeExtendedAdvertisingSupported()) &&
1286 (role == LE_CONNECTION_ROLE_SLAVE)) {
1287 pimpl->bleAdvertiser_->ReStartLegacyAdvertising();
1288 }
1289
1290 RawAddress peerAddr = RawAddress::ConvertToString(addr.addr);
1291 auto it = pimpl->peerConnDeviceList_.find(peerAddr.GetAddress());
1292 if (it != pimpl->peerConnDeviceList_.end()) {
1293 it->second.SetConnectionHandle(connectionHandle);
1294 it->second.SetRoles(role);
1295 it->second.SetAddressType(addr.type);
1296 if (pimpl->bleCentralManager_ != nullptr) {
1297 it->second.SetName(pimpl->bleCentralManager_->GetDeviceName(peerAddr.GetAddress()));
1298 }
1299 it->second.SetAclConnectState(BLE_CONNECTION_STATE_CONNECTED);
1300
1301 if ((it->second.GetPairedStatus() == BLE_PAIR_PAIRED) && (pimpl->bleSecurity_ != nullptr)) {
1302 pimpl->bleSecurity_->GapLeRequestSecurity(connectionHandle, addr, role);
1303 }
1304 } else {
1305 BlePeripheralDevice peerDevice;
1306 peerDevice.SetAddress(peerAddr);
1307 peerDevice.SetAddressType(addr.type);
1308 if (pimpl->bleCentralManager_ != nullptr) {
1309 peerDevice.SetName(pimpl->bleCentralManager_->GetDeviceName(peerAddr.GetAddress()));
1310 }
1311 peerDevice.SetRoles(role);
1312 peerDevice.SetConnectionHandle(connectionHandle);
1313 peerDevice.SetAclConnectState(BLE_CONNECTION_STATE_CONNECTED);
1314 pimpl->peerConnDeviceList_.insert(std::make_pair(peerAddr.GetAddress(), peerDevice));
1315 }
1316 }
1317
LeDisconnectionComplete(uint8_t status, uint16_t connectionHandle, uint8_t reason, void *context)1318 void BleAdapter::LeDisconnectionComplete(uint8_t status, uint16_t connectionHandle, uint8_t reason, void *context)
1319 {
1320 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
1321
1322 if (status != BT_SUCCESS) {
1323 LOG_DEBUG("[BleAdapter] %{public}s:%u", __func__, status);
1324 return;
1325 }
1326
1327 auto *adapter = static_cast<BleAdapter *>(context);
1328 adapter->GetDispatcher()->PostTask(
1329 std::bind(&BleAdapter::LeDisconnectionCompleteTask, adapter, status, connectionHandle, reason));
1330 }
1331
LeDisconnectionCompleteTask(uint8_t status, uint16_t connectionHandle, uint8_t reason) const1332 void BleAdapter::LeDisconnectionCompleteTask(uint8_t status, uint16_t connectionHandle, uint8_t reason) const
1333 {
1334 LOG_DEBUG("[BleAdapter] %{public}s, handle is %{public}d", __func__, connectionHandle);
1335
1336 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
1337 for (auto it = pimpl->peerConnDeviceList_.begin(); it != pimpl->peerConnDeviceList_.end(); it++) {
1338 if (connectionHandle == it->second.GetConnectionHandle()) {
1339 LOG_DEBUG("[BleAdapter] handle is %{public}d disconnect ", connectionHandle);
1340 it->second.SetAclConnectState(BLE_CONNECTION_STATE_DISCONNECTED);
1341 break;
1342 }
1343 }
1344 }
1345
LePairComplete(const RawAddress &device, const int status) const1346 void BleAdapter::LePairComplete(const RawAddress &device, const int status) const
1347 {
1348 LOG_DEBUG("[BleAdapter] %{public}s:result %{public}d.", __func__, status);
1349
1350 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
1351 if (status == BT_SUCCESS) {
1352 auto it = pimpl->peerConnDeviceList_.find(device.GetAddress());
1353 if (it == pimpl->peerConnDeviceList_.end()) {
1354 HILOGI("addr %{public}s.", GetEncryptAddr(device.GetAddress()).c_str());
1355 return;
1356 }
1357 it->second.SetPairedStatus(BLE_PAIR_PAIRED);
1358
1359 /// Peer Identity Addr
1360 BtAddr btAddr;
1361 (void)memset_s(&btAddr, sizeof(btAddr), 0x00, sizeof(btAddr));
1362 device.ConvertToUint8(btAddr.addr);
1363 btAddr.type = it->second.GetAddressType();
1364
1365 RawAddress peerDevice(BleConfig::GetInstance().GetPeerIdentityAddr(device.GetAddress()));
1366 BtAddr peerAddr;
1367 (void)memset_s(&peerAddr, sizeof(peerAddr), 0x00, sizeof(peerAddr));
1368 peerAddr.type = BleConfig::GetInstance().GetPeerDeviceType(device.GetAddress());
1369 peerDevice.ConvertToUint8(peerAddr.addr);
1370
1371 BtmLePairedDevice pairedDevice;
1372 (void)memset_s(&pairedDevice, sizeof(pairedDevice), 0x00, sizeof(pairedDevice));
1373 (void)memcpy_s(&pairedDevice.addr, sizeof(BtAddr), &btAddr, sizeof(BtAddr));
1374 (void)memcpy_s(&pairedDevice.remoteIdentityAddress, sizeof(BtAddr), &peerAddr, sizeof(BtAddr));
1375
1376 /// IRK
1377 std::string irk = BleConfig::GetInstance().GetPeerIrk(device.GetAddress());
1378 if (!irk.empty()) {
1379 std::vector<uint8_t> vec;
1380 BleUtils::ConvertHexStringToInt(irk, vec);
1381 /// Add paired device to btm
1382 (void)memcpy_s(pairedDevice.remoteIdentityResolvingKey.key, KEY_SIZE, &vec[0], vec.size());
1383 }
1384 StartOrStopAdvAndScan(STOP_ADV_TYPE_RESOLVING_LIST, STOP_SCAN_TYPE_RESOLVING_LIST);
1385 BTM_AddLePairedDevice(&pairedDevice);
1386 StartOrStopAdvAndScan(STOP_ADV_TYPE_RESOLVING_LIST, STOP_SCAN_TYPE_RESOLVING_LIST, true);
1387
1388 if (pimpl->blePeripheralCallback_ != nullptr) {
1389 pimpl->blePeripheralCallback_->ForEach([device](IBlePeripheralCallback &observer) {
1390 observer.OnPairStatusChanged(ADAPTER_BLE, device, BLE_PAIR_PAIRED);
1391 });
1392 }
1393 } else {
1394 auto it = pimpl->peerConnDeviceList_.find(device.GetAddress());
1395 if (it != pimpl->peerConnDeviceList_.end()) {
1396 it->second.SetPairedStatus(BLE_PAIR_NONE);
1397 }
1398 if (pimpl->blePeripheralCallback_ != nullptr) {
1399 pimpl->blePeripheralCallback_->ForEach([device](IBlePeripheralCallback &observer) {
1400 observer.OnPairStatusChanged(ADAPTER_BLE, device, BLE_PAIR_NONE);
1401 });
1402 }
1403 }
1404 }
1405
LePairingStatus(const RawAddress &device) const1406 void BleAdapter::LePairingStatus(const RawAddress &device) const
1407 {
1408 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
1409
1410 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
1411 auto it = pimpl->peerConnDeviceList_.find(device.GetAddress());
1412 if (it != pimpl->peerConnDeviceList_.end()) {
1413 it->second.SetPairedStatus(BLE_PAIR_PAIRING);
1414 } else {
1415 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
1416 BlePeripheralDevice peerDevice;
1417 peerDevice.SetAddress(device);
1418 peerDevice.SetPairedStatus(BLE_PAIR_PAIRING);
1419 pimpl->peerConnDeviceList_.insert(std::make_pair(device.GetAddress(), peerDevice));
1420 }
1421
1422 if (pimpl->blePeripheralCallback_ != nullptr) {
1423 pimpl->blePeripheralCallback_->ForEach([device](IBlePeripheralCallback &observer) {
1424 observer.OnPairStatusChanged(ADAPTER_BLE, device, BLE_PAIR_PAIRING);
1425 });
1426 }
1427 }
1428
EncryptionComplete(const RawAddress &device) const1429 void BleAdapter::EncryptionComplete(const RawAddress &device) const
1430 {
1431 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
1432
1433 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
1434 auto it = pimpl->peerConnDeviceList_.find(device.GetAddress());
1435 if (it != pimpl->peerConnDeviceList_.end()) {
1436 it->second.SetAclConnectState(BLE_CONNECTION_STATE_ENCRYPTED_LE);
1437 }
1438 }
1439
OnReadRemoteRssiEvent(uint8_t status, const BtAddr *addr, int8_t rssi, void *context)1440 void BleAdapter::OnReadRemoteRssiEvent(uint8_t status, const BtAddr *addr, int8_t rssi, void *context)
1441 {
1442 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
1443
1444 auto *adapter = static_cast<BleAdapter *>(context);
1445 BtAddr address;
1446 (void)memcpy_s(&address, sizeof(BtAddr), addr, sizeof(BtAddr));
1447 adapter->GetDispatcher()->PostTask(
1448 std::bind(&BleAdapter::OnReadRemoteRssiEventTask, adapter, status, address, rssi));
1449 }
1450
OnReadRemoteRssiEventTask(uint8_t status, const BtAddr &addr, int8_t rssi) const1451 void BleAdapter::OnReadRemoteRssiEventTask(uint8_t status, const BtAddr &addr, int8_t rssi) const
1452 {
1453 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
1454
1455 RawAddress device = RawAddress::ConvertToString(addr.addr);
1456 if (pimpl->blePeripheralCallback_ != nullptr) {
1457 pimpl->blePeripheralCallback_->ForEach([device, rssi, status](IBlePeripheralCallback &observer) {
1458 observer.OnReadRemoteRssiEvent(device, rssi, status);
1459 });
1460 }
1461 }
1462
ReadRemoteRssiValue(const RawAddress &device) const1463 bool BleAdapter::ReadRemoteRssiValue(const RawAddress &device) const
1464 {
1465 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
1466
1467 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
1468 BtAddr addr;
1469 (void)memset_s(&addr, sizeof(addr), 0x00, sizeof(addr));
1470 addr.type = GetPeerDeviceAddrType(device);
1471 device.ConvertToUint8(addr.addr);
1472 return (BTM_ReadRssi(&addr) == BT_SUCCESS);
1473 }
1474
GetDeviceType(const RawAddress &device) const1475 int BleAdapter::GetDeviceType(const RawAddress &device) const
1476 {
1477 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
1478
1479 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
1480 if (pimpl->bleCentralManager_ != nullptr) {
1481 return pimpl->bleCentralManager_->GetDeviceType(device.GetAddress());
1482 }
1483 return BLE_BT_DEVICE_TYPE_UNKNOWN;
1484 }
1485
GetAdvertiserHandle() const1486 uint8_t BleAdapter::GetAdvertiserHandle() const
1487 {
1488 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
1489
1490 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
1491 if (pimpl->bleAdvertiser_ != nullptr) {
1492 return pimpl->bleAdvertiser_->CreateAdvertiserSetHandle();
1493 }
1494 return BLE_INVALID_ADVERTISING_HANDLE;
1495 }
1496
StartAdvertising(const BleAdvertiserSettingsImpl &settings, const BleAdvertiserDataImpl &advData, const BleAdvertiserDataImpl &scanResponse, uint8_t advHandle) const1497 void BleAdapter::StartAdvertising(const BleAdvertiserSettingsImpl &settings, const BleAdvertiserDataImpl &advData,
1498 const BleAdvertiserDataImpl &scanResponse, uint8_t advHandle) const
1499 {
1500 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
1501
1502 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
1503 if (pimpl->bleAdvertiser_ != nullptr) {
1504 pimpl->bleAdvertiser_->StartAdvertising(settings, advData, scanResponse, advHandle);
1505 }
1506 }
1507
StopAdvertising(uint8_t advHandle) const1508 void BleAdapter::StopAdvertising(uint8_t advHandle) const
1509 {
1510 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
1511
1512 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
1513 if (pimpl->bleAdvertiser_ != nullptr) {
1514 pimpl->bleAdvertiser_->StopAdvertising(advHandle);
1515 }
1516 }
1517
Close(uint8_t advHandle) const1518 void BleAdapter::Close(uint8_t advHandle) const
1519 {
1520 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
1521
1522 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
1523 if (pimpl->bleAdvertiser_ != nullptr) {
1524 pimpl->bleAdvertiser_->Close(advHandle);
1525 }
1526 }
1527
StartScan(const BleScanSettingsImpl &setting) const1528 void BleAdapter::StartScan(const BleScanSettingsImpl &setting) const
1529 {
1530 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
1531
1532 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
1533 if (pimpl->bleCentralManager_ != nullptr) {
1534 pimpl->bleCentralManager_->StartScan(setting);
1535 }
1536 }
1537
StopScan() const1538 void BleAdapter::StopScan() const
1539 {
1540 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
1541
1542 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
1543 if (pimpl->bleCentralManager_ != nullptr) {
1544 pimpl->bleCentralManager_->StopScan();
1545 }
1546 }
1547
ConfigScanFilter(int32_t scannerId, const std::vector<BleScanFilterImpl> &filters)1548 int BleAdapter::ConfigScanFilter(int32_t scannerId, const std::vector<BleScanFilterImpl> &filters)
1549 {
1550 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
1551
1552 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
1553 if (pimpl->bleCentralManager_ != nullptr) {
1554 return pimpl->bleCentralManager_->ConfigScanFilter(scannerId, filters);
1555 }
1556 return 0;
1557 }
1558
RemoveScanFilter(int32_t scannerId)1559 void BleAdapter::RemoveScanFilter(int32_t scannerId)
1560 {
1561 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
1562
1563 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
1564 if (pimpl->bleCentralManager_ != nullptr) {
1565 pimpl->bleCentralManager_->RemoveScanFilter(scannerId);
1566 }
1567 }
1568
AllocScannerId()1569 int32_t BleAdapter::AllocScannerId()
1570 {
1571 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
1572 if (pimpl->bleCentralManager_ == nullptr) {
1573 LOG_DEBUG("[BleAdapter] bleCentralManager is null.");
1574 return 0;
1575 }
1576 return pimpl->bleCentralManager_->AllocScannerId();
1577 }
1578
RemoveScannerId(int32_t scannerId)1579 void BleAdapter::RemoveScannerId(int32_t scannerId)
1580 {
1581 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
1582 if (pimpl->bleCentralManager_ == nullptr) {
1583 LOG_DEBUG("[BleAdapter] bleCentralManager is null.");
1584 return;
1585 }
1586 return pimpl->bleCentralManager_->RemoveScannerId(scannerId);
1587 }
1588
OnStartAdvertisingEvt() const1589 void BleAdapter::OnStartAdvertisingEvt() const
1590 {
1591 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
1592
1593 if (pimpl->observer_ != nullptr) {
1594 int status = BLE_ADV_STATE_ADVERTISING;
1595 pimpl->observer_->ForEach(
1596 [status](IAdapterBleObserver &observer) { observer.OnAdvertisingStateChanged(status); });
1597 }
1598 }
1599
OnStopAdvertisingEvt() const1600 void BleAdapter::OnStopAdvertisingEvt() const
1601 {
1602 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
1603
1604 if (pimpl->observer_ != nullptr) {
1605 int status = BLE_ADV_STATE_IDLE;
1606 pimpl->observer_->ForEach(
1607 [status](IAdapterBleObserver &observer) { observer.OnAdvertisingStateChanged(status); });
1608 }
1609 }
1610
GetAdvertisingStatus() const1611 int BleAdapter::GetAdvertisingStatus() const
1612 {
1613 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
1614
1615 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
1616 if (pimpl->bleAdvertiser_ != nullptr) {
1617 if (pimpl->bleAdvertiser_->GetAdvertisingStatus() == ADVERTISE_FAILED_ALREADY_STARTED) {
1618 return BLE_ADV_STATE_ADVERTISING;
1619 } else {
1620 return BLE_ADV_STATE_IDLE;
1621 }
1622 }
1623 return BLE_ADV_STATE_IDLE;
1624 }
1625
IsLlPrivacySupported() const1626 bool BleAdapter::IsLlPrivacySupported() const
1627 {
1628 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
1629
1630 return BleFeature::GetInstance().IsPrivacySupported();
1631 }
1632
AddCharacteristicValue(uint8_t adtype, const std::string &data) const1633 void BleAdapter::AddCharacteristicValue(uint8_t adtype, const std::string &data) const
1634 {
1635 LOG_DEBUG("[BleAdapter] %{public}s", __func__);
1636
1637 std::lock_guard<std::recursive_mutex> lk(pimpl->syncMutex_);
1638 if (pimpl->bleAdvertiser_ != nullptr) {
1639 pimpl->bleAdvertiser_->AddCharacteristicValue(adtype, data);
1640 }
1641 }
1642
SetBleRoles() const1643 int BleAdapter::SetBleRoles() const
1644 {
1645 int roles = BleProperties::GetInstance().GetBleRoles();
1646
1647 LOG_DEBUG("[BleAdapter] %{public}s:%{public}d", __func__, roles);
1648
1649 if (roles > (GAP_LE_ROLE_BROADCASTER | GAP_LE_ROLE_OBSERVER | GAP_LE_ROLE_PREIPHERAL | GAP_LE_ROLE_CENTRAL) ||
1650 roles < GAP_LE_ROLE_BROADCASTER) {
1651 LOG_ERROR("[BleAdapter] %{public}s:Roles is invalid.", __func__);
1652 roles = (GAP_LE_ROLE_BROADCASTER | GAP_LE_ROLE_OBSERVER | GAP_LE_ROLE_PREIPHERAL | GAP_LE_ROLE_CENTRAL);
1653 }
1654 return GAPIF_LeSetRole(roles);
1655 }
1656
1657 REGISTER_CLASS_CREATOR(BleAdapter);
1658 } // namespace bluetooth
1659 } // namespace OHOS
1660