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