• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "bluetooth_ble_central_manager_server.h"
17 #include "ble_service_data.h"
18 #include "bluetooth_log.h"
19 #include "bluetooth_utils_server.h"
20 #include "bluetooth_errorcode.h"
21 #include "event_handler.h"
22 #include "event_runner.h"
23 #include "hisysevent.h"
24 #include "interface_adapter_ble.h"
25 #include "interface_adapter_manager.h"
26 #include "ipc_skeleton.h"
27 #include "remote_observer_list.h"
28 #include "permission_utils.h"
29 #include <string>
30 
31 namespace OHOS {
32 namespace Bluetooth {
33 using namespace OHOS::bluetooth;
34 struct BluetoothBleCentralManagerServer::impl {
35     impl();
36     ~impl();
37 
38     /// sys state observer
39     class SystemStateObserver;
40     std::unique_ptr<SystemStateObserver> systemStateObserver_ = nullptr;
41     RemoteObserverList<IBluetoothBleCentralManagerCallback, int32_t> observers_;
42     std::map<sptr<IRemoteObject>, uint32_t> observersToken_;
43     std::map<sptr<IRemoteObject>, int32_t> observersUid_;
44     class BleCentralManagerCallback;
45     std::unique_ptr<BleCentralManagerCallback> observerImp_ = std::make_unique<BleCentralManagerCallback>(this);
46 
47     struct ScanCallbackInfo;
48     struct ScanSettingsParam;
49     std::vector<ScanCallbackInfo> scanCallbackInfo_;
50 
51     BleScanSettingsImpl scanSettingImpl_;
52     bool isScanning; // Indicates the bluetooth service is scanning or not.
53 
54     std::shared_ptr<AppExecFwk::EventRunner> eventRunner_;
55     std::shared_ptr<AppExecFwk::EventHandler> eventHandler_;
56 };
57 
58 struct BluetoothBleCentralManagerServer::impl::ScanSettingsParam {
59     long reportDelayMillis;
60     uint16_t scanInterval;
61     uint16_t scanWindow;
62     int scanMode;
63     bool legacy;
64     int phy;
65 };
66 
67 struct BluetoothBleCentralManagerServer::impl::ScanCallbackInfo {
68     int pid;
69     int uid;
70     bool isStart; // Indicates the process for which scanning is started or not.
71     ScanSettingsParam param;
72     sptr<IBluetoothBleCentralManagerCallback> callback;
73 };
74 
75 class BluetoothBleCentralManagerServer::impl::BleCentralManagerCallback : public IBleCentralManagerCallback {
76 public:
BleCentralManagerCallback(BluetoothBleCentralManagerServer::impl * pimpl)77     explicit BleCentralManagerCallback(BluetoothBleCentralManagerServer::impl *pimpl) : pimpl_(pimpl) {};
78     ~BleCentralManagerCallback() override = default;
79 
OnScanCallback(const BleScanResultImpl & result)80     void OnScanCallback(const BleScanResultImpl &result) override
81     {
82         HILOGI("Address: %{public}s",
83             GetEncryptAddr(result.GetPeripheralDevice().GetRawAddress().GetAddress()).c_str());
84         observers_->ForEach([this, result](IBluetoothBleCentralManagerCallback *observer) {
85             uint32_t  tokenId = this->pimpl_->observersToken_[observer->AsObject()];
86             int32_t uid = this->pimpl_->observersUid_[observer->AsObject()];
87             if (BluetoothBleCentralManagerServer::IsProxyUid(uid)) {
88                 HILOGD("uid:%{public}d is proxy uid, not callback.", uid);
89                 return;
90             }
91             if (PermissionUtils::VerifyUseBluetoothPermission(tokenId) == PERMISSION_DENIED) {
92                 HILOGE("OnScanCallback(): failed, check permission failed, tokenId: %{public}u", tokenId);
93             } else {
94                 BluetoothBleScanResult bleScanResult(result);
95                 observer->OnScanCallback(bleScanResult);
96             }
97         });
98     }
99 
OnBleBatchScanResultsEvent(std::vector<BleScanResultImpl> & results)100     void OnBleBatchScanResultsEvent(std::vector<BleScanResultImpl> &results) override
101     {
102         HILOGI("enter");
103 
104         observers_->ForEach([this, results](IBluetoothBleCentralManagerCallback *observer) {
105             int32_t uid = this->pimpl_->observersUid_[observer->AsObject()];
106             if (BluetoothBleCentralManagerServer::IsProxyUid(uid)) {
107                 HILOGD("uid:%{public}d is proxy uid, not callback.", uid);
108                 return;
109             }
110             std::vector<BluetoothBleScanResult> bleScanResults;
111 
112             for (auto iter = results.begin(); iter != results.end(); iter++) {
113                 BluetoothBleScanResult bleScanResult;
114 
115                 if (iter->GetPeripheralDevice().IsRSSI()) {
116                     bleScanResult.SetRssi(iter->GetPeripheralDevice().GetRSSI());
117                 }
118 
119                 bleScanResult.SetAdvertiseFlag(iter->GetPeripheralDevice().GetAdFlag());
120 
121                 if (iter->GetPeripheralDevice().IsManufacturerData()) {
122                     std::map<uint16_t, std::string> manuData = iter->GetPeripheralDevice().GetManufacturerData();
123                     for (auto manuDataIter = manuData.begin(); manuDataIter != manuData.end(); manuDataIter++) {
124                         bleScanResult.AddManufacturerData(manuDataIter->first, manuDataIter->second);
125                     }
126                 }
127 
128                 bleScanResult.SetConnectable(iter->GetPeripheralDevice().IsConnectable());
129 
130                 if (iter->GetPeripheralDevice().IsServiceUUID()) {
131                     std::vector<Uuid> uuids = iter->GetPeripheralDevice().GetServiceUUID();
132                     for (auto serviceUuidIter = uuids.begin(); serviceUuidIter != uuids.end(); serviceUuidIter++) {
133                         bleScanResult.AddServiceUuid(*serviceUuidIter);
134                     }
135                 }
136 
137                 if (iter->GetPeripheralDevice().IsServiceData()) {
138                     std::vector<Uuid> uuids = iter->GetPeripheralDevice().GetServiceDataUUID();
139                     int index = 0;
140                     for (auto serviceDataIter = uuids.begin(); serviceDataIter != uuids.end(); serviceDataIter++) {
141                         bleScanResult.AddServiceData(
142                             *serviceDataIter, iter->GetPeripheralDevice().GetServiceData(index));
143                         ++index;
144                     }
145                 }
146 
147                 bleScanResult.SetPeripheralDevice(iter->GetPeripheralDevice().GetRawAddress());
148 
149                 bleScanResult.SetPayload(std::string(iter->GetPeripheralDevice().GetPayload(),
150                     iter->GetPeripheralDevice().GetPayload() + iter->GetPeripheralDevice().GetPayloadLen()));
151 
152                 bleScanResults.push_back(bleScanResult);
153             }
154             observer->OnBleBatchScanResultsEvent(bleScanResults);
155         });
156     }
157 
OnStartOrStopScanEvent(int resultCode,bool isStartScanEvt)158     void OnStartOrStopScanEvent(int resultCode, bool isStartScanEvt) override
159     {
160         HILOGI("code: %{public}d, isStartScanEvt: %{public}d", resultCode, isStartScanEvt);
161         if (pimpl_ == nullptr || pimpl_->eventHandler_ == nullptr) {
162             HILOGE("pimpl_ or eventHandler_ is nullptr");
163             return;
164         }
165         pimpl_->eventHandler_->PostTask([=]() {
166             /* start scan -> close bluetooth -> open bluetooth -> start scan
167                After the bluetooth is closed, the stack stops scanning.
168                When receiving this event, the related status needs to be cleared. Otherwise, the next scanning fails. */
169             HILOGI("isScanning: %{public}d", pimpl_->isScanning);
170             if (pimpl_->isScanning && !isStartScanEvt && resultCode == 0) {
171                 pimpl_->isScanning = false;
172                 ClearMultiProcessScanState();
173                 OnStartOrStopScanEventCb(resultCode, isStartScanEvt);
174                 return;
175             }
176 
177             if (resultCode != 0) {
178                 pimpl_->isScanning = !pimpl_->isScanning;
179             }
180             auto bleService = IAdapterManager::GetInstance()->GetBleAdapterInterface();
181             if (bleService == nullptr) {
182                 HILOGE("bleService is nullptr.");
183                 return;
184             }
185 
186             if (!pimpl_->isScanning && resultCode == 0) {
187                 // When updating params the scanning is stopped successfully and the scanning will be restarted.
188                 for (auto iter = pimpl_->scanCallbackInfo_.begin(); iter != pimpl_->scanCallbackInfo_.end(); ++iter) {
189                     if (iter->isStart) {
190                         bleService->StartScan(pimpl_->scanSettingImpl_);
191                         pimpl_->isScanning = true;
192                         break;
193                     }
194                 }
195             } else if (!pimpl_->isScanning && resultCode != 0) {
196                 // When updating params the scanning is stopped successfully and the scanning restart failed.
197                 ClearMultiProcessScanState();
198             }
199             OnStartOrStopScanEventCb(resultCode, isStartScanEvt);
200         });
201     }
202 
OnNotifyMsgReportFromLpDevice(FilterIdxInfo & info,int msgType,const std::vector<uint8_t> & notifyValue)203     void OnNotifyMsgReportFromLpDevice(FilterIdxInfo &info, int msgType,
204         const std::vector<uint8_t> &notifyValue) override
205     {
206         return;
207     }
208 
SetObserver(RemoteObserverList<IBluetoothBleCentralManagerCallback,int32_t> * observers)209     void SetObserver(RemoteObserverList<IBluetoothBleCentralManagerCallback, int32_t> *observers)
210     {
211         observers_ = observers;
212     }
213 
214 private:
215     RemoteObserverList<IBluetoothBleCentralManagerCallback, int32_t> *observers_ = nullptr;
216     BluetoothBleCentralManagerServer::impl *pimpl_ = nullptr;
217 
ClearMultiProcessScanState()218     void ClearMultiProcessScanState()
219     {
220         for (auto iter = pimpl_->scanCallbackInfo_.begin(); iter != pimpl_->scanCallbackInfo_.end(); ++iter) {
221             if (iter->isStart) {
222                 iter->isStart = false;
223             }
224         }
225     }
226 
OnStartOrStopScanEventCb(int resultCode,bool isStartScanEvt)227     void OnStartOrStopScanEventCb(int resultCode, bool isStartScanEvt)
228     {
229         observers_->ForEach([resultCode, isStartScanEvt](IBluetoothBleCentralManagerCallback *observer) {
230             observer->OnStartOrStopScanEvent(resultCode, isStartScanEvt);
231         });
232     }
233 };
234 
235 class BluetoothBleCentralManagerServer::impl::SystemStateObserver : public ISystemStateObserver {
236 public:
SystemStateObserver(BluetoothBleCentralManagerServer::impl * pimpl)237     explicit SystemStateObserver(BluetoothBleCentralManagerServer::impl *pimpl) : pimpl_(pimpl){};
OnSystemStateChange(const BTSystemState state)238     void OnSystemStateChange(const BTSystemState state) override
239     {
240         auto bleService = IAdapterManager::GetInstance()->GetBleAdapterInterface();
241         switch (state) {
242             case BTSystemState::ON:
243                 if (bleService != nullptr) {
244                     bleService->RegisterBleCentralManagerCallback(*pimpl_->observerImp_.get());
245                 }
246                 break;
247             default:
248                 break;
249         }
250     };
251 
252 private:
253     BluetoothBleCentralManagerServer::impl *pimpl_ = nullptr;
254 };
255 
impl()256 BluetoothBleCentralManagerServer::impl::impl()
257 {
258     eventRunner_ = AppExecFwk::EventRunner::Create("bt central manager server");
259     eventHandler_ = std::make_shared<AppExecFwk::EventHandler>(eventRunner_);
260     isScanning = false;
261 }
262 
~impl()263 BluetoothBleCentralManagerServer::impl::~impl()
264 {
265     auto bleService = IAdapterManager::GetInstance()->GetBleAdapterInterface();
266     if (bleService != nullptr) {
267         bleService->DeregisterBleCentralManagerCallback();
268     }
269 }
270 
BluetoothBleCentralManagerServer()271 BluetoothBleCentralManagerServer::BluetoothBleCentralManagerServer()
272 {
273     pimpl = std::make_unique<impl>();
274 
275     pimpl->eventHandler_->PostSyncTask(
276         [&]() {
277             pimpl->observerImp_->SetObserver(&(pimpl->observers_));
278             pimpl->systemStateObserver_ = std::make_unique<impl::SystemStateObserver>(pimpl.get());
279             IAdapterManager::GetInstance()->RegisterSystemStateObserver(*(pimpl->systemStateObserver_));
280 
281             auto bleService = IAdapterManager::GetInstance()->GetBleAdapterInterface();
282             if (bleService != nullptr) {
283                 bleService->RegisterBleCentralManagerCallback(*pimpl->observerImp_.get());
284             }
285         },
286         AppExecFwk::EventQueue::Priority::HIGH);
287 }
288 
~BluetoothBleCentralManagerServer()289 BluetoothBleCentralManagerServer::~BluetoothBleCentralManagerServer()
290 {
291     pimpl->eventHandler_->PostSyncTask(
292         [&]() { IAdapterManager::GetInstance()->DeregisterSystemStateObserver(*(pimpl->systemStateObserver_)); },
293         AppExecFwk::EventQueue::Priority::HIGH);
294 }
295 
296 std::mutex BluetoothBleCentralManagerServer::proxyMutex_;
297 std::set<int32_t> BluetoothBleCentralManagerServer::proxyUids_;
298 
ProxyUid(int32_t uid,bool isProxy)299 bool BluetoothBleCentralManagerServer::ProxyUid(int32_t uid, bool isProxy)
300 {
301     HILOGD("Start bluetooth proxy, uid: %{public}d, isProxy: %{public}d", uid, isProxy);
302     std::lock_guard<std::mutex> lock(proxyMutex_);
303     if (isProxy) {
304         proxyUids_.insert(uid);
305     } else {
306         proxyUids_.erase(uid);
307     }
308     return true;
309 }
310 
ResetAllProxy()311 bool BluetoothBleCentralManagerServer::ResetAllProxy()
312 {
313     HILOGI("Start bluetooth ResetAllProxy");
314     std::lock_guard<std::mutex> lock(proxyMutex_);
315     proxyUids_.clear();
316     return true;
317 }
318 
IsProxyUid(int32_t uid)319 bool BluetoothBleCentralManagerServer::IsProxyUid(int32_t uid)
320 {
321     std::lock_guard<std::mutex> lock(proxyMutex_);
322     return proxyUids_.find(uid) != proxyUids_.end();
323 }
324 
StartScan(int32_t scannerId)325 int BluetoothBleCentralManagerServer::StartScan(int32_t scannerId)
326 {
327     int32_t pid = IPCSkeleton::GetCallingPid();
328     int32_t uid = IPCSkeleton::GetCallingUid();
329     HILOGI("pid: %{public}d, uid: %{public}d", pid, uid);
330     if (PermissionUtils::VerifyDiscoverBluetoothPermission() == PERMISSION_DENIED ||
331         PermissionUtils::VerifyManageBluetoothPermission() == PERMISSION_DENIED) {
332         HILOGE("check permission failed.");
333         return BT_ERR_PERMISSION_FAILED;
334     }
335     if (PermissionUtils::VerifyApproximatelyPermission() == PERMISSION_DENIED &&
336         PermissionUtils::VerifyLocationPermission() == PERMISSION_DENIED) {
337         HILOGE("No location permission");
338         return BT_ERR_PERMISSION_FAILED;
339     }
340 
341     pimpl->eventHandler_->PostSyncTask([&]() {
342         auto bleService = IAdapterManager::GetInstance()->GetBleAdapterInterface();
343         if (bleService == nullptr) {
344             HILOGE("bleService is nullptr.");
345             return;
346         }
347 
348         for (auto iter = pimpl->scanCallbackInfo_.begin(); iter != pimpl->scanCallbackInfo_.end(); ++iter) {
349             if (iter->pid == pid && iter->uid == uid) {
350                 iter->isStart = true;
351                 iter->param.reportDelayMillis = 0;
352                 iter->param.scanInterval = BLE_SCAN_MODE_LOW_POWER_INTERVAL_MS;
353                 iter->param.scanWindow = BLE_SCAN_MODE_LOW_POWER_WINDOW_MS;
354                 iter->param.scanMode = SCAN_MODE_LOW_POWER;
355                 iter->param.legacy = true;
356                 iter->param.phy = PHY_LE_ALL_SUPPORTED;
357                 break;
358             }
359         }
360 
361         if (!pimpl->isScanning) {
362             HILOGI("start ble scan without params.");
363             bleService->StartScan();
364             pimpl->isScanning = true;
365             HiSysEventWrite(OHOS::HiviewDFX::HiSysEvent::Domain::BT_SERVICE, "BLE_SCAN_START",
366                 OHOS::HiviewDFX::HiSysEvent::EventType::STATISTIC, "PID", pid, "UID", uid, "TYPE", 0);
367         } else {
368             HILOGI("scan is already started.");
369         }
370     });
371     return NO_ERROR;
372 }
373 
StartScan(int32_t scannerId,const BluetoothBleScanSettings & settings)374 int BluetoothBleCentralManagerServer::StartScan(int32_t scannerId, const BluetoothBleScanSettings &settings)
375 {
376     int32_t pid = IPCSkeleton::GetCallingPid();
377     int32_t uid = IPCSkeleton::GetCallingUid();
378     HILOGI("pid: %{public}d, uid: %{public}d", pid, uid);
379     if (PermissionUtils::VerifyDiscoverBluetoothPermission() == PERMISSION_DENIED ||
380         PermissionUtils::VerifyManageBluetoothPermission() == PERMISSION_DENIED) {
381         HILOGE("check permission failed.");
382         return BT_ERR_PERMISSION_FAILED;
383     }
384     if (PermissionUtils::VerifyApproximatelyPermission() == PERMISSION_DENIED &&
385         PermissionUtils::VerifyLocationPermission() == PERMISSION_DENIED) {
386         HILOGE("No location permission");
387         return BT_ERR_PERMISSION_FAILED;
388     }
389 
390     pimpl->eventHandler_->PostSyncTask([&]() {
391         auto bleService = IAdapterManager::GetInstance()->GetBleAdapterInterface();
392         if (bleService == nullptr) {
393             HILOGE("bleService is nullptr.");
394             return;
395         }
396 
397         for (auto iter = pimpl->scanCallbackInfo_.begin(); iter != pimpl->scanCallbackInfo_.end(); ++iter) {
398             if (iter->pid == pid && iter->uid == uid) {
399                 iter->isStart = true;
400                 SetWindowAndInterval(settings.GetScanMode(), iter->param.scanWindow, iter->param.scanInterval);
401                 iter->param.reportDelayMillis = settings.GetReportDelayMillisValue();
402                 iter->param.scanMode = settings.GetScanMode();
403                 iter->param.legacy = settings.GetLegacy();
404                 iter->param.phy = settings.GetPhy();
405                 break;
406             }
407         }
408 
409         if (!pimpl->isScanning) {
410             HILOGI("start ble scan.");
411             SetScanParams(settings);
412             bleService->StartScan(pimpl->scanSettingImpl_);
413             pimpl->isScanning = true;
414             HiSysEventWrite(OHOS::HiviewDFX::HiSysEvent::Domain::BT_SERVICE, "BLE_SCAN_START",
415                 OHOS::HiviewDFX::HiSysEvent::EventType::STATISTIC, "PID", pid, "UID", uid,
416                 "TYPE", (settings.GetReportDelayMillisValue() > 0) ? 1 : 0);
417         } else if (IsNewScanParams()) {
418             // Stop an ongoing ble scan, update parameters and restart the ble scan in OnStartOrStopScanEvent().
419             HILOGI("restart ble scan.");
420             bleService->StopScan();
421             pimpl->isScanning = false;
422         } else {
423             HILOGI("scan is already started and has the same params.");
424         }
425     });
426     return NO_ERROR;
427 }
428 
StopScan(int32_t scannerId)429 int BluetoothBleCentralManagerServer::StopScan(int32_t scannerId)
430 {
431     int32_t pid = IPCSkeleton::GetCallingPid();
432     int32_t uid = IPCSkeleton::GetCallingUid();
433     HILOGI("pid: %{public}d, uid: %{public}d", pid, uid);
434     if (PermissionUtils::VerifyDiscoverBluetoothPermission() == PERMISSION_DENIED) {
435         HILOGE("check permission failed.");
436         return BT_ERR_PERMISSION_FAILED;
437     }
438 
439     pimpl->eventHandler_->PostSyncTask([&]() {
440         if (!pimpl->isScanning) {
441             HILOGE("scan is not started.");
442             return;
443         }
444 
445         auto bleService = IAdapterManager::GetInstance()->GetBleAdapterInterface();
446         if (bleService == nullptr) {
447             HILOGE("bleService is nullptr.");
448             return;
449         }
450 
451         for (auto iter = pimpl->scanCallbackInfo_.begin(); iter != pimpl->scanCallbackInfo_.end(); ++iter) {
452             if (iter->pid == pid && iter->uid == uid) {
453                 iter->isStart = false;
454                 break;
455             }
456         }
457 
458         if (IsAllStop() || IsNewScanParams()) {
459             HILOGI("stop ble scan.");
460             bleService->StopScan();
461             pimpl->isScanning = false;
462             HiSysEventWrite(OHOS::HiviewDFX::HiSysEvent::Domain::BT_SERVICE, "BLE_SCAN_STOP",
463                 OHOS::HiviewDFX::HiSysEvent::EventType::STATISTIC, "PID", pid, "UID", uid);
464         }
465     });
466     return NO_ERROR;
467 }
468 
ConfigScanFilter(int32_t scannerId,const std::vector<BluetoothBleScanFilter> & filters)469 int BluetoothBleCentralManagerServer::ConfigScanFilter(
470     int32_t scannerId, const std::vector<BluetoothBleScanFilter> &filters)
471 {
472     HILOGI("enter, scannerId: %{public}d", scannerId);
473 
474     auto bleService = IAdapterManager::GetInstance()->GetBleAdapterInterface();
475     if (bleService != nullptr) {
476         std::vector<BleScanFilterImpl> filterImpls {};
477         for (auto filter : filters) {
478             BleScanFilterImpl filterImpl;
479             filterImpl.SetDeviceId(filter.GetDeviceId());
480             filterImpl.SetName(filter.GetName());
481             if (filter.HasServiceUuid()) {
482                 filterImpl.SetServiceUuid(filter.GetServiceUuid());
483             }
484             if (filter.HasServiceUuidMask()) {
485                 filterImpl.SetServiceUuidMask(filter.GetServiceUuidMask());
486             }
487             if (filter.HasSolicitationUuid()) {
488                 filterImpl.SetServiceSolicitationUuid(filter.GetServiceSolicitationUuid());
489             }
490             if (filter.HasSolicitationUuidMask()) {
491                 filterImpl.SetServiceSolicitationUuidMask(filter.GetServiceSolicitationUuidMask());
492             }
493             filterImpl.SetServiceData(filter.GetServiceData());
494             filterImpl.SetServiceDataMask(filter.GetServiceDataMask());
495             filterImpl.SetManufacturerId(filter.GetManufacturerId());
496             filterImpl.SetManufactureData(filter.GetManufactureData());
497             filterImpl.SetManufactureDataMask(filter.GetManufactureDataMask());
498             filterImpls.push_back(filterImpl);
499         }
500         return bleService->ConfigScanFilter(scannerId, filterImpls);
501     }
502     return NO_ERROR;
503 }
504 
RemoveScanFilter(int32_t scannerId)505 void BluetoothBleCentralManagerServer::RemoveScanFilter(int32_t scannerId)
506 {
507     HILOGI("enter, scannerId: %{public}d", scannerId);
508 
509     auto bleService = IAdapterManager::GetInstance()->GetBleAdapterInterface();
510     if (bleService != nullptr) {
511         bleService->RemoveScanFilter(scannerId);
512     }
513 }
514 
RegisterBleCentralManagerCallback(int32_t & scannerId,bool enableRandomAddrMode,const sptr<IBluetoothBleCentralManagerCallback> & callback)515 void BluetoothBleCentralManagerServer::RegisterBleCentralManagerCallback(int32_t &scannerId, bool enableRandomAddrMode,
516     const sptr<IBluetoothBleCentralManagerCallback> &callback)
517 {
518     int32_t pid = IPCSkeleton::GetCallingPid();
519     int32_t uid = IPCSkeleton::GetCallingUid();
520     HILOGI("pid: %{public}d, uid: %{public}d", pid, uid);
521 
522     if (callback == nullptr) {
523         HILOGE("callback is null");
524         return;
525     }
526     auto bleService = IAdapterManager::GetInstance()->GetBleAdapterInterface();
527     if (bleService == nullptr) {
528         HILOGE("bleService is null");
529         return;
530     }
531     scannerId = bleService->AllocScannerId();
532     if (scannerId == 0) {
533         HILOGE("Alloc ScannerId fail.");
534         return;
535     }
536 
537     pimpl->eventHandler_->PostSyncTask([&]() {
538         if (pimpl != nullptr) {
539             pimpl->observersToken_[callback->AsObject()] = IPCSkeleton::GetCallingTokenID();
540             pimpl->observersUid_[callback->AsObject()] = uid;
541             auto func = std::bind(&BluetoothBleCentralManagerServer::DeregisterBleCentralManagerCallbackInner,
542                 this, std::placeholders::_1, std::placeholders::_2);
543             pimpl->observers_.Register(callback, func, scannerId);
544             impl::ScanCallbackInfo info;
545             info.pid = pid;
546             info.uid = uid;
547             info.isStart = false;
548             info.callback = callback;
549             pimpl->scanCallbackInfo_.push_back(info);
550         }
551     });
552 }
553 
DeregisterBleCentralManagerCallbackInner(const sptr<IBluetoothBleCentralManagerCallback> & callback,int32_t scannerId)554 void BluetoothBleCentralManagerServer::DeregisterBleCentralManagerCallbackInner(
555     const sptr<IBluetoothBleCentralManagerCallback> &callback, int32_t scannerId)
556 {
557     return DeregisterBleCentralManagerCallback(scannerId, callback);
558 }
559 
DeregisterBleCentralManagerCallback(int32_t scannerId,const sptr<IBluetoothBleCentralManagerCallback> & callback)560 void BluetoothBleCentralManagerServer::DeregisterBleCentralManagerCallback(int32_t scannerId,
561     const sptr<IBluetoothBleCentralManagerCallback> &callback)
562 {
563     HILOGI("enter, scannerId: %{public}d", scannerId);
564     pimpl->eventHandler_->PostSyncTask([&]() {
565         if (callback == nullptr || pimpl == nullptr) {
566             HILOGE("DeregisterBleCentralManagerCallback(): callback is null, or pimpl is null");
567             return;
568         }
569         for (auto iter = pimpl->scanCallbackInfo_.begin(); iter != pimpl->scanCallbackInfo_.end(); ++iter) {
570             if (iter->callback->AsObject() == callback->AsObject()) {
571                 pimpl->observers_.Deregister(iter->callback);
572                 pimpl->scanCallbackInfo_.erase(iter);
573                 break;
574             }
575         }
576         for (auto iter =  pimpl->observersToken_.begin(); iter !=  pimpl->observersToken_.end(); ++iter) {
577             if (iter->first == callback->AsObject()) {
578                 pimpl->observersToken_.erase(iter);
579                 break;
580             }
581         }
582         for (auto iter = pimpl->observersUid_.begin(); iter != pimpl->observersUid_.end(); ++iter) {
583             if (iter->first == callback->AsObject()) {
584                 pimpl->observersUid_.erase(iter);
585                 break;
586             }
587         }
588     });
589 
590     auto bleService = IAdapterManager::GetInstance()->GetBleAdapterInterface();
591     if (bleService == nullptr) {
592         HILOGE("bleService is null");
593         return;
594     }
595     bleService->RemoveScannerId(scannerId);
596 }
597 
SetScanParams(const BluetoothBleScanSettings & settings)598 void BluetoothBleCentralManagerServer::SetScanParams(const BluetoothBleScanSettings &settings)
599 {
600     if (pimpl == nullptr) {
601         HILOGE("pimpl is nullptr");
602     }
603     pimpl->scanSettingImpl_.SetReportDelay(settings.GetReportDelayMillisValue());
604     pimpl->scanSettingImpl_.SetScanMode(settings.GetScanMode());
605     pimpl->scanSettingImpl_.SetLegacy(settings.GetLegacy());
606     pimpl->scanSettingImpl_.SetPhy(settings.GetPhy());
607 }
608 
SetWindowAndInterval(const int mode,uint16_t & window,uint16_t & interval)609 void BluetoothBleCentralManagerServer::SetWindowAndInterval(const int mode, uint16_t &window, uint16_t &interval)
610 {
611     switch (mode) {
612         case SCAN_MODE_LOW_POWER:
613             window = BLE_SCAN_MODE_LOW_POWER_WINDOW_MS;
614             interval = BLE_SCAN_MODE_LOW_POWER_INTERVAL_MS;
615             break;
616         case SCAN_MODE_BALANCED:
617             window = BLE_SCAN_MODE_BALANCED_WINDOW_MS;
618             interval = BLE_SCAN_MODE_BALANCED_INTERVAL_MS;
619             break;
620         case SCAN_MODE_LOW_LATENCY:
621             window = BLE_SCAN_MODE_LOW_LATENCY_WINDOW_MS;
622             interval = BLE_SCAN_MODE_LOW_LATENCY_INTERVAL_MS;
623             break;
624         case SCAN_MODE_OP_P2_60_3000:
625             window = BLE_SCAN_MODE_OP_P2_60_3000_WINDOW_MS;
626             interval = BLE_SCAN_MODE_OP_P2_60_3000_INTERVAL_MS;
627             break;
628         case SCAN_MODE_OP_P10_60_600:
629             window = BLE_SCAN_MODE_OP_P10_60_600_WINDOW_MS;
630             interval = BLE_SCAN_MODE_OP_P10_60_600_INTERVAL_MS;
631             break;
632         case SCAN_MODE_OP_P25_60_240:
633             window = BLE_SCAN_MODE_OP_P25_60_240_WINDOW_MS;
634             interval = BLE_SCAN_MODE_OP_P25_60_240_INTERVAL_MS;
635             break;
636         case SCAN_MODE_OP_P100_1000_1000:
637             window = BLE_SCAN_MODE_OP_P100_1000_1000_WINDOW_MS;
638             interval = BLE_SCAN_MODE_OP_P100_1000_1000_INTERVAL_MS;
639             break;
640         default:
641             HILOGE("invalid scan mode.");
642             break;
643     }
644 }
645 
IsNewScanParams()646 bool BluetoothBleCentralManagerServer::IsNewScanParams()
647 {
648     int pid;
649     impl::ScanSettingsParam max;
650     auto iter = pimpl->scanCallbackInfo_.begin();
651     for (; iter != pimpl->scanCallbackInfo_.end(); ++iter) {
652         if (iter->isStart) {
653             max = iter->param;
654             pid = iter->pid;
655             break;
656         }
657     }
658     if (iter == pimpl->scanCallbackInfo_.end()) {
659         HILOGI("all is stop.");
660         return false;
661     }
662 
663     for (; iter != pimpl->scanCallbackInfo_.end(); ++iter) {
664         if (!iter->isStart) {
665             continue;
666         }
667         double maxDutyCycle = 1.0 * max.scanWindow / max.scanInterval;
668         double currDutyCycle = 1.0 * iter->param.scanWindow / iter->param.scanInterval;
669         if ((currDutyCycle > maxDutyCycle) ||
670             (currDutyCycle == maxDutyCycle && iter->param.scanInterval < max.scanInterval)) {
671             max = iter->param;
672             pid = iter->pid;
673         }
674     }
675 
676     HILOGI("maxPid=%{public}d, maxScanMode=%{public}s, currScanMode=%{public}s",
677         pid, GetScanModeName(max.scanMode).c_str(), GetScanModeName(pimpl->scanSettingImpl_.GetScanMode()).c_str());
678     if (pimpl->scanSettingImpl_.GetReportDelayMillisValue() != max.reportDelayMillis ||
679         pimpl->scanSettingImpl_.GetScanMode() != max.scanMode ||
680         pimpl->scanSettingImpl_.GetLegacy() != max.legacy ||
681         pimpl->scanSettingImpl_.GetPhy() != max.phy) {
682         pimpl->scanSettingImpl_.SetReportDelay(max.reportDelayMillis);
683         pimpl->scanSettingImpl_.SetScanMode(max.scanMode);
684         pimpl->scanSettingImpl_.SetLegacy(max.legacy);
685         pimpl->scanSettingImpl_.SetPhy(max.phy);
686         return true;
687     }
688     return false;
689 }
690 
IsAllStop()691 bool BluetoothBleCentralManagerServer::IsAllStop()
692 {
693     for (auto iter = pimpl->scanCallbackInfo_.begin(); iter != pimpl->scanCallbackInfo_.end(); ++iter) {
694         if (iter->isStart) {
695             return false;
696         }
697     }
698 
699     HILOGI("all is stop.");
700     pimpl->scanSettingImpl_.SetReportDelay(0);
701     pimpl->scanSettingImpl_.SetScanMode(SCAN_MODE_LOW_POWER);
702     pimpl->scanSettingImpl_.SetLegacy(true);
703     pimpl->scanSettingImpl_.SetPhy(PHY_LE_ALL_SUPPORTED);
704     return true;
705 }
706 
SetLpDeviceAdvParam(int duration,int maxExtAdvEvents,int window,int interval,int advHandle)707 int BluetoothBleCentralManagerServer::SetLpDeviceAdvParam(int duration, int maxExtAdvEvents,
708     int window, int interval, int advHandle)
709 {
710     HILOGI("NOT SUPPORT NOW");
711     return NO_ERROR;
712 }
713 
SetScanReportChannelToLpDevice(int32_t scannerId,bool enable)714 int BluetoothBleCentralManagerServer::SetScanReportChannelToLpDevice(int32_t scannerId, bool enable)
715 {
716     HILOGI("NOT SUPPORT NOW");
717     return NO_ERROR;
718 }
719 
EnableSyncDataToLpDevice()720 int BluetoothBleCentralManagerServer::EnableSyncDataToLpDevice()
721 {
722     HILOGI("NOT SUPPORT NOW");
723     return NO_ERROR;
724 }
725 
DisableSyncDataToLpDevice()726 int BluetoothBleCentralManagerServer::DisableSyncDataToLpDevice()
727 {
728     HILOGI("NOT SUPPORT NOW");
729     return NO_ERROR;
730 }
731 
SendParamsToLpDevice(const std::vector<uint8_t> & dataValue,int32_t type)732 int BluetoothBleCentralManagerServer::SendParamsToLpDevice(const std::vector<uint8_t> &dataValue, int32_t type)
733 {
734     HILOGI("NOT SUPPORT NOW");
735     return NO_ERROR;
736 }
737 
IsLpDeviceAvailable()738 bool BluetoothBleCentralManagerServer::IsLpDeviceAvailable()
739 {
740     HILOGI("NOT SUPPORT NOW");
741     return false;
742 }
743 
SetLpDeviceParam(const BluetoothLpDeviceParamSet & paramSet)744 int BluetoothBleCentralManagerServer::SetLpDeviceParam(const BluetoothLpDeviceParamSet &paramSet)
745 {
746     HILOGI("NOT SUPPORT NOW");
747     return NO_ERROR;
748 }
749 
RemoveLpDeviceParam(const bluetooth::Uuid & uuid)750 int BluetoothBleCentralManagerServer::RemoveLpDeviceParam(const bluetooth::Uuid &uuid)
751 {
752     HILOGI("NOT SUPPORT NOW");
753     return NO_ERROR;
754 }
755 }  // namespace Bluetooth
756 }  // namespace OHOS