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