1 /*
2 * Copyright (C) 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 "locator_ability.h"
17
18 #include "accesstoken_kit.h"
19 #include "event_runner.h"
20 #include "privacy_kit.h"
21 #include "system_ability_definition.h"
22 #include "uri.h"
23
24 #include "common_event_manager.h"
25 #include "common_hisysevent.h"
26 #include "location_log_event_ids.h"
27 #include "common_utils.h"
28 #include "constant_definition.h"
29 #ifdef FEATURE_GEOCODE_SUPPORT
30 #include "geo_convert_proxy.h"
31 #endif
32 #ifdef FEATURE_GNSS_SUPPORT
33 #include "gnss_ability_proxy.h"
34 #endif
35 #include "locator_background_proxy.h"
36 #include "location_config_manager.h"
37 #include "location_data_rdb_helper.h"
38 #include "location_log.h"
39 #include "location_sa_load_manager.h"
40 #include "locationhub_ipc_interface_code.h"
41 #include "locator_required_data_manager.h"
42 #ifdef FEATURE_NETWORK_SUPPORT
43 #include "network_ability_proxy.h"
44 #endif
45 #ifdef FEATURE_PASSIVE_SUPPORT
46 #include "passive_ability_proxy.h"
47 #endif
48 #include "permission_status_change_cb.h"
49
50 namespace OHOS {
51 namespace Location {
52 const bool REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(
53 DelayedSingleton<LocatorAbility>::GetInstance().get());
54
55 const uint32_t EVENT_UPDATE_SA = 0x0001;
56 const uint32_t EVENT_INIT_REQUEST_MANAGER = 0x0002;
57 const uint32_t EVENT_APPLY_REQUIREMENTS = 0x0003;
58 const uint32_t EVENT_RETRY_REGISTER_ACTION = 0x0004;
59 const uint32_t EVENT_REPORT_LOCATION_MESSAGE = 0x0005;
60 const uint32_t EVENT_SEND_SWITCHSTATE_TO_HIFENCE = 0x0006;
61 const uint32_t EVENT_START_LOCATING = 0x0007;
62 const uint32_t EVENT_STOP_LOCATING = 0x0008;
63 const uint32_t EVENT_UNLOAD_SA = 0x0010;
64
65 const uint32_t RETRY_INTERVAL_UNITE = 1000;
66 const uint32_t RETRY_INTERVAL_OF_INIT_REQUEST_MANAGER = 5 * RETRY_INTERVAL_UNITE;
67 const uint32_t RETRY_INTERVAL_OF_UNLOAD_SA = 30 * RETRY_INTERVAL_UNITE;
68 const float_t PRECISION = 0.000001;
69 const int COMMON_SA_ID = 4353;
70 const int COMMON_SWITCH_STATE_ID = 30;
71 const std::u16string COMMON_DESCRIPTION = u"location.IHifenceAbility";
72 const std::string UNLOAD_TASK = "locatior_sa_unload";
73 const std::string WIFI_SCAN_STATE_CHANGE = "wifiScanStateChange";
74 const uint32_t SET_ENABLE = 3;
75
LocatorAbility()76 LocatorAbility::LocatorAbility() : SystemAbility(LOCATION_LOCATOR_SA_ID, true)
77 {
78 switchCallbacks_ = std::make_unique<std::map<pid_t, sptr<ISwitchCallback>>>();
79 requests_ = std::make_shared<std::map<std::string, std::list<std::shared_ptr<Request>>>>();
80 receivers_ = std::make_shared<std::map<sptr<IRemoteObject>, std::list<std::shared_ptr<Request>>>>();
81 proxyMap_ = std::make_shared<std::map<std::string, sptr<IRemoteObject>>>();
82 loadedSaMap_ = std::make_shared<std::map<std::string, sptr<IRemoteObject>>>();
83 permissionMap_ = std::make_shared<std::map<uint32_t, std::shared_ptr<PermissionStatusChangeCb>>>();
84 InitRequestManagerMap();
85 reportManager_ = DelayedSingleton<ReportManager>::GetInstance();
86 LBSLOGI(LOCATOR, "LocatorAbility constructed.");
87 }
88
~LocatorAbility()89 LocatorAbility::~LocatorAbility() {}
90
OnStart()91 void LocatorAbility::OnStart()
92 {
93 if (state_ == ServiceRunningState::STATE_RUNNING) {
94 LBSLOGI(LOCATOR, "LocatorAbility has already started.");
95 return;
96 }
97 if (!Init()) {
98 LBSLOGE(LOCATOR, "failed to init LocatorAbility");
99 OnStop();
100 return;
101 }
102 state_ = ServiceRunningState::STATE_RUNNING;
103 AddSystemAbilityListener(COMMON_EVENT_SERVICE_ID);
104 LBSLOGI(LOCATOR, "LocatorAbility::OnStart start ability success.");
105 }
106
OnStop()107 void LocatorAbility::OnStop()
108 {
109 state_ = ServiceRunningState::STATE_NOT_START;
110 registerToAbility_ = false;
111 LBSLOGI(LOCATOR, "LocatorAbility::OnStop ability stopped.");
112 }
113
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)114 void LocatorAbility::OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId)
115 {
116 if (systemAbilityId != COMMON_EVENT_SERVICE_ID) {
117 LBSLOGE(LOCATOR, "systemAbilityId is not COMMON_EVENT_SERVICE_ID");
118 return;
119 }
120 if (locatorEventSubscriber_ == nullptr) {
121 LBSLOGE(LOCATOR, "OnAddSystemAbility subscribeer is nullptr");
122 return;
123 }
124 OHOS::EventFwk::MatchingSkills matchingSkills;
125 matchingSkills.AddEvent(MODE_CHANGED_EVENT);
126 OHOS::EventFwk::CommonEventSubscribeInfo subscriberInfo(matchingSkills);
127 bool result = OHOS::EventFwk::CommonEventManager::SubscribeCommonEvent(locatorEventSubscriber_);
128 LBSLOGI(LOCATOR, "SubscribeCommonEvent locatorEventSubscriber_ result = %{public}d", result);
129 }
130
OnRemoveSystemAbility(int32_t systemAbilityId,const std::string & deviceId)131 void LocatorAbility::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
132 {
133 if (systemAbilityId != COMMON_EVENT_SERVICE_ID) {
134 LBSLOGE(LOCATOR, "systemAbilityId is not COMMON_EVENT_SERVICE_ID");
135 return;
136 }
137 if (locatorEventSubscriber_ == nullptr) {
138 LBSLOGE(LOCATOR, "OnRemoveSystemAbility subscribeer is nullptr");
139 return;
140 }
141 bool result = OHOS::EventFwk::CommonEventManager::UnSubscribeCommonEvent(locatorEventSubscriber_);
142 LBSLOGI(LOCATOR, "UnSubscribeCommonEvent locatorEventSubscriber_ result = %{public}d", result);
143 }
144
Init()145 bool LocatorAbility::Init()
146 {
147 if (registerToAbility_) {
148 return true;
149 }
150 LBSLOGI(LOCATOR, "LocatorAbility Init.");
151 bool ret = Publish(AsObject());
152 if (!ret) {
153 LBSLOGE(LOCATOR, "Init add system ability failed!");
154 return false;
155 }
156
157 deviceId_ = CommonUtils::InitDeviceId();
158 requestManager_ = DelayedSingleton<RequestManager>::GetInstance();
159 locatorHandler_ = std::make_shared<LocatorHandler>(AppExecFwk::EventRunner::Create(true));
160 InitSaAbility();
161 if (locatorHandler_ != nullptr) {
162 locatorHandler_->SendHighPriorityEvent(EVENT_INIT_REQUEST_MANAGER, 0, RETRY_INTERVAL_OF_INIT_REQUEST_MANAGER);
163 }
164 RegisterAction();
165 registerToAbility_ = true;
166 return registerToAbility_;
167 }
168
InitRequestManagerMap()169 void LocatorAbility::InitRequestManagerMap()
170 {
171 std::unique_lock<std::mutex> lock(requestsMutex_);
172 if (requests_ != nullptr) {
173 #ifdef FEATURE_GNSS_SUPPORT
174 std::list<std::shared_ptr<Request>> gnssList;
175 requests_->insert(make_pair(GNSS_ABILITY, gnssList));
176 #endif
177 #ifdef FEATURE_NETWORK_SUPPORT
178 std::list<std::shared_ptr<Request>> networkList;
179 requests_->insert(make_pair(NETWORK_ABILITY, networkList));
180 #endif
181 #ifdef FEATURE_PASSIVE_SUPPORT
182 std::list<std::shared_ptr<Request>> passiveList;
183 requests_->insert(make_pair(PASSIVE_ABILITY, passiveList));
184 #endif
185 }
186 }
187
GetRequests()188 std::shared_ptr<std::map<std::string, std::list<std::shared_ptr<Request>>>> LocatorAbility::GetRequests()
189 {
190 std::unique_lock<std::mutex> lock(requestsMutex_);
191 return requests_;
192 }
193
GetActiveRequestNum()194 int LocatorAbility::GetActiveRequestNum()
195 {
196 std::unique_lock<std::mutex> lock(requestsMutex_);
197 int num = 0;
198 #ifdef FEATURE_GNSS_SUPPORT
199 auto gpsListIter = requests_->find(GNSS_ABILITY);
200 if (gpsListIter != requests_->end()) {
201 auto list = &(gpsListIter->second);
202 num += static_cast<int>(list->size());
203 }
204 #endif
205 #ifdef FEATURE_NETWORK_SUPPORT
206 auto networkListIter = requests_->find(NETWORK_ABILITY);
207 if (networkListIter != requests_->end()) {
208 auto list = &(networkListIter->second);
209 num += static_cast<int>(list->size());
210 }
211 #endif
212 return num;
213 }
214
GetReceivers()215 std::shared_ptr<std::map<sptr<IRemoteObject>, std::list<std::shared_ptr<Request>>>> LocatorAbility::GetReceivers()
216 {
217 std::unique_lock<std::mutex> lock(receiversMutex_);
218 return receivers_;
219 }
220
GetProxyMap()221 std::shared_ptr<std::map<std::string, sptr<IRemoteObject>>> LocatorAbility::GetProxyMap()
222 {
223 std::unique_lock<std::mutex> lock(proxyMapMutex_);
224 return proxyMap_;
225 }
226
ApplyRequests(int delay)227 void LocatorAbility::ApplyRequests(int delay)
228 {
229 if (locatorHandler_ != nullptr) {
230 locatorHandler_->SendHighPriorityEvent(EVENT_APPLY_REQUIREMENTS, 0, delay * RETRY_INTERVAL_UNITE);
231 }
232 }
233
InitSaAbility()234 void LocatorAbility::InitSaAbility()
235 {
236 LBSLOGI(LOCATOR, "initSaAbility start");
237 if (proxyMap_ == nullptr) {
238 return;
239 }
240 UpdateSaAbilityHandler();
241 }
242
CheckSaValid()243 bool LocatorAbility::CheckSaValid()
244 {
245 std::unique_lock<std::mutex> lock(proxyMapMutex_);
246 #ifdef FEATURE_GNSS_SUPPORT
247 auto objectGnss = proxyMap_->find(GNSS_ABILITY);
248 if (objectGnss == proxyMap_->end()) {
249 LBSLOGI(LOCATOR, "gnss sa is null");
250 return false;
251 }
252 #endif
253 #ifdef FEATURE_NETWORK_SUPPORT
254 auto objectNetwork = proxyMap_->find(NETWORK_ABILITY);
255 if (objectNetwork == proxyMap_->end()) {
256 LBSLOGI(LOCATOR, "network sa is null");
257 return false;
258 }
259 #endif
260 #ifdef FEATURE_PASSIVE_SUPPORT
261 auto objectPassive = proxyMap_->find(PASSIVE_ABILITY);
262 if (objectPassive == proxyMap_->end()) {
263 LBSLOGI(LOCATOR, "passive sa is null");
264 return false;
265 }
266 #endif
267 return true;
268 }
269
UpdateSaAbility()270 LocationErrCode LocatorAbility::UpdateSaAbility()
271 {
272 auto event = AppExecFwk::InnerEvent::Get(EVENT_UPDATE_SA, 0);
273 if (locatorHandler_ != nullptr) {
274 locatorHandler_->SendHighPriorityEvent(event);
275 }
276 return ERRCODE_SUCCESS;
277 }
278
UpdateSaAbilityHandler()279 void LocatorAbility::UpdateSaAbilityHandler()
280 {
281 int state = CommonUtils::QuerySwitchState();
282 LBSLOGI(LOCATOR, "update location subability enable state, switch state=%{public}d, action registered=%{public}d",
283 state, isActionRegistered);
284 bool isEnabled = (state == ENABLED);
285 auto locatorBackgroundProxy = DelayedSingleton<LocatorBackgroundProxy>::GetInstance();
286 if (locatorBackgroundProxy == nullptr) {
287 LBSLOGE(LOCATOR, "UpdateSaAbilityHandler: LocatorBackgroundProxy is nullptr");
288 return;
289 }
290 locatorBackgroundProxy.get()->OnSaStateChange(isEnabled);
291 UpdateLoadedSaMap();
292 std::unique_lock<std::mutex> lock(loadedSaMapMutex_);
293 for (auto iter = loadedSaMap_->begin(); iter != loadedSaMap_->end(); iter++) {
294 sptr<IRemoteObject> remoteObject = iter->second;
295 MessageParcel data;
296 if (iter->first == GNSS_ABILITY) {
297 #ifdef FEATURE_GNSS_SUPPORT
298 data.WriteInterfaceToken(GnssAbilityProxy::GetDescriptor());
299 #endif
300 } else if (iter->first == NETWORK_ABILITY) {
301 #ifdef FEATURE_NETWORK_SUPPORT
302 data.WriteInterfaceToken(NetworkAbilityProxy::GetDescriptor());
303 #endif
304 } else if (iter->first == PASSIVE_ABILITY) {
305 #ifdef FEATURE_PASSIVE_SUPPORT
306 data.WriteInterfaceToken(PassiveAbilityProxy::GetDescriptor());
307 #endif
308 }
309 data.WriteBool(isEnabled);
310
311 MessageParcel reply;
312 MessageOption option;
313 int error = remoteObject->SendRequest(SET_ENABLE, data, reply, option);
314 if (error != ERR_OK) {
315 LBSLOGI(LOCATOR, "enable %{public}s ability, remote result %{public}d", (iter->first).c_str(), error);
316 }
317 }
318 SendSwitchState(state);
319 }
320
RemoveUnloadTask(uint32_t code)321 void LocatorAbility::RemoveUnloadTask(uint32_t code)
322 {
323 if (locatorHandler_ == nullptr) {
324 LBSLOGE(LOCATOR, "%{public}s locatorHandler is nullptr", __func__);
325 return;
326 }
327 if (code == static_cast<uint16_t>(LocatorInterfaceCode::PROXY_UID_FOR_FREEZE) ||
328 code == static_cast<uint16_t>(LocatorInterfaceCode::RESET_ALL_PROXY)) {
329 return;
330 }
331 locatorHandler_->RemoveTask(UNLOAD_TASK);
332 }
333
PostUnloadTask(uint32_t code)334 void LocatorAbility::PostUnloadTask(uint32_t code)
335 {
336 if (code == static_cast<uint16_t>(LocatorInterfaceCode::PROXY_UID_FOR_FREEZE) ||
337 code == static_cast<uint16_t>(LocatorInterfaceCode::RESET_ALL_PROXY)) {
338 return;
339 }
340 if (CheckIfLocatorConnecting()) {
341 return;
342 }
343 auto task = [this]() {
344 auto instance = DelayedSingleton<LocationSaLoadManager>::GetInstance();
345 if (instance == nullptr) {
346 LBSLOGE(LOCATOR, "%{public}s instance is nullptr", __func__);
347 return;
348 }
349 instance->UnloadLocationSa(LOCATION_LOCATOR_SA_ID);
350 };
351 if (locatorHandler_ != nullptr) {
352 locatorHandler_->PostTask(task, UNLOAD_TASK, RETRY_INTERVAL_OF_UNLOAD_SA);
353 }
354 }
355
SendSwitchState(const int state)356 void LocatorAbility::SendSwitchState(const int state)
357 {
358 AppExecFwk::InnerEvent::Pointer event = AppExecFwk::InnerEvent::
359 Get(EVENT_SEND_SWITCHSTATE_TO_HIFENCE, state);
360 if (locatorHandler_ != nullptr && locatorHandler_->SendEvent(event)) {
361 LBSLOGD(LOCATOR, "%{public}s: EVENT_SEND_SWITCHSTATE_TO_HIFENCE Send Success", __func__);
362 }
363 }
364
CheckIfLocatorConnecting()365 bool LocatorAbility::CheckIfLocatorConnecting()
366 {
367 return DelayedSingleton<LocatorRequiredDataManager>::GetInstance()->IsConnecting();
368 }
369
EnableAbility(bool isEnabled)370 LocationErrCode LocatorAbility::EnableAbility(bool isEnabled)
371 {
372 LBSLOGI(LOCATOR, "EnableAbility %{public}d", isEnabled);
373 int modeValue = isEnabled ? 1 : 0;
374 if (modeValue == CommonUtils::QuerySwitchState()) {
375 LBSLOGD(LOCATOR, "no need to set location ability, enable:%{public}d", modeValue);
376 return ERRCODE_SUCCESS;
377 }
378 Uri locationDataEnableUri(LOCATION_DATA_URI);
379 LocationErrCode errCode = DelayedSingleton<LocationDataRdbHelper>::GetInstance()->
380 SetValue(locationDataEnableUri, LOCATION_DATA_COLUMN_ENABLE, modeValue);
381 if (errCode != ERRCODE_SUCCESS) {
382 LBSLOGE(LOCATOR, "%{public}s: can not set state to db", __func__);
383 return ERRCODE_SERVICE_UNAVAILABLE;
384 }
385 UpdateSaAbility();
386 std::string state = isEnabled ? "enable" : "disable";
387 WriteLocationSwitchStateEvent(state);
388 return ERRCODE_SUCCESS;
389 }
390
GetSwitchState(int & state)391 LocationErrCode LocatorAbility::GetSwitchState(int& state)
392 {
393 state = CommonUtils::QuerySwitchState();
394 return ERRCODE_SUCCESS;
395 }
396
IsLocationPrivacyConfirmed(const int type,bool & isConfirmed)397 LocationErrCode LocatorAbility::IsLocationPrivacyConfirmed(const int type, bool& isConfirmed)
398 {
399 return LocationConfigManager::GetInstance().GetPrivacyTypeState(type, isConfirmed);
400 }
401
SetLocationPrivacyConfirmStatus(const int type,bool isConfirmed)402 LocationErrCode LocatorAbility::SetLocationPrivacyConfirmStatus(const int type, bool isConfirmed)
403 {
404 return LocationConfigManager::GetInstance().SetPrivacyTypeState(type, isConfirmed);
405 }
406
RegisterSwitchCallback(const sptr<IRemoteObject> & callback,pid_t uid)407 LocationErrCode LocatorAbility::RegisterSwitchCallback(const sptr<IRemoteObject>& callback, pid_t uid)
408 {
409 if (callback == nullptr) {
410 LBSLOGE(LOCATOR, "register an invalid switch callback");
411 return ERRCODE_INVALID_PARAM;
412 }
413 sptr<IRemoteObject::DeathRecipient> death(new (std::nothrow) SwitchCallbackDeathRecipient());
414 callback->AddDeathRecipient(death);
415 sptr<ISwitchCallback> switchCallback = iface_cast<ISwitchCallback>(callback);
416 if (switchCallback == nullptr) {
417 LBSLOGE(LOCATOR, "cast switch callback fail!");
418 return ERRCODE_INVALID_PARAM;
419 }
420 std::unique_lock<std::mutex> lock(switchMutex_);
421 switchCallbacks_->erase(uid);
422 switchCallbacks_->insert(std::make_pair(uid, switchCallback));
423 LBSLOGD(LOCATOR, "after uid:%{public}d register, switch callback size:%{public}s",
424 uid, std::to_string(switchCallbacks_->size()).c_str());
425 return ERRCODE_SUCCESS;
426 }
427
UnregisterSwitchCallback(const sptr<IRemoteObject> & callback)428 LocationErrCode LocatorAbility::UnregisterSwitchCallback(const sptr<IRemoteObject>& callback)
429 {
430 if (callback == nullptr) {
431 LBSLOGE(LOCATOR, "unregister an invalid switch callback");
432 return ERRCODE_INVALID_PARAM;
433 }
434 sptr<ISwitchCallback> switchCallback = iface_cast<ISwitchCallback>(callback);
435 if (switchCallback == nullptr) {
436 LBSLOGE(LOCATOR, "cast switch callback fail!");
437 return ERRCODE_INVALID_PARAM;
438 }
439
440 std::unique_lock<std::mutex> lock(switchMutex_);
441 pid_t uid = -1;
442 for (auto iter = switchCallbacks_->begin(); iter != switchCallbacks_->end(); iter++) {
443 sptr<IRemoteObject> remoteObject = (iter->second)->AsObject();
444 if (remoteObject == callback) {
445 uid = iter->first;
446 break;
447 }
448 }
449 switchCallbacks_->erase(uid);
450 LBSLOGD(LOCATOR, "after uid:%{public}d unregister, switch callback size:%{public}s",
451 uid, std::to_string(switchCallbacks_->size()).c_str());
452 return ERRCODE_SUCCESS;
453 }
454
455 #ifdef FEATURE_GNSS_SUPPORT
SendGnssRequest(int type,MessageParcel & data,MessageParcel & reply)456 LocationErrCode LocatorAbility::SendGnssRequest(int type, MessageParcel &data, MessageParcel &reply)
457 {
458 if (!CommonUtils::InitLocationSa(LOCATION_GNSS_SA_ID)) {
459 return ERRCODE_SERVICE_UNAVAILABLE;
460 }
461 sptr<IRemoteObject> objectGnss =
462 CommonUtils::GetRemoteObject(LOCATION_GNSS_SA_ID, CommonUtils::InitDeviceId());
463 if (objectGnss == nullptr) {
464 return ERRCODE_SERVICE_UNAVAILABLE;
465 }
466 MessageOption option;
467 objectGnss->SendRequest(type, data, reply, option);
468 return LocationErrCode(reply.ReadInt32());
469 }
470 #endif
471
472 #ifdef FEATURE_GNSS_SUPPORT
RegisterGnssStatusCallback(const sptr<IRemoteObject> & callback,pid_t uid)473 LocationErrCode LocatorAbility::RegisterGnssStatusCallback(const sptr<IRemoteObject>& callback, pid_t uid)
474 {
475 LBSLOGD(LOCATOR, "uid is: %{public}d", uid);
476 MessageParcel dataToStub;
477 MessageParcel replyToStub;
478 if (!dataToStub.WriteInterfaceToken(GnssAbilityProxy::GetDescriptor())) {
479 return ERRCODE_SERVICE_UNAVAILABLE;
480 }
481 dataToStub.WriteRemoteObject(callback);
482 return SendGnssRequest(static_cast<int>(GnssInterfaceCode::REG_GNSS_STATUS), dataToStub, replyToStub);
483 }
484 #endif
485
486 #ifdef FEATURE_GNSS_SUPPORT
UnregisterGnssStatusCallback(const sptr<IRemoteObject> & callback)487 LocationErrCode LocatorAbility::UnregisterGnssStatusCallback(const sptr<IRemoteObject>& callback)
488 {
489 MessageParcel dataToStub;
490 MessageParcel replyToStub;
491 if (!dataToStub.WriteInterfaceToken(GnssAbilityProxy::GetDescriptor())) {
492 return ERRCODE_SERVICE_UNAVAILABLE;
493 }
494 dataToStub.WriteRemoteObject(callback);
495 return SendGnssRequest(static_cast<int>(GnssInterfaceCode::UNREG_GNSS_STATUS), dataToStub, replyToStub);
496 }
497 #endif
498
499 #ifdef FEATURE_GNSS_SUPPORT
RegisterNmeaMessageCallback(const sptr<IRemoteObject> & callback,pid_t uid)500 LocationErrCode LocatorAbility::RegisterNmeaMessageCallback(const sptr<IRemoteObject>& callback, pid_t uid)
501 {
502 MessageParcel dataToStub;
503 MessageParcel replyToStub;
504 if (!dataToStub.WriteInterfaceToken(GnssAbilityProxy::GetDescriptor())) {
505 return ERRCODE_SERVICE_UNAVAILABLE;
506 }
507 dataToStub.WriteRemoteObject(callback);
508 return SendGnssRequest(static_cast<int>(GnssInterfaceCode::REG_NMEA), dataToStub, replyToStub);
509 }
510 #endif
511
512 #ifdef FEATURE_GNSS_SUPPORT
UnregisterNmeaMessageCallback(const sptr<IRemoteObject> & callback)513 LocationErrCode LocatorAbility::UnregisterNmeaMessageCallback(const sptr<IRemoteObject>& callback)
514 {
515 MessageParcel dataToStub;
516 MessageParcel replyToStub;
517 if (!dataToStub.WriteInterfaceToken(GnssAbilityProxy::GetDescriptor())) {
518 return ERRCODE_SERVICE_UNAVAILABLE;
519 }
520 dataToStub.WriteRemoteObject(callback);
521 return SendGnssRequest(static_cast<int>(GnssInterfaceCode::UNREG_NMEA), dataToStub, replyToStub);
522 }
523 #endif
524
525 #ifdef FEATURE_GNSS_SUPPORT
RegisterCachedLocationCallback(std::unique_ptr<CachedGnssLocationsRequest> & request,sptr<ICachedLocationsCallback> & callback,std::string bundleName)526 LocationErrCode LocatorAbility::RegisterCachedLocationCallback(std::unique_ptr<CachedGnssLocationsRequest>& request,
527 sptr<ICachedLocationsCallback>& callback, std::string bundleName)
528 {
529 MessageParcel dataToStub;
530 MessageParcel replyToStub;
531 if (!dataToStub.WriteInterfaceToken(GnssAbilityProxy::GetDescriptor())) {
532 return ERRCODE_SERVICE_UNAVAILABLE;
533 }
534 dataToStub.WriteInt32(request->reportingPeriodSec);
535 dataToStub.WriteBool(request->wakeUpCacheQueueFull);
536 dataToStub.WriteRemoteObject(callback->AsObject());
537 dataToStub.WriteString16(Str8ToStr16(bundleName));
538 return SendGnssRequest(static_cast<int>(GnssInterfaceCode::REG_CACHED), dataToStub, replyToStub);
539 }
540 #endif
541
542 #ifdef FEATURE_GNSS_SUPPORT
UnregisterCachedLocationCallback(sptr<ICachedLocationsCallback> & callback)543 LocationErrCode LocatorAbility::UnregisterCachedLocationCallback(sptr<ICachedLocationsCallback>& callback)
544 {
545 MessageParcel dataToStub;
546 MessageParcel replyToStub;
547 if (!dataToStub.WriteInterfaceToken(GnssAbilityProxy::GetDescriptor())) {
548 return ERRCODE_SERVICE_UNAVAILABLE;
549 }
550 dataToStub.WriteRemoteObject(callback->AsObject());
551 return SendGnssRequest(static_cast<int>(GnssInterfaceCode::UNREG_CACHED), dataToStub, replyToStub);
552 }
553 #endif
554
555 #ifdef FEATURE_GNSS_SUPPORT
GetCachedGnssLocationsSize(int & size)556 LocationErrCode LocatorAbility::GetCachedGnssLocationsSize(int& size)
557 {
558 MessageParcel dataToStub;
559 MessageParcel replyToStub;
560 if (!dataToStub.WriteInterfaceToken(GnssAbilityProxy::GetDescriptor())) {
561 return ERRCODE_SERVICE_UNAVAILABLE;
562 }
563 LocationErrCode errorCode =
564 SendGnssRequest(static_cast<int>(GnssInterfaceCode::GET_CACHED_SIZE), dataToStub, replyToStub);
565 if (errorCode == ERRCODE_SUCCESS) {
566 size = replyToStub.ReadInt32();
567 }
568 return errorCode;
569 }
570 #endif
571
572 #ifdef FEATURE_GNSS_SUPPORT
FlushCachedGnssLocations()573 LocationErrCode LocatorAbility::FlushCachedGnssLocations()
574 {
575 MessageParcel dataToStub;
576 MessageParcel replyToStub;
577 if (!dataToStub.WriteInterfaceToken(GnssAbilityProxy::GetDescriptor())) {
578 return ERRCODE_SERVICE_UNAVAILABLE;
579 }
580 return SendGnssRequest(static_cast<int>(GnssInterfaceCode::FLUSH_CACHED), dataToStub, replyToStub);
581 }
582 #endif
583
584 #ifdef FEATURE_GNSS_SUPPORT
SendCommand(std::unique_ptr<LocationCommand> & commands)585 LocationErrCode LocatorAbility::SendCommand(std::unique_ptr<LocationCommand>& commands)
586 {
587 MessageParcel dataToStub;
588 MessageParcel replyToStub;
589 if (!dataToStub.WriteInterfaceToken(GnssAbilityProxy::GetDescriptor())) {
590 return ERRCODE_SERVICE_UNAVAILABLE;
591 }
592 dataToStub.WriteInt32(commands->scenario);
593 dataToStub.WriteString16(Str8ToStr16(commands->command));
594 return SendGnssRequest(static_cast<int>(GnssInterfaceCode::SEND_COMMANDS), dataToStub, replyToStub);
595 }
596 #endif
597
598 #ifdef FEATURE_GNSS_SUPPORT
AddFence(std::unique_ptr<GeofenceRequest> & request)599 LocationErrCode LocatorAbility::AddFence(std::unique_ptr<GeofenceRequest>& request)
600 {
601 MessageParcel dataToStub;
602 MessageParcel replyToStub;
603 if (!dataToStub.WriteInterfaceToken(GnssAbilityProxy::GetDescriptor())) {
604 return ERRCODE_SERVICE_UNAVAILABLE;
605 }
606 dataToStub.WriteInt32(request->scenario);
607 dataToStub.WriteDouble(request->geofence.latitude);
608 dataToStub.WriteDouble(request->geofence.longitude);
609 dataToStub.WriteDouble(request->geofence.radius);
610 dataToStub.WriteDouble(request->geofence.expiration);
611 return SendGnssRequest(static_cast<int>(GnssInterfaceCode::ADD_FENCE_INFO), dataToStub, replyToStub);
612 }
613 #endif
614
615 #ifdef FEATURE_GNSS_SUPPORT
RemoveFence(std::unique_ptr<GeofenceRequest> & request)616 LocationErrCode LocatorAbility::RemoveFence(std::unique_ptr<GeofenceRequest>& request)
617 {
618 MessageParcel dataToStub;
619 MessageParcel replyToStub;
620 if (!dataToStub.WriteInterfaceToken(GnssAbilityProxy::GetDescriptor())) {
621 return ERRCODE_SERVICE_UNAVAILABLE;
622 }
623 dataToStub.WriteInt32(request->scenario);
624 dataToStub.WriteDouble(request->geofence.latitude);
625 dataToStub.WriteDouble(request->geofence.longitude);
626 dataToStub.WriteDouble(request->geofence.radius);
627 dataToStub.WriteDouble(request->geofence.expiration);
628 return SendGnssRequest(static_cast<int>(GnssInterfaceCode::REMOVE_FENCE_INFO), dataToStub, replyToStub);
629 }
630 #endif
631
632 #ifdef FEATURE_GNSS_SUPPORT
SendLocationMockMsgToGnssSa(const sptr<IRemoteObject> obj,const int timeInterval,const std::vector<std::shared_ptr<Location>> & location,int msgId)633 LocationErrCode LocatorAbility::SendLocationMockMsgToGnssSa(const sptr<IRemoteObject> obj,
634 const int timeInterval, const std::vector<std::shared_ptr<Location>> &location, int msgId)
635 {
636 if (obj == nullptr) {
637 LBSLOGE(LOCATOR, "SendLocationMockMsgToGnssSa obj is nullptr");
638 return ERRCODE_SERVICE_UNAVAILABLE;
639 }
640 std::unique_ptr<GnssAbilityProxy> gnssProxy = std::make_unique<GnssAbilityProxy>(obj);
641 LocationErrCode errorCode = ERRCODE_NOT_SUPPORTED;
642 if (msgId == static_cast<int>(LocatorInterfaceCode::ENABLE_LOCATION_MOCK)) {
643 errorCode = gnssProxy->EnableMock();
644 } else if (msgId == static_cast<int>(LocatorInterfaceCode::DISABLE_LOCATION_MOCK)) {
645 errorCode = gnssProxy->DisableMock();
646 } else if (msgId == static_cast<int>(LocatorInterfaceCode::SET_MOCKED_LOCATIONS)) {
647 errorCode = gnssProxy->SetMocked(timeInterval, location);
648 }
649 return errorCode;
650 }
651 #endif
652
653 #ifdef FEATURE_NETWORK_SUPPORT
SendLocationMockMsgToNetworkSa(const sptr<IRemoteObject> obj,const int timeInterval,const std::vector<std::shared_ptr<Location>> & location,int msgId)654 LocationErrCode LocatorAbility::SendLocationMockMsgToNetworkSa(const sptr<IRemoteObject> obj,
655 const int timeInterval, const std::vector<std::shared_ptr<Location>> &location, int msgId)
656 {
657 if (obj == nullptr) {
658 LBSLOGE(LOCATOR, "SendLocationMockMsgToNetworkSa obj is nullptr");
659 return ERRCODE_SERVICE_UNAVAILABLE;
660 }
661 std::unique_ptr<NetworkAbilityProxy> networkProxy =
662 std::make_unique<NetworkAbilityProxy>(obj);
663 LocationErrCode errorCode = ERRCODE_NOT_SUPPORTED;
664 if (msgId == static_cast<int>(LocatorInterfaceCode::ENABLE_LOCATION_MOCK)) {
665 errorCode = networkProxy->EnableMock();
666 } else if (msgId == static_cast<int>(LocatorInterfaceCode::DISABLE_LOCATION_MOCK)) {
667 errorCode = networkProxy->DisableMock();
668 } else if (msgId == static_cast<int>(LocatorInterfaceCode::SET_MOCKED_LOCATIONS)) {
669 errorCode = networkProxy->SetMocked(timeInterval, location);
670 }
671 return errorCode;
672 }
673 #endif
674
675 #ifdef FEATURE_PASSIVE_SUPPORT
SendLocationMockMsgToPassiveSa(const sptr<IRemoteObject> obj,const int timeInterval,const std::vector<std::shared_ptr<Location>> & location,int msgId)676 LocationErrCode LocatorAbility::SendLocationMockMsgToPassiveSa(const sptr<IRemoteObject> obj,
677 const int timeInterval, const std::vector<std::shared_ptr<Location>> &location, int msgId)
678 {
679 if (obj == nullptr) {
680 LBSLOGE(LOCATOR, "SendLocationMockMsgToNetworkSa obj is nullptr");
681 return ERRCODE_SERVICE_UNAVAILABLE;
682 }
683 std::unique_ptr<PassiveAbilityProxy> passiveProxy =
684 std::make_unique<PassiveAbilityProxy>(obj);
685 LocationErrCode errorCode = ERRCODE_NOT_SUPPORTED;
686 if (msgId == static_cast<int>(LocatorInterfaceCode::ENABLE_LOCATION_MOCK)) {
687 errorCode = passiveProxy->EnableMock();
688 } else if (msgId == static_cast<int>(LocatorInterfaceCode::DISABLE_LOCATION_MOCK)) {
689 errorCode = passiveProxy->DisableMock();
690 } else if (msgId == static_cast<int>(LocatorInterfaceCode::SET_MOCKED_LOCATIONS)) {
691 errorCode = passiveProxy->SetMocked(timeInterval, location);
692 }
693 return errorCode;
694 }
695 #endif
696
ProcessLocationMockMsg(const int timeInterval,const std::vector<std::shared_ptr<Location>> & location,int msgId)697 LocationErrCode LocatorAbility::ProcessLocationMockMsg(
698 const int timeInterval, const std::vector<std::shared_ptr<Location>> &location, int msgId)
699 {
700 #if !defined(FEATURE_GNSS_SUPPORT) && !defined(FEATURE_NETWORK_SUPPORT) && !defined(FEATURE_PASSIVE_SUPPORT)
701 LBSLOGE(LOCATOR, "%{public}s: mock service unavailable", __func__);
702 return ERRCODE_NOT_SUPPORTED;
703 #endif
704 if (!CheckSaValid()) {
705 UpdateProxyMap();
706 }
707
708 std::unique_lock<std::mutex> lock(proxyMapMutex_);
709 for (auto iter = proxyMap_->begin(); iter != proxyMap_->end(); iter++) {
710 auto obj = iter->second;
711 if (iter->first == GNSS_ABILITY) {
712 #ifdef FEATURE_GNSS_SUPPORT
713 SendLocationMockMsgToGnssSa(obj, timeInterval, location, msgId);
714 #endif
715 } else if (iter->first == NETWORK_ABILITY) {
716 #ifdef FEATURE_NETWORK_SUPPORT
717 SendLocationMockMsgToNetworkSa(obj, timeInterval, location, msgId);
718 #endif
719 } else if (iter->first == PASSIVE_ABILITY) {
720 #ifdef FEATURE_PASSIVE_SUPPORT
721 SendLocationMockMsgToPassiveSa(obj, timeInterval, location, msgId);
722 #endif
723 }
724 }
725 return ERRCODE_SUCCESS;
726 }
727
UpdateLoadedSaMap()728 void LocatorAbility::UpdateLoadedSaMap()
729 {
730 std::unique_lock<std::mutex> lock(loadedSaMapMutex_);
731 loadedSaMap_->clear();
732 if (CommonUtils::CheckIfSystemAbilityAvailable(LOCATION_GNSS_SA_ID)) {
733 sptr<IRemoteObject> objectGnss =
734 CommonUtils::GetRemoteObject(LOCATION_GNSS_SA_ID, CommonUtils::InitDeviceId());
735 loadedSaMap_->insert(make_pair(GNSS_ABILITY, objectGnss));
736 }
737 if (CommonUtils::CheckIfSystemAbilityAvailable(LOCATION_NETWORK_LOCATING_SA_ID)) {
738 sptr<IRemoteObject> objectNetwork =
739 CommonUtils::GetRemoteObject(LOCATION_NETWORK_LOCATING_SA_ID, CommonUtils::InitDeviceId());
740 loadedSaMap_->insert(make_pair(NETWORK_ABILITY, objectNetwork));
741 }
742 if (CommonUtils::CheckIfSystemAbilityAvailable(LOCATION_NOPOWER_LOCATING_SA_ID)) {
743 sptr<IRemoteObject> objectPassive =
744 CommonUtils::GetRemoteObject(LOCATION_NOPOWER_LOCATING_SA_ID, CommonUtils::InitDeviceId());
745 loadedSaMap_->insert(make_pair(PASSIVE_ABILITY, objectPassive));
746 }
747 }
748
UpdateProxyMap()749 void LocatorAbility::UpdateProxyMap()
750 {
751 std::unique_lock<std::mutex> lock(proxyMapMutex_);
752 #ifdef FEATURE_GNSS_SUPPORT
753 // init gnss ability sa
754 if (!CommonUtils::InitLocationSa(LOCATION_GNSS_SA_ID)) {
755 return;
756 }
757 sptr<IRemoteObject> objectGnss = CommonUtils::GetRemoteObject(LOCATION_GNSS_SA_ID, CommonUtils::InitDeviceId());
758 if (objectGnss != nullptr) {
759 proxyMap_->insert(make_pair(GNSS_ABILITY, objectGnss));
760 } else {
761 LBSLOGE(LOCATOR, "GetRemoteObject gnss sa is null");
762 }
763 #endif
764 #ifdef FEATURE_NETWORK_SUPPORT
765 // init network ability sa
766 if (!CommonUtils::InitLocationSa(LOCATION_NETWORK_LOCATING_SA_ID)) {
767 return;
768 }
769 sptr<IRemoteObject> objectNetwork = CommonUtils::GetRemoteObject(LOCATION_NETWORK_LOCATING_SA_ID,
770 CommonUtils::InitDeviceId());
771 if (objectNetwork != nullptr) {
772 proxyMap_->insert(make_pair(NETWORK_ABILITY, objectNetwork));
773 } else {
774 LBSLOGE(LOCATOR, "GetRemoteObject network sa is null");
775 }
776 #endif
777 #ifdef FEATURE_PASSIVE_SUPPORT
778 // init passive ability sa
779 if (!CommonUtils::InitLocationSa(LOCATION_NOPOWER_LOCATING_SA_ID)) {
780 return;
781 }
782 sptr<IRemoteObject> objectPassive = CommonUtils::GetRemoteObject(LOCATION_NOPOWER_LOCATING_SA_ID,
783 CommonUtils::InitDeviceId());
784 if (objectPassive != nullptr) {
785 proxyMap_->insert(make_pair(PASSIVE_ABILITY, objectPassive));
786 } else {
787 LBSLOGE(LOCATOR, "GetRemoteObject passive sa is null");
788 }
789 #endif
790 }
791
EnableLocationMock()792 LocationErrCode LocatorAbility::EnableLocationMock()
793 {
794 int timeInterval = 0;
795 std::vector<std::shared_ptr<Location>> location;
796 return ProcessLocationMockMsg(timeInterval, location,
797 static_cast<int>(LocatorInterfaceCode::ENABLE_LOCATION_MOCK));
798 }
799
DisableLocationMock()800 LocationErrCode LocatorAbility::DisableLocationMock()
801 {
802 int timeInterval = 0;
803 std::vector<std::shared_ptr<Location>> location;
804 return ProcessLocationMockMsg(timeInterval, location,
805 static_cast<int>(LocatorInterfaceCode::DISABLE_LOCATION_MOCK));
806 }
807
SetMockedLocations(const int timeInterval,const std::vector<std::shared_ptr<Location>> & location)808 LocationErrCode LocatorAbility::SetMockedLocations(
809 const int timeInterval, const std::vector<std::shared_ptr<Location>> &location)
810 {
811 return ProcessLocationMockMsg(timeInterval, location,
812 static_cast<int>(LocatorInterfaceCode::SET_MOCKED_LOCATIONS));
813 }
814
InitRequest(std::unique_ptr<RequestConfig> & requestConfig,sptr<ILocatorCallback> & callback,AppIdentity & identity)815 std::shared_ptr<Request> LocatorAbility::InitRequest(std::unique_ptr<RequestConfig>& requestConfig,
816 sptr<ILocatorCallback>& callback, AppIdentity &identity)
817 {
818 // generate request object according to input params
819 std::shared_ptr<Request> request = std::make_shared<Request>();
820 requestConfig->SetTimeStamp(CommonUtils::GetCurrentTime());
821 request->SetUid(identity.GetUid());
822 request->SetPid(identity.GetPid());
823 request->SetTokenId(identity.GetTokenId());
824 request->SetTokenIdEx(identity.GetTokenIdEx());
825 request->SetFirstTokenId(identity.GetFirstTokenId());
826 request->SetPackageName(identity.GetBundleName());
827 request->SetRequestConfig(*requestConfig);
828 request->SetLocatorCallBack(callback);
829 request->SetUuid(std::to_string(CommonUtils::IntRandom(MIN_INT_RANDOM, MAX_INT_RANDOM)));
830 return request;
831 }
832
StartLocating(std::unique_ptr<RequestConfig> & requestConfig,sptr<ILocatorCallback> & callback,AppIdentity & identity)833 LocationErrCode LocatorAbility::StartLocating(std::unique_ptr<RequestConfig>& requestConfig,
834 sptr<ILocatorCallback>& callback, AppIdentity &identity)
835 {
836 #if !defined(FEATURE_GNSS_SUPPORT) && !defined(FEATURE_NETWORK_SUPPORT) && !defined(FEATURE_PASSIVE_SUPPORT)
837 LBSLOGE(LOCATOR, "%{public}s: service unavailable", __func__);
838 return ERRCODE_NOT_SUPPORTED;
839 #endif
840 if (CommonUtils::QuerySwitchState() == DISABLED) {
841 ReportErrorStatus(callback, ERROR_SWITCH_UNOPEN);
842 }
843 // update offset before add request
844 if (reportManager_ == nullptr || requestManager_ == nullptr) {
845 return ERRCODE_SERVICE_UNAVAILABLE;
846 }
847 reportManager_->UpdateRandom();
848 auto request = InitRequest(requestConfig, callback, identity);
849 LBSLOGI(LOCATOR, "start locating");
850 #ifdef EMULATOR_ENABLED
851 // for emulator, report cache location is unnecessary
852 HandleStartLocating(request, callback);
853 #else
854 if (NeedReportCacheLocation(request, callback)) {
855 LBSLOGI(LOCATOR, "report cache location.");
856 } else {
857 HandleStartLocating(request, callback);
858 }
859 #endif
860 return ERRCODE_SUCCESS;
861 }
862
IsCacheVaildScenario(const sptr<RequestConfig> & requestConfig)863 bool LocatorAbility::IsCacheVaildScenario(const sptr<RequestConfig>& requestConfig)
864 {
865 if (requestConfig->GetFixNumber() == 1 &&
866 ((requestConfig->GetScenario() == SCENE_DAILY_LIFE_SERVICE) ||
867 ((requestConfig->GetScenario() == SCENE_UNSET) && (requestConfig->GetPriority() == PRIORITY_FAST_FIRST_FIX)) ||
868 ((requestConfig->GetScenario() == SCENE_UNSET) && (requestConfig->GetPriority() == PRIORITY_LOW_POWER)))) {
869 return true;
870 }
871 return false;
872 }
873
NeedReportCacheLocation(const std::shared_ptr<Request> & request,sptr<ILocatorCallback> & callback)874 bool LocatorAbility::NeedReportCacheLocation(const std::shared_ptr<Request>& request, sptr<ILocatorCallback>& callback)
875 {
876 if (reportManager_ == nullptr || request == nullptr) {
877 return false;
878 }
879 // report cache location in single location request
880 if (IsCacheVaildScenario(request->GetRequestConfig())) {
881 auto cacheLocation = reportManager_->GetCacheLocation(request);
882 if (cacheLocation != nullptr && callback != nullptr) {
883 PrivacyKit::StartUsingPermission(request->GetTokenId(), ACCESS_APPROXIMATELY_LOCATION);
884 callback->OnLocationReport(cacheLocation);
885 // add location permission using record
886 PrivacyKit::AddPermissionUsedRecord(request->GetTokenId(), ACCESS_APPROXIMATELY_LOCATION, 1, 0);
887 PrivacyKit::StopUsingPermission(request->GetTokenId(), ACCESS_APPROXIMATELY_LOCATION);
888 return true;
889 }
890 }
891 return false;
892 }
893
HandleStartLocating(const std::shared_ptr<Request> & request,sptr<ILocatorCallback> & callback)894 void LocatorAbility::HandleStartLocating(const std::shared_ptr<Request>& request, sptr<ILocatorCallback>& callback)
895 {
896 AppExecFwk::InnerEvent::Pointer event = AppExecFwk::InnerEvent::
897 Get(EVENT_START_LOCATING, request);
898 if (locatorHandler_ != nullptr) {
899 locatorHandler_->SendEvent(event);
900 }
901 ReportLocationStatus(callback, SESSION_START);
902 }
903
StopLocating(sptr<ILocatorCallback> & callback)904 LocationErrCode LocatorAbility::StopLocating(sptr<ILocatorCallback>& callback)
905 {
906 #if !defined(FEATURE_GNSS_SUPPORT) && !defined(FEATURE_NETWORK_SUPPORT) && !defined(FEATURE_PASSIVE_SUPPORT)
907 LBSLOGE(LOCATOR, "%{public}s: service unavailable", __func__);
908 return ERRCODE_NOT_SUPPORTED;
909 #endif
910 if (requestManager_ == nullptr) {
911 return ERRCODE_SERVICE_UNAVAILABLE;
912 }
913 std::unique_ptr<LocatorCallbackMessage> callbackMessage = std::make_unique<LocatorCallbackMessage>();
914 callbackMessage->SetCallback(callback);
915 AppExecFwk::InnerEvent::Pointer event = AppExecFwk::InnerEvent::
916 Get(EVENT_STOP_LOCATING, callbackMessage);
917 if (locatorHandler_ != nullptr) {
918 locatorHandler_->SendEvent(event);
919 }
920 ReportLocationStatus(callback, SESSION_STOP);
921 return ERRCODE_SUCCESS;
922 }
923
GetCacheLocation(std::unique_ptr<Location> & loc,AppIdentity & identity)924 LocationErrCode LocatorAbility::GetCacheLocation(std::unique_ptr<Location>& loc, AppIdentity &identity)
925 {
926 PrivacyKit::StartUsingPermission(identity.GetTokenId(), ACCESS_APPROXIMATELY_LOCATION);
927 auto lastLocation = reportManager_->GetLastLocation();
928 loc = reportManager_->GetPermittedLocation(identity.GetUid(), identity.GetTokenId(),
929 identity.GetFirstTokenId(), lastLocation);
930 reportManager_->UpdateLocationByRequest(identity.GetTokenId(), identity.GetTokenIdEx(), loc);
931 if (loc == nullptr) {
932 PrivacyKit::AddPermissionUsedRecord(identity.GetTokenId(), ACCESS_APPROXIMATELY_LOCATION, 0, 1);
933 PrivacyKit::StopUsingPermission(identity.GetTokenId(), ACCESS_APPROXIMATELY_LOCATION);
934 return ERRCODE_LOCATING_FAIL;
935 }
936 if (fabs(loc->GetLatitude() - 0.0) > PRECISION
937 && fabs(loc->GetLongitude() - 0.0) > PRECISION) {
938 // add location permission using record
939 PrivacyKit::AddPermissionUsedRecord(identity.GetTokenId(), ACCESS_APPROXIMATELY_LOCATION, 1, 0);
940 PrivacyKit::StopUsingPermission(identity.GetTokenId(), ACCESS_APPROXIMATELY_LOCATION);
941 return ERRCODE_SUCCESS;
942 }
943 PrivacyKit::AddPermissionUsedRecord(identity.GetTokenId(), ACCESS_APPROXIMATELY_LOCATION, 0, 1);
944 PrivacyKit::StopUsingPermission(identity.GetTokenId(), ACCESS_APPROXIMATELY_LOCATION);
945 return ERRCODE_LOCATING_FAIL;
946 }
947
ReportLocation(const std::unique_ptr<Location> & location,std::string abilityName)948 LocationErrCode LocatorAbility::ReportLocation(const std::unique_ptr<Location>& location, std::string abilityName)
949 {
950 if (requests_ == nullptr) {
951 return ERRCODE_SERVICE_UNAVAILABLE;
952 }
953 int state = DISABLED;
954 LocationErrCode errorCode = GetSwitchState(state);
955 if (errorCode != ERRCODE_SUCCESS) {
956 return errorCode;
957 }
958 if (state == DISABLED) {
959 LBSLOGE(LOCATOR, "%{public}s line:%{public}d location switch is off",
960 __func__, __LINE__);
961 return ERRCODE_SWITCH_OFF;
962 }
963 std::unique_ptr<LocationMessage> locationMessage = std::make_unique<LocationMessage>();
964 locationMessage->SetAbilityName(abilityName);
965 locationMessage->SetLocation(location);
966 AppExecFwk::InnerEvent::Pointer event = AppExecFwk::InnerEvent::
967 Get(EVENT_REPORT_LOCATION_MESSAGE, locationMessage);
968 if (locatorHandler_ != nullptr && locatorHandler_->SendEvent(event)) {
969 return ERRCODE_SUCCESS;
970 }
971 return ERRCODE_SERVICE_UNAVAILABLE;
972 }
973
ReportLocationStatus(sptr<ILocatorCallback> & callback,int result)974 LocationErrCode LocatorAbility::ReportLocationStatus(sptr<ILocatorCallback>& callback, int result)
975 {
976 int state = DISABLED;
977 LocationErrCode errorCode = GetSwitchState(state);
978 if (errorCode != ERRCODE_SUCCESS) {
979 return errorCode;
980 }
981 if (state == DISABLED) {
982 LBSLOGE(LOCATOR, "%{public}s line:%{public}d location switch is off",
983 __func__, __LINE__);
984 return ERRCODE_SWITCH_OFF;
985 }
986 if (reportManager_->ReportRemoteCallback(callback, ILocatorCallback::RECEIVE_LOCATION_STATUS_EVENT, result)) {
987 return ERRCODE_SUCCESS;
988 }
989 return ERRCODE_SERVICE_UNAVAILABLE;
990 }
991
ReportErrorStatus(sptr<ILocatorCallback> & callback,int result)992 LocationErrCode LocatorAbility::ReportErrorStatus(sptr<ILocatorCallback>& callback, int result)
993 {
994 int state = DISABLED;
995 LocationErrCode errorCode = GetSwitchState(state);
996 if (errorCode != ERRCODE_SUCCESS) {
997 return errorCode;
998 }
999 if (state == DISABLED) {
1000 LBSLOGE(LOCATOR, "%{public}s line:%{public}d location switch is off",
1001 __func__, __LINE__);
1002 return ERRCODE_SWITCH_OFF;
1003 }
1004 if (reportManager_->ReportRemoteCallback(callback, ILocatorCallback::RECEIVE_ERROR_INFO_EVENT, result)) {
1005 return ERRCODE_SUCCESS;
1006 }
1007 return ERRCODE_SERVICE_UNAVAILABLE;
1008 }
1009
RegisterAction()1010 void LocatorAbility::RegisterAction()
1011 {
1012 if (isActionRegistered) {
1013 LBSLOGI(LOCATOR, "action has already registered");
1014 return;
1015 }
1016 OHOS::EventFwk::MatchingSkills matchingSkills;
1017 matchingSkills.AddEvent(MODE_CHANGED_EVENT);
1018 OHOS::EventFwk::CommonEventSubscribeInfo subscriberInfo(matchingSkills);
1019 locatorEventSubscriber_ = std::make_shared<LocatorEventSubscriber>(subscriberInfo);
1020
1021 bool result = OHOS::EventFwk::CommonEventManager::SubscribeCommonEvent(locatorEventSubscriber_);
1022 if (!result) {
1023 LBSLOGE(LOCATOR, "Failed to subscriber locator event, result = %{public}d", result);
1024 isActionRegistered = false;
1025 } else {
1026 LBSLOGI(LOCATOR, "success to subscriber locator event, result = %{public}d", result);
1027 isActionRegistered = true;
1028 }
1029 }
1030
1031 #ifdef FEATURE_GEOCODE_SUPPORT
IsGeoConvertAvailable(bool & isAvailable)1032 LocationErrCode LocatorAbility::IsGeoConvertAvailable(bool &isAvailable)
1033 {
1034 MessageParcel dataParcel;
1035 MessageParcel replyParcel;
1036 if (!dataParcel.WriteInterfaceToken(GeoConvertProxy::GetDescriptor())) {
1037 isAvailable = false;
1038 return ERRCODE_SERVICE_UNAVAILABLE;
1039 }
1040 SendGeoRequest(static_cast<int>(LocatorInterfaceCode::GEO_IS_AVAILABLE), dataParcel, replyParcel);
1041 LocationErrCode errorCode = LocationErrCode(replyParcel.ReadInt32());
1042 if (errorCode == ERRCODE_SUCCESS) {
1043 isAvailable = replyParcel.ReadBool();
1044 } else {
1045 isAvailable = false;
1046 }
1047 return errorCode;
1048 }
1049 #endif
1050
1051 #ifdef FEATURE_GEOCODE_SUPPORT
GetAddressByCoordinate(MessageParcel & data,MessageParcel & reply,std::string bundleName)1052 void LocatorAbility::GetAddressByCoordinate(MessageParcel &data, MessageParcel &reply, std::string bundleName)
1053 {
1054 LBSLOGI(LOCATOR, "locator_ability GetAddressByCoordinate");
1055 MessageParcel dataParcel;
1056 if (!dataParcel.WriteInterfaceToken(GeoConvertProxy::GetDescriptor())) {
1057 reply.WriteInt32(ERRCODE_SERVICE_UNAVAILABLE);
1058 return;
1059 }
1060 dataParcel.WriteString16(data.ReadString16()); // locale
1061 dataParcel.WriteDouble(data.ReadDouble()); // latitude
1062 dataParcel.WriteDouble(data.ReadDouble()); // longitude
1063 dataParcel.WriteInt32(data.ReadInt32()); // maxItems
1064 dataParcel.WriteString16(Str8ToStr16(bundleName)); // bundleName
1065 WriteLocationInnerEvent(GEOCODE_REQUEST, {
1066 "code", "2",
1067 "appName", bundleName
1068 });
1069 SendGeoRequest(static_cast<int>(LocatorInterfaceCode::GET_FROM_COORDINATE), dataParcel, reply);
1070 int errorCode = reply.ReadInt32();
1071 if (errorCode != ERRCODE_SUCCESS) {
1072 WriteLocationInnerEvent(GEOCODE_ERROR_EVENT, {
1073 "code", "2",
1074 "appName", bundleName,
1075 "subCode", std::to_string(errorCode)
1076 });
1077 } else {
1078 WriteLocationInnerEvent(GEOCODE_SUCCESS, {
1079 "code", "2",
1080 "appName", bundleName
1081 });
1082 }
1083 reply.RewindRead(0);
1084 }
1085 #endif
1086
1087 #ifdef FEATURE_GEOCODE_SUPPORT
GetAddressByLocationName(MessageParcel & data,MessageParcel & reply,std::string bundleName)1088 void LocatorAbility::GetAddressByLocationName(MessageParcel &data, MessageParcel &reply, std::string bundleName)
1089 {
1090 LBSLOGI(LOCATOR, "locator_ability GetAddressByLocationName");
1091 MessageParcel dataParcel;
1092 if (!dataParcel.WriteInterfaceToken(GeoConvertProxy::GetDescriptor())) {
1093 reply.WriteInt32(ERRCODE_SERVICE_UNAVAILABLE);
1094 return;
1095 }
1096 dataParcel.WriteString16(data.ReadString16()); // locale
1097 dataParcel.WriteString16(data.ReadString16()); // description
1098 dataParcel.WriteInt32(data.ReadInt32()); // maxItems
1099 dataParcel.WriteDouble(data.ReadDouble()); // minLatitude
1100 dataParcel.WriteDouble(data.ReadDouble()); // minLongitude
1101 dataParcel.WriteDouble(data.ReadDouble()); // maxLatitude
1102 dataParcel.WriteDouble(data.ReadDouble()); // maxLongitude
1103 dataParcel.WriteString16(Str8ToStr16(bundleName)); // bundleName
1104 WriteLocationInnerEvent(GEOCODE_REQUEST, {
1105 "code", "1",
1106 "appName", bundleName
1107 });
1108 SendGeoRequest(static_cast<int>(LocatorInterfaceCode::GET_FROM_LOCATION_NAME), dataParcel, reply);
1109 int errorCode = reply.ReadInt32();
1110 if (errorCode != ERRCODE_SUCCESS) {
1111 WriteLocationInnerEvent(GEOCODE_ERROR_EVENT, {
1112 "code", "1",
1113 "appName", bundleName,
1114 "subCode", std::to_string(errorCode)
1115 });
1116 } else {
1117 WriteLocationInnerEvent(GEOCODE_SUCCESS, {
1118 "code", "1",
1119 "appName", bundleName
1120 });
1121 }
1122 reply.RewindRead(0);
1123 }
1124 #endif
1125
1126 #ifdef FEATURE_GEOCODE_SUPPORT
SendGeoRequest(int type,MessageParcel & data,MessageParcel & reply)1127 LocationErrCode LocatorAbility::SendGeoRequest(int type, MessageParcel &data, MessageParcel &reply)
1128 {
1129 if (!CommonUtils::InitLocationSa(LOCATION_GEO_CONVERT_SA_ID)) {
1130 reply.WriteInt32(ERRCODE_SERVICE_UNAVAILABLE);
1131 return ERRCODE_SERVICE_UNAVAILABLE;
1132 }
1133 sptr<IRemoteObject> remoteObject = CommonUtils::GetRemoteObject(LOCATION_GEO_CONVERT_SA_ID,
1134 CommonUtils::InitDeviceId());
1135 if (remoteObject == nullptr) {
1136 reply.WriteInt32(ERRCODE_SERVICE_UNAVAILABLE);
1137 return ERRCODE_SERVICE_UNAVAILABLE;
1138 }
1139 MessageOption option;
1140 remoteObject->SendRequest(type, data, reply, option);
1141 return ERRCODE_SUCCESS;
1142 }
1143 #endif
1144
1145 #ifdef FEATURE_GEOCODE_SUPPORT
EnableReverseGeocodingMock()1146 LocationErrCode LocatorAbility::EnableReverseGeocodingMock()
1147 {
1148 MessageParcel dataParcel;
1149 MessageParcel replyParcel;
1150 if (!dataParcel.WriteInterfaceToken(GeoConvertProxy::GetDescriptor())) {
1151 return ERRCODE_SERVICE_UNAVAILABLE;
1152 }
1153 SendGeoRequest(static_cast<int>(LocatorInterfaceCode::ENABLE_REVERSE_GEOCODE_MOCK), dataParcel, replyParcel);
1154 return LocationErrCode(replyParcel.ReadInt32());
1155 }
1156 #endif
1157
1158 #ifdef FEATURE_GEOCODE_SUPPORT
DisableReverseGeocodingMock()1159 LocationErrCode LocatorAbility::DisableReverseGeocodingMock()
1160 {
1161 MessageParcel dataParcel;
1162 MessageParcel replyParcel;
1163 if (!dataParcel.WriteInterfaceToken(GeoConvertProxy::GetDescriptor())) {
1164 return ERRCODE_SERVICE_UNAVAILABLE;
1165 }
1166 SendGeoRequest(static_cast<int>(LocatorInterfaceCode::DISABLE_REVERSE_GEOCODE_MOCK), dataParcel, replyParcel);
1167 return LocationErrCode(replyParcel.ReadInt32());
1168 }
1169 #endif
1170
1171 #ifdef FEATURE_GEOCODE_SUPPORT
SetReverseGeocodingMockInfo(std::vector<std::shared_ptr<GeocodingMockInfo>> & mockInfo)1172 LocationErrCode LocatorAbility::SetReverseGeocodingMockInfo(std::vector<std::shared_ptr<GeocodingMockInfo>>& mockInfo)
1173 {
1174 MessageParcel dataParcel;
1175 MessageParcel replyParcel;
1176 if (!dataParcel.WriteInterfaceToken(GeoConvertProxy::GetDescriptor())) {
1177 return ERRCODE_SERVICE_UNAVAILABLE;
1178 }
1179 dataParcel.WriteInt32(mockInfo.size());
1180 for (size_t i = 0; i < mockInfo.size(); i++) {
1181 mockInfo[i]->Marshalling(dataParcel);
1182 }
1183 SendGeoRequest(static_cast<int>(LocatorInterfaceCode::SET_REVERSE_GEOCODE_MOCKINFO), dataParcel, replyParcel);
1184 return LocationErrCode(replyParcel.ReadInt32());
1185 }
1186 #endif
1187
ProxyUidForFreeze(int32_t uid,bool isProxy)1188 LocationErrCode LocatorAbility::ProxyUidForFreeze(int32_t uid, bool isProxy)
1189 {
1190 LBSLOGI(LOCATOR, "Start locator proxy, uid: %{public}d, isProxy: %{public}d, timestamp = %{public}s",
1191 uid, isProxy, std::to_string(CommonUtils::GetCurrentTimeStamp()).c_str());
1192 std::unique_lock<std::mutex> lock(proxyUidsMutex_);
1193 if (isProxy) {
1194 proxyUids_.insert(uid);
1195 } else {
1196 proxyUids_.erase(uid);
1197 }
1198 if (GetActiveRequestNum() <= 0) {
1199 LBSLOGD(LOCATOR, "no active request, do not refresh.");
1200 return ERRCODE_SUCCESS;
1201 }
1202 // for proxy uid update, should send message to refresh requests
1203 ApplyRequests(0);
1204 return ERRCODE_SUCCESS;
1205 }
1206
ResetAllProxy()1207 LocationErrCode LocatorAbility::ResetAllProxy()
1208 {
1209 LBSLOGI(LOCATOR, "Start locator ResetAllProxy");
1210 std::unique_lock<std::mutex> lock(proxyUidsMutex_);
1211 proxyUids_.clear();
1212 if (GetActiveRequestNum() <= 0) {
1213 LBSLOGD(LOCATOR, "no active request, do not refresh.");
1214 return ERRCODE_SUCCESS;
1215 }
1216 // for proxy uid update, should send message to refresh requests
1217 ApplyRequests(0);
1218 return ERRCODE_SUCCESS;
1219 }
1220
IsProxyUid(int32_t uid)1221 bool LocatorAbility::IsProxyUid(int32_t uid)
1222 {
1223 std::unique_lock<std::mutex> lock(proxyUidsMutex_);
1224 return proxyUids_.find(uid) != proxyUids_.end();
1225 }
1226
GetProxyUid()1227 std::set<int32_t> LocatorAbility::GetProxyUid()
1228 {
1229 std::unique_lock<std::mutex> lock(proxyUidsMutex_);
1230 return proxyUids_;
1231 }
1232
RegisterPermissionCallback(const uint32_t callingTokenId,const std::vector<std::string> & permissionNameList)1233 void LocatorAbility::RegisterPermissionCallback(const uint32_t callingTokenId,
1234 const std::vector<std::string>& permissionNameList)
1235 {
1236 std::unique_lock<std::mutex> lock(permissionMapMutex_);
1237 if (permissionMap_ == nullptr) {
1238 LBSLOGE(LOCATOR, "permissionMap is null.");
1239 return;
1240 }
1241 PermStateChangeScope scopeInfo;
1242 scopeInfo.permList = permissionNameList;
1243 scopeInfo.tokenIDs = {callingTokenId};
1244 auto callbackPtr = std::make_shared<PermissionStatusChangeCb>(scopeInfo);
1245 permissionMap_->erase(callingTokenId);
1246 permissionMap_->insert(std::make_pair(callingTokenId, callbackPtr));
1247 LBSLOGD(LOCATOR, "after tokenId:%{public}d register, permission callback size:%{public}s",
1248 callingTokenId, std::to_string(permissionMap_->size()).c_str());
1249 int32_t res = AccessTokenKit::RegisterPermStateChangeCallback(callbackPtr);
1250 if (res != SUCCESS) {
1251 LBSLOGE(LOCATOR, "RegisterPermStateChangeCallback failed.");
1252 }
1253 }
1254
UnregisterPermissionCallback(const uint32_t callingTokenId)1255 void LocatorAbility::UnregisterPermissionCallback(const uint32_t callingTokenId)
1256 {
1257 std::unique_lock<std::mutex> lock(permissionMapMutex_);
1258 if (permissionMap_ == nullptr) {
1259 LBSLOGE(LOCATOR, "permissionMap is null.");
1260 return;
1261 }
1262 auto iter = permissionMap_->find(callingTokenId);
1263 if (iter != permissionMap_->end()) {
1264 auto callbackPtr = iter->second;
1265 int32_t res = AccessTokenKit::UnRegisterPermStateChangeCallback(callbackPtr);
1266 if (res != SUCCESS) {
1267 LBSLOGE(LOCATOR, "UnRegisterPermStateChangeCallback failed.");
1268 }
1269 }
1270 permissionMap_->erase(callingTokenId);
1271 LBSLOGD(LOCATOR, "after tokenId:%{public}d unregister, permission callback size:%{public}s",
1272 callingTokenId, std::to_string(permissionMap_->size()).c_str());
1273 }
1274
SetAbilityName(std::string abilityName)1275 void LocationMessage::SetAbilityName(std::string abilityName)
1276 {
1277 abilityName_ = abilityName;
1278 }
1279
GetAbilityName()1280 std::string LocationMessage::GetAbilityName()
1281 {
1282 return abilityName_;
1283 }
1284
SetLocation(const std::unique_ptr<Location> & location)1285 void LocationMessage::SetLocation(const std::unique_ptr<Location>& location)
1286 {
1287 if (location != nullptr) {
1288 location_ = std::make_unique<Location>(*location);
1289 }
1290 }
1291
GetLocation()1292 std::unique_ptr<Location> LocationMessage::GetLocation()
1293 {
1294 if (location_ != nullptr) {
1295 return std::make_unique<Location>(*location_);
1296 } else {
1297 return nullptr;
1298 }
1299 }
1300
SetCallback(const sptr<ILocatorCallback> & callback)1301 void LocatorCallbackMessage::SetCallback(const sptr<ILocatorCallback>& callback)
1302 {
1303 callback_ = callback;
1304 }
1305
GetCallback()1306 sptr<ILocatorCallback> LocatorCallbackMessage::GetCallback()
1307 {
1308 return callback_;
1309 }
1310
LocatorHandler(const std::shared_ptr<AppExecFwk::EventRunner> & runner)1311 LocatorHandler::LocatorHandler(const std::shared_ptr<AppExecFwk::EventRunner>& runner) : EventHandler(runner)
1312 {
1313 InitLocatorHandlerEventMap();
1314 }
1315
~LocatorHandler()1316 LocatorHandler::~LocatorHandler() {}
1317
InitLocatorHandlerEventMap()1318 void LocatorHandler::InitLocatorHandlerEventMap()
1319 {
1320 if (locatorHandlerEventMap_.size() != 0) {
1321 return;
1322 }
1323 locatorHandlerEventMap_[EVENT_UPDATE_SA] = &LocatorHandler::UpdateSaEvent;
1324 locatorHandlerEventMap_[EVENT_INIT_REQUEST_MANAGER] = &LocatorHandler::InitRequestManagerEvent;
1325 locatorHandlerEventMap_[EVENT_APPLY_REQUIREMENTS] = &LocatorHandler::ApplyRequirementsEvent;
1326 locatorHandlerEventMap_[EVENT_RETRY_REGISTER_ACTION] = &LocatorHandler::RetryRegisterActionEvent;
1327 locatorHandlerEventMap_[EVENT_REPORT_LOCATION_MESSAGE] = &LocatorHandler::ReportLocationMessageEvent;
1328 locatorHandlerEventMap_[EVENT_SEND_SWITCHSTATE_TO_HIFENCE] = &LocatorHandler::SendSwitchStateToHifenceEvent;
1329 locatorHandlerEventMap_[EVENT_START_LOCATING] = &LocatorHandler::StartLocatingEvent;
1330 locatorHandlerEventMap_[EVENT_STOP_LOCATING] = &LocatorHandler::StopLocatingEvent;
1331 locatorHandlerEventMap_[EVENT_UNLOAD_SA] = &LocatorHandler::UnloadSaEvent;
1332 }
1333
UpdateSaEvent(const AppExecFwk::InnerEvent::Pointer & event)1334 void LocatorHandler::UpdateSaEvent(const AppExecFwk::InnerEvent::Pointer& event)
1335 {
1336 auto locatorAbility = DelayedSingleton<LocatorAbility>::GetInstance();
1337 if (locatorAbility != nullptr) {
1338 locatorAbility->UpdateSaAbilityHandler();
1339 }
1340 }
1341
InitRequestManagerEvent(const AppExecFwk::InnerEvent::Pointer & event)1342 void LocatorHandler::InitRequestManagerEvent(const AppExecFwk::InnerEvent::Pointer& event)
1343 {
1344 auto requestManager = DelayedSingleton<RequestManager>::GetInstance();
1345 if (requestManager == nullptr || !requestManager->InitSystemListeners()) {
1346 LBSLOGE(LOCATOR, "InitSystemListeners failed");
1347 }
1348 }
1349
ApplyRequirementsEvent(const AppExecFwk::InnerEvent::Pointer & event)1350 void LocatorHandler::ApplyRequirementsEvent(const AppExecFwk::InnerEvent::Pointer& event)
1351 {
1352 auto requestManager = DelayedSingleton<RequestManager>::GetInstance();
1353 if (requestManager != nullptr) {
1354 requestManager->HandleRequest();
1355 }
1356 }
1357
RetryRegisterActionEvent(const AppExecFwk::InnerEvent::Pointer & event)1358 void LocatorHandler::RetryRegisterActionEvent(const AppExecFwk::InnerEvent::Pointer& event)
1359 {
1360 auto locatorAbility = DelayedSingleton<LocatorAbility>::GetInstance();
1361 if (locatorAbility != nullptr) {
1362 locatorAbility->RegisterAction();
1363 }
1364 }
1365
ReportLocationMessageEvent(const AppExecFwk::InnerEvent::Pointer & event)1366 void LocatorHandler::ReportLocationMessageEvent(const AppExecFwk::InnerEvent::Pointer& event)
1367 {
1368 auto reportManager = DelayedSingleton<ReportManager>::GetInstance();
1369 if (reportManager != nullptr) {
1370 std::unique_ptr<LocationMessage> locationMessage = event->GetUniqueObject<LocationMessage>();
1371 if (locationMessage == nullptr) {
1372 return;
1373 }
1374 std::unique_ptr<Location> location = locationMessage->GetLocation();
1375 std::string abilityName = locationMessage->GetAbilityName();
1376 int64_t time = location->GetTimeStamp();
1377 int64_t timeSinceBoot = location->GetTimeSinceBoot();
1378 double acc = location->GetAccuracy();
1379 LBSLOGI(LOCATOR,
1380 "receive location: [%{public}s time=%{public}s timeSinceBoot=%{public}s acc=%{public}f]",
1381 abilityName.c_str(), std::to_string(time).c_str(), std::to_string(timeSinceBoot).c_str(), acc);
1382 reportManager->OnReportLocation(location, abilityName);
1383 }
1384 }
1385
SendSwitchStateToHifenceEvent(const AppExecFwk::InnerEvent::Pointer & event)1386 void LocatorHandler::SendSwitchStateToHifenceEvent(const AppExecFwk::InnerEvent::Pointer& event)
1387 {
1388 auto locatorAbility = DelayedSingleton<LocatorAbility>::GetInstance();
1389 if (locatorAbility != nullptr) {
1390 int state = event->GetParam();
1391 if (!CommonUtils::InitLocationSa(COMMON_SA_ID)) {
1392 return;
1393 }
1394 MessageParcel data;
1395 MessageParcel reply;
1396 MessageOption option;
1397 if (!data.WriteInterfaceToken(COMMON_DESCRIPTION)) {
1398 return;
1399 }
1400 data.WriteInt32(state);
1401 sptr<IRemoteObject> object =
1402 CommonUtils::GetRemoteObject(COMMON_SA_ID, CommonUtils::InitDeviceId());
1403 if (object == nullptr) {
1404 return;
1405 }
1406 object->SendRequest(COMMON_SWITCH_STATE_ID, data, reply, option);
1407 }
1408 }
1409
StartLocatingEvent(const AppExecFwk::InnerEvent::Pointer & event)1410 void LocatorHandler::StartLocatingEvent(const AppExecFwk::InnerEvent::Pointer& event)
1411 {
1412 auto requestManager = DelayedSingleton<RequestManager>::GetInstance();
1413 std::shared_ptr<Request> request = event->GetSharedObject<Request>();
1414 if (request == nullptr) {
1415 return;
1416 }
1417 if (requestManager != nullptr) {
1418 requestManager->HandleStartLocating(request);
1419 }
1420 }
1421
StopLocatingEvent(const AppExecFwk::InnerEvent::Pointer & event)1422 void LocatorHandler::StopLocatingEvent(const AppExecFwk::InnerEvent::Pointer& event)
1423 {
1424 auto requestManager = DelayedSingleton<RequestManager>::GetInstance();
1425 std::unique_ptr<LocatorCallbackMessage> callbackMessage = event->GetUniqueObject<LocatorCallbackMessage>();
1426 if (callbackMessage == nullptr) {
1427 return;
1428 }
1429 if (requestManager != nullptr) {
1430 requestManager->HandleStopLocating(callbackMessage->GetCallback());
1431 }
1432 }
1433
UnloadSaEvent(const AppExecFwk::InnerEvent::Pointer & event)1434 void LocatorHandler::UnloadSaEvent(const AppExecFwk::InnerEvent::Pointer& event)
1435 {
1436 auto locationSaLoadManager = DelayedSingleton<LocationSaLoadManager>::GetInstance();
1437 auto locatorAbility = DelayedSingleton<LocatorAbility>::GetInstance();
1438 if (locationSaLoadManager != nullptr) {
1439 locationSaLoadManager->UnloadLocationSa(LOCATION_LOCATOR_SA_ID);
1440 }
1441 }
1442
ProcessEvent(const AppExecFwk::InnerEvent::Pointer & event)1443 void LocatorHandler::ProcessEvent(const AppExecFwk::InnerEvent::Pointer& event)
1444 {
1445 uint32_t eventId = event->GetInnerEventId();
1446 LBSLOGI(LOCATOR, "ProcessEvent event:%{public}d, timestamp = %{public}s",
1447 eventId, std::to_string(CommonUtils::GetCurrentTimeStamp()).c_str());
1448 auto handleFunc = locatorHandlerEventMap_.find(eventId);
1449 if (handleFunc != locatorHandlerEventMap_.end() && handleFunc->second != nullptr) {
1450 auto memberFunc = handleFunc->second;
1451 (this->*memberFunc)(event);
1452 } else {
1453 LBSLOGE(LOCATOR, "ProcessEvent event:%{public}d, unsupport service.", eventId);
1454 }
1455 }
1456
1457 } // namespace Location
1458 } // namespace OHOS
1459