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