• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2023 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 #include "locator_required_data_manager.h"
16 #include "location_log.h"
17 #ifdef WIFI_ENABLE
18 #include "wifi_errcode.h"
19 #include "wifi_device.h"
20 #endif
21 #include "iservice_registry.h"
22 #include "common_utils.h"
23 #include "permission_manager.h"
24 #include "locator_ability.h"
25 #include "hook_utils.h"
26 #ifdef LOCATION_HICOLLIE_ENABLE
27 #include "xcollie/xcollie.h"
28 #include "xcollie/xcollie_define.h"
29 #endif
30 
31 namespace OHOS {
32 namespace Location {
33 const uint32_t EVENT_START_SCAN = 0x0100;
34 const uint32_t EVENT_GET_WIFI_LIST = 0x0300;
35 const uint32_t EVENT_REGISTER_WIFI_CALLBACK = 0x0400;
36 const uint32_t EVENT_UNREGISTER_WIFI_CALLBACK = 0x0500;
37 const uint32_t EVENT_START_BLUETOOTH_SCAN = 0x0600;
38 const uint32_t EVENT_STOP_BLUETOOTH_SCAN = 0x0700;
39 const int32_t DEFAULT_TIMEOUT_4S = 4000;
40 const int32_t DEFAULT_TIMEOUT_MS = 1500;
41 const int64_t DEFAULT_TIMEOUT_30_MIN = 30 * 60 * MILLI_PER_SEC * MICRO_PER_MILLI;
42 const int64_t DEFAULT_INVALID_10_SECONDS = 10 * MILLI_PER_SEC * MICRO_PER_MILLI;
43 const int64_t DEFAULT_NOT_RETRY_TIME_10_SECONDS = 10 * MILLI_PER_SEC * MICRO_PER_MILLI; //10s
44 const int64_t WLAN_SCAN_RESULTS_VALIDITY_PERIOD = 2 * MILLI_PER_SEC * MICRO_PER_MILLI;
45 const int TIMEOUT_WATCHDOG = 60; // s
46 const int32_t MAX_CALLBACKS_MAP_NUM = 1000;
47 
48 const std::string TYPE_BLE = "ble";
LocatorRequiredDataManager()49 LocatorRequiredDataManager::LocatorRequiredDataManager()
50 {
51 #ifdef BLUETOOTH_ENABLE
52     std::shared_ptr<LocatorBleCallbackWapper> bleCallback = std::make_shared<LocatorBleCallbackWapper>();
53     bleCentralManager_ = std::make_shared<Bluetooth::BleCentralManager>(bleCallback);
54 #endif
55     scanHandler_ = std::make_shared<ScanHandler>(AppExecFwk::EventRunner::Create(true, AppExecFwk::ThreadMode::FFRT));
56     wifiSdkHandler_ =
57         std::make_shared<WifiSdkHandler>(AppExecFwk::EventRunner::Create(true, AppExecFwk::ThreadMode::FFRT));
58 #ifndef TDD_CASES_ENABLED
59     if (wifiSdkHandler_ != nullptr) {
60         wifiSdkHandler_->SendEvent(EVENT_REGISTER_WIFI_CALLBACK, 0, 0);
61     }
62 #endif
63 }
64 
GetInstance()65 LocatorRequiredDataManager* LocatorRequiredDataManager::GetInstance()
66 {
67     static LocatorRequiredDataManager data;
68     return &data;
69 }
70 
~LocatorRequiredDataManager()71 LocatorRequiredDataManager::~LocatorRequiredDataManager()
72 {
73 #ifndef TDD_CASES_ENABLED
74     if (wifiSdkHandler_ != nullptr) {
75         wifiSdkHandler_->SendEvent(EVENT_UNREGISTER_WIFI_CALLBACK, 0, 0);
76     }
77 #endif
78 }
79 
SyncStillMovementState(bool state)80 void LocatorRequiredDataManager::SyncStillMovementState(bool state)
81 {
82     std::unique_lock<std::mutex> lock(lastStillTimeMutex_);
83     if (state) {
84         lastStillTime_ = CommonUtils::GetSinceBootTime();
85     } else {
86         lastStillTime_ = 0;
87     }
88 }
89 
GetlastStillTime()90 int64_t LocatorRequiredDataManager::GetlastStillTime()
91 {
92     std::unique_lock<std::mutex> lock(lastStillTimeMutex_);
93     return lastStillTime_;
94 }
95 
IsStill()96 bool LocatorRequiredDataManager::IsStill()
97 {
98     std::unique_lock<std::mutex> lock(lastStillTimeMutex_);
99     return lastStillTime_ > 0;
100 }
101 
SendStartBluetoothScanEvent()102 void LocatorRequiredDataManager::SendStartBluetoothScanEvent()
103 {
104     if (scanHandler_ != nullptr) {
105         AppExecFwk::InnerEvent::Pointer event = AppExecFwk::InnerEvent::Get(
106             EVENT_START_BLUETOOTH_SCAN);
107         scanHandler_->SendEvent(event);
108     }
109 }
110 
SendStopBluetoothScanEvent()111 void LocatorRequiredDataManager::SendStopBluetoothScanEvent()
112 {
113     if (scanHandler_ != nullptr) {
114         AppExecFwk::InnerEvent::Pointer event = AppExecFwk::InnerEvent::Get(
115             EVENT_STOP_BLUETOOTH_SCAN);
116         scanHandler_->SendEvent(event);
117     }
118 }
119 
SendWifiScanEvent()120 void LocatorRequiredDataManager::SendWifiScanEvent()
121 {
122     if (scanHandler_ != nullptr) {
123         AppExecFwk::InnerEvent::Pointer event = AppExecFwk::InnerEvent::Get(
124             EVENT_START_SCAN, 1);
125         scanHandler_->SendEvent(event);
126     }
127 }
128 
SendGetWifiListEvent(int timeout,bool needRetryScan)129 void LocatorRequiredDataManager::SendGetWifiListEvent(int timeout, bool needRetryScan)
130 {
131     if (wifiSdkHandler_ == nullptr) {
132         return;
133     }
134     if (timeout > 0 && wifiSdkHandler_->HasInnerEvent(EVENT_GET_WIFI_LIST)) {
135         return;
136     }
137     AppExecFwk::InnerEvent::Pointer event = AppExecFwk::InnerEvent::
138         Get(EVENT_GET_WIFI_LIST, needRetryScan);
139     wifiSdkHandler_->SendHighPriorityEvent(event, timeout);
140 }
141 
RemoveGetWifiListEvent()142 void LocatorRequiredDataManager::RemoveGetWifiListEvent()
143 {
144     if (wifiSdkHandler_ != nullptr) {
145         wifiSdkHandler_->RemoveEvent(EVENT_GET_WIFI_LIST);
146     }
147 }
148 
RegisterCallback(AppIdentity & identity,std::shared_ptr<LocatingRequiredDataConfig> & config,const sptr<IRemoteObject> & callback)149 __attribute__((no_sanitize("cfi"))) LocationErrCode LocatorRequiredDataManager::RegisterCallback(
150     AppIdentity &identity, std::shared_ptr<LocatingRequiredDataConfig>& config, const sptr<IRemoteObject>& callback)
151 {
152     if (callback == nullptr || config == nullptr) {
153         LBSLOGE(LOCATOR, "%{public}s nullptr.", __func__);
154         return ERRCODE_INVALID_PARAM;
155     }
156     if (config->GetType() == LocatingRequiredDataType::WIFI) {
157 #ifdef WIFI_ENABLE
158         std::unique_lock<std::mutex> lock(mutex_, std::defer_lock);
159         lock.lock();
160         if (callbacksMap_.size() <= MAX_CALLBACKS_MAP_NUM) {
161             callbacksMap_[callback] = identity;
162         } else {
163             LBSLOGE(LOCATOR, "LocatorRequiredDataManager::RegisterCallback fail,Exceeded the maximum number limit");
164             lock.unlock();
165             return ERRCODE_SCAN_FAIL;
166         }
167         LBSLOGD(LOCATOR, "after RegisterCallback, callback size:%{public}s",
168             std::to_string(callbacksMap_.size()).c_str());
169         if (!IsWifiCallbackRegistered() && wifiSdkHandler_ != nullptr) {
170             wifiSdkHandler_->SendEvent(EVENT_REGISTER_WIFI_CALLBACK, 0, 0);
171         }
172         bool needScan = false;
173         if (config->GetNeedStartScan()) {
174             needScan = true;
175         }
176         lock.unlock();
177         if (needScan) {
178             SendWifiScanEvent();
179             SendGetWifiListEvent(DEFAULT_TIMEOUT_4S >= config->GetScanTimeoutMs() ?
180                 config->GetScanTimeoutMs() : DEFAULT_TIMEOUT_4S, false);
181         } else {
182             SendGetWifiListEvent(0, false);
183         }
184 #endif
185     } else if (config->GetType() == LocatingRequiredDataType::BLUE_TOOTH) {
186         return LOCATION_ERRCODE_NOT_SUPPORTED;
187     }
188     return ERRCODE_SUCCESS;
189 }
190 
UnregisterCallback(const sptr<IRemoteObject> & callback)191 LocationErrCode LocatorRequiredDataManager::UnregisterCallback(const sptr<IRemoteObject>& callback)
192 {
193 #ifdef WIFI_ENABLE
194     std::unique_lock<std::mutex> lock(mutex_);
195     auto iter = callbacksMap_.find(callback);
196     if (iter != callbacksMap_.end()) {
197         callbacksMap_.erase(iter);
198     }
199     LBSLOGD(LOCATOR, "after UnregisterCallback,  callback size:%{public}s",
200         std::to_string(callbacksMap_.size()).c_str());
201 #endif
202     return ERRCODE_SUCCESS;
203 }
204 
StartScanBluetoothDevice(sptr<IBluetoothScanResultCallback> callback,AppIdentity identity)205 void LocatorRequiredDataManager::StartScanBluetoothDevice(sptr<IBluetoothScanResultCallback> callback,
206     AppIdentity identity)
207 {
208     if (callback == nullptr) {
209         LBSLOGE(LOCATOR, "%{public}s.callback == nullptr", __func__);
210         return;
211     }
212     if (!HookUtils::ExecuteHookWhenStartScanBluetoothDevice(identity.GetBundleName(), TYPE_BLE)) {
213         return;
214     }
215 #ifdef BLUETOOTH_ENABLE
216     sptr<IRemoteObject::DeathRecipient> death(new (std::nothrow)
217         BluetoothScanCallbackDeathRecipient());
218     if (callback->AsObject() != nullptr) {
219         callback->AsObject()->AddDeathRecipient(death);
220     }
221     {
222         std::lock_guard<std::mutex> lock(bluetoothcallbacksMapMutex_);
223         if (bluetoothcallbacksMap_.size() <= MAX_CALLBACKS_MAP_NUM) {
224             bluetoothcallbacksMap_.insert(std::make_pair(callback->AsObject(), std::make_pair(identity, death)));
225         } else {
226             LBSLOGE(LOCATOR, "%{public}s fail,Exceeded the maximum number limit", __func__);
227             return;
228         }
229         LBSLOGI(LOCATOR, "after StartScanBluetoothDevice, callback size:%{public}zu",
230             bluetoothcallbacksMap_.size());
231     }
232     SendStartBluetoothScanEvent();
233 #endif
234 }
235 
StopScanBluetoothDevice(sptr<IRemoteObject> callbackObj)236 void LocatorRequiredDataManager::StopScanBluetoothDevice(sptr<IRemoteObject> callbackObj)
237 {
238 #ifdef BLUETOOTH_ENABLE
239     RemoveBluetoothScanCallbackDeathRecipientByCallback(callbackObj);
240     RemoveBluetoothScanCallback(callbackObj);
241     SendStopBluetoothScanEvent();
242 #endif
243 }
244 
RemoveBluetoothScanCallback(sptr<IRemoteObject> callbackObj)245 void LocatorRequiredDataManager::RemoveBluetoothScanCallback(sptr<IRemoteObject> callbackObj)
246 {
247     if (callbackObj == nullptr) {
248         LBSLOGE(LOCATOR, "%{public}s, callbackObj is nullptr", __func__);
249         return;
250     }
251     std::unique_lock<std::mutex> lock(bluetoothcallbacksMapMutex_);
252     auto iter = bluetoothcallbacksMap_.find(callbackObj);
253     if (iter != bluetoothcallbacksMap_.end()) {
254         bluetoothcallbacksMap_.erase(iter);
255     }
256     LBSLOGI(LOCATOR, "after RemoveBluetoothScanCallback, callback size:%{public}zu",
257         bluetoothcallbacksMap_.size());
258 }
259 
RemoveBluetoothScanCallbackDeathRecipientByCallback(sptr<IRemoteObject> callbackObj)260 void LocatorRequiredDataManager::RemoveBluetoothScanCallbackDeathRecipientByCallback(sptr<IRemoteObject> callbackObj)
261 {
262     if (callbackObj == nullptr) {
263         LBSLOGE(LOCATOR, "%{public}s, callbackObj is nullptr", __func__);
264         return;
265     }
266     {
267         std::unique_lock<std::mutex> lock(bluetoothcallbacksMapMutex_);
268         for (auto iter = bluetoothcallbacksMap_.begin(); iter != bluetoothcallbacksMap_.end();) {
269             auto callback = iter->first;
270             auto deathRecipientPair = iter->second;
271             auto death = deathRecipientPair.second;
272             if (callbackObj == callback) {
273                 callback->RemoveDeathRecipient(death);
274                 break;
275             } else {
276                 iter++;
277             }
278         }
279     }
280 }
281 
282 #ifdef BLUETOOTH_ENABLE
283 
GetLocatingRequiredDataByBtHost(const Bluetooth::BluetoothRemoteDevice & device)284 std::vector<std::shared_ptr<LocatingRequiredData>> LocatorBluetoothHost::GetLocatingRequiredDataByBtHost(
285     const Bluetooth::BluetoothRemoteDevice &device)
286 {
287     std::vector<std::shared_ptr<LocatingRequiredData>> result;
288     std::shared_ptr<LocatingRequiredData> info = std::make_shared<LocatingRequiredData>();
289     std::shared_ptr<BluetoothScanInfo> btData = std::make_shared<BluetoothScanInfo>();
290     btData->SetMac(device.GetDeviceAddr());
291     btData->SetDeviceName(device.GetDeviceName());
292     info->SetType(LocatingRequiredDataType::BLUE_TOOTH);
293     info->SetBluetoothScanInfo(btData);
294     result.push_back(info);
295     return result;
296 }
297 
GetLocatingRequiredDataByBle(const Bluetooth::BleScanResult & result)298 std::vector<std::shared_ptr<LocatingRequiredData>> LocatorBleCallbackWapper::GetLocatingRequiredDataByBle(
299     const Bluetooth::BleScanResult &result)
300 {
301     std::vector<std::shared_ptr<LocatingRequiredData>> res;
302     std::shared_ptr<LocatingRequiredData> info = std::make_shared<LocatingRequiredData>();
303     std::shared_ptr<BluetoothScanInfo> btData = std::make_shared<BluetoothScanInfo>();
304     btData->SetMac(result.GetPeripheralDevice().GetDeviceAddr());
305     btData->SetDeviceName(result.GetPeripheralDevice().GetDeviceName());
306     btData->SetRssi(result.GetRssi());
307     info->SetType(LocatingRequiredDataType::BLUE_TOOTH);
308     info->SetBluetoothScanInfo(btData);
309     res.push_back(info);
310     return res;
311 }
312 
GetBluetoothScanResultByBle(const Bluetooth::BleScanResult & result)313 std::unique_ptr<BluetoothScanResult> LocatorBleCallbackWapper::GetBluetoothScanResultByBle(
314     const Bluetooth::BleScanResult &result)
315 {
316     std::unique_ptr<BluetoothScanResult> res = std::make_unique<BluetoothScanResult>();
317     Bluetooth::BluetoothRemoteDevice peripheralDevice = result.GetPeripheralDevice();
318     res->SetDeviceId(result.GetPeripheralDevice().GetDeviceAddr());
319     res->SetDeviceName(const_cast<Bluetooth::BleScanResult&>(result).GetName());
320     res->SetRssi(result.GetRssi());
321     res->SetConnectable(result.IsConnectable());
322     res->SetData(result.GetPayload());
323     return res;
324 }
325 
OnStateChanged(const int transport,const int status)326 void LocatorBluetoothHost::OnStateChanged(const int transport, const int status) {}
327 
OnDiscoveryStateChanged(int status)328 void LocatorBluetoothHost::OnDiscoveryStateChanged(int status) {}
329 
OnDiscoveryResult(const Bluetooth::BluetoothRemoteDevice & device,int rssi,const std::string deviceName,int deviceClass)330 void LocatorBluetoothHost::OnDiscoveryResult(const Bluetooth::BluetoothRemoteDevice &device, int rssi,
331     const std::string deviceName, int deviceClass)
332 {
333     std::vector<std::shared_ptr<LocatingRequiredData>> result = GetLocatingRequiredDataByBtHost(device);
334     auto dataManager = LocatorRequiredDataManager::GetInstance();
335     dataManager->ReportData(result);
336 }
337 
OnPairRequested(const Bluetooth::BluetoothRemoteDevice & device)338 void LocatorBluetoothHost::OnPairRequested(const Bluetooth::BluetoothRemoteDevice &device) {}
339 
OnPairConfirmed(const Bluetooth::BluetoothRemoteDevice & device,int reqType,int number)340 void LocatorBluetoothHost::OnPairConfirmed(const Bluetooth::BluetoothRemoteDevice &device, int reqType, int number) {}
341 
OnScanModeChanged(int mode)342 void LocatorBluetoothHost::OnScanModeChanged(int mode) {}
343 
OnDeviceNameChanged(const std::string & deviceName)344 void LocatorBluetoothHost::OnDeviceNameChanged(const std::string &deviceName) {}
345 
OnDeviceAddrChanged(const std::string & address)346 void LocatorBluetoothHost::OnDeviceAddrChanged(const std::string &address) {}
347 
OnScanCallback(const Bluetooth::BleScanResult & result)348 void LocatorBleCallbackWapper::OnScanCallback(const Bluetooth::BleScanResult &result)
349 {
350     std::unique_ptr<BluetoothScanResult> res = GetBluetoothScanResultByBle(result);
351     LocatorRequiredDataManager::GetInstance()->ReportBluetoothScanResult(res);
352 }
353 
OnFoundOrLostCallback(const Bluetooth::BleScanResult & result,uint8_t callbackType)354 void LocatorBleCallbackWapper::OnFoundOrLostCallback(const Bluetooth::BleScanResult &result, uint8_t callbackType) {}
355 
OnBleBatchScanResultsEvent(const std::vector<Bluetooth::BleScanResult> & results)356 void LocatorBleCallbackWapper::OnBleBatchScanResultsEvent(const std::vector<Bluetooth::BleScanResult> &results) {}
357 
OnStartOrStopScanEvent(int32_t resultCode,bool isStartScan)358 void LocatorBleCallbackWapper::OnStartOrStopScanEvent(int32_t resultCode, bool isStartScan) {}
359 
OnNotifyMsgReportFromLpDevice(const Bluetooth::UUID & btUuid,int msgType,const std::vector<uint8_t> & value)360 void LocatorBleCallbackWapper::OnNotifyMsgReportFromLpDevice(const Bluetooth::UUID &btUuid, int msgType,
361     const std::vector<uint8_t> &value) {}
362 #endif
363 
364 #ifdef WIFI_ENABLE
IsWifiCallbackRegistered()365 bool LocatorRequiredDataManager::IsWifiCallbackRegistered()
366 {
367     std::unique_lock<std::mutex> lock(wifiRegisteredMutex_);
368     return isWifiCallbackRegistered_;
369 }
370 
SetIsWifiCallbackRegistered(bool isWifiCallbackRegistered)371 void LocatorRequiredDataManager::SetIsWifiCallbackRegistered(bool isWifiCallbackRegistered)
372 {
373     std::unique_lock<std::mutex> lock(wifiRegisteredMutex_);
374     isWifiCallbackRegistered_ = isWifiCallbackRegistered;
375 }
376 
RegisterWifiCallBack()377 __attribute__((no_sanitize("cfi"))) bool LocatorRequiredDataManager::RegisterWifiCallBack()
378 {
379     LBSLOGD(LOCATOR, "%{public}s enter", __func__);
380     wifiScanEventCallback_.OnWifiScanStateChanged = LocatorWifiScanEventCallback::OnWifiScanStateChanged;
381     int32_t ret = RegisterWifiEvent(&wifiScanEventCallback_);
382     if (ret != Wifi::WIFI_OPT_SUCCESS) {
383         LBSLOGE(LOCATOR, "%{public}s WifiScan RegisterCallBack failed!", __func__);
384         SetIsWifiCallbackRegistered(false);
385         return false;
386     }
387     SetIsWifiCallbackRegistered(true);
388     return true;
389 }
390 
UnregisterWifiCallBack()391 __attribute__((no_sanitize("cfi"))) bool LocatorRequiredDataManager::UnregisterWifiCallBack()
392 {
393     LBSLOGD(LOCATOR, "%{public}s enter", __func__);
394     int ret = UnRegisterWifiEvent(&wifiScanEventCallback_);
395     if (ret != Wifi::WIFI_OPT_SUCCESS) {
396         LBSLOGE(LOCATOR, "%{public}s WifiScan RegisterCallBack failed!", __func__);
397         return false;
398     }
399     SetIsWifiCallbackRegistered(false);
400     return true;
401 }
402 
GetWifiScanList(std::vector<Wifi::WifiScanInfo> & wifiScanInfo)403 __attribute__((no_sanitize("cfi"))) void LocatorRequiredDataManager::GetWifiScanList(
404     std::vector<Wifi::WifiScanInfo>& wifiScanInfo)
405 {
406     std::shared_ptr<Wifi::WifiScan> ptrWifiScan = Wifi::WifiScan::GetInstance(WIFI_SCAN_ABILITY_ID);
407     if (ptrWifiScan == nullptr) {
408         LBSLOGE(LOCATOR, "%{public}s WifiScan get instance failed", __func__);
409         return;
410     }
411     int ret = ptrWifiScan->GetScanInfoList(wifiScanInfo);
412     if (ret != Wifi::WIFI_OPT_SUCCESS) {
413         LBSLOGE(LOCATOR, "GetScanInfoList failed");
414         return;
415     }
416 }
417 
GetLocatingRequiredDataByWifi(std::vector<std::shared_ptr<LocatingRequiredData>> & requiredData,const std::vector<Wifi::WifiScanInfo> & wifiScanInfo)418 bool LocatorRequiredDataManager::GetLocatingRequiredDataByWifi(
419     std::vector<std::shared_ptr<LocatingRequiredData>>& requiredData,
420     const std::vector<Wifi::WifiScanInfo>& wifiScanInfo)
421 {
422     auto deltaMis = (CommonUtils::GetSinceBootTime() - GetWifiScanCompleteTimestamp()) / NANOS_PER_MICRO;
423     int validTimes = 0;
424     for (size_t i = 0; i < wifiScanInfo.size(); i++) {
425         std::shared_ptr<LocatingRequiredData> info = std::make_shared<LocatingRequiredData>();
426         std::shared_ptr<WifiScanInfo> wifiData = std::make_shared<WifiScanInfo>();
427         wifiData->SetSsid(wifiScanInfo[i].ssid);
428         wifiData->SetBssid(wifiScanInfo[i].bssid);
429         wifiData->SetRssi(wifiScanInfo[i].rssi);
430         wifiData->SetFrequency(wifiScanInfo[i].frequency);
431         if (IsStill() && GetWifiScanCompleteTimestamp() > GetlastStillTime()) {
432             wifiData->SetTimestamp(wifiScanInfo[i].timestamp + deltaMis);
433         } else {
434             wifiData->SetTimestamp(wifiScanInfo[i].timestamp);
435         }
436         if (((CommonUtils::GetSinceBootTime() / NANOS_PER_MICRO) - wifiData->GetTimestamp()) <=
437             DEFAULT_INVALID_10_SECONDS) {
438             validTimes ++;
439         }
440         info->SetType(LocatingRequiredDataType::WIFI);
441         info->SetWifiScanInfo(wifiData);
442         requiredData.push_back(info);
443     }
444     if (validTimes > 0) {
445         return true;
446     }
447     return false;
448 }
449 
UpdateWifiScanCompleteTimestamp()450 void LocatorRequiredDataManager::UpdateWifiScanCompleteTimestamp()
451 {
452     std::unique_lock<std::mutex> lock(wifiScanCompleteTimestampMutex_);
453     wifiScanCompleteTimestamp_ = CommonUtils::GetSinceBootTime();
454 }
455 
GetWifiScanCompleteTimestamp()456 int64_t LocatorRequiredDataManager::GetWifiScanCompleteTimestamp()
457 {
458     std::unique_lock<std::mutex> lock(wifiScanCompleteTimestampMutex_);
459     return wifiScanCompleteTimestamp_;
460 }
461 
OnWifiScanStateChanged(int state,int size)462 void LocatorWifiScanEventCallback::OnWifiScanStateChanged(int state, int size)
463 {
464     LBSLOGD(LOCATOR, "OnWifiScanStateChanged state=%{public}d", state);
465     auto dataManager = LocatorRequiredDataManager::GetInstance();
466     if (state == 0) {
467         LBSLOGE(LOCATOR, "OnWifiScanStateChanged false");
468         dataManager->SendGetWifiListEvent(0, false);
469     } else {
470         dataManager->UpdateWifiScanCompleteTimestamp();
471         dataManager->SendGetWifiListEvent(0, true);
472     }
473     return;
474 }
475 #endif
476 
ReportData(const std::vector<std::shared_ptr<LocatingRequiredData>> & result)477 void LocatorRequiredDataManager::ReportData(const std::vector<std::shared_ptr<LocatingRequiredData>>& result)
478 {
479     std::unique_lock<std::mutex> lock(mutex_);
480     for (const auto& pair : callbacksMap_) {
481         auto callback = pair.first;
482         sptr<ILocatingRequiredDataCallback> locatingRequiredDataCallback =
483             iface_cast<ILocatingRequiredDataCallback>(callback);
484         if (locatingRequiredDataCallback == nullptr) {
485             LBSLOGW(LOCATOR, "ReportData nullptr callback.");
486             continue;
487         }
488         AppIdentity identity = pair.second;
489         if (CommonUtils::IsAppBelongCurrentAccount(identity)) {
490             locatingRequiredDataCallback->OnLocatingDataChange(result);
491         }
492     }
493 }
494 
ReportBluetoothScanResult(const std::unique_ptr<BluetoothScanResult> & bluetoothScanResult)495 void LocatorRequiredDataManager::ReportBluetoothScanResult(
496     const std::unique_ptr<BluetoothScanResult>& bluetoothScanResult)
497 {
498     std::unique_lock<std::mutex> lock(bluetoothcallbacksMapMutex_);
499     for (const auto& pair : bluetoothcallbacksMap_) {
500         auto callback = pair.first;
501         sptr<IBluetoothScanResultCallback> bluetoothScanResultCallback =
502             iface_cast<IBluetoothScanResultCallback>(callback);
503         if (bluetoothScanResultCallback == nullptr) {
504             LBSLOGW(LOCATOR, "ReportBluetoothScanResult nullptr callback.");
505             continue;
506         }
507         auto deathRecipientPair = pair.second;
508         AppIdentity identity = deathRecipientPair.first;
509         if (CommonUtils::IsAppBelongCurrentAccount(identity) &&
510             PermissionManager::CheckLocationPermission(identity.GetTokenId(), identity.GetFirstTokenId()) &&
511             HookUtils::ExecuteHookWhenReportBluetoothScanResult(identity.GetBundleName(), TYPE_BLE) &&
512             !ProxyFreezeManager::GetInstance()->IsProxyPid(identity.GetPid())) {
513             bluetoothScanResultCallback->OnBluetoothScanResultChange(bluetoothScanResult);
514         }
515     }
516 }
517 
StartWifiScan(int fixNumber,bool flag)518 __attribute__((no_sanitize("cfi"))) void LocatorRequiredDataManager::StartWifiScan(int fixNumber, bool flag)
519 {
520 #ifdef WIFI_ENABLE
521     int64_t currentTime = CommonUtils::GetSinceBootTime();
522     if ((currentTime - GetWifiScanCompleteTimestamp()) / NANOS_PER_MICRO < WLAN_SCAN_RESULTS_VALIDITY_PERIOD) {
523         SendGetWifiListEvent(0, true);
524         return;
525     }
526     if (IsStill() && GetWifiScanCompleteTimestamp() > GetlastStillTime() &&
527         (currentTime - GetWifiScanCompleteTimestamp()) / NANOS_PER_MICRO < DEFAULT_TIMEOUT_30_MIN) {
528         SendGetWifiListEvent(0, true);
529         return;
530     }
531     int ret = TriggerWifiScan();
532     if (ret != Wifi::WIFI_OPT_SUCCESS) {
533         LBSLOGE(LOCATOR, "%{public}s WifiScan failed, ret=%{public}d", __func__, ret);
534         SendGetWifiListEvent(0, false);
535     }
536 #endif
537 }
538 
StartBluetoothScan()539 void LocatorRequiredDataManager::StartBluetoothScan()
540 {
541     if (bleCentralManager_ == nullptr) {
542         LBSLOGE(LOCATOR, "%{public}s, bleCentralManager_ == nullptr", __func__);
543         return;
544     }
545     {
546         std::lock_guard<std::mutex> lock(bluetoothcallbacksMapMutex_);
547         if (bluetoothcallbacksMap_.size() > 1) {
548             return;
549         }
550     }
551     Bluetooth::BleScanSettings settings;
552     settings.SetScanMode(Bluetooth::SCAN_MODE::SCAN_MODE_LOW_POWER);
553     std::vector<Bluetooth::BleScanFilter> filters;
554     Bluetooth::BleScanFilter scanFilter;
555     filters.push_back(scanFilter);
556 
557     bleCentralManager_->StartScan(settings, filters);
558 }
559 
StoptBluetoothScan()560 void LocatorRequiredDataManager::StoptBluetoothScan()
561 {
562     if (bleCentralManager_ == nullptr) {
563         LBSLOGE(LOCATOR, "%{public}s, bleCentralManager_ == nullptr", __func__);
564         return;
565     }
566     {
567         std::lock_guard<std::mutex> lock(bluetoothcallbacksMapMutex_);
568         if (bluetoothcallbacksMap_.size() != 0) {
569             return;
570         }
571     }
572     bleCentralManager_->StopScan();
573 }
574 
575 #ifdef WIFI_ENABLE
TriggerWifiScan()576 int LocatorRequiredDataManager::TriggerWifiScan()
577 {
578     wifiScanStartTimeStamp_ = CommonUtils::GetSinceBootTime() / NANOS_PER_MICRO;
579     auto wifiService = Wifi::WifiScan::GetInstance(WIFI_SCAN_ABILITY_ID);
580     if (wifiService == nullptr) {
581         return Wifi::WIFI_OPT_FAILED;
582     }
583     return wifiService->Scan();
584 }
585 #endif
586 
IsWifiConnecting()587 bool LocatorRequiredDataManager::IsWifiConnecting()
588 {
589     std::unique_lock<std::mutex> lock(mutex_);
590     if (callbacksMap_.size() > 0) {
591         return true;
592     }
593     return false;
594 }
595 
IsBluetoothConnecting()596 bool LocatorRequiredDataManager::IsBluetoothConnecting()
597 {
598     std::unique_lock<std::mutex> lock(bluetoothcallbacksMapMutex_);
599     if (bluetoothcallbacksMap_.size() > 0) {
600         return true;
601     }
602     return false;
603 }
604 
GetCurrentWifiBssidForLocating(std::string & bssid)605 LocationErrCode LocatorRequiredDataManager::GetCurrentWifiBssidForLocating(std::string& bssid)
606 {
607 #ifdef WIFI_ENABLE
608     auto wifiDeviceSharedPtr = Wifi::WifiDevice::GetInstance(WIFI_DEVICE_ABILITY_ID);
609     Wifi::WifiDevice* wifiDevicePtr = wifiDeviceSharedPtr.get();
610     if (wifiDevicePtr == nullptr) {
611         LBSLOGE(LOCATOR, "Enter WifiEnhanceNewUtils:: wifiDevicePtr is null");
612         return ERRCODE_SERVICE_UNAVAILABLE;
613     }
614     OHOS::Wifi::WifiLinkedInfo linkedInfo;
615     ErrCode ret = wifiDevicePtr->GetLinkedInfo(linkedInfo);
616     if (ret == Wifi::WIFI_OPT_STA_NOT_OPENED) {
617         LBSLOGE(LOCATOR, "Enter WifiEnhanceNewUtils::GetLinkedInfo fail: %{public}d", ret);
618         return ERRCODE_WIFI_IS_NOT_CONNECTED;
619     }
620     if (ret != Wifi::WIFI_OPT_SUCCESS) {
621         LBSLOGE(LOCATOR, "Enter WifiEnhanceNewUtils::GetLinkedInfo fail: %{public}d", ret);
622         return ERRCODE_SERVICE_UNAVAILABLE;
623     }
624     if (linkedInfo.bssid.size() == 0) {
625         LBSLOGE(LOCATOR, "linkedInfo.bssid.size() is 0");
626         return ERRCODE_WIFI_IS_NOT_CONNECTED;
627     }
628     bssid = linkedInfo.bssid;
629     return ERRCODE_SUCCESS;
630 #else
631     return LOCATION_ERRCODE_NOT_SUPPORTED;
632 #endif
633 }
634 
ScanHandler(const std::shared_ptr<AppExecFwk::EventRunner> & runner)635 ScanHandler::ScanHandler(const std::shared_ptr<AppExecFwk::EventRunner>& runner) : EventHandler(runner)
636 {
637     InitScanHandlerEventMap();
638 }
639 
~ScanHandler()640 ScanHandler::~ScanHandler() {}
641 
InitScanHandlerEventMap()642 void ScanHandler::InitScanHandlerEventMap()
643 {
644     if (scanHandlerEventMap_.size() != 0) {
645         return;
646     }
647     scanHandlerEventMap_[EVENT_START_SCAN] =
648         [this](const AppExecFwk::InnerEvent::Pointer& event) { StartScanEvent(event); };
649     scanHandlerEventMap_[EVENT_START_BLUETOOTH_SCAN] =
650         [this](const AppExecFwk::InnerEvent::Pointer& event) { StartBluetoothScanEvent(event); };
651     scanHandlerEventMap_[EVENT_STOP_BLUETOOTH_SCAN] =
652         [this](const AppExecFwk::InnerEvent::Pointer& event) { StopBluetoothScanEvent(event); };
653 }
654 
StartBluetoothScanEvent(const AppExecFwk::InnerEvent::Pointer & event)655 void ScanHandler::StartBluetoothScanEvent(const AppExecFwk::InnerEvent::Pointer& event)
656 {
657     auto dataManager = LocatorRequiredDataManager::GetInstance();
658     dataManager->StartBluetoothScan();
659 }
660 
StopBluetoothScanEvent(const AppExecFwk::InnerEvent::Pointer & event)661 void ScanHandler::StopBluetoothScanEvent(const AppExecFwk::InnerEvent::Pointer& event)
662 {
663     auto dataManager = LocatorRequiredDataManager::GetInstance();
664     dataManager->StoptBluetoothScan();
665 }
666 
StartScanEvent(const AppExecFwk::InnerEvent::Pointer & event)667 void ScanHandler::StartScanEvent(const AppExecFwk::InnerEvent::Pointer& event)
668 {
669     auto dataManager = LocatorRequiredDataManager::GetInstance();
670     int fixNumber = event->GetParam();
671     dataManager->StartWifiScan(fixNumber, true);
672 }
673 
ProcessEvent(const AppExecFwk::InnerEvent::Pointer & event)674 void ScanHandler::ProcessEvent(const AppExecFwk::InnerEvent::Pointer& event)
675 {
676     uint32_t eventId = event->GetInnerEventId();
677     LBSLOGD(LOCATOR, "ScanHandler processEvent event:%{public}d, timestamp = %{public}s",
678         eventId, std::to_string(CommonUtils::GetCurrentTimeStamp()).c_str());
679     auto handleFunc = scanHandlerEventMap_.find(eventId);
680     if (handleFunc != scanHandlerEventMap_.end() && handleFunc->second != nullptr) {
681         auto memberFunc = handleFunc->second;
682 #ifdef LOCATION_HICOLLIE_ENABLE
683         int tid = gettid();
684         std::string moduleName = "ScanHandler";
685         XCollieCallback callbackFunc = [moduleName, eventId, tid](void *) {
686             LBSLOGE(LOCATOR, "TimeoutCallback tid:%{public}d moduleName:%{public}s excute eventId:%{public}u timeout.",
687                 tid, moduleName.c_str(), eventId);
688         };
689         std::string dfxInfo = moduleName + "_" + std::to_string(eventId) + "_" + std::to_string(tid);
690         int timerId = HiviewDFX::XCollie::GetInstance().SetTimer(dfxInfo, TIMEOUT_WATCHDOG, callbackFunc, nullptr,
691             HiviewDFX::XCOLLIE_FLAG_LOG|HiviewDFX::XCOLLIE_FLAG_RECOVERY);
692         memberFunc(event);
693         HiviewDFX::XCollie::GetInstance().CancelTimer(timerId);
694 #else
695         memberFunc(event);
696 #endif
697     }
698 }
699 
WifiSdkHandler(const std::shared_ptr<AppExecFwk::EventRunner> & runner)700 WifiSdkHandler::WifiSdkHandler(const std::shared_ptr<AppExecFwk::EventRunner>& runner) : EventHandler(runner)
701 {
702     InitWifiSdkHandlerEventMap();
703 }
704 
~WifiSdkHandler()705 WifiSdkHandler::~WifiSdkHandler() {}
706 
InitWifiSdkHandlerEventMap()707 void WifiSdkHandler::InitWifiSdkHandlerEventMap()
708 {
709     if (wifiSdkHandlerEventMap_.size() != 0) {
710         return;
711     }
712     wifiSdkHandlerEventMap_[EVENT_GET_WIFI_LIST] =
713         [this](const AppExecFwk::InnerEvent::Pointer& event) { GetWifiListEvent(event); };
714     wifiSdkHandlerEventMap_[EVENT_REGISTER_WIFI_CALLBACK] =
715         [this](const AppExecFwk::InnerEvent::Pointer& event) { RegisterWifiCallbackEvent(event); };
716     wifiSdkHandlerEventMap_[EVENT_UNREGISTER_WIFI_CALLBACK] =
717         [this](const AppExecFwk::InnerEvent::Pointer& event) { UnregisterWifiCallbackEvent(event); };
718 }
719 
GetWifiListEvent(const AppExecFwk::InnerEvent::Pointer & event)720 void WifiSdkHandler::GetWifiListEvent(const AppExecFwk::InnerEvent::Pointer& event)
721 {
722     bool needRetryScan = event->GetParam();
723     auto dataManager = LocatorRequiredDataManager::GetInstance();
724     if (!dataManager->IsWifiConnecting()) {
725         LBSLOGE(LOCATOR, "%{public}s no valid callback, return. time = %{public}s",
726             __func__, std::to_string(CommonUtils::GetCurrentTimeMilSec()).c_str());
727         return;
728     }
729     std::vector<Wifi::WifiScanInfo> wifiScanInfo;
730     dataManager->GetWifiScanList(wifiScanInfo);
731     std::vector<std::shared_ptr<LocatingRequiredData>> requiredData;
732     bool requiredDataValid = dataManager->GetLocatingRequiredDataByWifi(requiredData, wifiScanInfo);
733     HookUtils::ExecuteHookWhenWifiScanStateChanged(requiredData);
734     if (needRetryScan && !requiredDataValid &&
735         CommonUtils::GetSinceBootTime() / NANOS_PER_MICRO - dataManager->wifiScanStartTimeStamp_ >
736         DEFAULT_NOT_RETRY_TIME_10_SECONDS) {
737         LBSLOGI(LOCATOR, "%{public}s retry scan", __func__);
738         int ret = dataManager->TriggerWifiScan();
739         if (ret != Wifi::WIFI_OPT_SUCCESS) {
740             LBSLOGE(LOCATOR, "%{public}s retry WifiScan failed, ret=%{public}d", __func__, ret);
741             dataManager->ReportData(requiredData);
742             dataManager->RemoveGetWifiListEvent();
743         }
744     } else {
745         dataManager->ReportData(requiredData);
746         dataManager->RemoveGetWifiListEvent();
747     }
748 }
749 
RegisterWifiCallbackEvent(const AppExecFwk::InnerEvent::Pointer & event)750 void WifiSdkHandler::RegisterWifiCallbackEvent(const AppExecFwk::InnerEvent::Pointer& event)
751 {
752     auto dataManager = LocatorRequiredDataManager::GetInstance();
753     dataManager->RegisterWifiCallBack();
754 }
755 
UnregisterWifiCallbackEvent(const AppExecFwk::InnerEvent::Pointer & event)756 void WifiSdkHandler::UnregisterWifiCallbackEvent(const AppExecFwk::InnerEvent::Pointer& event)
757 {
758     auto dataManager = LocatorRequiredDataManager::GetInstance();
759     dataManager->UnregisterWifiCallBack();
760 }
761 
ProcessEvent(const AppExecFwk::InnerEvent::Pointer & event)762 void WifiSdkHandler::ProcessEvent(const AppExecFwk::InnerEvent::Pointer& event)
763 {
764     uint32_t eventId = event->GetInnerEventId();
765     LBSLOGD(LOCATOR, "WifiSdkHandler processEvent event:%{public}d, timestamp = %{public}s",
766         eventId, std::to_string(CommonUtils::GetCurrentTimeStamp()).c_str());
767     auto handleFunc = wifiSdkHandlerEventMap_.find(eventId);
768     if (handleFunc != wifiSdkHandlerEventMap_.end() && handleFunc->second != nullptr) {
769         auto memberFunc = handleFunc->second;
770 #ifdef LOCATION_HICOLLIE_ENABLE
771         int tid = gettid();
772         std::string moduleName = "WifiSdkHandler";
773         XCollieCallback callbackFunc = [moduleName, eventId, tid](void *) {
774             LBSLOGE(LOCATOR, "TimeoutCallback tid:%{public}d moduleName:%{public}s excute eventId:%{public}u timeout.",
775                 tid, moduleName.c_str(), eventId);
776         };
777         std::string dfxInfo = moduleName + "_" + std::to_string(eventId) + "_" + std::to_string(tid);
778         int timerId = HiviewDFX::XCollie::GetInstance().SetTimer(dfxInfo, TIMEOUT_WATCHDOG, callbackFunc, nullptr,
779             HiviewDFX::XCOLLIE_FLAG_LOG|HiviewDFX::XCOLLIE_FLAG_RECOVERY);
780         memberFunc(event);
781         HiviewDFX::XCollie::GetInstance().CancelTimer(timerId);
782 #else
783         memberFunc(event);
784 #endif
785     }
786 }
787 
BluetoothScanCallbackDeathRecipient()788 BluetoothScanCallbackDeathRecipient::BluetoothScanCallbackDeathRecipient()
789 {
790 }
791 
~BluetoothScanCallbackDeathRecipient()792 BluetoothScanCallbackDeathRecipient::~BluetoothScanCallbackDeathRecipient()
793 {
794 }
795 
OnRemoteDied(const wptr<IRemoteObject> & remote)796 void BluetoothScanCallbackDeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &remote)
797 {
798     LBSLOGI(LOCATOR, "bluetooth scan callback OnRemoteDied");
799     LocatorRequiredDataManager::GetInstance()->StopScanBluetoothDevice(remote.promote());
800 }
801 } // namespace Location
802 } // namespace OHOS
803