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> ¬ifyValue) 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,bool isNewApi)371 int BluetoothBleCentralManagerServer::StartScan(int32_t scannerId, const BluetoothBleScanSettings &settings,
372 const std::vector<BluetoothBleScanFilter> &filters, bool isNewApi)
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 if (isNewApi) {
382 HILOGE("This api is not supported.");
383 return BT_ERR_API_NOT_SUPPORT;
384 }
385
386 ConfigScanFilterInner(scannerId, filters);
387
388 pimpl->eventHandler_->PostSyncTask([&]() {
389 auto bleService = IAdapterManager::GetInstance()->GetBleAdapterInterface();
390 if (bleService == nullptr) {
391 HILOGE("bleService is nullptr.");
392 return;
393 }
394
395 for (auto iter = pimpl->scanCallbackInfo_.begin(); iter != pimpl->scanCallbackInfo_.end(); ++iter) {
396 if (iter->pid == pid && iter->uid == uid) {
397 iter->isStart = true;
398 SetWindowAndInterval(settings.GetScanMode(), iter->param.scanWindow, iter->param.scanInterval);
399 iter->param.reportDelayMillis = settings.GetReportDelayMillisValue();
400 iter->param.scanMode = settings.GetScanMode();
401 iter->param.legacy = settings.GetLegacy();
402 iter->param.phy = settings.GetPhy();
403 break;
404 }
405 }
406
407 if (!pimpl->isScanning) {
408 HILOGI("start ble scan.");
409 SetScanParams(settings);
410 bleService->StartScan(pimpl->scanSettingImpl_);
411 pimpl->isScanning = true;
412 HiSysEventWrite(OHOS::HiviewDFX::HiSysEvent::Domain::BT_SERVICE, "BLE_SCAN_START",
413 OHOS::HiviewDFX::HiSysEvent::EventType::STATISTIC, "PID", pid, "UID", uid,
414 "TYPE", (settings.GetReportDelayMillisValue() > 0) ? 1 : 0);
415 } else if (IsNewScanParams()) {
416 // Stop an ongoing ble scan, update parameters and restart the ble scan in OnStartOrStopScanEvent().
417 HILOGI("restart ble scan.");
418 bleService->StopScan();
419 pimpl->isScanning = false;
420 } else {
421 HILOGI("scan is already started and has the same params.");
422 }
423 });
424 return NO_ERROR;
425 }
426
StopScan(int32_t scannerId)427 int BluetoothBleCentralManagerServer::StopScan(int32_t scannerId)
428 {
429 int32_t pid = IPCSkeleton::GetCallingPid();
430 int32_t uid = IPCSkeleton::GetCallingUid();
431 HILOGI("pid: %{public}d, uid: %{public}d", pid, uid);
432 if (PermissionUtils::VerifyDiscoverBluetoothPermission() == PERMISSION_DENIED) {
433 HILOGE("check permission failed.");
434 return BT_ERR_PERMISSION_FAILED;
435 }
436
437 pimpl->eventHandler_->PostSyncTask([&]() {
438 if (!pimpl->isScanning) {
439 HILOGE("scan is not started.");
440 return;
441 }
442
443 auto bleService = IAdapterManager::GetInstance()->GetBleAdapterInterface();
444 if (bleService == nullptr) {
445 HILOGE("bleService is nullptr.");
446 return;
447 }
448
449 for (auto iter = pimpl->scanCallbackInfo_.begin(); iter != pimpl->scanCallbackInfo_.end(); ++iter) {
450 if (iter->pid == pid && iter->uid == uid) {
451 iter->isStart = false;
452 break;
453 }
454 }
455
456 if (IsAllStop() || IsNewScanParams()) {
457 HILOGI("stop ble scan.");
458 bleService->StopScan();
459 pimpl->isScanning = false;
460 HiSysEventWrite(OHOS::HiviewDFX::HiSysEvent::Domain::BT_SERVICE, "BLE_SCAN_STOP",
461 OHOS::HiviewDFX::HiSysEvent::EventType::STATISTIC, "PID", pid, "UID", uid);
462 }
463 });
464 return NO_ERROR;
465 }
466
ConfigScanFilterInner(int32_t scannerId,const std::vector<BluetoothBleScanFilter> & filters)467 int BluetoothBleCentralManagerServer::ConfigScanFilterInner(
468 int32_t scannerId, const std::vector<BluetoothBleScanFilter> &filters)
469 {
470 HILOGI("enter, scannerId: %{public}d", scannerId);
471
472 auto bleService = IAdapterManager::GetInstance()->GetBleAdapterInterface();
473 if (bleService != nullptr) {
474 std::vector<BleScanFilterImpl> filterImpls {};
475 for (auto filter : filters) {
476 BleScanFilterImpl filterImpl;
477 filterImpl.SetDeviceId(filter.GetDeviceId());
478 filterImpl.SetName(filter.GetName());
479 if (filter.HasServiceUuid()) {
480 filterImpl.SetServiceUuid(filter.GetServiceUuid());
481 }
482 if (filter.HasServiceUuidMask()) {
483 filterImpl.SetServiceUuidMask(filter.GetServiceUuidMask());
484 }
485 if (filter.HasSolicitationUuid()) {
486 filterImpl.SetServiceSolicitationUuid(filter.GetServiceSolicitationUuid());
487 }
488 if (filter.HasSolicitationUuidMask()) {
489 filterImpl.SetServiceSolicitationUuidMask(filter.GetServiceSolicitationUuidMask());
490 }
491 filterImpl.SetServiceData(filter.GetServiceData());
492 filterImpl.SetServiceDataMask(filter.GetServiceDataMask());
493 filterImpl.SetManufacturerId(filter.GetManufacturerId());
494 filterImpl.SetManufactureData(filter.GetManufactureData());
495 filterImpl.SetManufactureDataMask(filter.GetManufactureDataMask());
496 filterImpls.push_back(filterImpl);
497 }
498 std::lock_guard<std::mutex> lock(pimpl->bleScanFiltersMutex_);
499 pimpl->observersBleScanFilters_[scannerId] = filterImpls;
500 pimpl->observersScanFiltersIsEnanled_[scannerId] = true;
501 return bleService->ConfigScanFilter(scannerId, filterImpls);
502 }
503 return NO_ERROR;
504 }
505
RemoveScanFilter(int32_t scannerId)506 void BluetoothBleCentralManagerServer::RemoveScanFilter(int32_t scannerId)
507 {
508 HILOGI("enter, scannerId: %{public}d", scannerId);
509
510 auto bleService = IAdapterManager::GetInstance()->GetBleAdapterInterface();
511 if (bleService != nullptr) {
512 bleService->RemoveScanFilter(scannerId);
513 }
514 std::lock_guard<std::mutex> lock(pimpl->bleScanFiltersMutex_);
515 pimpl->observersScanFiltersIsEnanled_[scannerId] = false;
516 pimpl->observersBleScanFilters_.erase(scannerId);
517 }
518
RegisterBleCentralManagerCallback(int32_t & scannerId,bool enableRandomAddrMode,const sptr<IBluetoothBleCentralManagerCallback> & callback)519 void BluetoothBleCentralManagerServer::RegisterBleCentralManagerCallback(int32_t &scannerId, bool enableRandomAddrMode,
520 const sptr<IBluetoothBleCentralManagerCallback> &callback)
521 {
522 int32_t pid = IPCSkeleton::GetCallingPid();
523 int32_t uid = IPCSkeleton::GetCallingUid();
524 HILOGI("pid: %{public}d, uid: %{public}d", pid, uid);
525
526 if (callback == nullptr) {
527 HILOGE("callback is null");
528 return;
529 }
530 auto bleService = IAdapterManager::GetInstance()->GetBleAdapterInterface();
531 if (bleService == nullptr) {
532 HILOGE("bleService is null");
533 return;
534 }
535 scannerId = bleService->AllocScannerId();
536 if (scannerId == 0) {
537 HILOGE("Alloc ScannerId fail.");
538 return;
539 }
540
541 pimpl->eventHandler_->PostSyncTask([&]() {
542 if (pimpl != nullptr) {
543 pimpl->observersToken_.EnsureInsert(callback->AsObject(), IPCSkeleton::GetCallingTokenID());
544 pimpl->observersPid_[callback->AsObject()] = pid;
545 pimpl->observersScannerId_[callback->AsObject()] = scannerId;
546 auto func = std::bind(&BluetoothBleCentralManagerServer::DeregisterBleCentralManagerCallbackInner,
547 this, std::placeholders::_1, std::placeholders::_2);
548 pimpl->observers_.Register(callback, func, scannerId);
549 impl::ScanCallbackInfo info;
550 info.pid = pid;
551 info.uid = uid;
552 info.isStart = false;
553 info.callback = callback;
554 pimpl->scanCallbackInfo_.push_back(info);
555 }
556 });
557 }
558
DeregisterBleCentralManagerCallbackInner(const sptr<IBluetoothBleCentralManagerCallback> & callback,int32_t scannerId)559 void BluetoothBleCentralManagerServer::DeregisterBleCentralManagerCallbackInner(
560 const sptr<IBluetoothBleCentralManagerCallback> &callback, int32_t scannerId)
561 {
562 return DeregisterBleCentralManagerCallback(scannerId, callback);
563 }
564
ChangeScanParams(int32_t scannerId,const BluetoothBleScanSettings & settings,const std::vector<BluetoothBleScanFilter> & filters,uint32_t filterAction)565 int BluetoothBleCentralManagerServer::ChangeScanParams(int32_t scannerId, const BluetoothBleScanSettings &settings,
566 const std::vector<BluetoothBleScanFilter> &filters, uint32_t filterAction)
567 {
568 return BT_ERR_API_NOT_SUPPORT;
569 }
570
IsValidScannerId(int32_t scannerId,bool & isValid)571 int BluetoothBleCentralManagerServer::IsValidScannerId(int32_t scannerId, bool &isValid)
572 {
573 isValid = true;
574 return NO_ERROR;
575 }
576
DeregisterBleCentralManagerCallback(int32_t scannerId,const sptr<IBluetoothBleCentralManagerCallback> & callback)577 void BluetoothBleCentralManagerServer::DeregisterBleCentralManagerCallback(int32_t scannerId,
578 const sptr<IBluetoothBleCentralManagerCallback> &callback)
579 {
580 HILOGI("enter, scannerId: %{public}d", scannerId);
581 pimpl->eventHandler_->PostSyncTask([&]() {
582 if (callback == nullptr || pimpl == nullptr) {
583 HILOGE("DeregisterBleCentralManagerCallback(): callback is null, or pimpl is null");
584 return;
585 }
586 for (auto iter = pimpl->scanCallbackInfo_.begin(); iter != pimpl->scanCallbackInfo_.end(); ++iter) {
587 if (iter->callback->AsObject() == callback->AsObject()) {
588 pimpl->observers_.Deregister(iter->callback);
589 pimpl->scanCallbackInfo_.erase(iter);
590 break;
591 }
592 }
593 pimpl->observersToken_.Erase(callback->AsObject());
594
595 for (auto iter = pimpl->observersPid_.begin(); iter != pimpl->observersPid_.end(); ++iter) {
596 if (iter->first == callback->AsObject()) {
597 pimpl->observersPid_.erase(iter);
598 break;
599 }
600 }
601 for (auto iter = pimpl->observersScannerId_.begin(); iter != pimpl->observersScannerId_.end(); ++iter) {
602 if (iter->first == callback->AsObject()) {
603 pimpl->observersScannerId_.erase(iter);
604 break;
605 }
606 }
607 });
608
609 auto bleService = IAdapterManager::GetInstance()->GetBleAdapterInterface();
610 if (bleService == nullptr) {
611 HILOGE("bleService is null");
612 return;
613 }
614 bleService->RemoveScannerId(scannerId);
615 }
616
SetScanParams(const BluetoothBleScanSettings & settings)617 void BluetoothBleCentralManagerServer::SetScanParams(const BluetoothBleScanSettings &settings)
618 {
619 if (pimpl == nullptr) {
620 HILOGE("pimpl is nullptr");
621 }
622 pimpl->scanSettingImpl_.SetReportDelay(settings.GetReportDelayMillisValue());
623 pimpl->scanSettingImpl_.SetScanMode(settings.GetScanMode());
624 pimpl->scanSettingImpl_.SetLegacy(settings.GetLegacy());
625 pimpl->scanSettingImpl_.SetPhy(settings.GetPhy());
626 }
627
SetWindowAndInterval(const int mode,uint16_t & window,uint16_t & interval)628 void BluetoothBleCentralManagerServer::SetWindowAndInterval(const int mode, uint16_t &window, uint16_t &interval)
629 {
630 switch (mode) {
631 case SCAN_MODE_LOW_POWER:
632 window = BLE_SCAN_MODE_LOW_POWER_WINDOW_MS;
633 interval = BLE_SCAN_MODE_LOW_POWER_INTERVAL_MS;
634 break;
635 case SCAN_MODE_BALANCED:
636 window = BLE_SCAN_MODE_BALANCED_WINDOW_MS;
637 interval = BLE_SCAN_MODE_BALANCED_INTERVAL_MS;
638 break;
639 case SCAN_MODE_LOW_LATENCY:
640 window = BLE_SCAN_MODE_LOW_LATENCY_WINDOW_MS;
641 interval = BLE_SCAN_MODE_LOW_LATENCY_INTERVAL_MS;
642 break;
643 case SCAN_MODE_OP_P2_60_3000:
644 window = BLE_SCAN_MODE_OP_P2_60_3000_WINDOW_MS;
645 interval = BLE_SCAN_MODE_OP_P2_60_3000_INTERVAL_MS;
646 break;
647 case SCAN_MODE_OP_P10_60_600:
648 window = BLE_SCAN_MODE_OP_P10_60_600_WINDOW_MS;
649 interval = BLE_SCAN_MODE_OP_P10_60_600_INTERVAL_MS;
650 break;
651 case SCAN_MODE_OP_P25_60_240:
652 window = BLE_SCAN_MODE_OP_P25_60_240_WINDOW_MS;
653 interval = BLE_SCAN_MODE_OP_P25_60_240_INTERVAL_MS;
654 break;
655 case SCAN_MODE_OP_P100_1000_1000:
656 window = BLE_SCAN_MODE_OP_P100_1000_1000_WINDOW_MS;
657 interval = BLE_SCAN_MODE_OP_P100_1000_1000_INTERVAL_MS;
658 break;
659 case SCAN_MODE_OP_P50_100_200:
660 window = BLE_SCAN_MODE_OP_P50_100_200_WINDOW_MS;
661 interval = BLE_SCAN_MODE_OP_P50_100_200_INTERVAL_MS;
662 break;
663 case SCAN_MODE_OP_P10_30_300:
664 window = BLE_SCAN_MODE_OP_P10_30_300_WINDOW_MS;
665 interval = BLE_SCAN_MODE_OP_P10_30_300_INTERVAL_MS;
666 break;
667 default:
668 SetOtherWindowAndInterval(mode, window, interval);
669 break;
670 }
671 }
672
SetOtherWindowAndInterval(const int mode,uint16_t & window,uint16_t & interval)673 void BluetoothBleCentralManagerServer::SetOtherWindowAndInterval(const int mode, uint16_t &window, uint16_t &interval)
674 {
675 switch (mode) {
676 case SCAN_MODE_OP_P2_30_1500:
677 window = BLE_SCAN_MODE_OP_P2_30_1500_WINDOW_MS;
678 interval = BLE_SCAN_MODE_OP_P2_30_1500_INTERVAL_MS;
679 break;
680 case SCAN_MODE_OP_P75_30_40:
681 window = BLE_SCAN_MODE_OP_P75_30_40_WINDOW_MS;
682 interval = BLE_SCAN_MODE_OP_P75_30_40_INTERVAL_MS;
683 break;
684 case SCAN_MODE_OP_P50_30_60:
685 window = BLE_SCAN_MODE_OP_P50_30_60_WINDOW_MS;
686 interval = BLE_SCAN_MODE_OP_P50_30_60_INTERVAL_MS;
687 break;
688 default:
689 HILOGE("invalid scan mode.");
690 break;
691 }
692 }
693
IsNewScanParams()694 bool BluetoothBleCentralManagerServer::IsNewScanParams()
695 {
696 int pid;
697 impl::ScanSettingsParam max;
698 auto iter = pimpl->scanCallbackInfo_.begin();
699 for (; iter != pimpl->scanCallbackInfo_.end(); ++iter) {
700 if (iter->isStart) {
701 max = iter->param;
702 pid = iter->pid;
703 break;
704 }
705 }
706 if (iter == pimpl->scanCallbackInfo_.end()) {
707 HILOGI("all is stop.");
708 return false;
709 }
710
711 for (; iter != pimpl->scanCallbackInfo_.end(); ++iter) {
712 if (!iter->isStart) {
713 continue;
714 }
715 double maxDutyCycle = 1.0 * max.scanWindow / max.scanInterval;
716 double currDutyCycle = 1.0 * iter->param.scanWindow / iter->param.scanInterval;
717 if ((currDutyCycle > maxDutyCycle) ||
718 (currDutyCycle == maxDutyCycle && iter->param.scanInterval < max.scanInterval)) {
719 max = iter->param;
720 pid = iter->pid;
721 }
722 }
723
724 HILOGI("maxPid=%{public}d, maxScanMode=%{public}s, currScanMode=%{public}s",
725 pid, GetScanModeName(max.scanMode).c_str(), GetScanModeName(pimpl->scanSettingImpl_.GetScanMode()).c_str());
726 if (pimpl->scanSettingImpl_.GetReportDelayMillisValue() != max.reportDelayMillis ||
727 pimpl->scanSettingImpl_.GetScanMode() != max.scanMode ||
728 pimpl->scanSettingImpl_.GetLegacy() != max.legacy ||
729 pimpl->scanSettingImpl_.GetPhy() != max.phy) {
730 pimpl->scanSettingImpl_.SetReportDelay(max.reportDelayMillis);
731 pimpl->scanSettingImpl_.SetScanMode(max.scanMode);
732 pimpl->scanSettingImpl_.SetLegacy(max.legacy);
733 pimpl->scanSettingImpl_.SetPhy(max.phy);
734 return true;
735 }
736 return false;
737 }
738
IsAllStop()739 bool BluetoothBleCentralManagerServer::IsAllStop()
740 {
741 for (auto iter = pimpl->scanCallbackInfo_.begin(); iter != pimpl->scanCallbackInfo_.end(); ++iter) {
742 if (iter->isStart) {
743 return false;
744 }
745 }
746
747 HILOGI("all is stop.");
748 pimpl->scanSettingImpl_.SetReportDelay(0);
749 pimpl->scanSettingImpl_.SetScanMode(SCAN_MODE_LOW_POWER);
750 pimpl->scanSettingImpl_.SetLegacy(true);
751 pimpl->scanSettingImpl_.SetPhy(PHY_LE_ALL_SUPPORTED);
752 return true;
753 }
754
SetLpDeviceAdvParam(int duration,int maxExtAdvEvents,int window,int interval,int advHandle)755 int BluetoothBleCentralManagerServer::SetLpDeviceAdvParam(int duration, int maxExtAdvEvents,
756 int window, int interval, int advHandle)
757 {
758 HILOGI("NOT SUPPORT NOW");
759 return NO_ERROR;
760 }
761
SetScanReportChannelToLpDevice(int32_t scannerId,bool enable)762 int BluetoothBleCentralManagerServer::SetScanReportChannelToLpDevice(int32_t scannerId, bool enable)
763 {
764 HILOGI("NOT SUPPORT NOW");
765 return NO_ERROR;
766 }
767
EnableSyncDataToLpDevice()768 int BluetoothBleCentralManagerServer::EnableSyncDataToLpDevice()
769 {
770 HILOGI("NOT SUPPORT NOW");
771 return NO_ERROR;
772 }
773
DisableSyncDataToLpDevice()774 int BluetoothBleCentralManagerServer::DisableSyncDataToLpDevice()
775 {
776 HILOGI("NOT SUPPORT NOW");
777 return NO_ERROR;
778 }
779
SendParamsToLpDevice(const std::vector<uint8_t> & dataValue,int32_t type)780 int BluetoothBleCentralManagerServer::SendParamsToLpDevice(const std::vector<uint8_t> &dataValue, int32_t type)
781 {
782 HILOGI("NOT SUPPORT NOW");
783 return NO_ERROR;
784 }
785
IsLpDeviceAvailable()786 bool BluetoothBleCentralManagerServer::IsLpDeviceAvailable()
787 {
788 HILOGI("NOT SUPPORT NOW");
789 return false;
790 }
791
SetLpDeviceParam(const BluetoothLpDeviceParamSet & paramSet)792 int BluetoothBleCentralManagerServer::SetLpDeviceParam(const BluetoothLpDeviceParamSet ¶mSet)
793 {
794 HILOGI("NOT SUPPORT NOW");
795 return NO_ERROR;
796 }
797
RemoveLpDeviceParam(const bluetooth::Uuid & uuid)798 int BluetoothBleCentralManagerServer::RemoveLpDeviceParam(const bluetooth::Uuid &uuid)
799 {
800 HILOGI("NOT SUPPORT NOW");
801 return NO_ERROR;
802 }
803 } // namespace Bluetooth
804 } // namespace OHOS
805