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 #ifdef FEATURE_GEOCODE_SUPPORT
17 #include "geo_convert_service.h"
18 #include <file_ex.h>
19 #include <thread>
20 #include "ability_connect_callback_interface.h"
21 #include "ability_connect_callback_stub.h"
22 #include "ability_manager_client.h"
23 #include "geo_address.h"
24 #include "common_utils.h"
25 #include "location_config_manager.h"
26 #include "location_dumper.h"
27 #include "location_sa_load_manager.h"
28 #include "system_ability_definition.h"
29
30 namespace OHOS {
31 namespace Location {
32 const bool REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(
33 DelayedSingleton<GeoConvertService>::GetInstance().get());
34 static constexpr int REQUEST_GEOCODE = 1;
35 static constexpr int REQUEST_REVERSE_GEOCODE = 2;
36 constexpr uint32_t WAIT_MS = 100;
37 const int MAX_RETRY_COUNT = 5;
GeoConvertService()38 GeoConvertService::GeoConvertService() : SystemAbility(LOCATION_GEO_CONVERT_SA_ID, true)
39 {
40 LBSLOGI(GEO_CONVERT, "GeoConvertService constructed.");
41 }
42
~GeoConvertService()43 GeoConvertService::~GeoConvertService()
44 {
45 }
46
OnStart()47 void GeoConvertService::OnStart()
48 {
49 if (state_ == ServiceRunningState::STATE_RUNNING) {
50 LBSLOGI(GEO_CONVERT, "GeoConvertService has already started.");
51 return;
52 }
53 if (!Init()) {
54 LBSLOGE(GEO_CONVERT, "failed to init GeoConvertService");
55 OnStop();
56 return;
57 }
58 state_ = ServiceRunningState::STATE_RUNNING;
59 LBSLOGI(GEO_CONVERT, "GeoConvertService::OnStart start service success.");
60 }
61
OnStop()62 void GeoConvertService::OnStop()
63 {
64 state_ = ServiceRunningState::STATE_NOT_START;
65 registerToService_ = false;
66 LBSLOGI(GEO_CONVERT, "GeoConvertService::OnStop service stopped.");
67 }
68
Init()69 bool GeoConvertService::Init()
70 {
71 if (!registerToService_) {
72 bool ret = Publish(AsObject());
73 if (!ret) {
74 LBSLOGE(GEO_CONVERT, "GeoConvertService::Init Publish failed!");
75 return false;
76 }
77 registerToService_ = true;
78 }
79 return true;
80 }
81
82 class AbilityConnection : public AAFwk::AbilityConnectionStub {
83 public:
OnAbilityConnectDone(const AppExecFwk::ElementName & element,const sptr<IRemoteObject> & remoteObject,int resultCode)84 void OnAbilityConnectDone(
85 const AppExecFwk::ElementName& element, const sptr<IRemoteObject>& remoteObject, int resultCode) override
86 {
87 std::string uri = element.GetURI();
88 LBSLOGD(GEO_CONVERT, "Connected uri is %{public}s, result is %{public}d.", uri.c_str(), resultCode);
89 if (resultCode != ERR_OK) {
90 return;
91 }
92 DelayedSingleton<GeoConvertService>::GetInstance().get()->NotifyConnected(remoteObject);
93 }
94
OnAbilityDisconnectDone(const AppExecFwk::ElementName & element,int)95 void OnAbilityDisconnectDone(const AppExecFwk::ElementName& element, int) override
96 {
97 std::string uri = element.GetURI();
98 LBSLOGD(GEO_CONVERT, "Disconnected uri is %{public}s.", uri.c_str());
99 DelayedSingleton<GeoConvertService>::GetInstance().get()->NotifyDisConnected();
100 }
101 };
102
ReConnectService()103 bool GeoConvertService::ReConnectService()
104 {
105 int retryCount = 0;
106 if (IsConnect()) {
107 LBSLOGI(GEO_CONVERT, "Connect success!");
108 return true;
109 }
110 while (retryCount < MAX_RETRY_COUNT) {
111 retryCount++;
112 bool ret = ConnectService();
113 if (ret) {
114 LBSLOGI(GEO_CONVERT, "Connect success!");
115 return true;
116 }
117 std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_MS));
118 }
119 return false;
120 }
121
ConnectService()122 bool GeoConvertService::ConnectService()
123 {
124 LBSLOGD(GEO_CONVERT, "start ConnectService");
125 if (!IsConnect()) {
126 AAFwk::Want connectionWant;
127 std::string serviceName;
128 bool result = LocationConfigManager::GetInstance().GetGeocodeServiceName(serviceName);
129 if (!result || serviceName.empty()) {
130 LBSLOGE(GEO_CONVERT, "get service name failed!");
131 return false;
132 }
133 std::string abilityName;
134 bool res = LocationConfigManager::GetInstance().GetGeocodeAbilityName(abilityName);
135 if (!res || abilityName.empty()) {
136 LBSLOGE(GEO_CONVERT, "get service name failed!");
137 return false;
138 }
139 connectionWant.SetElementName(serviceName, abilityName);
140 sptr<AAFwk::IAbilityConnection> conn = new (std::nothrow) AbilityConnection();
141 if (conn == nullptr) {
142 LBSLOGE(GEO_CONVERT, "get connection failed!");
143 return false;
144 }
145 int32_t ret = AAFwk::AbilityManagerClient::GetInstance()->ConnectAbility(connectionWant, conn, -1);
146 if (ret != ERR_OK) {
147 LBSLOGE(GEO_CONVERT, "Connect cloud service failed!");
148 return false;
149 }
150 std::unique_lock<std::mutex> uniqueLock(mutex_);
151 auto waitStatus = connectCondition_.wait_for(
152 uniqueLock, std::chrono::seconds(CONNECT_TIME_OUT), [this]() { return serviceProxy_ != nullptr; });
153 if (!waitStatus) {
154 LBSLOGE(GEO_CONVERT, "Connect cloudService timeout!");
155 return false;
156 }
157 }
158 RegisterGeoServiceDeathRecipient();
159 return true;
160 }
161
NotifyConnected(const sptr<IRemoteObject> & remoteObject)162 void GeoConvertService::NotifyConnected(const sptr<IRemoteObject>& remoteObject)
163 {
164 std::unique_lock<std::mutex> uniqueLock(mutex_);
165 serviceProxy_ = remoteObject;
166 connectCondition_.notify_all();
167 }
168
NotifyDisConnected()169 void GeoConvertService::NotifyDisConnected()
170 {
171 std::unique_lock<std::mutex> uniqueLock(mutex_);
172 serviceProxy_ = nullptr;
173 connectCondition_.notify_all();
174 }
175
IsGeoConvertAvailable(MessageParcel & reply)176 int GeoConvertService::IsGeoConvertAvailable(MessageParcel &reply)
177 {
178 std::string serviceName;
179 bool result = LocationConfigManager::GetInstance().GetGeocodeServiceName(serviceName);
180 if (!result || serviceName.empty()) {
181 LBSLOGE(GEO_CONVERT, "get service name failed!");
182 reply.WriteInt32(ERRCODE_SUCCESS);
183 reply.WriteBool(false);
184 return ERRCODE_SUCCESS;
185 }
186 reply.WriteInt32(ERRCODE_SUCCESS);
187 if (!CommonUtils::CheckAppInstalled(serviceName)) { // app is not installed
188 reply.WriteBool(false);
189 } else {
190 reply.WriteBool(true);
191 }
192 return ERRCODE_SUCCESS;
193 }
194
GetAddressByCoordinate(MessageParcel & data,MessageParcel & reply)195 int GeoConvertService::GetAddressByCoordinate(MessageParcel &data, MessageParcel &reply)
196 {
197 if (mockEnabled_) {
198 ReportAddressMock(data, reply);
199 return ERRCODE_SUCCESS;
200 }
201 if (!GetService()) {
202 reply.WriteInt32(ERRCODE_REVERSE_GEOCODING_FAIL);
203 return ERRCODE_REVERSE_GEOCODING_FAIL;
204 }
205
206 MessageParcel dataParcel;
207 MessageParcel replyParcel;
208 MessageOption option;
209
210 if (!WriteInfoToParcel(data, dataParcel, true)) {
211 reply.WriteInt32(ERRCODE_REVERSE_GEOCODING_FAIL);
212 return ERRCODE_REVERSE_GEOCODING_FAIL;
213 }
214 sptr<GeoConvertCallbackHost> callback = new (std::nothrow) GeoConvertCallbackHost();
215 if (callback == nullptr) {
216 LBSLOGE(GEO_CONVERT, "can not get valid callback.");
217 reply.WriteInt32(ERRCODE_REVERSE_GEOCODING_FAIL);
218 return ERRCODE_REVERSE_GEOCODING_FAIL;
219 }
220 dataParcel.WriteRemoteObject(callback->AsObject());
221 bool ret = SendGeocodeRequest(REQUEST_REVERSE_GEOCODE, dataParcel, replyParcel, option);
222 if (!ret) {
223 reply.WriteInt32(ERRCODE_REVERSE_GEOCODING_FAIL);
224 return ERRCODE_REVERSE_GEOCODING_FAIL;
225 }
226 std::list<std::shared_ptr<GeoAddress>> result = callback->GetResult();
227 if (!WriteResultToParcel(result, reply, true)) {
228 return ERRCODE_REVERSE_GEOCODING_FAIL;
229 }
230 return ERRCODE_SUCCESS;
231 }
232
ReportAddressMock(MessageParcel & data,MessageParcel & reply)233 void GeoConvertService::ReportAddressMock(MessageParcel &data, MessageParcel &reply)
234 {
235 int arraySize = 0;
236 std::vector<std::shared_ptr<GeoAddress>> array;
237 ReverseGeocodeRequest request;
238 request.latitude = data.ReadDouble();
239 request.longitude = data.ReadDouble();
240 request.maxItems = data.ReadInt32();
241 data.ReadInt32(); // locale size
242 request.locale = Str16ToStr8(data.ReadString16());
243 std::unique_lock<std::mutex> lock(mockInfoMutex_, std::defer_lock);
244 lock.lock();
245 for (size_t i = 0; i < mockInfo_.size(); i++) {
246 std::shared_ptr<GeocodingMockInfo> info = mockInfo_[i];
247 if (!CommonUtils::DoubleEqual(request.latitude, info->GetLocation()->latitude) ||
248 !CommonUtils::DoubleEqual(request.longitude, info->GetLocation()->longitude)) {
249 continue;
250 }
251 arraySize++;
252 array.push_back(info->GetGeoAddressInfo());
253 }
254 lock.unlock();
255 reply.WriteInt32(ERRCODE_SUCCESS);
256 if (arraySize > 0) {
257 reply.WriteInt32(arraySize);
258 for (size_t i = 0; i < array.size(); i++) {
259 array[i]->Marshalling(reply);
260 }
261 } else {
262 reply.WriteInt32(0);
263 }
264 }
265
GetAddressByLocationName(MessageParcel & data,MessageParcel & reply)266 int GeoConvertService::GetAddressByLocationName(MessageParcel &data, MessageParcel &reply)
267 {
268 if (!GetService()) {
269 reply.WriteInt32(ERRCODE_GEOCODING_FAIL);
270 return ERRCODE_GEOCODING_FAIL;
271 }
272
273 MessageParcel dataParcel;
274 MessageParcel replyParcel;
275 MessageOption option;
276
277 if (!WriteInfoToParcel(data, dataParcel, false)) {
278 reply.WriteInt32(ERRCODE_GEOCODING_FAIL);
279 return ERRCODE_GEOCODING_FAIL;
280 }
281 sptr<GeoConvertCallbackHost> callback = new (std::nothrow) GeoConvertCallbackHost();
282 if (callback == nullptr) {
283 LBSLOGE(GEO_CONVERT, "can not get valid callback.");
284 reply.WriteInt32(ERRCODE_GEOCODING_FAIL);
285 return ERRCODE_GEOCODING_FAIL;
286 }
287 dataParcel.WriteRemoteObject(callback->AsObject());
288 bool ret = SendGeocodeRequest(REQUEST_GEOCODE, dataParcel, replyParcel, option);
289 if (!ret) {
290 reply.WriteInt32(ERRCODE_GEOCODING_FAIL);
291 return ERRCODE_GEOCODING_FAIL;
292 }
293 std::list<std::shared_ptr<GeoAddress>> result = callback->GetResult();
294 if (!WriteResultToParcel(result, reply, false)) {
295 return ERRCODE_GEOCODING_FAIL;
296 }
297 return ERRCODE_SUCCESS;
298 }
299
300 /*
301 * get info from data and write to dataParcel.
302 * flag: true for reverse geocoding, false for geocoding.
303 */
WriteInfoToParcel(MessageParcel & data,MessageParcel & dataParcel,bool flag)304 bool GeoConvertService::WriteInfoToParcel(MessageParcel &data, MessageParcel &dataParcel, bool flag)
305 {
306 if (flag) {
307 dataParcel.WriteString16(data.ReadString16()); // locale
308 dataParcel.WriteDouble(data.ReadDouble()); // latitude
309 dataParcel.WriteDouble(data.ReadDouble()); // longitude
310 dataParcel.WriteInt32(data.ReadInt32()); // maxItems
311 } else {
312 dataParcel.WriteString16(data.ReadString16()); // locale
313 dataParcel.WriteString16(data.ReadString16()); // description
314 dataParcel.WriteInt32(data.ReadInt32()); // maxItems
315 dataParcel.WriteDouble(data.ReadDouble()); // minLatitude
316 dataParcel.WriteDouble(data.ReadDouble()); // minLongitude
317 dataParcel.WriteDouble(data.ReadDouble()); // maxLatitude
318 dataParcel.WriteDouble(data.ReadDouble()); // maxLongitude
319 }
320 dataParcel.WriteString16(data.ReadString16()); // bundleName
321 return true;
322 }
323
324 /*
325 * write result info to reply.
326 * flag: true for reverse geocoding, false for geocoding.
327 */
WriteResultToParcel(const std::list<std::shared_ptr<GeoAddress>> result,MessageParcel & reply,bool flag)328 bool GeoConvertService::WriteResultToParcel(const std::list<std::shared_ptr<GeoAddress>> result,
329 MessageParcel &reply, bool flag)
330 {
331 if (result.size() == 0) {
332 LBSLOGE(GEO_CONVERT, "empty result!");
333 reply.WriteInt32(flag ? ERRCODE_REVERSE_GEOCODING_FAIL : ERRCODE_GEOCODING_FAIL);
334 return false;
335 }
336 reply.WriteInt32(ERRCODE_SUCCESS);
337 reply.WriteInt32(result.size());
338 for (auto iter = result.begin(); iter != result.end(); iter++) {
339 std::shared_ptr<GeoAddress> address = *iter;
340 if (address != nullptr) {
341 address->Marshalling(reply);
342 }
343 }
344 return true;
345 }
346
GetService()347 bool GeoConvertService::GetService()
348 {
349 if (!IsConnect()) {
350 std::string serviceName;
351 bool result = LocationConfigManager::GetInstance().GetGeocodeServiceName(serviceName);
352 if (!result || serviceName.empty()) {
353 LBSLOGE(GEO_CONVERT, "get service name failed!");
354 return false;
355 }
356 if (!CommonUtils::CheckAppInstalled(serviceName)) { // app is not installed
357 LBSLOGE(GEO_CONVERT, "service is not available.");
358 return false;
359 } else if (!ReConnectService()) {
360 return false;
361 }
362 }
363 return true;
364 }
365
IsConnect()366 bool GeoConvertService::IsConnect()
367 {
368 std::unique_lock<std::mutex> uniqueLock(mutex_);
369 return serviceProxy_ != nullptr;
370 }
371
EnableReverseGeocodingMock()372 bool GeoConvertService::EnableReverseGeocodingMock()
373 {
374 LBSLOGD(GEO_CONVERT, "EnableReverseGeocodingMock");
375 mockEnabled_ = true;
376 return true;
377 }
378
DisableReverseGeocodingMock()379 bool GeoConvertService::DisableReverseGeocodingMock()
380 {
381 LBSLOGD(GEO_CONVERT, "DisableReverseGeocodingMock");
382 mockEnabled_ = false;
383 return true;
384 }
385
SetReverseGeocodingMockInfo(std::vector<std::shared_ptr<GeocodingMockInfo>> & mockInfo)386 LocationErrCode GeoConvertService::SetReverseGeocodingMockInfo(
387 std::vector<std::shared_ptr<GeocodingMockInfo>>& mockInfo)
388 {
389 LBSLOGD(GEO_CONVERT, "SetReverseGeocodingMockInfo");
390 std::unique_lock<std::mutex> lock(mockInfoMutex_, std::defer_lock);
391 lock.lock();
392 mockInfo_.assign(mockInfo.begin(), mockInfo.end());
393 lock.unlock();
394 return ERRCODE_SUCCESS;
395 }
396
UnloadGeoConvertSystemAbility()397 void GeoConvertService::UnloadGeoConvertSystemAbility()
398 {
399 auto locationSaLoadManager = DelayedSingleton<LocationSaLoadManager>::GetInstance();
400 if (!CheckIfGeoConvertConnecting() && locationSaLoadManager != nullptr) {
401 locationSaLoadManager->UnloadLocationSa(LOCATION_GEO_CONVERT_SA_ID);
402 }
403 }
404
CheckIfGeoConvertConnecting()405 bool GeoConvertService::CheckIfGeoConvertConnecting()
406 {
407 return mockEnabled_;
408 }
409
SaDumpInfo(std::string & result)410 void GeoConvertService::SaDumpInfo(std::string& result)
411 {
412 result += "GeoConvert enable status: false";
413 result += "\n";
414 }
415
Dump(int32_t fd,const std::vector<std::u16string> & args)416 int32_t GeoConvertService::Dump(int32_t fd, const std::vector<std::u16string>& args)
417 {
418 std::vector<std::string> vecArgs;
419 std::transform(args.begin(), args.end(), std::back_inserter(vecArgs), [](const std::u16string &arg) {
420 return Str16ToStr8(arg);
421 });
422
423 LocationDumper dumper;
424 std::string result;
425 dumper.GeocodeDump(SaDumpInfo, vecArgs, result);
426 if (!SaveStringToFd(fd, result)) {
427 LBSLOGE(GEO_CONVERT, "Geocode save string to fd failed!");
428 return ERR_OK;
429 }
430 return ERR_OK;
431 }
432
ResetServiceProxy()433 bool GeoConvertService::ResetServiceProxy()
434 {
435 std::unique_lock<std::mutex> uniqueLock(mutex_);
436 serviceProxy_ = nullptr;
437 return true;
438 }
439
RegisterGeoServiceDeathRecipient()440 void GeoConvertService::RegisterGeoServiceDeathRecipient()
441 {
442 std::unique_lock<std::mutex> uniqueLock(mutex_);
443 if (serviceProxy_ == nullptr) {
444 LBSLOGE(GEO_CONVERT, "%{public}s: geoServiceProxy_ is nullptr", __func__);
445 return;
446 }
447 sptr<IRemoteObject::DeathRecipient> death(new (std::nothrow) GeoServiceDeathRecipient());
448 serviceProxy_->AddDeathRecipient(death);
449 }
450
SendGeocodeRequest(int code,MessageParcel & dataParcel,MessageParcel & replyParcel,MessageOption & option)451 bool GeoConvertService::SendGeocodeRequest(int code, MessageParcel& dataParcel, MessageParcel& replyParcel,
452 MessageOption& option)
453 {
454 std::unique_lock<std::mutex> uniqueLock(mutex_);
455 if (serviceProxy_ == nullptr) {
456 LBSLOGE(GEO_CONVERT, "serviceProxy is nullptr!");
457 return false;
458 }
459 int error = serviceProxy_->SendRequest(code, dataParcel, replyParcel, option);
460 if (error != ERR_OK) {
461 LBSLOGE(GEO_CONVERT, "SendRequest to cloud service failed. error = %{public}d", error);
462 return false;
463 }
464 return true;
465 }
466
GeoServiceDeathRecipient()467 GeoServiceDeathRecipient::GeoServiceDeathRecipient()
468 {
469 }
470
~GeoServiceDeathRecipient()471 GeoServiceDeathRecipient::~GeoServiceDeathRecipient()
472 {
473 }
474
OnRemoteDied(const wptr<IRemoteObject> & remote)475 void GeoServiceDeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &remote)
476 {
477 auto geoConvertService = DelayedSingleton<GeoConvertService>::GetInstance();
478 if (geoConvertService != nullptr) {
479 LBSLOGI(GEO_CONVERT, "geo OnRemoteDied");
480 geoConvertService->ResetServiceProxy();
481 }
482 }
483 } // namespace Location
484 } // namespace OHOS
485 #endif
486