Merge branch 'master' of gitee.com:openharmony/base_location into master

Signed-off-by: smilebear <245252081@qq.com>
This commit is contained in:
smilebear 2024-07-18 07:49:34 +00:00 committed by 李文龙
commit c900f5a4d5
243 changed files with 10246 additions and 2484 deletions

View File

@ -54,6 +54,7 @@
"drivers_interface_location_gnss",
"drivers_interface_location_geofence",
"eventhandler",
"ffrt",
"form_fwk",
"hdf_core",
"hisysevent",
@ -76,14 +77,13 @@
"movement",
"device_standby",
"time_service"
],
"third_party": [
"libuv"
]
},
"build": {
"group_type": {
"base_group": [],
"base_group": [
"//base/location/services/utils:lbsresources"
],
"fwk_group": [
"//base/location/frameworks/native/locator_sdk:locator_sdk",
"//base/location/frameworks/js/napi:geolocation",
@ -137,6 +137,7 @@
"test": [
"//base/location/test/location_common:unittest",
"//base/location/test/location_geocode:unittest",
"//base/location/test/location_geofence:unittest",
"//base/location/test/location_gnss:unittest",
"//base/location/test/location_locator:unittest",
"//base/location/test/location_network:unittest",

View File

@ -26,7 +26,6 @@ SAMGR_ROOT_DIR = "//foundation/systemabilitymgr"
SECURITY_ROOT_DIR = "//base/security"
START_UP_ROOT_DIR = "//base/startup"
GOOGLE_TEST_DIR = "//third_party/googletest"
LIB_UV_DIR = "//third_party/libuv"
DFX_HILOG_DIR = "//base/hiviewdfx/hilog"
ABILITY_RUNTIME = "//foundation/ability/ability_runtime"
LOCATION_NATIVE_DIR = "$LOCATION_ROOT_DIR/frameworks/native"

View File

@ -1,4 +1,4 @@
# Copyright (C) 2022 Huawei Device Co., Ltd.
# Copyright (C) 2022-2024 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
@ -14,6 +14,44 @@
import("//base/location/config.gni")
import("//build/ohos.gni")
local_base_sources = [
"$LOCATION_ROOT_DIR/frameworks/js/napi/source/cached_locations_callback_napi.cpp",
"$LOCATION_ROOT_DIR/frameworks/js/napi/source/country_code_callback_napi.cpp",
"$LOCATION_ROOT_DIR/frameworks/js/napi/source/geofence_napi.cpp",
"$LOCATION_ROOT_DIR/frameworks/js/napi/source/gnss_status_callback_napi.cpp",
"$LOCATION_ROOT_DIR/frameworks/js/napi/source/locating_required_data_callback_napi.cpp",
"$LOCATION_ROOT_DIR/frameworks/js/napi/source/location_error_callback_napi.cpp",
"$LOCATION_ROOT_DIR/frameworks/js/napi/source/location_gnss_geofence_callback_napi.cpp",
"$LOCATION_ROOT_DIR/frameworks/js/napi/source/location_napi_adapter.cpp",
"$LOCATION_ROOT_DIR/frameworks/js/napi/source/location_napi_entry.cpp",
"$LOCATION_ROOT_DIR/frameworks/js/napi/source/location_napi_errcode.cpp",
"$LOCATION_ROOT_DIR/frameworks/js/napi/source/location_napi_event.cpp",
"$LOCATION_ROOT_DIR/frameworks/js/napi/source/location_napi_system.cpp",
"$LOCATION_ROOT_DIR/frameworks/js/napi/source/location_switch_callback_napi.cpp",
"$LOCATION_ROOT_DIR/frameworks/js/napi/source/locator_callback_napi.cpp",
"$LOCATION_ROOT_DIR/frameworks/js/napi/source/napi_util.cpp",
"$LOCATION_ROOT_DIR/frameworks/js/napi/source/nmea_message_callback_napi.cpp",
]
if (notification_distributed_notification_service_enable) {
local_notification_sources = [
"$LOCATION_ROOT_DIR/frameworks/js/napi/notification/src/notification_napi.cpp",
"$LOCATION_ROOT_DIR/frameworks/js/napi/notification/src/notification_napi_convert_content.cpp",
"$LOCATION_ROOT_DIR/frameworks/js/napi/notification/src/notification_napi_convert_liveview.cpp",
"$LOCATION_ROOT_DIR/frameworks/js/napi/notification/src/notification_napi_convert_notification.cpp",
"$LOCATION_ROOT_DIR/frameworks/js/napi/notification/src/notification_napi_convert_request.cpp",
"$LOCATION_ROOT_DIR/frameworks/js/napi/notification/src/notification_napi_utils.cpp",
]
notification_external_deps = [
"ability_base:want",
"ability_runtime:napi_common",
"distributed_notification_service:ans_innerkits",
"image_framework:image",
"relational_store:native_rdb",
]
}
ohos_shared_library("geolocation") {
sanitize = {
cfi = true
@ -24,15 +62,11 @@ ohos_shared_library("geolocation") {
install_enable = true
include_dirs = [
"$LOCATION_ROOT_DIR/frameworks/js/napi/include",
"$LOCATION_ROOT_DIR/frameworks/js/napi/notification/include",
"$LOCATION_ROOT_DIR/interfaces/inner_api/include",
]
sources = [
"$LOCATION_ROOT_DIR/frameworks/js/napi/source/location_napi_adapter.cpp",
"$LOCATION_ROOT_DIR/frameworks/js/napi/source/location_napi_entry.cpp",
"$LOCATION_ROOT_DIR/frameworks/js/napi/source/location_napi_event.cpp",
"$LOCATION_ROOT_DIR/frameworks/js/napi/source/location_napi_system.cpp",
]
sources = local_base_sources
deps = [
"$LOCATION_ROOT_DIR/frameworks/location_common/common:lbsservice_common",
@ -41,20 +75,24 @@ ohos_shared_library("geolocation") {
]
external_deps = [
"c_utils:utils",
"hilog:libhilog",
"ipc:ipc_single",
"napi:ace_napi",
]
defines = []
if (notification_distributed_notification_service_enable) {
sources += local_notification_sources
external_deps += notification_external_deps
defines += [ "NOTIFICATION_ENABLE" ]
}
if (location_feature_with_jsstack) {
defines += [ "SUPPORT_JSSTACK" ]
external_deps += [ "hiview:libxpower_event_js" ]
}
if (notification_distributed_notification_service_enable) {
defines += [ "NOTIFICATION_ENABLE" ]
}
relative_install_dir = "module"
part_name = "location"
subsystem_name = "location"
@ -70,14 +108,10 @@ ohos_static_library("geolocation_static") {
include_dirs = [
"$LOCATION_ROOT_DIR/frameworks/js/napi/include",
"$LOCATION_ROOT_DIR/interfaces/inner_api/include",
"$LOCATION_ROOT_DIR/frameworks/js/napi/notification/include",
]
sources = [
"$LOCATION_ROOT_DIR/frameworks/js/napi/source/location_napi_adapter.cpp",
"$LOCATION_ROOT_DIR/frameworks/js/napi/source/location_napi_entry.cpp",
"$LOCATION_ROOT_DIR/frameworks/js/napi/source/location_napi_event.cpp",
"$LOCATION_ROOT_DIR/frameworks/js/napi/source/location_napi_system.cpp",
]
sources = local_base_sources
deps = [
"$LOCATION_ROOT_DIR/frameworks/location_common/common:lbsservice_common",
@ -86,13 +120,16 @@ ohos_static_library("geolocation_static") {
]
external_deps = [
"c_utils:utils",
"hilog:libhilog",
"ipc:ipc_single",
"napi:ace_napi",
]
defines = []
if (notification_distributed_notification_service_enable) {
sources += local_notification_sources
external_deps += notification_external_deps
defines += [ "NOTIFICATION_ENABLE" ]
}
part_name = "location"
@ -110,15 +147,10 @@ ohos_shared_library("geolocationmanager") {
include_dirs = [
"$LOCATION_ROOT_DIR/frameworks/js/napi/include",
"$LOCATION_ROOT_DIR/interfaces/inner_api/include",
"$LOCATION_ROOT_DIR/frameworks/js/napi/notification/include",
]
sources = [
"$LOCATION_ROOT_DIR/frameworks/js/napi/source/location_napi_adapter.cpp",
"$LOCATION_ROOT_DIR/frameworks/js/napi/source/location_napi_entry.cpp",
"$LOCATION_ROOT_DIR/frameworks/js/napi/source/location_napi_errcode.cpp",
"$LOCATION_ROOT_DIR/frameworks/js/napi/source/location_napi_event.cpp",
"$LOCATION_ROOT_DIR/frameworks/js/napi/source/location_napi_system.cpp",
]
sources = local_base_sources
deps = [
"$LOCATION_ROOT_DIR/frameworks/location_common/common:lbsservice_common",
@ -129,19 +161,21 @@ ohos_shared_library("geolocationmanager") {
defines = [ "ENABLE_NAPI_MANAGER" ]
external_deps = [
"c_utils:utils",
"hilog:libhilog",
"ipc:ipc_single",
"napi:ace_napi",
]
if (notification_distributed_notification_service_enable) {
sources += local_notification_sources
external_deps += notification_external_deps
defines += [ "NOTIFICATION_ENABLE" ]
}
if (location_feature_with_jsstack) {
defines += [ "SUPPORT_JSSTACK" ]
external_deps += [ "hiview:libxpower_event_js" ]
}
if (notification_distributed_notification_service_enable) {
defines += [ "NOTIFICATION_ENABLE" ]
}
relative_install_dir = "module"
part_name = "location"
subsystem_name = "location"

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2022 Huawei Device Co., Ltd.
* Copyright (C) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -13,8 +13,8 @@
* limitations under the License.
*/
#ifndef CACHED_LOCATIONS_CALLBACK_HOST_H
#define CACHED_LOCATIONS_CALLBACK_HOST_H
#ifndef CACHED_LOCATIONS_CALLBACK_NAPI_H
#define CACHED_LOCATIONS_CALLBACK_NAPI_H
#include <vector>
@ -30,10 +30,10 @@
namespace OHOS {
namespace Location {
class CachedLocationsCallbackHost : public IRemoteStub<ICachedLocationsCallback> {
class CachedLocationsCallbackNapi : public IRemoteStub<ICachedLocationsCallback> {
public:
CachedLocationsCallbackHost();
virtual ~CachedLocationsCallbackHost();
CachedLocationsCallbackNapi();
virtual ~CachedLocationsCallbackNapi();
virtual int OnRemoteRequest(
uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) override;
bool IsRemoteDied();
@ -42,6 +42,20 @@ public:
void DeleteHandler();
void UvQueueWork(uv_loop_s* loop, uv_work_t* work);
template <typename T>
bool InitContext(T* context)
{
if (context == nullptr) {
LBSLOGE(CACHED_LOCATIONS_CALLBACK, "context == nullptr.");
return false;
}
context->env = env_;
callbackValid_ = handlerCb_ == nullptr ? false : true;
context->callbackValid = &callbackValid_;
context->callback[SUCCESS_CALLBACK] = handlerCb_;
return true;
}
inline napi_env GetEnv() const
{
return env_;
@ -77,7 +91,8 @@ private:
napi_ref handlerCb_;
bool remoteDied_;
std::mutex mutex_;
bool callbackValid_;
};
} // namespace Location
} // namespace OHOS
#endif // CACHED_LOCATIONS_CALLBACK_HOST_H
#endif // CACHED_LOCATIONS_CALLBACK_NAPI_H

View File

@ -18,6 +18,7 @@
#include <mutex>
#include "location_napi_errcode.h"
namespace OHOS {
namespace Location {
template <typename T>

View File

@ -0,0 +1,62 @@
/*
* Copyright (C) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef COUNTRY_CODE_CALLBACK_NAPI_H
#define COUNTRY_CODE_CALLBACK_NAPI_H
#include "i_country_code_callback.h"
#include "iremote_stub.h"
#include "napi/native_api.h"
#include "uv.h"
#include "country_code.h"
#include "location_log.h"
namespace OHOS {
namespace Location {
class CountryCodeCallbackNapi : public IRemoteStub<ICountryCodeCallback> {
public:
CountryCodeCallbackNapi();
virtual ~CountryCodeCallbackNapi();
virtual int OnRemoteRequest(uint32_t code,
MessageParcel& data, MessageParcel& reply, MessageOption& option) override;
void OnCountryCodeChange(const std::shared_ptr<CountryCode>& country) override;
bool Send(const std::shared_ptr<CountryCode>& country);
void SetEnv(napi_env env);
void SetCallback(napi_ref cb);
void DeleteHandler();
void UvQueueWork(uv_loop_s* loop, uv_work_t* work);
template <typename T>
bool InitContext(T* context)
{
if (context == nullptr) {
LBSLOGE(COUNTRY_CODE_CALLBACK, "context == nullptr.");
return false;
}
context->env = env_;
callbackValid_ = handlerCb_ == nullptr ? false : true;
context->callbackValid = &callbackValid_;
context->callback[SUCCESS_CALLBACK] = handlerCb_;
return true;
}
private:
napi_env env_;
napi_ref handlerCb_;
std::mutex mutex_;
bool callbackValid_;
};
} // namespace Location
} // namespace OHOS
#endif // COUNTRY_CODE_CALLBACK_NAPI_H

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2022 Huawei Device Co., Ltd.
* Copyright (C) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -13,8 +13,8 @@
* limitations under the License.
*/
#ifndef GNSS_STATUS_CALLBACK_HOST_H
#define GNSS_STATUS_CALLBACK_HOST_H
#ifndef GNSS_STATUS_CALLBACK_NAPI_H
#define GNSS_STATUS_CALLBACK_NAPI_H
#include "iremote_stub.h"
#include "message_option.h"
@ -28,10 +28,10 @@
namespace OHOS {
namespace Location {
class GnssStatusCallbackHost : public IRemoteStub<IGnssStatusCallback> {
class GnssStatusCallbackNapi : public IRemoteStub<IGnssStatusCallback> {
public:
GnssStatusCallbackHost();
virtual ~GnssStatusCallbackHost();
GnssStatusCallbackNapi();
virtual ~GnssStatusCallbackNapi();
virtual int OnRemoteRequest(
uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) override;
bool IsRemoteDied();
@ -40,6 +40,20 @@ public:
void DeleteHandler();
void UvQueueWork(uv_loop_s* loop, uv_work_t* work);
template <typename T>
bool InitContext(T* context)
{
if (context == nullptr) {
LBSLOGE(GNSS_STATUS_CALLBACK, "context == nullptr.");
return false;
}
context->env = env_;
callbackValid_ = handlerCb_ == nullptr ? false : true;
context->callbackValid = &callbackValid_;
context->callback[SUCCESS_CALLBACK] = handlerCb_;
return true;
}
inline napi_env GetEnv() const
{
return env_;
@ -75,7 +89,8 @@ private:
napi_ref handlerCb_;
bool remoteDied_;
std::mutex mutex_;
bool callbackValid_;
};
} // namespace Location
} // namespace OHOS
#endif // GNSS_STATUS_CALLBACK_HOST_H
#endif // GNSS_STATUS_CALLBACK_NAPI_H

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2023 Huawei Device Co., Ltd.
* Copyright (C) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -13,8 +13,8 @@
* limitations under the License.
*/
#ifndef LOCATING_REQUIRED_DATA_CALLBACK_HOST_H
#define LOCATING_REQUIRED_DATA_CALLBACK_HOST_H
#ifndef LOCATING_REQUIRED_DATA_CALLBACK_NAPI_H
#define LOCATING_REQUIRED_DATA_CALLBACK_NAPI_H
#include "i_locating_required_data_callback.h"
#include "iremote_stub.h"
@ -26,10 +26,10 @@
namespace OHOS {
namespace Location {
class LocatingRequiredDataCallbackHost : public IRemoteStub<ILocatingRequiredDataCallback> {
class LocatingRequiredDataCallbackNapi : public IRemoteStub<ILocatingRequiredDataCallback> {
public:
LocatingRequiredDataCallbackHost();
virtual ~LocatingRequiredDataCallbackHost();
LocatingRequiredDataCallbackNapi();
virtual ~LocatingRequiredDataCallbackNapi();
virtual int OnRemoteRequest(
uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) override;
bool IsRemoteDied();
@ -46,6 +46,20 @@ public:
void ClearSingleResult();
void SetSingleResult(
std::vector<std::shared_ptr<LocatingRequiredData>> singleResult);
template <typename T>
bool InitContext(T* context)
{
if (context == nullptr) {
LBSLOGE(LOCATING_DATA_CALLBACK, "context == nullptr.");
return false;
}
context->env = env_;
callbackValid_ = handlerCb_ == nullptr ? false : true;
context->callbackValid = &callbackValid_;
context->callback[SUCCESS_CALLBACK] = handlerCb_;
return true;
}
inline napi_env GetEnv() const
{
@ -93,6 +107,7 @@ public:
fixNumber_ = fixNumber;
}
private:
bool callbackValid_;
int fixNumber_;
napi_env env_;
napi_ref handlerCb_;
@ -104,4 +119,4 @@ private:
};
} // namespace Location
} // namespace OHOS
#endif // LOCATING_REQUIRED_DATA_CALLBACK_HOST_H
#endif // LOCATING_REQUIRED_DATA_CALLBACK_NAPI_H

View File

@ -13,8 +13,8 @@
* limitations under the License.
*/
#ifndef LOCATION_ERROR_CALLBACK_HOST_H
#define LOCATION_ERROR_CALLBACK_HOST_H
#ifndef LOCATION_ERROR_CALLBACK_NAPI_H
#define LOCATION_ERROR_CALLBACK_NAPI_H
#include "iremote_stub.h"
#include "napi/native_api.h"
#include "uv.h"
@ -26,10 +26,10 @@
namespace OHOS {
namespace Location {
class LocationErrorCallbackHost : public IRemoteStub<ILocatorCallback> {
class LocationErrorCallbackNapi : public IRemoteStub<ILocatorCallback> {
public:
LocationErrorCallbackHost();
virtual ~LocationErrorCallbackHost();
LocationErrorCallbackNapi();
virtual ~LocationErrorCallbackNapi();
virtual int OnRemoteRequest(
uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) override;
void OnLocationReport(const std::unique_ptr<Location>& location) override;
@ -40,6 +40,20 @@ public:
void DeleteHandler();
void UvQueueWork(uv_loop_s* loop, uv_work_t* work);
template <typename T>
bool InitContext(T* context)
{
if (context == nullptr) {
LBSLOGE(LOCATION_ERR_CALLBACK, "context == nullptr.");
return false;
}
context->env = env_;
callbackValid_ = handlerCb_ == nullptr ? false : true;
context->callbackValid = &callbackValid_;
context->callback[SUCCESS_CALLBACK] = handlerCb_;
return true;
}
inline napi_env GetEnv() const
{
return env_;
@ -64,7 +78,8 @@ private:
napi_env env_;
napi_ref handlerCb_;
std::mutex mutex_;
bool callbackValid_;
};
} // namespace Location
} // namespace OHOS
#endif // LOCATION_SWITCH_CALLBACK_HOST_H
#endif // LOCATION_ERROR_CALLBACK_NAPI_H

View File

@ -21,7 +21,7 @@
#include "napi_util.h"
#include "geofence_request.h"
#include "constant_definition.h"
#include "location_gnss_geofence_callback_host.h"
#include "location_gnss_geofence_callback_napi.h"
#include "geofence_async_context.h"
namespace OHOS {
@ -52,13 +52,13 @@ LocationErrCode CheckLocationSwitchState();
napi_value GetLocatingRequiredData(napi_env env, napi_callback_info info);
napi_value AddGnssGeofence(napi_env env, napi_callback_info info);
GnssGeofenceAsyncContext* CreateAsyncContextForAddGnssGeofence(const napi_env& env,
std::shared_ptr<GeofenceRequest>& request, sptr<LocationGnssGeofenceCallbackHost> callback);
std::shared_ptr<GeofenceRequest>& request, sptr<LocationGnssGeofenceCallbackNapi> callback);
napi_value RemoveGnssGeofence(napi_env env, napi_callback_info info);
GnssGeofenceAsyncContext* CreateAsyncContextForRemoveGnssGeofence(const napi_env& env, int fenceId);
napi_value GetGeofenceSupportedCoordTypes(napi_env env, napi_callback_info info);
void AddCallbackToGnssGeofenceCallbackHostMap(int fenceId, sptr<LocationGnssGeofenceCallbackHost> callbackHost);
void AddCallbackToGnssGeofenceCallbackHostMap(int fenceId, sptr<LocationGnssGeofenceCallbackNapi> callbackHost);
void RemoveCallbackToGnssGeofenceCallbackHostMap(int fenceId);
sptr<LocationGnssGeofenceCallbackHost> FindCallbackInGnssGeofenceCallbackHostMap(int fenceId);
sptr<LocationGnssGeofenceCallbackNapi> FindCallbackInGnssGeofenceCallbackHostMap(int fenceId);
#endif
} // namespace Location
} // namespace OHOS

View File

@ -16,15 +16,15 @@
#ifndef LOCATION_NAPI_EVENT_H
#define LOCATION_NAPI_EVENT_H
#include "cached_locations_callback_host.h"
#include "gnss_status_callback_host.h"
#include "locating_required_data_callback_host.h"
#include "location_switch_callback_host.h"
#include "cached_locations_callback_napi.h"
#include "gnss_status_callback_napi.h"
#include "locating_required_data_callback_napi.h"
#include "location_switch_callback_napi.h"
#include "locator.h"
#include "locator_callback_host.h"
#include "nmea_message_callback_host.h"
#include "locator_callback_napi.h"
#include "nmea_message_callback_napi.h"
#include "request_config.h"
#include "location_error_callback_host.h"
#include "location_error_callback_napi.h"
namespace OHOS {
namespace Location {
@ -61,22 +61,22 @@ bool OffLocationErrorCallback(const napi_env& env, const napi_value& handler);
#endif
void SubscribeLocationServiceState(const napi_env& env,
const napi_ref& handlerRef, sptr<LocationSwitchCallbackHost>& switchCallbackHost);
const napi_ref& handlerRef, sptr<LocationSwitchCallbackNapi>& switchCallbackHost);
void SubscribeGnssStatus(const napi_env& env, const napi_ref& handlerRef,
sptr<GnssStatusCallbackHost>& gnssStatusCallbackHost);
sptr<GnssStatusCallbackNapi>& gnssStatusCallbackHost);
void SubscribeNmeaMessage(const napi_env& env, const napi_ref& handlerRef,
sptr<NmeaMessageCallbackHost>& nmeaMessageCallbackHost);
sptr<NmeaMessageCallbackNapi>& nmeaMessageCallbackHost);
void SubscribeLocationChange(const napi_env& env, const napi_value& object,
const napi_ref& handlerRef, sptr<LocatorCallbackHost>& locatorCallbackHost);
const napi_ref& handlerRef, sptr<LocatorCallbackNapi>& locatorCallbackHost);
void SubscribeCacheLocationChange(const napi_env& env, const napi_value& object,
const napi_ref& handlerRef, sptr<CachedLocationsCallbackHost>& cachedCallbackHost);
const napi_ref& handlerRef, sptr<CachedLocationsCallbackNapi>& cachedCallbackHost);
void SubscribeFenceStatusChange(const napi_env& env, const napi_value& object, const napi_value& handler);
void UnSubscribeLocationChange(sptr<ILocatorCallback>& callback);
void UnSubscribeFenceStatusChange(const napi_env& env, const napi_value& object, const napi_value& handler);
void UnSubscribeCacheLocationChange(sptr<ICachedLocationsCallback>& callback);
void UnSubscribeLocationServiceState(sptr<LocationSwitchCallbackHost>& switchCallbackHost);
void UnSubscribeGnssStatus(sptr<GnssStatusCallbackHost>& gnssStatusCallbackHost);
void UnSubscribeNmeaMessage(sptr<NmeaMessageCallbackHost>& nmeaMessageCallbackHost);
void UnSubscribeLocationServiceState(sptr<LocationSwitchCallbackNapi>& switchCallbackHost);
void UnSubscribeGnssStatus(sptr<GnssStatusCallbackNapi>& gnssStatusCallbackHost);
void UnSubscribeNmeaMessage(sptr<NmeaMessageCallbackNapi>& nmeaMessageCallbackHost);
bool IsCallbackEquals(const napi_env& env, const napi_value& handler, const napi_ref& savedCallback);
void GenRequestConfig(const napi_env& env, const napi_value* argv,
const size_t& objectArgsNum, std::unique_ptr<RequestConfig>& requestConfig);
@ -89,28 +89,28 @@ int GetCurrentLocationType(std::unique_ptr<RequestConfig>& config);
#ifdef ENABLE_NAPI_MANAGER
LocationErrCode SubscribeLocationServiceStateV9(const napi_env& env,
const napi_ref& handlerRef, sptr<LocationSwitchCallbackHost>& switchCallbackHost);
const napi_ref& handlerRef, sptr<LocationSwitchCallbackNapi>& switchCallbackHost);
LocationErrCode SubscribeGnssStatusV9(const napi_env& env, const napi_ref& handlerRef,
sptr<GnssStatusCallbackHost>& gnssStatusCallbackHost);
sptr<GnssStatusCallbackNapi>& gnssStatusCallbackHost);
LocationErrCode SubscribeNmeaMessageV9(const napi_env& env, const napi_ref& handlerRef,
sptr<NmeaMessageCallbackHost>& nmeaMessageCallbackHost);
sptr<NmeaMessageCallbackNapi>& nmeaMessageCallbackHost);
LocationErrCode SubscribeLocationChangeV9(const napi_env& env, const napi_value& object,
const napi_ref& handlerRef, sptr<LocatorCallbackHost>& locatorCallbackHost);
const napi_ref& handlerRef, sptr<LocatorCallbackNapi>& locatorCallbackHost);
LocationErrCode SubscribeCacheLocationChangeV9(const napi_env& env, const napi_value& object,
const napi_ref& handlerRef, sptr<CachedLocationsCallbackHost>& cachedCallbackHost);
const napi_ref& handlerRef, sptr<CachedLocationsCallbackNapi>& cachedCallbackHost);
LocationErrCode SubscribeFenceStatusChangeV9(const napi_env& env, const napi_value& object, const napi_value& handler);
LocationErrCode SubscribeLocatingRequiredDataChange(const napi_env& env, const napi_value& object,
const napi_ref& handlerRef, sptr<LocatingRequiredDataCallbackHost>& locatingCallbackHost);
const napi_ref& handlerRef, sptr<LocatingRequiredDataCallbackNapi>& locatingCallbackHost);
LocationErrCode SubscribeLocationError(const napi_env& env,
const napi_ref& handlerRef, sptr<LocationErrorCallbackHost>& locationErrorCallbackHost);
const napi_ref& handlerRef, sptr<LocationErrorCallbackNapi>& locationErrorCallbackHost);
LocationErrCode UnSubscribeLocationChangeV9(sptr<ILocatorCallback>& callback);
LocationErrCode UnSubscribeFenceStatusChangeV9(const napi_env& env,
const napi_value& object, const napi_value& handler);
LocationErrCode UnSubscribeCacheLocationChangeV9(sptr<ICachedLocationsCallback>& callback);
LocationErrCode UnSubscribeLocationServiceStateV9(sptr<LocationSwitchCallbackHost>& switchCallbackHost);
LocationErrCode UnSubscribeGnssStatusV9(sptr<GnssStatusCallbackHost>& gnssStatusCallbackHost);
LocationErrCode UnSubscribeNmeaMessageV9(sptr<NmeaMessageCallbackHost>& nmeaMessageCallbackHost);
LocationErrCode UnSubscribeLocatingRequiredDataChange(sptr<LocatingRequiredDataCallbackHost>& callbackHost);
LocationErrCode UnSubscribeLocationServiceStateV9(sptr<LocationSwitchCallbackNapi>& switchCallbackHost);
LocationErrCode UnSubscribeGnssStatusV9(sptr<GnssStatusCallbackNapi>& gnssStatusCallbackHost);
LocationErrCode UnSubscribeNmeaMessageV9(sptr<NmeaMessageCallbackNapi>& nmeaMessageCallbackHost);
LocationErrCode UnSubscribeLocatingRequiredDataChange(sptr<LocatingRequiredDataCallbackNapi>& callbackHost);
LocationErrCode UnSubscribeLocationError(sptr<ILocatorCallback>& callback);
napi_value RequestLocationOnceV9(const napi_env& env, const size_t argc, const napi_value* argv);
LocationErrCode CheckLocationSwitchEnable();

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2022 Huawei Device Co., Ltd.
* Copyright (C) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -13,8 +13,8 @@
* limitations under the License.
*/
#ifndef LOCATION_SWITCH_CALLBACK_HOST_H
#define LOCATION_SWITCH_CALLBACK_HOST_H
#ifndef LOCATION_SWITCH_CALLBACK_NAPI_H
#define LOCATION_SWITCH_CALLBACK_NAPI_H
#include "i_switch_callback.h"
#include "iremote_stub.h"
@ -26,10 +26,10 @@
namespace OHOS {
namespace Location {
class LocationSwitchCallbackHost : public IRemoteStub<ISwitchCallback> {
class LocationSwitchCallbackNapi : public IRemoteStub<ISwitchCallback> {
public:
LocationSwitchCallbackHost();
virtual ~LocationSwitchCallbackHost();
LocationSwitchCallbackNapi();
virtual ~LocationSwitchCallbackNapi();
virtual int OnRemoteRequest(
uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) override;
bool IsRemoteDied();
@ -39,6 +39,20 @@ public:
void DeleteHandler();
void UvQueueWork(uv_loop_s* loop, uv_work_t* work);
template <typename T>
bool InitContext(T* context)
{
if (context == nullptr) {
LBSLOGE(SWITCH_CALLBACK, "context == nullptr.");
return false;
}
context->env = env_;
callbackValid_ = handlerCb_ == nullptr ? false : true;
context->callbackValid = &callbackValid_;
context->callback[SUCCESS_CALLBACK] = handlerCb_;
return true;
}
inline napi_env GetEnv() const
{
return env_;
@ -74,7 +88,8 @@ private:
napi_ref handlerCb_;
bool remoteDied_;
std::mutex mutex_;
bool callbackValid_;
};
} // namespace Location
} // namespace OHOS
#endif // LOCATION_SWITCH_CALLBACK_HOST_H
#endif // LOCATION_SWITCH_CALLBACK_NAPI_H

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2022 Huawei Device Co., Ltd.
* Copyright (C) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -13,8 +13,8 @@
* limitations under the License.
*/
#ifndef LOCATOR_CALLBACK_HOST_H
#define LOCATOR_CALLBACK_HOST_H
#ifndef LOCATOR_CALLBACK_NAPI_H
#define LOCATOR_CALLBACK_NAPI_H
#include "iremote_stub.h"
#include "napi/native_api.h"
@ -27,10 +27,10 @@
namespace OHOS {
namespace Location {
class LocatorCallbackHost : public IRemoteStub<ILocatorCallback> {
class LocatorCallbackNapi : public IRemoteStub<ILocatorCallback> {
public:
LocatorCallbackHost();
virtual ~LocatorCallbackHost();
LocatorCallbackNapi();
virtual ~LocatorCallbackNapi();
virtual int OnRemoteRequest(uint32_t code,
MessageParcel& data, MessageParcel& reply, MessageOption& option) override;
void DoSendWork(uv_loop_s *&loop, uv_work_t *&work);
@ -61,13 +61,14 @@ public:
return false;
}
context->env = env_;
callbackValid_ = handlerCb_ == nullptr ? false : true;
context->callbackValid = &callbackValid_;
if (IsSystemGeoLocationApi()) {
context->callback[SUCCESS_CALLBACK] = successHandlerCb_;
context->callback[FAIL_CALLBACK] = failHandlerCb_;
context->callback[COMPLETE_CALLBACK] = completeHandlerCb_;
} else {
context->callback[SUCCESS_CALLBACK] = handlerCb_;
context->deferred = deferred_;
}
return true;
}
@ -132,16 +133,6 @@ public:
fixNumber_ = fixNumber;
}
inline napi_deferred GetDeferred() const
{
return deferred_;
}
inline void SetDeferred(const napi_deferred& deferred)
{
deferred_ = deferred;
}
inline void SetLocationPriority(const int locationPriority)
{
locationPriority_ = locationPriority;
@ -168,13 +159,13 @@ private:
napi_ref failHandlerCb_;
napi_ref completeHandlerCb_;
int fixNumber_;
napi_deferred deferred_;
std::mutex mutex_;
CountDownLatch* latch_;
std::shared_ptr<Location> singleLocation_;
int locationPriority_;
bool inHdArea_;
bool callbackValid_;
};
} // namespace Location
} // namespace OHOS
#endif // LOCATOR_CALLBACK_HOST_H
#endif // LOCATOR_CALLBACK_NAPI_H

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2022 Huawei Device Co., Ltd.
* Copyright (C) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -13,8 +13,8 @@
* limitations under the License.
*/
#ifndef NMEA_MESSAGE_CALLBACK_HOST_H
#define NMEA_MESSAGE_CALLBACK_HOST_H
#ifndef NMEA_MESSAGE_CALLBACK_NAPI_H
#define NMEA_MESSAGE_CALLBACK_NAPI_H
#include <string>
@ -29,10 +29,10 @@
namespace OHOS {
namespace Location {
class NmeaMessageCallbackHost : public IRemoteStub<INmeaMessageCallback> {
class NmeaMessageCallbackNapi : public IRemoteStub<INmeaMessageCallback> {
public:
NmeaMessageCallbackHost();
virtual ~NmeaMessageCallbackHost();
NmeaMessageCallbackNapi();
virtual ~NmeaMessageCallbackNapi();
virtual int OnRemoteRequest(
uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) override;
bool IsRemoteDied();
@ -42,6 +42,20 @@ public:
void DeleteHandler();
void UvQueueWork(uv_loop_s* loop, uv_work_t* work);
template <typename T>
bool InitContext(T* context)
{
if (context == nullptr) {
LBSLOGE(NMEA_MESSAGE_CALLBACK, "context == nullptr.");
return false;
}
context->env = env_;
callbackValid_ = handlerCb_ == nullptr ? false : true;
context->callbackValid = &callbackValid_;
context->callback[SUCCESS_CALLBACK] = handlerCb_;
return true;
}
inline napi_env GetEnv() const
{
return env_;
@ -77,7 +91,8 @@ private:
napi_ref handlerCb_;
bool remoteDied_;
std::mutex mutex_;
bool callbackValid_;
};
} // namespace Location
} // namespace OHOS
#endif // NMEA_MESSAGE_CALLBACK_HOST_H
#endif // NMEA_MESSAGE_CALLBACK_NAPI_H

View File

@ -51,7 +51,7 @@ void GenNotificationRequest(const napi_env& env, const napi_value& elementValue,
void GeofenceTransitionToJs(const napi_env& env,
const GeofenceTransition geofenceTransition, napi_value& result);
void JsObjToGeofenceTransitionCallback(const napi_env& env, const napi_value& object,
sptr<LocationGnssGeofenceCallbackHost> callbackHost);
sptr<LocationGnssGeofenceCallbackNapi> callbackHost);
} // namespace Location
} // namespace OHOS
#endif // GEOFENCE_NAPI_H

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2022 Huawei Device Co., Ltd.
* Copyright (C) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -12,7 +12,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "cached_locations_callback_host.h"
#include "cached_locations_callback_napi.h"
#include "ipc_skeleton.h"
#include "napi/native_common.h"
@ -23,21 +23,22 @@
namespace OHOS {
namespace Location {
CachedLocationsCallbackHost::CachedLocationsCallbackHost()
CachedLocationsCallbackNapi::CachedLocationsCallbackNapi()
{
env_ = nullptr;
handlerCb_ = nullptr;
remoteDied_ = false;
callbackValid_ = false;
}
CachedLocationsCallbackHost::~CachedLocationsCallbackHost()
CachedLocationsCallbackNapi::~CachedLocationsCallbackNapi()
{
}
int CachedLocationsCallbackHost::OnRemoteRequest(
int CachedLocationsCallbackNapi::OnRemoteRequest(
uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option)
{
LBSLOGD(CACHED_LOCATIONS_CALLBACK, "CachedLocationsCallbackHost::OnRemoteRequest!");
LBSLOGD(CACHED_LOCATIONS_CALLBACK, "CachedLocationsCallbackNapi::OnRemoteRequest!");
if (data.ReadInterfaceToken() != GetDescriptor()) {
LBSLOGE(CACHED_LOCATIONS_CALLBACK, "invalid token.");
return -1;
@ -67,12 +68,12 @@ int CachedLocationsCallbackHost::OnRemoteRequest(
return 0;
}
bool CachedLocationsCallbackHost::IsRemoteDied()
bool CachedLocationsCallbackNapi::IsRemoteDied()
{
return remoteDied_;
}
bool CachedLocationsCallbackHost::Send(std::vector<std::unique_ptr<Location>>& locations)
bool CachedLocationsCallbackNapi::Send(std::vector<std::unique_ptr<Location>>& locations)
{
std::unique_lock<std::mutex> guard(mutex_);
uv_loop_s *loop = nullptr;
@ -81,6 +82,10 @@ bool CachedLocationsCallbackHost::Send(std::vector<std::unique_ptr<Location>>& l
LBSLOGE(CACHED_LOCATIONS_CALLBACK, "loop == nullptr.");
return false;
}
if (handlerCb_ == nullptr) {
LBSLOGE(CACHED_LOCATIONS_CALLBACK, "handler is nullptr.");
return false;
}
uv_work_t *work = new (std::nothrow) uv_work_t;
if (work == nullptr) {
LBSLOGE(CACHED_LOCATIONS_CALLBACK, "work == nullptr.");
@ -92,8 +97,10 @@ bool CachedLocationsCallbackHost::Send(std::vector<std::unique_ptr<Location>>& l
delete work;
return false;
}
context->env = env_;
context->callback[SUCCESS_CALLBACK] = handlerCb_;
if (!InitContext(context)) {
LBSLOGE(CACHED_LOCATIONS_CALLBACK, "InitContext fail");
return false;
}
for (std::unique_ptr<Location>& location : locations) {
context->locationList.emplace_back(std::move(location));
}
@ -102,7 +109,7 @@ bool CachedLocationsCallbackHost::Send(std::vector<std::unique_ptr<Location>>& l
return true;
}
void CachedLocationsCallbackHost::UvQueueWork(uv_loop_s* loop, uv_work_t* work)
void CachedLocationsCallbackNapi::UvQueueWork(uv_loop_s* loop, uv_work_t* work)
{
uv_queue_work(
loop,
@ -116,7 +123,7 @@ void CachedLocationsCallbackHost::UvQueueWork(uv_loop_s* loop, uv_work_t* work)
return;
}
context = static_cast<CachedLocationAsyncContext *>(work->data);
if (context == nullptr || context->env == nullptr) {
if (context == nullptr || context->env == nullptr || context->callbackValid == nullptr) {
LBSLOGE(CACHED_LOCATIONS_CALLBACK, "context is nullptr");
delete work;
return;
@ -132,7 +139,7 @@ void CachedLocationsCallbackHost::UvQueueWork(uv_loop_s* loop, uv_work_t* work)
CHK_NAPI_ERR_CLOSE_SCOPE(context->env, napi_create_object(context->env, &jsEvent),
scope, context, work);
LocationsToJs(context->env, context->locationList, jsEvent);
if (context->callback[0] != nullptr) {
if (context->callback[0] != nullptr && *(context->callbackValid)) {
napi_value undefine;
napi_value handler = nullptr;
CHK_NAPI_ERR_CLOSE_SCOPE(context->env, napi_get_undefined(context->env, &undefine),
@ -150,27 +157,21 @@ void CachedLocationsCallbackHost::UvQueueWork(uv_loop_s* loop, uv_work_t* work)
});
}
void CachedLocationsCallbackHost::OnCacheLocationsReport(const std::vector<std::unique_ptr<Location>>& locations)
void CachedLocationsCallbackNapi::OnCacheLocationsReport(const std::vector<std::unique_ptr<Location>>& locations)
{
LBSLOGD(CACHED_LOCATIONS_CALLBACK, "CachedLocationsCallbackHost::OnCacheLocationsReport");
LBSLOGD(CACHED_LOCATIONS_CALLBACK, "CachedLocationsCallbackNapi::OnCacheLocationsReport");
}
void CachedLocationsCallbackHost::DeleteHandler()
void CachedLocationsCallbackNapi::DeleteHandler()
{
std::unique_lock<std::mutex> guard(mutex_);
if (handlerCb_ == nullptr || env_ == nullptr) {
LBSLOGE(CACHED_LOCATIONS_CALLBACK, "handler or env is nullptr.");
return;
}
auto context = new (std::nothrow) AsyncContext(env_);
if (context == nullptr) {
LBSLOGE(CACHED_LOCATIONS_CALLBACK, "context == nullptr.");
return;
}
context->env = env_;
context->callback[SUCCESS_CALLBACK] = handlerCb_;
DeleteQueueWork(context);
NAPI_CALL_RETURN_VOID(env_, napi_delete_reference(env_, handlerCb_));
handlerCb_ = nullptr;
callbackValid_ = false;
}
} // namespace Location
} // namespace OHOS

View File

@ -0,0 +1,185 @@
/*
* Copyright (C) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "country_code_callback_napi.h"
#include "common_utils.h"
#include "ipc_skeleton.h"
#include "location_log.h"
#include "napi/native_api.h"
#include "country_code.h"
#include "napi_util.h"
namespace OHOS {
namespace Location {
CountryCodeCallbackNapi::CountryCodeCallbackNapi()
{
env_ = nullptr;
handlerCb_ = nullptr;
callbackValid_ = false;
}
CountryCodeCallbackNapi::~CountryCodeCallbackNapi()
{
}
int CountryCodeCallbackNapi::OnRemoteRequest(
uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option)
{
LBSLOGD(COUNTRY_CODE_CALLBACK, "CountryCodeCallbackNapi::OnRemoteRequest!");
if (data.ReadInterfaceToken() != GetDescriptor()) {
LBSLOGE(COUNTRY_CODE_CALLBACK, "invalid token.");
return -1;
}
switch (code) {
case COUNTRY_CODE_CHANGE_EVENT: {
auto countryCodePtr = CountryCode::Unmarshalling(data);
OnCountryCodeChange(countryCodePtr);
break;
}
default: {
IPCObjectStub::OnRemoteRequest(code, data, reply, option);
break;
}
}
return 0;
}
bool CountryCodeCallbackNapi::Send(const std::shared_ptr<CountryCode>& country)
{
std::unique_lock<std::mutex> guard(mutex_);
uv_loop_s *loop = nullptr;
if (env_ == nullptr) {
LBSLOGE(COUNTRY_CODE_CALLBACK, "env_ == nullptr.");
return false;
}
if (handlerCb_ == nullptr) {
LBSLOGE(COUNTRY_CODE_CALLBACK, "handler is nullptr.");
return false;
}
if (country == nullptr) {
LBSLOGE(COUNTRY_CODE_CALLBACK, "country == nullptr.");
return false;
}
NAPI_CALL_BASE(env_, napi_get_uv_event_loop(env_, &loop), false);
if (loop == nullptr) {
LBSLOGE(COUNTRY_CODE_CALLBACK, "loop == nullptr.");
return false;
}
uv_work_t *work = new (std::nothrow) uv_work_t;
if (work == nullptr) {
LBSLOGE(COUNTRY_CODE_CALLBACK, "work == nullptr.");
return false;
}
auto context = new (std::nothrow) CountryCodeContext(env_);
if (context == nullptr) {
LBSLOGE(COUNTRY_CODE_CALLBACK, "context == nullptr.");
delete work;
return false;
}
if (!InitContext(context)) {
LBSLOGE(COUNTRY_CODE_CALLBACK, "InitContext fail");
return false;
}
context->country = country;
work->data = context;
UvQueueWork(loop, work);
return true;
}
void CountryCodeCallbackNapi::UvQueueWork(uv_loop_s* loop, uv_work_t* work)
{
uv_queue_work(
loop,
work,
[](uv_work_t *work) {},
[](uv_work_t *work, int status) {
CountryCodeContext *context = nullptr;
napi_handle_scope scope = nullptr;
if (work == nullptr) {
LBSLOGE(LOCATOR_CALLBACK, "work is nullptr!");
return;
}
context = static_cast<CountryCodeContext *>(work->data);
if (context == nullptr || context->env == nullptr || context->callbackValid == nullptr) {
LBSLOGE(LOCATOR_CALLBACK, "context is nullptr!");
delete work;
return;
}
NAPI_CALL_RETURN_VOID(context->env, napi_open_handle_scope(context->env, &scope));
if (scope == nullptr) {
LBSLOGE(COUNTRY_CODE_CALLBACK, "scope is nullptr");
delete context;
delete work;
return;
}
napi_value jsEvent;
CHK_NAPI_ERR_CLOSE_SCOPE(context->env, napi_create_object(context->env, &jsEvent),
scope, context, work);
if (context->country) {
CountryCodeToJs(context->env, context->country, jsEvent);
} else {
LBSLOGE(LOCATOR_STANDARD, "country is nullptr!");
}
if (context->callback[0] != nullptr && *(context->callbackValid)) {
napi_value undefine;
napi_value handler = nullptr;
CHK_NAPI_ERR_CLOSE_SCOPE(context->env,
napi_get_undefined(context->env, &undefine), scope, context, work);
CHK_NAPI_ERR_CLOSE_SCOPE(context->env,
napi_get_reference_value(context->env, context->callback[SUCCESS_CALLBACK], &handler),
scope, context, work);
if (napi_call_function(context->env, nullptr, handler, 1, &jsEvent, &undefine) != napi_ok) {
LBSLOGE(COUNTRY_CODE_CALLBACK, "Report event failed");
}
}
NAPI_CALL_RETURN_VOID(context->env, napi_close_handle_scope(context->env, scope));
delete context;
delete work;
});
}
void CountryCodeCallbackNapi::OnCountryCodeChange(const std::shared_ptr<CountryCode>& country)
{
LBSLOGD(COUNTRY_CODE_CALLBACK, "CountryCodeCallbackNapi::OnCountryCodeChange");
Send(country);
}
void CountryCodeCallbackNapi::SetEnv(napi_env env)
{
std::unique_lock<std::mutex> guard(mutex_);
env_ = env;
}
void CountryCodeCallbackNapi::SetCallback(napi_ref cb)
{
std::unique_lock<std::mutex> guard(mutex_);
handlerCb_ = cb;
}
void CountryCodeCallbackNapi::DeleteHandler()
{
std::unique_lock<std::mutex> guard(mutex_);
if (handlerCb_ == nullptr || env_ == nullptr) {
LBSLOGE(COUNTRY_CODE_CALLBACK, "handler or env is nullptr.");
return;
}
NAPI_CALL_RETURN_VOID(env_, napi_delete_reference(env_, handlerCb_));
handlerCb_ = nullptr;
callbackValid_ = false;
}
} // namespace Location
} // namespace OHOS

View File

@ -65,7 +65,7 @@ bool GenGnssGeofenceRequest(
}
void JsObjToGeofenceTransitionCallback(const napi_env& env, const napi_value& object,
sptr<LocationGnssGeofenceCallbackHost> callbackHost)
sptr<LocationGnssGeofenceCallbackNapi> callbackHost)
{
napi_ref handlerRef = nullptr;
napi_value callbackNapiValue = nullptr;

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2022 Huawei Device Co., Ltd.
* Copyright (C) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -12,7 +12,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "gnss_status_callback_host.h"
#include "gnss_status_callback_napi.h"
#include "napi/native_common.h"
@ -25,21 +25,22 @@
namespace OHOS {
namespace Location {
GnssStatusCallbackHost::GnssStatusCallbackHost()
GnssStatusCallbackNapi::GnssStatusCallbackNapi()
{
env_ = nullptr;
handlerCb_ = nullptr;
remoteDied_ = false;
callbackValid_ = false;
}
GnssStatusCallbackHost::~GnssStatusCallbackHost()
GnssStatusCallbackNapi::~GnssStatusCallbackNapi()
{
}
int GnssStatusCallbackHost::OnRemoteRequest(
int GnssStatusCallbackNapi::OnRemoteRequest(
uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option)
{
LBSLOGD(GNSS_STATUS_CALLBACK, "GnssStatusCallbackHost::OnRemoteRequest!");
LBSLOGD(GNSS_STATUS_CALLBACK, "GnssStatusCallbackNapi::OnRemoteRequest!");
if (data.ReadInterfaceToken() != GetDescriptor()) {
LBSLOGE(GNSS_STATUS_CALLBACK, "invalid token.");
return -1;
@ -63,12 +64,12 @@ int GnssStatusCallbackHost::OnRemoteRequest(
return 0;
}
bool GnssStatusCallbackHost::IsRemoteDied()
bool GnssStatusCallbackNapi::IsRemoteDied()
{
return remoteDied_;
}
bool GnssStatusCallbackHost::Send(std::unique_ptr<SatelliteStatus>& statusInfo)
bool GnssStatusCallbackNapi::Send(std::unique_ptr<SatelliteStatus>& statusInfo)
{
std::unique_lock<std::mutex> guard(mutex_);
uv_loop_s *loop = nullptr;
@ -77,6 +78,10 @@ bool GnssStatusCallbackHost::Send(std::unique_ptr<SatelliteStatus>& statusInfo)
LBSLOGE(GNSS_STATUS_CALLBACK, "loop == nullptr.");
return false;
}
if (handlerCb_ == nullptr) {
LBSLOGE(GNSS_STATUS_CALLBACK, "handler is nullptr.");
return false;
}
uv_work_t *work = new (std::nothrow) uv_work_t;
if (work == nullptr) {
LBSLOGE(GNSS_STATUS_CALLBACK, "work == nullptr.");
@ -88,15 +93,17 @@ bool GnssStatusCallbackHost::Send(std::unique_ptr<SatelliteStatus>& statusInfo)
delete work;
return false;
}
context->env = env_;
context->callback[SUCCESS_CALLBACK] = handlerCb_;
if (!InitContext(context)) {
LBSLOGE(GNSS_STATUS_CALLBACK, "InitContext fail");
return false;
}
context->statusInfo = std::move(statusInfo);
work->data = context;
UvQueueWork(loop, work);
return true;
}
void GnssStatusCallbackHost::UvQueueWork(uv_loop_s* loop, uv_work_t* work)
void GnssStatusCallbackNapi::UvQueueWork(uv_loop_s* loop, uv_work_t* work)
{
uv_queue_work(
loop,
@ -110,7 +117,7 @@ void GnssStatusCallbackHost::UvQueueWork(uv_loop_s* loop, uv_work_t* work)
return;
}
context = static_cast<GnssStatusAsyncContext *>(work->data);
if (context == nullptr || context->env == nullptr) {
if (context == nullptr || context->env == nullptr || context->callbackValid == nullptr) {
LBSLOGE(LOCATOR_CALLBACK, "context is nullptr!");
delete work;
return;
@ -128,7 +135,7 @@ void GnssStatusCallbackHost::UvQueueWork(uv_loop_s* loop, uv_work_t* work)
scope, context, work);
SatelliteStatusToJs(context->env, context->statusInfo, jsEvent);
}
if (context->callback[0] != nullptr) {
if (context->callback[0] != nullptr && *(context->callbackValid)) {
napi_value undefine;
napi_value handler = nullptr;
CHK_NAPI_ERR_CLOSE_SCOPE(context->env, napi_get_undefined(context->env, &undefine),
@ -146,27 +153,21 @@ void GnssStatusCallbackHost::UvQueueWork(uv_loop_s* loop, uv_work_t* work)
});
}
void GnssStatusCallbackHost::OnStatusChange(const std::unique_ptr<SatelliteStatus>& statusInfo)
void GnssStatusCallbackNapi::OnStatusChange(const std::unique_ptr<SatelliteStatus>& statusInfo)
{
LBSLOGD(GNSS_STATUS_CALLBACK, "GnssStatusCallbackHost::OnStatusChange");
LBSLOGD(GNSS_STATUS_CALLBACK, "GnssStatusCallbackNapi::OnStatusChange");
}
void GnssStatusCallbackHost::DeleteHandler()
void GnssStatusCallbackNapi::DeleteHandler()
{
std::unique_lock<std::mutex> guard(mutex_);
if (handlerCb_ == nullptr || env_ == nullptr) {
LBSLOGE(GNSS_STATUS_CALLBACK, "handler or env is nullptr.");
return;
}
auto context = new (std::nothrow) AsyncContext(env_);
if (context == nullptr) {
LBSLOGE(GNSS_STATUS_CALLBACK, "context == nullptr.");
return;
}
context->env = env_;
context->callback[SUCCESS_CALLBACK] = handlerCb_;
DeleteQueueWork(context);
NAPI_CALL_RETURN_VOID(env_, napi_delete_reference(env_, handlerCb_));
handlerCb_ = nullptr;
callbackValid_ = false;
}
} // namespace Location
} // namespace OHOS

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2023 Huawei Device Co., Ltd.
* Copyright (C) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -12,7 +12,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "locating_required_data_callback_host.h"
#include "locating_required_data_callback_napi.h"
#include "ipc_skeleton.h"
#include "napi/native_common.h"
@ -23,16 +23,17 @@
namespace OHOS {
namespace Location {
LocatingRequiredDataCallbackHost::LocatingRequiredDataCallbackHost()
LocatingRequiredDataCallbackNapi::LocatingRequiredDataCallbackNapi()
{
env_ = nullptr;
handlerCb_ = nullptr;
remoteDied_ = false;
fixNumber_ = 0;
InitLatch();
callbackValid_ = false;
}
LocatingRequiredDataCallbackHost::~LocatingRequiredDataCallbackHost()
LocatingRequiredDataCallbackNapi::~LocatingRequiredDataCallbackNapi()
{
if (latch_ != nullptr) {
delete latch_;
@ -40,16 +41,16 @@ LocatingRequiredDataCallbackHost::~LocatingRequiredDataCallbackHost()
}
}
void LocatingRequiredDataCallbackHost::InitLatch()
void LocatingRequiredDataCallbackNapi::InitLatch()
{
latch_ = new CountDownLatch();
latch_->SetCount(1);
}
int LocatingRequiredDataCallbackHost::OnRemoteRequest(
int LocatingRequiredDataCallbackNapi::OnRemoteRequest(
uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option)
{
LBSLOGD(LOCATING_DATA_CALLBACK, "LocatingRequiredDataCallbackHost::OnRemoteRequest!");
LBSLOGD(LOCATING_DATA_CALLBACK, "LocatingRequiredDataCallbackNapi::OnRemoteRequest!");
if (data.ReadInterfaceToken() != GetDescriptor()) {
LBSLOGE(LOCATING_DATA_CALLBACK, "invalid token.");
return -1;
@ -84,12 +85,12 @@ int LocatingRequiredDataCallbackHost::OnRemoteRequest(
return 0;
}
bool LocatingRequiredDataCallbackHost::IsRemoteDied()
bool LocatingRequiredDataCallbackNapi::IsRemoteDied()
{
return remoteDied_;
}
bool LocatingRequiredDataCallbackHost::Send(const std::vector<std::shared_ptr<LocatingRequiredData>>& data)
bool LocatingRequiredDataCallbackNapi::Send(const std::vector<std::shared_ptr<LocatingRequiredData>>& data)
{
if (IsSingleLocationRequest()) {
return false;
@ -101,6 +102,10 @@ bool LocatingRequiredDataCallbackHost::Send(const std::vector<std::shared_ptr<Lo
LBSLOGE(LOCATING_DATA_CALLBACK, "loop == nullptr.");
return false;
}
if (handlerCb_ == nullptr) {
LBSLOGE(LOCATING_DATA_CALLBACK, "handler is nullptr.");
return false;
}
uv_work_t *work = new (std::nothrow) uv_work_t;
if (work == nullptr) {
LBSLOGE(LOCATING_DATA_CALLBACK, "work == nullptr.");
@ -112,15 +117,17 @@ bool LocatingRequiredDataCallbackHost::Send(const std::vector<std::shared_ptr<Lo
delete work;
return false;
}
context->env = env_;
context->callback[SUCCESS_CALLBACK] = handlerCb_;
if (!InitContext(context)) {
LBSLOGE(LOCATING_DATA_CALLBACK, "InitContext fail");
return false;
}
context->locatingRequiredDataList_ = data;
work->data = context;
UvQueueWork(loop, work);
return true;
}
void LocatingRequiredDataCallbackHost::UvQueueWork(uv_loop_s* loop, uv_work_t* work)
void LocatingRequiredDataCallbackNapi::UvQueueWork(uv_loop_s* loop, uv_work_t* work)
{
uv_queue_work(
loop,
@ -134,7 +141,7 @@ void LocatingRequiredDataCallbackHost::UvQueueWork(uv_loop_s* loop, uv_work_t* w
return;
}
context = static_cast<LocatingRequiredDataAsyncContext *>(work->data);
if (context == nullptr || context->env == nullptr) {
if (context == nullptr || context->env == nullptr || context->callbackValid == nullptr) {
LBSLOGE(LOCATING_DATA_CALLBACK, "context is nullptr");
delete work;
return;
@ -151,7 +158,7 @@ void LocatingRequiredDataCallbackHost::UvQueueWork(uv_loop_s* loop, uv_work_t* w
napi_create_array_with_length(context->env, context->locatingRequiredDataList_.size(), &jsEvent),
scope, context, work);
LocatingRequiredDataToJsObj(context->env, context->locatingRequiredDataList_, jsEvent);
if (context->callback[0] != nullptr) {
if (context->callback[0] != nullptr && *(context->callbackValid)) {
napi_value undefine;
napi_value handler = nullptr;
CHK_NAPI_ERR_CLOSE_SCOPE(context->env, napi_get_undefined(context->env, &undefine),
@ -169,51 +176,45 @@ void LocatingRequiredDataCallbackHost::UvQueueWork(uv_loop_s* loop, uv_work_t* w
});
}
void LocatingRequiredDataCallbackHost::OnLocatingDataChange(
void LocatingRequiredDataCallbackNapi::OnLocatingDataChange(
const std::vector<std::shared_ptr<LocatingRequiredData>>& data)
{
LBSLOGD(LOCATING_DATA_CALLBACK, "LocatingRequiredDataCallbackHost::OnLocatingDataChange");
LBSLOGD(LOCATING_DATA_CALLBACK, "LocatingRequiredDataCallbackNapi::OnLocatingDataChange");
Send(data);
}
void LocatingRequiredDataCallbackHost::DeleteHandler()
void LocatingRequiredDataCallbackNapi::DeleteHandler()
{
std::unique_lock<std::mutex> guard(mutex_);
if (handlerCb_ == nullptr || env_ == nullptr) {
LBSLOGE(LOCATING_DATA_CALLBACK, "handler or env is nullptr.");
return;
}
auto context = new (std::nothrow) AsyncContext(env_);
if (context == nullptr) {
LBSLOGE(LOCATING_DATA_CALLBACK, "context == nullptr.");
return;
}
context->env = env_;
context->callback[SUCCESS_CALLBACK] = handlerCb_;
DeleteQueueWork(context);
NAPI_CALL_RETURN_VOID(env_, napi_delete_reference(env_, handlerCb_));
handlerCb_ = nullptr;
callbackValid_ = false;
}
bool LocatingRequiredDataCallbackHost::IsSingleLocationRequest()
bool LocatingRequiredDataCallbackNapi::IsSingleLocationRequest()
{
return (fixNumber_ == 1);
}
void LocatingRequiredDataCallbackHost::CountDown()
void LocatingRequiredDataCallbackNapi::CountDown()
{
if (IsSingleLocationRequest() && latch_ != nullptr) {
latch_->CountDown();
}
}
void LocatingRequiredDataCallbackHost::Wait(int time)
void LocatingRequiredDataCallbackNapi::Wait(int time)
{
if (IsSingleLocationRequest() && latch_ != nullptr) {
latch_->Wait(time);
}
}
int LocatingRequiredDataCallbackHost::GetCount()
int LocatingRequiredDataCallbackNapi::GetCount()
{
if (IsSingleLocationRequest() && latch_ != nullptr) {
return latch_->GetCount();
@ -221,20 +222,20 @@ int LocatingRequiredDataCallbackHost::GetCount()
return 0;
}
void LocatingRequiredDataCallbackHost::SetCount(int count)
void LocatingRequiredDataCallbackNapi::SetCount(int count)
{
if (IsSingleLocationRequest() && latch_ != nullptr) {
return latch_->SetCount(count);
}
}
void LocatingRequiredDataCallbackHost::ClearSingleResult()
void LocatingRequiredDataCallbackNapi::ClearSingleResult()
{
std::unique_lock<std::mutex> guard(singleResultMutex_);
singleResult_.clear();
}
void LocatingRequiredDataCallbackHost::SetSingleResult(
void LocatingRequiredDataCallbackNapi::SetSingleResult(
std::vector<std::shared_ptr<LocatingRequiredData>> singleResult)
{
std::unique_lock<std::mutex> guard(singleResultMutex_);

View File

@ -13,7 +13,7 @@
* limitations under the License.
*/
#include "location_error_callback_host.h"
#include "location_error_callback_napi.h"
#include "common_utils.h"
#include "ipc_skeleton.h"
#include "location_log.h"
@ -23,22 +23,23 @@
namespace OHOS {
namespace Location {
LocationErrorCallbackHost::LocationErrorCallbackHost()
LocationErrorCallbackNapi::LocationErrorCallbackNapi()
{
env_ = nullptr;
handlerCb_ = nullptr;
callbackValid_ = false;
}
LocationErrorCallbackHost::~LocationErrorCallbackHost()
LocationErrorCallbackNapi::~LocationErrorCallbackNapi()
{
}
int LocationErrorCallbackHost::OnRemoteRequest(
int LocationErrorCallbackNapi::OnRemoteRequest(
uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option)
{
LBSLOGI(LOCATOR_CALLBACK, "LocatorCallbackHost::OnRemoteRequest! code = %{public}d", code);
LBSLOGI(LOCATION_ERR_CALLBACK, "LocatorCallbackHost::OnRemoteRequest! code = %{public}d", code);
if (data.ReadInterfaceToken() != GetDescriptor()) {
LBSLOGE(LOCATOR_CALLBACK, "invalid token.");
LBSLOGE(LOCATION_ERR_CALLBACK, "invalid token.");
return -1;
}
@ -55,36 +56,42 @@ int LocationErrorCallbackHost::OnRemoteRequest(
return 0;
}
bool LocationErrorCallbackHost::Send(int32_t errorCode)
bool LocationErrorCallbackNapi::Send(int32_t errorCode)
{
LBSLOGI(LOCATOR_CALLBACK, "LocatorCallbackHost::OnRemoteRequest! errorCode = %{public}d", errorCode);
LBSLOGI(LOCATION_ERR_CALLBACK, "LocatorCallbackNapi::OnRemoteRequest! errorCode = %{public}d", errorCode);
std::unique_lock<std::mutex> guard(mutex_);
uv_loop_s *loop = nullptr;
NAPI_CALL_BASE(env_, napi_get_uv_event_loop(env_, &loop), false);
if (loop == nullptr) {
LBSLOGE(LOCATOR_CALLBACK, "loop == nullptr.");
LBSLOGE(LOCATION_ERR_CALLBACK, "loop == nullptr.");
return false;
}
if (handlerCb_ == nullptr) {
LBSLOGE(LOCATION_ERR_CALLBACK, "handler is nullptr.");
return false;
}
uv_work_t *work = new (std::nothrow) uv_work_t;
if (work == nullptr) {
LBSLOGE(LOCATOR_CALLBACK, "work == nullptr.");
LBSLOGE(LOCATION_ERR_CALLBACK, "work == nullptr.");
return false;
}
LocationErrorAsyncContext *context = new (std::nothrow) LocationErrorAsyncContext(env_);
if (context == nullptr) {
LBSLOGE(LOCATOR_CALLBACK, "context == nullptr.");
LBSLOGE(LOCATION_ERR_CALLBACK, "context == nullptr.");
delete work;
return false;
}
context->env = env_;
context->callback[SUCCESS_CALLBACK] = handlerCb_;
if (!InitContext(context)) {
LBSLOGE(LOCATION_ERR_CALLBACK, "InitContext fail");
return false;
}
context->errCode = errorCode;
work->data = context;
UvQueueWork(loop, work);
return true;
}
void LocationErrorCallbackHost::UvQueueWork(uv_loop_s* loop, uv_work_t* work)
void LocationErrorCallbackNapi::UvQueueWork(uv_loop_s* loop, uv_work_t* work)
{
uv_queue_work(
loop,
@ -94,12 +101,12 @@ void LocationErrorCallbackHost::UvQueueWork(uv_loop_s* loop, uv_work_t* work)
LocationErrorAsyncContext *context = nullptr;
napi_handle_scope scope = nullptr;
if (work == nullptr) {
LBSLOGE(LOCATOR_CALLBACK, "work is nullptr!");
LBSLOGE(LOCATION_ERR_CALLBACK, "work is nullptr!");
return;
}
context = static_cast<LocationErrorAsyncContext *>(work->data);
if (context == nullptr || context->env == nullptr) {
LBSLOGE(LOCATOR_CALLBACK, "context is nullptr!");
if (context == nullptr || context->env == nullptr || context->callbackValid == nullptr) {
LBSLOGE(LOCATION_ERR_CALLBACK, "context is nullptr!");
delete work;
return;
}
@ -108,12 +115,12 @@ void LocationErrorCallbackHost::UvQueueWork(uv_loop_s* loop, uv_work_t* work)
CHK_NAPI_ERR_CLOSE_SCOPE(context->env, napi_create_int32(context->env, context->errCode, &jsEvent),
scope, context, work);
if (scope == nullptr) {
LBSLOGE(LOCATOR_CALLBACK, "scope is nullptr");
LBSLOGE(LOCATION_ERR_CALLBACK, "scope is nullptr");
delete context;
delete work;
return;
}
if (context->callback[0] != nullptr) {
if (context->callback[0] != nullptr && *(context->callbackValid)) {
napi_value undefine;
napi_value handler = nullptr;
CHK_NAPI_ERR_CLOSE_SCOPE(context->env, napi_get_undefined(context->env, &undefine),
@ -122,7 +129,7 @@ void LocationErrorCallbackHost::UvQueueWork(uv_loop_s* loop, uv_work_t* work)
napi_get_reference_value(context->env, context->callback[0], &handler), scope, context, work);
if (napi_call_function(context->env, nullptr, handler, 1,
&jsEvent, &undefine) != napi_ok) {
LBSLOGE(LOCATOR_CALLBACK, "Report event failed");
LBSLOGE(LOCATION_ERR_CALLBACK, "Report event failed");
}
}
NAPI_CALL_RETURN_VOID(context->env, napi_close_handle_scope(context->env, scope));
@ -131,36 +138,30 @@ void LocationErrorCallbackHost::UvQueueWork(uv_loop_s* loop, uv_work_t* work)
});
}
void LocationErrorCallbackHost::OnLocationReport(const std::unique_ptr<Location>& location)
void LocationErrorCallbackNapi::OnLocationReport(const std::unique_ptr<Location>& location)
{
}
void LocationErrorCallbackHost::OnLocatingStatusChange(const int status)
void LocationErrorCallbackNapi::OnLocatingStatusChange(const int status)
{
}
void LocationErrorCallbackHost::OnErrorReport(const int errorCode)
void LocationErrorCallbackNapi::OnErrorReport(const int errorCode)
{
LBSLOGI(LOCATOR_CALLBACK, "LocatorCallbackHost::OnRemoteRequest! errorCode = %{public}d", errorCode);
LBSLOGI(LOCATION_ERR_CALLBACK, "LocatorCallbackNapi::OnRemoteRequest! errorCode = %{public}d", errorCode);
Send(errorCode);
}
void LocationErrorCallbackHost::DeleteHandler()
void LocationErrorCallbackNapi::DeleteHandler()
{
std::unique_lock<std::mutex> guard(mutex_);
if (handlerCb_ == nullptr || env_ == nullptr) {
LBSLOGE(LOCATOR_CALLBACK, "handler or env is nullptr.");
LBSLOGE(LOCATION_ERR_CALLBACK, "handler or env is nullptr.");
return;
}
auto context = new (std::nothrow) AsyncContext(env_);
if (context == nullptr) {
LBSLOGE(LOCATOR_CALLBACK, "context == nullptr.");
return;
}
context->env = env_;
context->callback[SUCCESS_CALLBACK] = handlerCb_;
DeleteQueueWork(context);
NAPI_CALL_RETURN_VOID(env_, napi_delete_reference(env_, handlerCb_));
handlerCb_ = nullptr;
callbackValid_ = false;
}
} // namespace Location
} // namespace OHOS

View File

@ -12,7 +12,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "location_gnss_geofence_callback_host.h"
#include "location_gnss_geofence_callback_napi.h"
#include "ipc_skeleton.h"
#include "napi/native_common.h"
@ -26,7 +26,7 @@
namespace OHOS {
namespace Location {
LocationGnssGeofenceCallbackHost::LocationGnssGeofenceCallbackHost()
LocationGnssGeofenceCallbackNapi::LocationGnssGeofenceCallbackNapi()
{
env_ = nullptr;
handlerCb_ = nullptr;
@ -34,10 +34,11 @@ LocationGnssGeofenceCallbackHost::LocationGnssGeofenceCallbackHost()
fenceId_ = -1;
type_ = GNSS_GEOFENCE_OPT_TYPE_ADD;
result_ = GNSS_GEOFENCE_OPERATION_SUCCESS;
callbackValid_ = false;
InitLatch();
}
LocationGnssGeofenceCallbackHost::~LocationGnssGeofenceCallbackHost()
LocationGnssGeofenceCallbackNapi::~LocationGnssGeofenceCallbackNapi()
{
if (latch_ != nullptr) {
delete latch_;
@ -45,13 +46,13 @@ LocationGnssGeofenceCallbackHost::~LocationGnssGeofenceCallbackHost()
}
}
void LocationGnssGeofenceCallbackHost::InitLatch()
void LocationGnssGeofenceCallbackNapi::InitLatch()
{
latch_ = new CountDownLatch();
latch_->SetCount(1);
}
int LocationGnssGeofenceCallbackHost::OnRemoteRequest(
int LocationGnssGeofenceCallbackNapi::OnRemoteRequest(
uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option)
{
LBSLOGD(LOCATION_GNSS_GEOFENCE_CALLBACK, "OnRemoteRequest enter");
@ -88,7 +89,7 @@ int LocationGnssGeofenceCallbackHost::OnRemoteRequest(
return 0;
}
void LocationGnssGeofenceCallbackHost::OnTransitionStatusChange(
void LocationGnssGeofenceCallbackNapi::OnTransitionStatusChange(
GeofenceTransition transition)
{
std::unique_lock<std::mutex> guard(mutex_);
@ -98,6 +99,10 @@ void LocationGnssGeofenceCallbackHost::OnTransitionStatusChange(
LBSLOGE(LOCATION_GNSS_GEOFENCE_CALLBACK, "loop == nullptr.");
return;
}
if (handlerCb_ == nullptr) {
LBSLOGE(LOCATION_GNSS_GEOFENCE_CALLBACK, "handler is nullptr.");
return;
}
uv_work_t *work = new (std::nothrow) uv_work_t;
if (work == nullptr) {
LBSLOGE(LOCATION_GNSS_GEOFENCE_CALLBACK, "work == nullptr.");
@ -109,14 +114,16 @@ void LocationGnssGeofenceCallbackHost::OnTransitionStatusChange(
delete work;
return;
}
context->env = env_;
context->callback[SUCCESS_CALLBACK] = handlerCb_;
if (!InitContext(context)) {
LBSLOGE(LOCATION_GNSS_GEOFENCE_CALLBACK, "InitContext fail");
return;
}
context->transition_ = transition;
work->data = context;
UvQueueWork(loop, work);
}
void LocationGnssGeofenceCallbackHost::OnReportOperationResult(int fenceId, int type, int result)
void LocationGnssGeofenceCallbackNapi::OnReportOperationResult(int fenceId, int type, int result)
{
int addValue = static_cast<int>(GnssGeofenceOperateType::GNSS_GEOFENCE_OPT_TYPE_ADD);
if ((type != addValue && fenceId == GetFenceId()) ||
@ -132,12 +139,12 @@ void LocationGnssGeofenceCallbackHost::OnReportOperationResult(int fenceId, int
}
}
bool LocationGnssGeofenceCallbackHost::IsRemoteDied()
bool LocationGnssGeofenceCallbackNapi::IsRemoteDied()
{
return remoteDied_;
}
void LocationGnssGeofenceCallbackHost::UvQueueWork(uv_loop_s* loop, uv_work_t* work)
void LocationGnssGeofenceCallbackNapi::UvQueueWork(uv_loop_s* loop, uv_work_t* work)
{
uv_queue_work(
loop, work, [](uv_work_t *work) {}, [](uv_work_t *work, int status) {
@ -148,7 +155,7 @@ void LocationGnssGeofenceCallbackHost::UvQueueWork(uv_loop_s* loop, uv_work_t* w
return;
}
context = static_cast<GnssGeofenceAsyncContext *>(work->data);
if (context == nullptr || context->env == nullptr) {
if (context == nullptr || context->env == nullptr || context->callbackValid == nullptr) {
LBSLOGE(LOCATION_GNSS_GEOFENCE_CALLBACK, "context is nullptr");
delete work;
return;
@ -166,7 +173,7 @@ void LocationGnssGeofenceCallbackHost::UvQueueWork(uv_loop_s* loop, uv_work_t* w
CHK_NAPI_ERR_CLOSE_SCOPE(context->env, napi_get_undefined(context->env, &jsEvent[PARAM0]),
scope, context, work);
GeofenceTransitionToJs(context->env, context->transition_, jsEvent[PARAM1]);
if (context->callback[SUCCESS_CALLBACK] != nullptr) {
if (context->callback[SUCCESS_CALLBACK] != nullptr && *(context->callbackValid)) {
napi_value undefine;
napi_value handler = nullptr;
CHK_NAPI_ERR_CLOSE_SCOPE(context->env, napi_get_undefined(context->env, &undefine),
@ -185,39 +192,33 @@ void LocationGnssGeofenceCallbackHost::UvQueueWork(uv_loop_s* loop, uv_work_t* w
});
}
void LocationGnssGeofenceCallbackHost::DeleteHandler()
void LocationGnssGeofenceCallbackNapi::DeleteHandler()
{
std::unique_lock<std::mutex> guard(mutex_);
if (handlerCb_ == nullptr || env_ == nullptr) {
LBSLOGE(LOCATION_GNSS_GEOFENCE_CALLBACK, "handler or env is nullptr.");
return;
}
auto context = new (std::nothrow) AsyncContext(env_);
if (context == nullptr) {
LBSLOGE(LOCATION_GNSS_GEOFENCE_CALLBACK, "context == nullptr.");
return;
}
context->env = env_;
context->callback[SUCCESS_CALLBACK] = handlerCb_;
DeleteQueueWork(context);
NAPI_CALL_RETURN_VOID(env_, napi_delete_reference(env_, handlerCb_));
handlerCb_ = nullptr;
callbackValid_ = false;
}
void LocationGnssGeofenceCallbackHost::CountDown()
void LocationGnssGeofenceCallbackNapi::CountDown()
{
if (latch_ != nullptr) {
latch_->CountDown();
}
}
void LocationGnssGeofenceCallbackHost::Wait(int time)
void LocationGnssGeofenceCallbackNapi::Wait(int time)
{
if (latch_ != nullptr) {
latch_->Wait(time);
}
}
int LocationGnssGeofenceCallbackHost::GetCount()
int LocationGnssGeofenceCallbackNapi::GetCount()
{
if (latch_ != nullptr) {
return latch_->GetCount();
@ -225,56 +226,56 @@ int LocationGnssGeofenceCallbackHost::GetCount()
return 0;
}
void LocationGnssGeofenceCallbackHost::SetCount(int count)
void LocationGnssGeofenceCallbackNapi::SetCount(int count)
{
if (latch_ != nullptr) {
return latch_->SetCount(count);
}
}
void LocationGnssGeofenceCallbackHost::ClearFenceId()
void LocationGnssGeofenceCallbackNapi::ClearFenceId()
{
std::unique_lock<std::mutex> guard(operationResultMutex_);
fenceId_ = -1;
}
int LocationGnssGeofenceCallbackHost::GetFenceId()
int LocationGnssGeofenceCallbackNapi::GetFenceId()
{
std::unique_lock<std::mutex> guard(operationResultMutex_);
return fenceId_;
}
void LocationGnssGeofenceCallbackHost::SetFenceId(int fenceId)
void LocationGnssGeofenceCallbackNapi::SetFenceId(int fenceId)
{
std::unique_lock<std::mutex> guard(operationResultMutex_);
fenceId_ = fenceId;
}
GnssGeofenceOperateType LocationGnssGeofenceCallbackHost::GetGeofenceOperationType()
GnssGeofenceOperateType LocationGnssGeofenceCallbackNapi::GetGeofenceOperationType()
{
std::unique_lock<std::mutex> guard(operationResultMutex_);
return type_;
}
void LocationGnssGeofenceCallbackHost::SetGeofenceOperationType(GnssGeofenceOperateType type)
void LocationGnssGeofenceCallbackNapi::SetGeofenceOperationType(GnssGeofenceOperateType type)
{
std::unique_lock<std::mutex> guard(operationResultMutex_);
type_ = type;
}
GnssGeofenceOperateResult LocationGnssGeofenceCallbackHost::GetGeofenceOperationResult()
GnssGeofenceOperateResult LocationGnssGeofenceCallbackNapi::GetGeofenceOperationResult()
{
std::unique_lock<std::mutex> guard(operationResultMutex_);
return result_;
}
void LocationGnssGeofenceCallbackHost::SetGeofenceOperationResult(GnssGeofenceOperateResult result)
void LocationGnssGeofenceCallbackNapi::SetGeofenceOperationResult(GnssGeofenceOperateResult result)
{
std::unique_lock<std::mutex> guard(operationResultMutex_);
result_ = result;
}
LocationErrCode LocationGnssGeofenceCallbackHost::DealGeofenceOperationResult()
LocationErrCode LocationGnssGeofenceCallbackNapi::DealGeofenceOperationResult()
{
std::unique_lock<std::mutex> guard(operationResultMutex_);
LocationErrCode errCode = ERRCODE_SUCCESS;

View File

@ -25,7 +25,7 @@ namespace OHOS {
namespace Location {
auto g_locatorClient = Locator::GetInstance();
auto g_geofenceClient = GeofenceManager::GetInstance();
std::map<int, sptr<LocationGnssGeofenceCallbackHost>> g_gnssGeofenceCallbackHostMap;
std::map<int, sptr<LocationGnssGeofenceCallbackNapi>> g_gnssGeofenceCallbackHostMap;
std::mutex g_gnssGeofenceCallbackHostMutex;
napi_value GetLastLocation(napi_env env, napi_callback_info info)
@ -942,10 +942,10 @@ LocationErrCode CheckLocationSwitchState()
return ERRCODE_SUCCESS;
}
sptr<LocatingRequiredDataCallbackHost> CreateSingleCallbackHost()
sptr<LocatingRequiredDataCallbackNapi> CreateSingleCallbackHost()
{
auto callbackHost =
sptr<LocatingRequiredDataCallbackHost>(new (std::nothrow) LocatingRequiredDataCallbackHost());
sptr<LocatingRequiredDataCallbackNapi>(new (std::nothrow) LocatingRequiredDataCallbackNapi());
if (callbackHost) {
callbackHost->SetFixNumber(1);
}
@ -953,7 +953,7 @@ sptr<LocatingRequiredDataCallbackHost> CreateSingleCallbackHost()
}
SingleScanAsyncContext* CreateSingleScanAsyncContext(const napi_env& env,
std::unique_ptr<LocatingRequiredDataConfig>& config, sptr<LocatingRequiredDataCallbackHost> callback)
std::unique_ptr<LocatingRequiredDataConfig>& config, sptr<LocatingRequiredDataCallbackNapi> callback)
{
auto asyncContext = new (std::nothrow) SingleScanAsyncContext(env);
NAPI_ASSERT(env, asyncContext != nullptr, "asyncContext is null.");
@ -1048,7 +1048,7 @@ napi_value GetLocatingRequiredData(napi_env env, napi_callback_info info)
napi_value AddGnssGeofence(napi_env env, napi_callback_info info)
{
LBSLOGD(LOCATOR_STANDARD, "%{public}s called.", __func__);
LBSLOGI(LOCATOR_STANDARD, "%{public}s called.", __func__);
size_t argc = MAXIMUM_JS_PARAMS;
napi_value argv[MAXIMUM_JS_PARAMS];
napi_value thisVar = nullptr;
@ -1066,7 +1066,7 @@ napi_value AddGnssGeofence(napi_env env, napi_callback_info info)
return UndefinedNapiValue(env);
}
auto locationGnssGeofenceCallbackHost =
sptr<LocationGnssGeofenceCallbackHost>(new (std::nothrow) LocationGnssGeofenceCallbackHost());
sptr<LocationGnssGeofenceCallbackNapi>(new (std::nothrow) LocationGnssGeofenceCallbackNapi());
JsObjToGeofenceTransitionCallback(env, argv[0], locationGnssGeofenceCallbackHost);
auto callbackPtr = sptr<IGnssGeofenceCallback>(locationGnssGeofenceCallbackHost);
gnssGeofenceRequest->SetGeofenceTransitionCallback(callbackPtr->AsObject());
@ -1080,7 +1080,7 @@ napi_value AddGnssGeofence(napi_env env, napi_callback_info info)
}
GnssGeofenceAsyncContext* CreateAsyncContextForAddGnssGeofence(const napi_env& env,
std::shared_ptr<GeofenceRequest>& request, sptr<LocationGnssGeofenceCallbackHost> callback)
std::shared_ptr<GeofenceRequest>& request, sptr<LocationGnssGeofenceCallbackNapi> callback)
{
auto asyncContext = new (std::nothrow) GnssGeofenceAsyncContext(env);
NAPI_ASSERT(env, asyncContext != nullptr, "asyncContext is null.");
@ -1094,8 +1094,7 @@ GnssGeofenceAsyncContext* CreateAsyncContextForAddGnssGeofence(const napi_env& e
auto context = static_cast<GnssGeofenceAsyncContext*>(data);
auto callbackHost = context->callbackHost_;
auto gnssGeofenceRequest = context->request_;
if (callbackHost != nullptr || gnssGeofenceRequest != nullptr) {
auto callbackPtr = sptr<IGnssGeofenceCallback>(callbackHost);
if (callbackHost != nullptr && gnssGeofenceRequest != nullptr) {
auto errCode = g_geofenceClient->AddGnssGeofence(gnssGeofenceRequest);
if (errCode != ERRCODE_SUCCESS) {
context->errCode = errCode;
@ -1132,7 +1131,7 @@ GnssGeofenceAsyncContext* CreateAsyncContextForAddGnssGeofence(const napi_env& e
napi_value RemoveGnssGeofence(napi_env env, napi_callback_info info)
{
LBSLOGD(LOCATOR_STANDARD, "%{public}s called.", __func__);
LBSLOGI(LOCATOR_STANDARD, "%{public}s called.", __func__);
size_t argc = MAXIMUM_JS_PARAMS;
napi_value argv[MAXIMUM_JS_PARAMS];
napi_value thisVar = nullptr;
@ -1237,7 +1236,7 @@ napi_value GetGeofenceSupportedCoordTypes(napi_env env, napi_callback_info info)
return res;
}
void AddCallbackToGnssGeofenceCallbackHostMap(int fenceId, sptr<LocationGnssGeofenceCallbackHost> callbackHost)
void AddCallbackToGnssGeofenceCallbackHostMap(int fenceId, sptr<LocationGnssGeofenceCallbackNapi> callbackHost)
{
std::unique_lock<std::mutex> lock(g_gnssGeofenceCallbackHostMutex);
g_gnssGeofenceCallbackHostMap.insert(std::make_pair(fenceId, callbackHost));
@ -1252,7 +1251,7 @@ void RemoveCallbackToGnssGeofenceCallbackHostMap(int fenceId)
}
}
sptr<LocationGnssGeofenceCallbackHost> FindCallbackInGnssGeofenceCallbackHostMap(int fenceId)
sptr<LocationGnssGeofenceCallbackNapi> FindCallbackInGnssGeofenceCallbackHostMap(int fenceId)
{
std::unique_lock<std::mutex> lock(g_gnssGeofenceCallbackHostMutex);
auto iter = g_gnssGeofenceCallbackHostMap.find(fenceId);

View File

@ -191,6 +191,33 @@ napi_value LocatingRequiredDataTypeConstructor(napi_env env)
return locatingPriority;
}
napi_value LocationSourceTypeConstructor(napi_env env)
{
napi_value locationSourceType = nullptr;
NAPI_CALL(env, napi_create_object(env, &locationSourceType));
SetEnumPropertyByInteger(env, locationSourceType, LocationSourceType::GNSS_TYPE, "GNSS");
SetEnumPropertyByInteger(env, locationSourceType, LocationSourceType::NETWORK_TYPE, "NETWORK");
SetEnumPropertyByInteger(env, locationSourceType, LocationSourceType::INDOOR_TYPE, "INDOOR");
SetEnumPropertyByInteger(env, locationSourceType, LocationSourceType::RTK_TYPE, "RTK");
return locationSourceType;
}
napi_value LocationErrorConstructor(napi_env env)
{
napi_value locationError = nullptr;
NAPI_CALL(env, napi_create_object(env, &locationError));
SetEnumPropertyByInteger(env, locationError, LocationErr::LOCATING_FAILED_DEFAULT, "LOCATING_FAILED_DEFAULT");
SetEnumPropertyByInteger(env, locationError,
LocationErr::LOCATING_FAILED_LOCATION_PERMISSION_DENIED, "LOCATING_FAILED_LOCATION_PERMISSION_DENIED");
SetEnumPropertyByInteger(env, locationError,
LocationErr::LOCATING_FAILED_BACKGROUND_PERMISSION_DENIED, "LOCATING_FAILED_BACKGROUND_PERMISSION_DENIED");
SetEnumPropertyByInteger(env, locationError,
LocationErr::LOCATING_FAILED_LOCATION_SWITCH_OFF, "LOCATING_FAILED_LOCATION_SWITCH_OFF");
SetEnumPropertyByInteger(env, locationError,
LocationErr::LOCATING_FAILED_INTERNET_ACCESS_FAILURE, "LOCATING_FAILED_INTERNET_ACCESS_FAILURE");
return locationError;
}
#ifndef ENABLE_NAPI_MANAGER
/*
* Module initialization function
@ -291,6 +318,8 @@ static napi_value InitManager(napi_env env, napi_value exports)
DECLARE_NAPI_PROPERTY("UserActivityScenario", UserActivityScenarioTypeConstructor(env)),
DECLARE_NAPI_PROPERTY("LocatingPriority", LocatingPriorityTypeConstructor(env)),
DECLARE_NAPI_PROPERTY("PowerConsumptionScenario", PowerConsumptionScenarioTypeConstructor(env)),
DECLARE_NAPI_PROPERTY("LocationSourceType", LocationSourceTypeConstructor(env)),
DECLARE_NAPI_PROPERTY("LocationError", LocationErrorConstructor(env)),
};
NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(napi_property_descriptor), desc));

View File

@ -18,7 +18,7 @@
#include "common_utils.h"
#include "location_log.h"
#include "location_napi_errcode.h"
#include "country_code_callback_host.h"
#include "country_code_callback_napi.h"
#include "locator.h"
#include "geofence_sdk.h"
#include "geofence_napi.h"
@ -30,14 +30,14 @@
namespace OHOS {
namespace Location {
CallbackManager<LocationSwitchCallbackHost> g_switchCallbacks;
CallbackManager<LocatorCallbackHost> g_locationCallbacks;
CallbackManager<GnssStatusCallbackHost> g_gnssStatusInfoCallbacks;
CallbackManager<NmeaMessageCallbackHost> g_nmeaCallbacks;
CallbackManager<CachedLocationsCallbackHost> g_cachedLocationCallbacks;
CallbackManager<CountryCodeCallbackHost> g_countryCodeCallbacks;
CallbackManager<LocatingRequiredDataCallbackHost> g_locatingRequiredDataCallbacks;
CallbackManager<LocationErrorCallbackHost> g_locationErrorCallbackHosts;
CallbackManager<LocationSwitchCallbackNapi> g_switchCallbacks;
CallbackManager<LocatorCallbackNapi> g_locationCallbacks;
CallbackManager<GnssStatusCallbackNapi> g_gnssStatusInfoCallbacks;
CallbackManager<NmeaMessageCallbackNapi> g_nmeaCallbacks;
CallbackManager<CachedLocationsCallbackNapi> g_cachedLocationCallbacks;
CallbackManager<CountryCodeCallbackNapi> g_countryCodeCallbacks;
CallbackManager<LocatingRequiredDataCallbackNapi> g_locatingRequiredDataCallbacks;
CallbackManager<LocationErrorCallbackNapi> g_locationErrorCallbackHosts;
std::unique_ptr<CachedGnssLocationsRequest> g_cachedRequest = std::make_unique<CachedGnssLocationsRequest>();
auto g_locatorProxy = Locator::GetInstance();
@ -115,7 +115,7 @@ void InitOffFuncMap()
}
void SubscribeLocationServiceState(const napi_env& env,
const napi_ref& handlerRef, sptr<LocationSwitchCallbackHost>& switchCallbackHost)
const napi_ref& handlerRef, sptr<LocationSwitchCallbackNapi>& switchCallbackHost)
{
switchCallbackHost->SetEnv(env);
switchCallbackHost->SetHandleCb(handlerRef);
@ -124,7 +124,7 @@ void SubscribeLocationServiceState(const napi_env& env,
#ifdef ENABLE_NAPI_MANAGER
LocationErrCode SubscribeLocationServiceStateV9(const napi_env& env,
const napi_ref& handlerRef, sptr<LocationSwitchCallbackHost>& switchCallbackHost)
const napi_ref& handlerRef, sptr<LocationSwitchCallbackNapi>& switchCallbackHost)
{
switchCallbackHost->SetEnv(env);
switchCallbackHost->SetHandleCb(handlerRef);
@ -133,7 +133,7 @@ LocationErrCode SubscribeLocationServiceStateV9(const napi_env& env,
#endif
void SubscribeGnssStatus(const napi_env& env, const napi_ref& handlerRef,
sptr<GnssStatusCallbackHost>& gnssStatusCallbackHost)
sptr<GnssStatusCallbackNapi>& gnssStatusCallbackHost)
{
gnssStatusCallbackHost->SetEnv(env);
gnssStatusCallbackHost->SetHandleCb(handlerRef);
@ -142,7 +142,7 @@ void SubscribeGnssStatus(const napi_env& env, const napi_ref& handlerRef,
#ifdef ENABLE_NAPI_MANAGER
LocationErrCode SubscribeGnssStatusV9(const napi_env& env, const napi_ref& handlerRef,
sptr<GnssStatusCallbackHost>& gnssStatusCallbackHost)
sptr<GnssStatusCallbackNapi>& gnssStatusCallbackHost)
{
LocationErrCode errorCode = CheckLocationSwitchEnable();
if (errorCode != ERRCODE_SUCCESS) {
@ -155,7 +155,7 @@ LocationErrCode SubscribeGnssStatusV9(const napi_env& env, const napi_ref& handl
#endif
void SubscribeNmeaMessage(const napi_env& env, const napi_ref& handlerRef,
sptr<NmeaMessageCallbackHost>& nmeaMessageCallbackHost)
sptr<NmeaMessageCallbackNapi>& nmeaMessageCallbackHost)
{
nmeaMessageCallbackHost->SetEnv(env);
nmeaMessageCallbackHost->SetHandleCb(handlerRef);
@ -164,7 +164,7 @@ void SubscribeNmeaMessage(const napi_env& env, const napi_ref& handlerRef,
#ifdef ENABLE_NAPI_MANAGER
LocationErrCode SubscribeNmeaMessageV9(const napi_env& env, const napi_ref& handlerRef,
sptr<NmeaMessageCallbackHost>& nmeaMessageCallbackHost)
sptr<NmeaMessageCallbackNapi>& nmeaMessageCallbackHost)
{
LocationErrCode errorCode = CheckLocationSwitchEnable();
if (errorCode != ERRCODE_SUCCESS) {
@ -176,42 +176,42 @@ LocationErrCode SubscribeNmeaMessageV9(const napi_env& env, const napi_ref& hand
}
#endif
void UnSubscribeLocationServiceState(sptr<LocationSwitchCallbackHost>& switchCallbackHost)
void UnSubscribeLocationServiceState(sptr<LocationSwitchCallbackNapi>& switchCallbackHost)
{
LBSLOGD(LOCATION_NAPI, "UnSubscribeLocationServiceState");
g_locatorProxy->UnregisterSwitchCallback(switchCallbackHost->AsObject());
}
#ifdef ENABLE_NAPI_MANAGER
LocationErrCode UnSubscribeLocationServiceStateV9(sptr<LocationSwitchCallbackHost>& switchCallbackHost)
LocationErrCode UnSubscribeLocationServiceStateV9(sptr<LocationSwitchCallbackNapi>& switchCallbackHost)
{
LBSLOGD(LOCATION_NAPI, "UnSubscribeLocationServiceStateV9");
return g_locatorProxy->UnregisterSwitchCallbackV9(switchCallbackHost->AsObject());
}
#endif
void UnSubscribeGnssStatus(sptr<GnssStatusCallbackHost>& gnssStatusCallbackHost)
void UnSubscribeGnssStatus(sptr<GnssStatusCallbackNapi>& gnssStatusCallbackHost)
{
LBSLOGD(LOCATION_NAPI, "UnSubscribeGnssStatus");
g_locatorProxy->UnregisterGnssStatusCallback(gnssStatusCallbackHost->AsObject());
}
#ifdef ENABLE_NAPI_MANAGER
LocationErrCode UnSubscribeGnssStatusV9(sptr<GnssStatusCallbackHost>& gnssStatusCallbackHost)
LocationErrCode UnSubscribeGnssStatusV9(sptr<GnssStatusCallbackNapi>& gnssStatusCallbackHost)
{
LBSLOGD(LOCATION_NAPI, "UnSubscribeGnssStatusV9");
return g_locatorProxy->UnregisterGnssStatusCallbackV9(gnssStatusCallbackHost->AsObject());
}
#endif
void UnSubscribeNmeaMessage(sptr<NmeaMessageCallbackHost>& nmeaMessageCallbackHost)
void UnSubscribeNmeaMessage(sptr<NmeaMessageCallbackNapi>& nmeaMessageCallbackHost)
{
LBSLOGD(LOCATION_NAPI, "UnSubscribeNmeaMessage");
g_locatorProxy->UnregisterNmeaMessageCallback(nmeaMessageCallbackHost->AsObject());
}
#ifdef ENABLE_NAPI_MANAGER
LocationErrCode UnSubscribeNmeaMessageV9(sptr<NmeaMessageCallbackHost>& nmeaMessageCallbackHost)
LocationErrCode UnSubscribeNmeaMessageV9(sptr<NmeaMessageCallbackNapi>& nmeaMessageCallbackHost)
{
LBSLOGD(LOCATION_NAPI, "UnSubscribeNmeaMessageV9");
return g_locatorProxy->UnregisterNmeaMessageCallbackV9(nmeaMessageCallbackHost->AsObject());
@ -219,7 +219,7 @@ LocationErrCode UnSubscribeNmeaMessageV9(sptr<NmeaMessageCallbackHost>& nmeaMess
#endif
void SubscribeLocationChange(const napi_env& env, const napi_value& object,
const napi_ref& handlerRef, sptr<LocatorCallbackHost>& locatorCallbackHost)
const napi_ref& handlerRef, sptr<LocatorCallbackNapi>& locatorCallbackHost)
{
auto locatorCallback = sptr<ILocatorCallback>(locatorCallbackHost);
locatorCallbackHost->SetFixNumber(0);
@ -232,7 +232,7 @@ void SubscribeLocationChange(const napi_env& env, const napi_value& object,
#ifdef ENABLE_NAPI_MANAGER
LocationErrCode SubscribeLocationChangeV9(const napi_env& env, const napi_value& object,
const napi_ref& handlerRef, sptr<LocatorCallbackHost>& locatorCallbackHost)
const napi_ref& handlerRef, sptr<LocatorCallbackNapi>& locatorCallbackHost)
{
LocationErrCode errorCode = CheckLocationSwitchEnable();
if (errorCode != ERRCODE_SUCCESS) {
@ -252,7 +252,7 @@ LocationErrCode SubscribeLocationChangeV9(const napi_env& env, const napi_value&
#endif
void SubscribeCountryCodeChange(const napi_env& env,
const napi_ref& handlerRef, sptr<CountryCodeCallbackHost>& callbackHost)
const napi_ref& handlerRef, sptr<CountryCodeCallbackNapi>& callbackHost)
{
auto callbackPtr = sptr<ICountryCodeCallback>(callbackHost);
callbackHost->SetEnv(env);
@ -262,7 +262,7 @@ void SubscribeCountryCodeChange(const napi_env& env,
#ifdef ENABLE_NAPI_MANAGER
LocationErrCode SubscribeCountryCodeChangeV9(const napi_env& env,
const napi_ref& handlerRef, sptr<CountryCodeCallbackHost>& callbackHost)
const napi_ref& handlerRef, sptr<CountryCodeCallbackNapi>& callbackHost)
{
auto callbackPtr = sptr<ICountryCodeCallback>(callbackHost);
callbackHost->SetEnv(env);
@ -273,7 +273,7 @@ LocationErrCode SubscribeCountryCodeChangeV9(const napi_env& env,
#ifdef ENABLE_NAPI_MANAGER
LocationErrCode SubscribeLocatingRequiredDataChange(const napi_env& env, const napi_value& object,
const napi_ref& handlerRef, sptr<LocatingRequiredDataCallbackHost>& locatingCallbackHost)
const napi_ref& handlerRef, sptr<LocatingRequiredDataCallbackNapi>& locatingCallbackHost)
{
auto callbackPtr = sptr<ILocatingRequiredDataCallback>(locatingCallbackHost);
locatingCallbackHost->SetEnv(env);
@ -284,7 +284,7 @@ LocationErrCode SubscribeLocatingRequiredDataChange(const napi_env& env, const n
}
LocationErrCode SubscribeLocationError(const napi_env& env,
const napi_ref& handlerRef, sptr<LocationErrorCallbackHost>& locationErrorCallbackHost)
const napi_ref& handlerRef, sptr<LocationErrorCallbackNapi>& locationErrorCallbackHost)
{
locationErrorCallbackHost->SetEnv(env);
locationErrorCallbackHost->SetHandleCb(handlerRef);
@ -293,14 +293,14 @@ LocationErrCode SubscribeLocationError(const napi_env& env,
}
#endif
void UnsubscribeCountryCodeChange(sptr<CountryCodeCallbackHost>& callbackHost)
void UnsubscribeCountryCodeChange(sptr<CountryCodeCallbackNapi>& callbackHost)
{
LBSLOGD(LOCATION_NAPI, "UnsubscribeCountryCodeChange");
g_locatorProxy->UnregisterCountryCodeCallback(callbackHost->AsObject());
}
#ifdef ENABLE_NAPI_MANAGER
LocationErrCode UnsubscribeCountryCodeChangeV9(sptr<CountryCodeCallbackHost>& callbackHost)
LocationErrCode UnsubscribeCountryCodeChangeV9(sptr<CountryCodeCallbackNapi>& callbackHost)
{
LBSLOGD(LOCATION_NAPI, "UnsubscribeCountryCodeChangeV9");
return g_locatorProxy->UnregisterCountryCodeCallbackV9(callbackHost->AsObject());
@ -308,7 +308,7 @@ LocationErrCode UnsubscribeCountryCodeChangeV9(sptr<CountryCodeCallbackHost>& ca
#endif
void SubscribeCacheLocationChange(const napi_env& env, const napi_value& object,
const napi_ref& handlerRef, sptr<CachedLocationsCallbackHost>& cachedCallbackHost)
const napi_ref& handlerRef, sptr<CachedLocationsCallbackNapi>& cachedCallbackHost)
{
auto cachedCallback = sptr<ICachedLocationsCallback>(cachedCallbackHost);
cachedCallbackHost->SetEnv(env);
@ -319,7 +319,7 @@ void SubscribeCacheLocationChange(const napi_env& env, const napi_value& object,
#ifdef ENABLE_NAPI_MANAGER
LocationErrCode SubscribeCacheLocationChangeV9(const napi_env& env, const napi_value& object,
const napi_ref& handlerRef, sptr<CachedLocationsCallbackHost>& cachedCallbackHost)
const napi_ref& handlerRef, sptr<CachedLocationsCallbackNapi>& cachedCallbackHost)
{
LocationErrCode errorCode = CheckLocationSwitchEnable();
if (errorCode != ERRCODE_SUCCESS) {
@ -400,7 +400,7 @@ LocationErrCode UnSubscribeFenceStatusChangeV9(const napi_env& env, const napi_v
#endif
#ifdef ENABLE_NAPI_MANAGER
LocationErrCode UnSubscribeLocatingRequiredDataChange(sptr<LocatingRequiredDataCallbackHost>& callbackHost)
LocationErrCode UnSubscribeLocatingRequiredDataChange(sptr<LocatingRequiredDataCallbackNapi>& callbackHost)
{
LBSLOGD(LOCATION_NAPI, "%{public}s start", __func__);
auto callbackPtr = sptr<ILocatingRequiredDataCallback>(callbackHost);
@ -464,7 +464,7 @@ void GenerateCompleteContext(SingleLocationAsyncContext* context)
}
SingleLocationAsyncContext* CreateSingleLocationAsyncContext(const napi_env& env,
std::unique_ptr<RequestConfig>& config, sptr<LocatorCallbackHost> callback)
std::unique_ptr<RequestConfig>& config, sptr<LocatorCallbackNapi> callback)
{
auto asyncContext = new (std::nothrow) SingleLocationAsyncContext(env);
NAPI_ASSERT(env, asyncContext != nullptr, "asyncContext is null.");
@ -527,10 +527,10 @@ std::unique_ptr<RequestConfig> CreateRequestConfig(const napi_env& env,
return requestConfig;
}
sptr<LocatorCallbackHost> CreateSingleLocationCallbackHost()
sptr<LocatorCallbackNapi> CreateSingleLocationCallbackHost()
{
auto callbackHost =
sptr<LocatorCallbackHost>(new (std::nothrow) LocatorCallbackHost());
sptr<LocatorCallbackNapi>(new (std::nothrow) LocatorCallbackNapi());
if (callbackHost) {
callbackHost->SetFixNumber(1);
}
@ -651,7 +651,7 @@ bool OnLocationServiceStateCallback(const napi_env& env, const size_t argc, cons
return false;
}
auto switchCallbackHost =
sptr<LocationSwitchCallbackHost>(new (std::nothrow) LocationSwitchCallbackHost());
sptr<LocationSwitchCallbackNapi>(new (std::nothrow) LocationSwitchCallbackNapi());
if (switchCallbackHost != nullptr) {
napi_ref handlerRef = nullptr;
NAPI_CALL_BASE(env, napi_create_reference(env, argv[PARAM1], 1, &handlerRef), false);
@ -699,7 +699,7 @@ bool OnCachedGnssLocationsReportingCallback(const napi_env& env, const size_t ar
return false;
}
auto cachedCallbackHost =
sptr<CachedLocationsCallbackHost>(new (std::nothrow) CachedLocationsCallbackHost());
sptr<CachedLocationsCallbackNapi>(new (std::nothrow) CachedLocationsCallbackNapi());
if (cachedCallbackHost != nullptr) {
napi_ref handlerRef = nullptr;
NAPI_CALL_BASE(env, napi_create_reference(env, argv[PARAM2], PARAM1, &handlerRef), false);
@ -738,7 +738,7 @@ bool OnGnssStatusChangeCallback(const napi_env& env, const size_t argc, const na
return false;
}
auto gnssCallbackHost =
sptr<GnssStatusCallbackHost>(new (std::nothrow) GnssStatusCallbackHost());
sptr<GnssStatusCallbackNapi>(new (std::nothrow) GnssStatusCallbackNapi());
if (gnssCallbackHost != nullptr) {
napi_ref handlerRef = nullptr;
NAPI_CALL_BASE(env, napi_create_reference(env, argv[PARAM1], PARAM1, &handlerRef), false);
@ -787,7 +787,7 @@ bool OnLocationChangeCallback(const napi_env& env, const size_t argc, const napi
return false;
}
auto locatorCallbackHost =
sptr<LocatorCallbackHost>(new (std::nothrow) LocatorCallbackHost());
sptr<LocatorCallbackNapi>(new (std::nothrow) LocatorCallbackNapi());
if (locatorCallbackHost != nullptr) {
napi_ref handlerRef = nullptr;
NAPI_CALL_BASE(env, napi_create_reference(env, argv[PARAM2], 1, &handlerRef), false);
@ -827,7 +827,7 @@ bool OnNmeaMessageChangeCallback(const napi_env& env, const size_t argc, const n
return false;
}
auto nmeaCallbackHost =
sptr<NmeaMessageCallbackHost>(new (std::nothrow) NmeaMessageCallbackHost());
sptr<NmeaMessageCallbackNapi>(new (std::nothrow) NmeaMessageCallbackNapi());
if (nmeaCallbackHost != nullptr) {
napi_ref handlerRef = nullptr;
NAPI_CALL_BASE(env, napi_create_reference(env, argv[PARAM1], PARAM1, &handlerRef), false);
@ -866,7 +866,7 @@ bool OnCountryCodeChangeCallback(const napi_env& env, const size_t argc, const n
return false;
}
auto callbackHost =
sptr<CountryCodeCallbackHost>(new (std::nothrow) CountryCodeCallbackHost());
sptr<CountryCodeCallbackNapi>(new (std::nothrow) CountryCodeCallbackNapi());
if (callbackHost) {
napi_ref handlerRef = nullptr;
NAPI_CALL_BASE(env, napi_create_reference(env, argv[PARAM1], 1, &handlerRef), false);
@ -927,7 +927,7 @@ bool OnLocatingRequiredDataChangeCallback(const napi_env& env, const size_t argc
return false;
}
auto locatingCallbackHost =
sptr<LocatingRequiredDataCallbackHost>(new (std::nothrow) LocatingRequiredDataCallbackHost());
sptr<LocatingRequiredDataCallbackNapi>(new (std::nothrow) LocatingRequiredDataCallbackNapi());
if (locatingCallbackHost != nullptr) {
napi_ref handlerRef = nullptr;
NAPI_CALL_BASE(env, napi_create_reference(env, argv[PARAM2], 1, &handlerRef), false);
@ -980,7 +980,7 @@ napi_value On(napi_env env, napi_callback_info cbinfo)
bool OffAllLocationServiceStateCallback(const napi_env& env)
{
std::map<napi_env, std::map<napi_ref, sptr<LocationSwitchCallbackHost>>> callbackMap =
std::map<napi_env, std::map<napi_ref, sptr<LocationSwitchCallbackNapi>>> callbackMap =
g_switchCallbacks.GetCallbackMap();
auto iter = callbackMap.find(env);
if (iter == callbackMap.end()) {
@ -1009,7 +1009,7 @@ bool OffAllLocationServiceStateCallback(const napi_env& env)
bool OffAllLocationChangeCallback(const napi_env& env)
{
std::map<napi_env, std::map<napi_ref, sptr<LocatorCallbackHost>>> callbackMap =
std::map<napi_env, std::map<napi_ref, sptr<LocatorCallbackNapi>>> callbackMap =
g_locationCallbacks.GetCallbackMap();
auto iter = callbackMap.find(env);
if (iter == callbackMap.end()) {
@ -1039,7 +1039,7 @@ bool OffAllLocationChangeCallback(const napi_env& env)
bool OffAllGnssStatusChangeCallback(const napi_env& env)
{
std::map<napi_env, std::map<napi_ref, sptr<GnssStatusCallbackHost>>> callbackMap =
std::map<napi_env, std::map<napi_ref, sptr<GnssStatusCallbackNapi>>> callbackMap =
g_gnssStatusInfoCallbacks.GetCallbackMap();
auto iter = callbackMap.find(env);
if (iter == callbackMap.end()) {
@ -1068,7 +1068,7 @@ bool OffAllGnssStatusChangeCallback(const napi_env& env)
bool OffAllNmeaMessageChangeCallback(const napi_env& env)
{
std::map<napi_env, std::map<napi_ref, sptr<NmeaMessageCallbackHost>>> callbackMap =
std::map<napi_env, std::map<napi_ref, sptr<NmeaMessageCallbackNapi>>> callbackMap =
g_nmeaCallbacks.GetCallbackMap();
auto iter = callbackMap.find(env);
if (iter == callbackMap.end()) {
@ -1097,7 +1097,7 @@ bool OffAllNmeaMessageChangeCallback(const napi_env& env)
bool OffAllCachedGnssLocationsReportingCallback(const napi_env& env)
{
std::map<napi_env, std::map<napi_ref, sptr<CachedLocationsCallbackHost>>> callbackMap =
std::map<napi_env, std::map<napi_ref, sptr<CachedLocationsCallbackNapi>>> callbackMap =
g_cachedLocationCallbacks.GetCallbackMap();
auto iter = callbackMap.find(env);
if (iter == callbackMap.end()) {
@ -1130,7 +1130,7 @@ bool OffAllCachedGnssLocationsReportingCallback(const napi_env& env)
bool OffAllCountryCodeChangeCallback(const napi_env& env)
{
std::map<napi_env, std::map<napi_ref, sptr<CountryCodeCallbackHost>>> callbackMap =
std::map<napi_env, std::map<napi_ref, sptr<CountryCodeCallbackNapi>>> callbackMap =
g_countryCodeCallbacks.GetCallbackMap();
auto iter = callbackMap.find(env);
if (iter == callbackMap.end()) {
@ -1160,7 +1160,7 @@ bool OffAllCountryCodeChangeCallback(const napi_env& env)
#ifdef ENABLE_NAPI_MANAGER
bool OffAllLocatingRequiredDataChangeCallback(const napi_env& env)
{
std::map<napi_env, std::map<napi_ref, sptr<LocatingRequiredDataCallbackHost>>> callbackMap =
std::map<napi_env, std::map<napi_ref, sptr<LocatingRequiredDataCallbackNapi>>> callbackMap =
g_locatingRequiredDataCallbacks.GetCallbackMap();
auto iter = callbackMap.find(env);
if (iter == callbackMap.end()) {
@ -1539,7 +1539,7 @@ bool OnLocationErrorCallback(const napi_env& env, const size_t argc, const napi_
return false;
}
auto locationErrorCallbackHost =
sptr<LocationErrorCallbackHost>(new (std::nothrow) LocationErrorCallbackHost());
sptr<LocationErrorCallbackNapi>(new (std::nothrow) LocationErrorCallbackNapi());
if (locationErrorCallbackHost != nullptr) {
napi_ref handlerRef = nullptr;
NAPI_CALL_BASE(env, napi_create_reference(env, argv[PARAM1], 1, &handlerRef), false);

View File

@ -15,17 +15,17 @@
#include "location_napi_system.h"
#include "locator_callback_host.h"
#include "locator_callback_napi.h"
#include "location_log.h"
#include "locator.h"
#include "napi_util.h"
namespace OHOS {
namespace Location {
sptr<LocatorCallbackHost> g_systemSingleLocatorCallbackHost =
sptr<LocatorCallbackHost>(new (std::nothrow)LocatorCallbackHost());
sptr<LocatorCallbackHost> g_systemSubcribeCallbackHost =
sptr<LocatorCallbackHost>(new (std::nothrow)LocatorCallbackHost());
sptr<LocatorCallbackNapi> g_systemSingleLocatorCallbackHost =
sptr<LocatorCallbackNapi>(new (std::nothrow)LocatorCallbackNapi());
sptr<LocatorCallbackNapi> g_systemSubcribeCallbackHost =
sptr<LocatorCallbackNapi>(new (std::nothrow)LocatorCallbackNapi());
auto g_locatorImpl = Locator::GetInstance();
napi_value GetLocationOnce(const napi_env& env,
@ -188,7 +188,7 @@ void SubscribeSystemLocationChange(napi_env env,
napi_ref& successHandlerRef,
napi_ref& failHandlerRef,
int fixNumber,
sptr<LocatorCallbackHost>& locatorCallbackHost)
sptr<LocatorCallbackNapi>& locatorCallbackHost)
{
auto locatorCallback = sptr<ILocatorCallback>(locatorCallbackHost);
if (locatorCallbackHost->GetSuccHandleCb() != nullptr ||

View File

@ -0,0 +1,172 @@
/*
* Copyright (C) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "location_switch_callback_napi.h"
#include "common_utils.h"
#include "ipc_skeleton.h"
#include "location_log.h"
namespace OHOS {
namespace Location {
LocationSwitchCallbackNapi::LocationSwitchCallbackNapi()
{
env_ = nullptr;
handlerCb_ = nullptr;
remoteDied_ = false;
callbackValid_ = false;
}
LocationSwitchCallbackNapi::~LocationSwitchCallbackNapi()
{
}
int LocationSwitchCallbackNapi::OnRemoteRequest(
uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option)
{
LBSLOGD(SWITCH_CALLBACK, "LocatorCallbackNapi::OnRemoteRequest!");
if (data.ReadInterfaceToken() != GetDescriptor()) {
LBSLOGE(SWITCH_CALLBACK, "invalid token.");
return -1;
}
if (remoteDied_) {
LBSLOGD(SWITCH_CALLBACK, "Failed to `%{public}s`,Remote service is died!", __func__);
return -1;
}
switch (code) {
case RECEIVE_SWITCH_STATE_EVENT: {
OnSwitchChange(data.ReadInt32());
break;
}
default: {
IPCObjectStub::OnRemoteRequest(code, data, reply, option);
break;
}
}
return 0;
}
bool LocationSwitchCallbackNapi::IsRemoteDied()
{
return remoteDied_;
}
napi_value LocationSwitchCallbackNapi::PackResult(bool switchState)
{
napi_value result;
NAPI_CALL(env_, napi_get_boolean(env_, switchState, &result));
return result;
}
bool LocationSwitchCallbackNapi::Send(int switchState)
{
std::unique_lock<std::mutex> guard(mutex_);
uv_loop_s *loop = nullptr;
NAPI_CALL_BASE(env_, napi_get_uv_event_loop(env_, &loop), false);
if (loop == nullptr) {
LBSLOGE(SWITCH_CALLBACK, "loop == nullptr.");
return false;
}
if (handlerCb_ == nullptr) {
LBSLOGE(SWITCH_CALLBACK, "handler is nullptr.");
return false;
}
uv_work_t *work = new (std::nothrow) uv_work_t;
if (work == nullptr) {
LBSLOGE(SWITCH_CALLBACK, "work == nullptr.");
return false;
}
SwitchAsyncContext *context = new (std::nothrow) SwitchAsyncContext(env_);
if (context == nullptr) {
LBSLOGE(SWITCH_CALLBACK, "context == nullptr.");
delete work;
return false;
}
if (!InitContext(context)) {
LBSLOGE(LOCATOR_CALLBACK, "InitContext fail");
return false;
}
context->enable = (switchState == 1 ? true : false);
work->data = context;
UvQueueWork(loop, work);
return true;
}
void LocationSwitchCallbackNapi::UvQueueWork(uv_loop_s* loop, uv_work_t* work)
{
uv_queue_work(
loop,
work,
[](uv_work_t *work) {},
[](uv_work_t *work, int status) {
SwitchAsyncContext *context = nullptr;
napi_handle_scope scope = nullptr;
if (work == nullptr) {
LBSLOGE(LOCATOR_CALLBACK, "work is nullptr!");
return;
}
context = static_cast<SwitchAsyncContext *>(work->data);
if (context == nullptr || context->env == nullptr || context->callbackValid == nullptr) {
LBSLOGE(LOCATOR_CALLBACK, "context is nullptr!");
delete work;
return;
}
NAPI_CALL_RETURN_VOID(context->env, napi_open_handle_scope(context->env, &scope));
napi_value jsEvent;
CHK_NAPI_ERR_CLOSE_SCOPE(context->env, napi_get_boolean(context->env, context->enable, &jsEvent),
scope, context, work);
if (scope == nullptr) {
LBSLOGE(SWITCH_CALLBACK, "scope is nullptr");
delete context;
delete work;
return;
}
if (context->callback[0] != nullptr && *(context->callbackValid)) {
napi_value undefine;
napi_value handler = nullptr;
CHK_NAPI_ERR_CLOSE_SCOPE(context->env, napi_get_undefined(context->env, &undefine),
scope, context, work);
CHK_NAPI_ERR_CLOSE_SCOPE(context->env,
napi_get_reference_value(context->env, context->callback[0], &handler), scope, context, work);
if (napi_call_function(context->env, nullptr, handler, 1,
&jsEvent, &undefine) != napi_ok) {
LBSLOGE(SWITCH_CALLBACK, "Report event failed");
}
}
NAPI_CALL_RETURN_VOID(context->env, napi_close_handle_scope(context->env, scope));
delete context;
delete work;
});
}
void LocationSwitchCallbackNapi::OnSwitchChange(int switchState)
{
LBSLOGD(SWITCH_CALLBACK, "LocatorCallbackNapi::OnSwitchChange");
Send(switchState);
}
void LocationSwitchCallbackNapi::DeleteHandler()
{
std::unique_lock<std::mutex> guard(mutex_);
if (handlerCb_ == nullptr || env_ == nullptr) {
LBSLOGE(SWITCH_CALLBACK, "handler or env is nullptr.");
return;
}
NAPI_CALL_RETURN_VOID(env_, napi_delete_reference(env_, handlerCb_));
handlerCb_ = nullptr;
callbackValid_ = false;
}
} // namespace Location
} // namespace OHOS

View File

@ -0,0 +1,388 @@
/*
* Copyright (C) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "locator_callback_napi.h"
#include "ipc_object_stub.h"
#include "ipc_skeleton.h"
#include "js_native_api.h"
#include "message_option.h"
#include "message_parcel.h"
#include "napi/native_common.h"
#include "uv.h"
#include "common_utils.h"
#include "constant_definition.h"
#include "i_locator_callback.h"
#include "location.h"
#include "location_async_context.h"
#include "location_log.h"
#include "napi_util.h"
namespace OHOS {
namespace Location {
LocatorCallbackNapi::LocatorCallbackNapi()
{
env_ = nullptr;
handlerCb_ = nullptr;
successHandlerCb_ = nullptr;
failHandlerCb_ = nullptr;
completeHandlerCb_ = nullptr;
fixNumber_ = 0;
inHdArea_ = true;
singleLocation_ = nullptr;
callbackValid_ = false;
InitLatch();
}
void LocatorCallbackNapi::InitLatch()
{
latch_ = new CountDownLatch();
latch_->SetCount(1);
}
LocatorCallbackNapi::~LocatorCallbackNapi()
{
delete latch_;
}
int LocatorCallbackNapi::OnRemoteRequest(uint32_t code,
MessageParcel& data, MessageParcel& reply, MessageOption& option)
{
if (data.ReadInterfaceToken() != GetDescriptor()) {
LBSLOGE(LOCATOR_CALLBACK, "invalid token.");
return -1;
}
switch (code) {
case RECEIVE_LOCATION_INFO_EVENT: {
std::unique_ptr<Location> location = Location::Unmarshalling(data);
OnLocationReport(location);
if (location->GetLocationSourceType() == LocationSourceType::NETWORK_TYPE &&
location->GetAdditionsMap()["inHdArea"] != "") {
inHdArea_ = (location->GetAdditionsMap()["inHdArea"] == "true");
}
if (NeedSetSingleLocation(location)) {
SetSingleLocation(location);
}
if (IfReportAccuracyLocation()) {
CountDown();
}
break;
}
case RECEIVE_LOCATION_STATUS_EVENT: {
int status = data.ReadInt32();
OnLocatingStatusChange(status);
break;
}
case RECEIVE_ERROR_INFO_EVENT: {
int errorCode = data.ReadInt32();
LBSLOGI(LOCATOR_STANDARD, "CallbackSutb receive ERROR_EVENT. errorCode:%{public}d", errorCode);
if (errorCode == LOCATING_FAILED_INTERNET_ACCESS_FAILURE) {
inHdArea_ = false;
if (GetSingleLocation() != nullptr) {
CountDown();
}
} else {
OnErrorReport(errorCode);
}
break;
}
default: {
IPCObjectStub::OnRemoteRequest(code, data, reply, option);
break;
}
}
return 0;
}
void LocatorCallbackNapi::DoSendWork(uv_loop_s*& loop, uv_work_t*& work)
{
uv_queue_work(loop, work, [](uv_work_t* work) {}, [](uv_work_t* work, int status) {
if (work == nullptr) {
return;
}
napi_handle_scope scope = nullptr;
auto context = static_cast<LocationAsyncContext*>(work->data);
if (context == nullptr) {
delete work;
return;
}
if (context->env == nullptr || context->loc == nullptr || context->callbackValid == nullptr) {
delete context;
delete work;
return;
}
napi_open_handle_scope(context->env, &scope);
if (scope == nullptr) {
DELETE_SCOPE_CONTEXT_WORK(context->env, scope, context, work);
return;
}
napi_value jsEvent = nullptr;
CHK_NAPI_ERR_CLOSE_SCOPE(context->env, napi_create_object(context->env, &jsEvent), scope, context, work);
if (context->callback[1]) {
SystemLocationToJs(context->env, context->loc, jsEvent);
} else {
LocationToJs(context->env, context->loc, jsEvent);
}
if (context->callback[0] != nullptr && *(context->callbackValid)) {
napi_value undefine = nullptr;
napi_value handler = nullptr;
CHK_NAPI_ERR_CLOSE_SCOPE(context->env, napi_get_undefined(context->env, &undefine),
scope, context, work);
CHK_NAPI_ERR_CLOSE_SCOPE(context->env,
napi_get_reference_value(context->env, context->callback[0], &handler), scope, context, work);
if (napi_call_function(context->env, nullptr, handler, 1, &jsEvent, &undefine) != napi_ok) {
LBSLOGE(LOCATOR_CALLBACK, "Report location failed");
}
}
DELETE_SCOPE_CONTEXT_WORK(context->env, scope, context, work);
});
}
void LocatorCallbackNapi::DoSendErrorCode(uv_loop_s *&loop, uv_work_t *&work)
{
uv_queue_work(loop, work, [](uv_work_t *work) {},
[](uv_work_t *work, int status) {
AsyncContext *context = nullptr;
napi_handle_scope scope = nullptr;
if (work == nullptr) {
LBSLOGE(LOCATOR_CALLBACK, "work is nullptr");
return;
}
context = static_cast<AsyncContext *>(work->data);
if (context == nullptr || context->env == nullptr || context->callbackValid == nullptr) {
LBSLOGE(LOCATOR_CALLBACK, "context is nullptr");
delete work;
return;
}
NAPI_CALL_RETURN_VOID(context->env, napi_open_handle_scope(context->env, &scope));
if (scope == nullptr) {
LBSLOGE(LOCATOR_CALLBACK, "scope is nullptr");
delete context;
delete work;
return;
}
if (context->callback[FAIL_CALLBACK] != nullptr && *(context->callbackValid)) {
napi_value undefine;
napi_value handler = nullptr;
CHK_NAPI_ERR_CLOSE_SCOPE(context->env, napi_get_undefined(context->env, &undefine),
scope, context, work);
CHK_NAPI_ERR_CLOSE_SCOPE(context->env,
napi_get_reference_value(context->env, context->callback[FAIL_CALLBACK], &handler),
scope, context, work);
std::string msg = GetErrorMsgByCode(context->errCode);
CreateFailCallBackParams(*context, msg, context->errCode);
if (napi_call_function(context->env, nullptr, handler, RESULT_SIZE,
context->result, &undefine) != napi_ok) {
LBSLOGE(LOCATOR_CALLBACK, "Report system error failed");
}
}
NAPI_CALL_RETURN_VOID(context->env, napi_close_handle_scope(context->env, scope));
delete context;
delete work;
});
}
bool LocatorCallbackNapi::SendErrorCode(const int& errorCode)
{
std::unique_lock<std::mutex> guard(mutex_);
if (!IsSystemGeoLocationApi() && !IsSingleLocationRequest()) {
LBSLOGE(LOCATOR_CALLBACK, "this is Callback type,cant send error msg.");
return false;
}
if (env_ == nullptr) {
LBSLOGE(LOCATOR_CALLBACK, "env_ is nullptr.");
return false;
}
if (handlerCb_ == nullptr) {
LBSLOGE(LOCATOR_CALLBACK, "handler is nullptr.");
return false;
}
uv_loop_s *loop = nullptr;
NAPI_CALL_BASE(env_, napi_get_uv_event_loop(env_, &loop), false);
if (loop == nullptr) {
LBSLOGE(LOCATOR_CALLBACK, "loop == nullptr.");
return false;
}
uv_work_t *work = new (std::nothrow) uv_work_t;
if (work == nullptr) {
LBSLOGE(LOCATOR_CALLBACK, "work == nullptr.");
return false;
}
AsyncContext *context = new (std::nothrow) AsyncContext(env_);
if (context == nullptr) {
LBSLOGE(LOCATOR_CALLBACK, "context == nullptr.");
delete work;
return false;
}
if (!InitContext(context)) {
LBSLOGE(LOCATOR_CALLBACK, "InitContext fail");
}
context->errCode = errorCode;
work->data = context;
DoSendErrorCode(loop, work);
return true;
}
void LocatorCallbackNapi::OnLocationReport(const std::unique_ptr<Location>& location)
{
std::unique_lock<std::mutex> guard(mutex_);
uv_loop_s *loop = nullptr;
if (env_ == nullptr) {
LBSLOGD(LOCATOR_CALLBACK, "env_ is nullptr.");
return;
}
if (handlerCb_ == nullptr) {
LBSLOGE(LOCATOR_CALLBACK, "handler is nullptr.");
return;
}
NAPI_CALL_RETURN_VOID(env_, napi_get_uv_event_loop(env_, &loop));
if (loop == nullptr) {
LBSLOGE(LOCATOR_CALLBACK, "loop == nullptr.");
return;
}
uv_work_t *work = new (std::nothrow) uv_work_t;
if (work == nullptr) {
LBSLOGE(LOCATOR_CALLBACK, "work == nullptr.");
return;
}
auto context = new (std::nothrow) LocationAsyncContext(env_);
if (context == nullptr) {
LBSLOGE(LOCATOR_CALLBACK, "context == nullptr.");
delete work;
return;
}
if (!InitContext(context)) {
LBSLOGE(LOCATOR_CALLBACK, "InitContext fail");
}
context->loc = std::make_unique<Location>(*location);
work->data = context;
DoSendWork(loop, work);
}
void LocatorCallbackNapi::OnLocatingStatusChange(const int status)
{
}
void LocatorCallbackNapi::OnErrorReport(const int errorCode)
{
SendErrorCode(errorCode);
}
void LocatorCallbackNapi::DeleteAllCallbacks()
{
DeleteHandler();
}
void LocatorCallbackNapi::DeleteHandler()
{
LBSLOGD(LOCATOR_CALLBACK, "before DeleteHandler");
std::unique_lock<std::mutex> guard(mutex_);
if (env_ == nullptr) {
LBSLOGE(LOCATOR_CALLBACK, "env is nullptr.");
return;
}
if (IsSystemGeoLocationApi()) {
if (successHandlerCb_ != nullptr) {
NAPI_CALL_RETURN_VOID(env_, napi_delete_reference(env_, successHandlerCb_));
successHandlerCb_ = nullptr;
}
if (failHandlerCb_ != nullptr) {
NAPI_CALL_RETURN_VOID(env_, napi_delete_reference(env_, failHandlerCb_));
failHandlerCb_ = nullptr;
}
if (completeHandlerCb_ != nullptr) {
NAPI_CALL_RETURN_VOID(env_, napi_delete_reference(env_, completeHandlerCb_));
completeHandlerCb_ = nullptr;
}
} else {
if (handlerCb_ != nullptr) {
NAPI_CALL_RETURN_VOID(env_, napi_delete_reference(env_, handlerCb_));
handlerCb_ = nullptr;
}
}
callbackValid_ = false;
}
bool LocatorCallbackNapi::IsSystemGeoLocationApi()
{
return (successHandlerCb_ != nullptr) ? true : false;
}
bool LocatorCallbackNapi::IsSingleLocationRequest()
{
return (fixNumber_ == 1);
}
void LocatorCallbackNapi::CountDown()
{
if (IsSingleLocationRequest() && latch_ != nullptr) {
latch_->CountDown();
}
}
void LocatorCallbackNapi::Wait(int time)
{
if (IsSingleLocationRequest() && latch_ != nullptr) {
latch_->Wait(time);
}
}
int LocatorCallbackNapi::GetCount()
{
if (IsSingleLocationRequest() && latch_ != nullptr) {
return latch_->GetCount();
}
return 0;
}
void LocatorCallbackNapi::SetCount(int count)
{
if (IsSingleLocationRequest() && latch_ != nullptr) {
return latch_->SetCount(count);
}
}
bool LocatorCallbackNapi::NeedSetSingleLocation(const std::unique_ptr<Location>& location)
{
if (locationPriority_ == LOCATION_PRIORITY_ACCURACY &&
singleLocation_ != nullptr &&
location->GetLocationSourceType() == LocationSourceType::NETWORK_TYPE) {
return false;
} else {
return true;
}
}
bool LocatorCallbackNapi::IfReportAccuracyLocation()
{
if (locationPriority_ == LOCATION_PRIORITY_ACCURACY &&
(((singleLocation_->GetLocationSourceType() == LocationSourceType::GNSS_TYPE ||
singleLocation_->GetLocationSourceType() == LocationSourceType::RTK_TYPE) && inHdArea_) ||
singleLocation_->GetLocationSourceType() == LocationSourceType::NETWORK_TYPE)) {
return false;
} else {
return true;
}
}
void LocatorCallbackNapi::SetSingleLocation(const std::unique_ptr<Location>& location)
{
std::unique_lock<std::mutex> guard(mutex_);
singleLocation_ = std::make_shared<Location>(*location);
}
} // namespace Location
} // namespace OHOS

View File

@ -1037,7 +1037,7 @@ void DeleteCallbackHandler(uv_loop_s *&loop, uv_work_t *&work)
return;
}
context = static_cast<AsyncContext *>(work->data);
if (context == nullptr || context->env == nullptr) {
if (context == nullptr || context->env == nullptr || context->callbackValid == nullptr) {
LBSLOGE(LOCATOR_CALLBACK, "context is nullptr");
delete work;
return;
@ -1049,6 +1049,13 @@ void DeleteCallbackHandler(uv_loop_s *&loop, uv_work_t *&work)
delete work;
return;
}
if (*(context->callbackValid) == false) {
LBSLOGE(LOCATOR_CALLBACK, "callbackValid is false");
NAPI_CALL_RETURN_VOID(context->env, napi_close_handle_scope(context->env, scope));
delete context;
delete work;
return;
}
if (context->callback[SUCCESS_CALLBACK] != nullptr) {
CHK_NAPI_ERR_CLOSE_SCOPE(context->env,
napi_delete_reference(context->env, context->callback[SUCCESS_CALLBACK]),
@ -1064,6 +1071,7 @@ void DeleteCallbackHandler(uv_loop_s *&loop, uv_work_t *&work)
napi_delete_reference(context->env, context->callback[COMPLETE_CALLBACK]),
scope, context, work);
}
*(context->callbackValid) = false;
NAPI_CALL_RETURN_VOID(context->env, napi_close_handle_scope(context->env, scope));
delete context;
delete work;

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2022 Huawei Device Co., Ltd.
* Copyright (C) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -12,7 +12,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "nmea_message_callback_host.h"
#include "nmea_message_callback_napi.h"
#include "common_utils.h"
#include "ipc_skeleton.h"
@ -24,21 +24,22 @@
namespace OHOS {
namespace Location {
NmeaMessageCallbackHost::NmeaMessageCallbackHost()
NmeaMessageCallbackNapi::NmeaMessageCallbackNapi()
{
env_ = nullptr;
handlerCb_ = nullptr;
remoteDied_ = false;
callbackValid_ = false;
}
NmeaMessageCallbackHost::~NmeaMessageCallbackHost()
NmeaMessageCallbackNapi::~NmeaMessageCallbackNapi()
{
}
int NmeaMessageCallbackHost::OnRemoteRequest(
int NmeaMessageCallbackNapi::OnRemoteRequest(
uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option)
{
LBSLOGD(NMEA_MESSAGE_CALLBACK, "NmeaMessageCallbackHost::OnRemoteRequest!");
LBSLOGD(NMEA_MESSAGE_CALLBACK, "NmeaMessageCallbackNapi::OnRemoteRequest!");
if (data.ReadInterfaceToken() != GetDescriptor()) {
LBSLOGE(NMEA_MESSAGE_CALLBACK, "invalid token.");
return -1;
@ -63,19 +64,19 @@ int NmeaMessageCallbackHost::OnRemoteRequest(
return 0;
}
bool NmeaMessageCallbackHost::IsRemoteDied()
bool NmeaMessageCallbackNapi::IsRemoteDied()
{
return remoteDied_;
}
napi_value NmeaMessageCallbackHost::PackResult(const std::string msg)
napi_value NmeaMessageCallbackNapi::PackResult(const std::string msg)
{
napi_value result;
NAPI_CALL(env_, napi_create_string_utf8(env_, msg.c_str(), NAPI_AUTO_LENGTH, &result));
return result;
}
bool NmeaMessageCallbackHost::Send(const std::string msg)
bool NmeaMessageCallbackNapi::Send(const std::string msg)
{
std::unique_lock<std::mutex> guard(mutex_);
uv_loop_s *loop = nullptr;
@ -84,6 +85,10 @@ bool NmeaMessageCallbackHost::Send(const std::string msg)
LBSLOGE(NMEA_MESSAGE_CALLBACK, "loop == nullptr.");
return false;
}
if (handlerCb_ == nullptr) {
LBSLOGE(NMEA_MESSAGE_CALLBACK, "handler is nullptr.");
return false;
}
uv_work_t *work = new (std::nothrow) uv_work_t;
if (work == nullptr) {
LBSLOGE(NMEA_MESSAGE_CALLBACK, "work == nullptr.");
@ -95,8 +100,10 @@ bool NmeaMessageCallbackHost::Send(const std::string msg)
delete work;
return false;
}
context->env = env_;
context->callback[SUCCESS_CALLBACK] = handlerCb_;
if (!InitContext(context)) {
LBSLOGE(NMEA_MESSAGE_CALLBACK, "InitContext fail");
return false;
}
context->msg = msg;
work->data = context;
UvQueueWork(loop, work);
@ -104,7 +111,7 @@ bool NmeaMessageCallbackHost::Send(const std::string msg)
}
void NmeaMessageCallbackHost::UvQueueWork(uv_loop_s* loop, uv_work_t* work)
void NmeaMessageCallbackNapi::UvQueueWork(uv_loop_s* loop, uv_work_t* work)
{
uv_queue_work(
loop,
@ -118,7 +125,7 @@ void NmeaMessageCallbackHost::UvQueueWork(uv_loop_s* loop, uv_work_t* work)
return;
}
context = static_cast<NmeaAsyncContext *>(work->data);
if (context == nullptr || context->env == nullptr) {
if (context == nullptr || context->env == nullptr || context->callbackValid == nullptr) {
LBSLOGE(LOCATOR_CALLBACK, "context is nullptr!");
delete work;
return;
@ -134,7 +141,7 @@ void NmeaMessageCallbackHost::UvQueueWork(uv_loop_s* loop, uv_work_t* work)
CHK_NAPI_ERR_CLOSE_SCOPE(context->env,
napi_create_string_utf8(context->env, context->msg.c_str(), NAPI_AUTO_LENGTH, &jsEvent),
scope, context, work);
if (context->callback[0] != nullptr) {
if (context->callback[0] != nullptr && *(context->callbackValid)) {
napi_value undefine;
napi_value handler = nullptr;
CHK_NAPI_ERR_CLOSE_SCOPE(context->env, napi_get_undefined(context->env, &undefine),
@ -153,28 +160,22 @@ void NmeaMessageCallbackHost::UvQueueWork(uv_loop_s* loop, uv_work_t* work)
});
}
void NmeaMessageCallbackHost::OnMessageChange(int64_t timestamp, const std::string msg)
void NmeaMessageCallbackNapi::OnMessageChange(int64_t timestamp, const std::string msg)
{
LBSLOGD(NMEA_MESSAGE_CALLBACK, "NmeaMessageCallbackHost::OnMessageChange");
LBSLOGD(NMEA_MESSAGE_CALLBACK, "NmeaMessageCallbackNapi::OnMessageChange");
Send(msg);
}
void NmeaMessageCallbackHost::DeleteHandler()
void NmeaMessageCallbackNapi::DeleteHandler()
{
std::unique_lock<std::mutex> guard(mutex_);
if (handlerCb_ == nullptr || env_ == nullptr) {
LBSLOGE(NMEA_MESSAGE_CALLBACK, "handler or env is nullptr.");
return;
}
auto context = new (std::nothrow) AsyncContext(env_);
if (context == nullptr) {
LBSLOGE(NMEA_MESSAGE_CALLBACK, "context == nullptr.");
return;
}
context->env = env_;
context->callback[SUCCESS_CALLBACK] = handlerCb_;
DeleteQueueWork(context);
NAPI_CALL_RETURN_VOID(env_, napi_delete_reference(env_, handlerCb_));
handlerCb_ = nullptr;
callbackValid_ = false;
}
} // namespace Location
} // namespace OHOS

View File

@ -1,4 +1,4 @@
# Copyright (C) 2022 Huawei Device Co., Ltd.
# Copyright (C) 2022-2024 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
@ -19,6 +19,25 @@ config("location_common_config") {
include_dirs = [ "$LOCATION_ROOT_DIR/interfaces/inner_api/include" ]
}
local_base_sources = [
"$LOCATION_COMMON_DIR/source/app_identity.cpp",
"$LOCATION_COMMON_DIR/source/common_hisysevent.cpp",
"$LOCATION_COMMON_DIR/source/common_utils.cpp",
"$LOCATION_COMMON_DIR/source/geo_address.cpp",
"$LOCATION_COMMON_DIR/source/geo_coding_mock_info.cpp",
"$LOCATION_COMMON_DIR/source/hook_utils.cpp",
"$LOCATION_COMMON_DIR/source/location.cpp",
"$LOCATION_COMMON_DIR/source/location_data_rdb_helper.cpp",
"$LOCATION_COMMON_DIR/source/location_data_rdb_manager.cpp",
"$LOCATION_COMMON_DIR/source/location_dumper.cpp",
"$LOCATION_COMMON_DIR/source/location_sa_load_manager.cpp",
"$LOCATION_COMMON_DIR/source/permission_manager.cpp",
"$LOCATION_COMMON_DIR/source/request.cpp",
"$LOCATION_COMMON_DIR/source/request_config.cpp",
"$LOCATION_COMMON_DIR/source/satellite_status.cpp",
"$LOCATION_COMMON_DIR/source/ui_extension_ability_connection.cpp",
]
ohos_shared_library("lbsservice_common") {
public_configs = [ ":location_common_config" ]
@ -29,24 +48,7 @@ ohos_shared_library("lbsservice_common") {
}
branch_protector_ret = "pac_ret"
sources = [
"$LOCATION_COMMON_DIR/source/app_identity.cpp",
"$LOCATION_COMMON_DIR/source/common_hisysevent.cpp",
"$LOCATION_COMMON_DIR/source/common_utils.cpp",
"$LOCATION_COMMON_DIR/source/geo_address.cpp",
"$LOCATION_COMMON_DIR/source/geo_coding_mock_info.cpp",
"$LOCATION_COMMON_DIR/source/hook_utils.cpp",
"$LOCATION_COMMON_DIR/source/location.cpp",
"$LOCATION_COMMON_DIR/source/location_data_rdb_helper.cpp",
"$LOCATION_COMMON_DIR/source/location_data_rdb_manager.cpp",
"$LOCATION_COMMON_DIR/source/location_dumper.cpp",
"$LOCATION_COMMON_DIR/source/location_sa_load_manager.cpp",
"$LOCATION_COMMON_DIR/source/permission_manager.cpp",
"$LOCATION_COMMON_DIR/source/request.cpp",
"$LOCATION_COMMON_DIR/source/request_config.cpp",
"$LOCATION_COMMON_DIR/source/satellite_status.cpp",
"$LOCATION_COMMON_DIR/source/ui_extension_ability_connection.cpp",
]
sources = local_base_sources
deps = []
@ -69,15 +71,69 @@ ohos_shared_library("lbsservice_common") {
]
defines = []
if (notification_distributed_notification_service_enable) {
defines += [ "NOTIFICATION_ENABLE" ]
}
if (is_emulator) {
defines += [ "EMULATOR_ENABLED" ]
}
ldflags = [
"-Wl,--as-needed",
"-Wl,--gc-sections",
]
cflags_cc = [
"-ffunction-sections",
"-fdata-sections",
"-flto=thin",
"-Os",
]
# Used to control the export of dynamic library symbols.
version_script = "liblbsservice_common_version_script.txt"
innerapi_tags = [ "platformsdk" ]
part_name = "location"
subsystem_name = "location"
}
ohos_static_library("lbsservice_common_static") {
public_configs = [ ":location_common_config" ]
sanitize = {
cfi = true
cfi_cross_dso = true
debug = false
}
branch_protector_ret = "pac_ret"
sources = local_base_sources
deps = []
public_external_deps = [
"ability_base:zuri",
"ability_runtime:extension_manager",
"ability_runtime:wantagent_innerkits",
"access_token:libaccesstoken_sdk",
"access_token:libtokenid_sdk",
"bundle_framework:appexecfwk_base",
"bundle_framework:appexecfwk_core",
"c_utils:utils",
"data_share:datashare_consumer",
"hilog:libhilog",
"hisysevent:libhisysevent",
"init:libbegetutil",
"ipc:ipc_single",
"os_account:os_account_innerkits",
"samgr:samgr_proxy",
]
defines = []
if (is_emulator) {
defines += [ "EMULATOR_ENABLED" ]
}
part_name = "location"
subsystem_name = "location"
}

View File

@ -0,0 +1,27 @@
{
global:
"*RequestConfig*";
"*LocationSaLoadManager*";
"*Unmarshalling*";
"*GetLabel*";
"*GetCapability*";
"*Request*";
"*SetLocationWorkingState*";
"*LocationDumper*";
"*CommonUtils*";
"*GeocodingMockInfo*";
"*PermissionManager*";
"*AppIdentity*";
"*QuerySwitchState*";
"*WriteLocationInnerEvent*";
"*Location*Location*";
"*Location*CountDownLatch*";
"*Location*GeoAddress*";
"*Location*UIExtensionAbilityConnection*";
"*Location*WriteGnssStateEvent*";
"*Location*SatelliteStatus*";
"*Location*WriteAppLocatingStateEvent*";
"*ExecuteHookWhenAddWorkRecord*";
local:
*;
};

View File

@ -64,13 +64,11 @@ void WriteLocationInnerEvent(const int event, std::initializer_list<std::string>
}
flag = !flag;
}
WriteEvent("LBS_CHR_INNER_EVENT", "EVENT", event, "NAMES", names, "VALUES", values);
HookUtils::ExecuteHookWhenReportInnerInfo(event, names, values);
}
void WriteLocationInnerEvent(const int event, std::vector<std::string> names, std::vector<std::string>& values)
{
WriteEvent("LBS_CHR_INNER_EVENT", "EVENT", event, "NAMES", names, "VALUES", values);
HookUtils::ExecuteHookWhenReportInnerInfo(event, names, values);
}
} // namespace Location

View File

@ -407,12 +407,13 @@ bool CommonUtils::CheckAppForUser(int32_t uid)
{
int currentUserId = 0;
int userId = 0;
if (!GetCurrentUserId(currentUserId)) {
currentUserId = 100;
bool ret = GetCurrentUserId(currentUserId);
if (!ret) {
return true;
}
auto result = AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(uid, userId);
if (result != ERR_OK) {
return false;
return true;
}
if (userId != currentUserId) {
return false;

View File

@ -29,6 +29,9 @@
namespace OHOS {
namespace Location {
constexpr const char* LOCATION_DATA_COLUMN_KEYWORD = "KEYWORD";
constexpr const char* LOCATION_DATA_COLUMN_VALUE = "VALUE";
LocationDataRdbHelper* LocationDataRdbHelper::GetInstance()
{
static LocationDataRdbHelper data;

View File

@ -26,6 +26,8 @@ const int UNKNOW_ERROR = -1;
const int MAX_SIZE = 100;
const char* LOCATION_SWITCH_MODE = "persist.location.switch_mode";
std::mutex LocationDataRdbManager::mutex_;
const std::string LOCATION_ENHANCE_STATUS = "location_enhance_status";
std::string LocationDataRdbManager::GetLocationDataUri(std::string key)
{
int userId = 0;

View File

@ -351,5 +351,14 @@ sptr<ILocatorCallback> Request::GetLocationErrorCallBack()
return locationErrorcallBack_;
}
void Request::SetLocatorCallbackRecipient(const sptr<IRemoteObject::DeathRecipient>& recipient)
{
locatorCallbackRecipient_ = recipient;
}
sptr<IRemoteObject::DeathRecipient> Request::GetLocatorCallbackRecipient()
{
return locatorCallbackRecipient_;
}
} // namespace Location
} // namespace OHOS

View File

@ -19,9 +19,15 @@ config("geofence_sdk_config") {
include_dirs = [
"$LOCATION_ROOT_DIR/interfaces/inner_api/include",
"$LOCATION_ROOT_DIR/frameworks/native/notification/include",
"$LOCATION_ROOT_DIR/frameworks/js/napi/include",
]
}
local_base_sources = [
"$LOCATION_NATIVE_DIR/geofence_sdk/source/geofence_request.cpp",
"$LOCATION_NATIVE_DIR/geofence_sdk/source/geofence_sdk.cpp",
]
ohos_shared_library("geofence_sdk") {
install_enable = true
@ -34,45 +40,76 @@ ohos_shared_library("geofence_sdk") {
}
branch_protector_ret = "pac_ret"
sources = [
"$LOCATION_COMMON_DIR/source/geofence_request.cpp",
"$LOCATION_NATIVE_DIR/geofence_sdk/source/geofence_napi.cpp",
"$LOCATION_NATIVE_DIR/geofence_sdk/source/geofence_sdk.cpp",
"$LOCATION_NATIVE_DIR/geofence_sdk/source/location_gnss_geofence_callback_host.cpp",
"$LOCATION_NATIVE_DIR/locator_sdk/source/locator_proxy.cpp",
"$LOCATION_NATIVE_DIR/locator_sdk/source/napi_util.cpp",
]
sources = local_base_sources
deps = [ "$LOCATION_COMMON_DIR:lbsservice_common" ]
public_external_deps = [
"ability_base:zuri",
"ability_runtime:napi_common",
"ability_runtime:wantagent_innerkits",
"access_token:libaccesstoken_sdk",
"bundle_framework:appexecfwk_base",
"bundle_framework:appexecfwk_core",
"c_utils:utils",
"data_share:datashare_consumer",
"hilog:libhilog",
"hisysevent:libhisysevent",
"init:libbegetutil",
"ipc:ipc_single",
"napi:ace_napi",
"os_account:os_account_innerkits",
"samgr:samgr_proxy",
]
defines = []
if (notification_distributed_notification_service_enable) {
public_external_deps += [ "distributed_notification_service:ans_innerkits" ]
defines += [ "NOTIFICATION_ENABLE" ]
}
if (is_emulator) {
defines += [ "EMULATOR_ENABLED" ]
}
cflags_cc = [
"-std=c++17",
"-fno-rtti",
"-ffunction-sections",
"-fdata-sections",
"-Os",
]
ldflags = [
"-fPIC",
"-Wl,-E",
"-Wl,--as-needed",
"-Wl,--gc-sections",
]
# Used to control the export of dynamic library symbols.
version_script = "libgeofence_sdk_version_script.txt"
innerapi_tags = [ "platformsdk" ]
part_name = "location"
subsystem_name = "location"
}
ohos_static_library("geofence_sdk_static") {
public_configs = [ ":geofence_sdk_config" ]
sanitize = {
cfi = true
cfi_cross_dso = true
debug = false
}
branch_protector_ret = "pac_ret"
sources = local_base_sources
deps = [ "$LOCATION_COMMON_DIR:lbsservice_common" ]
public_external_deps = [
"hilog:libhilog",
"init:libbegetutil",
"ipc:ipc_single",
"samgr:samgr_proxy",
]
defines = []
if (notification_distributed_notification_service_enable) {
sources += [ "$LOCATION_NATIVE_DIR/notification/src/notification_napi.cpp" ]
sources += [ "$LOCATION_NATIVE_DIR/notification/src/notification_napi_convert_content.cpp" ]
sources += [ "$LOCATION_NATIVE_DIR/notification/src/notification_napi_convert_liveview.cpp" ]
sources += [ "$LOCATION_NATIVE_DIR/notification/src/notification_napi_convert_notification.cpp" ]
sources += [ "$LOCATION_NATIVE_DIR/notification/src/notification_napi_convert_request.cpp" ]
sources +=
[ "$LOCATION_NATIVE_DIR/notification/src/notification_napi_utils.cpp" ]
public_external_deps += [ "distributed_notification_service:ans_innerkits" ]
public_external_deps += [ "ability_base:want" ]
public_external_deps += [ "image_framework:image" ]
public_external_deps += [ "relational_store:native_rdb" ]
defines += [ "NOTIFICATION_ENABLE" ]
}
@ -90,7 +127,6 @@ ohos_shared_library("geofence_sdk") {
"-Wl,-E",
]
innerapi_tags = [ "platformsdk" ]
part_name = "location"
subsystem_name = "location"
}

View File

@ -0,0 +1,36 @@
{
global:
"*GeofenceManager*GetInstance*";
"*GeofenceManager*AddFenceV9*";
"*GeofenceManager*RemoveFenceV9*";
"*DoAsyncWork*";
"*LocationToJs*";
"*JsObjToReverseGeoCodeRequest*";
"*GeoAddressesToJsObj*";
"*JsObjToGeoCodeRequest*";
"*JsObjToCommand*";
"*SetEnumPropertyByInteger*";
"*CheckIfParamIsFunctionType*";
"*JsObjToLocationRequest*";
"*JsObjToGeoFenceRequest*";
"*GeofenceRequest*";
"*JsObjToCachedLocationRequest*";
"*JsObjToCurrentLocationRequest*";
"*UndefinedNapiValue*";
"*CountryCodeToJs*";
"*JsObjectToInt*";
"*GetLocationArray*";
"*JsObjToRevGeocodeMock*";
"*LocatingRequiredDataToJsObj*";
"*CheckIfParamIsObjectType*";
"*JsObjToLocatingRequiredDataConfig*";
"*ParseGnssGeofenceRequest*";
"*LocationGnssGeofenceCallbackNapi*";
"*Unmarshalling*";
"*GetErrorMsgByCode*";
"*GeofenceManager*GetGeofenceSupportedCoordTypes*";
"*GeofenceSdk*";
"*LocatorProxy*";
local:
*;
};

View File

@ -24,6 +24,131 @@
namespace OHOS {
namespace Location {
GeofenceRequest::GeofenceRequest()
{
callback_ = nullptr;
scenario_ = -1;
fenceId_ = -1;
}
GeofenceRequest::GeofenceRequest(GeofenceRequest& geofenceRequest)
{
this->SetGeofence(geofenceRequest.GetGeofence());
this->SetScenario(geofenceRequest.GetScenario());
this->SetWantAgent(geofenceRequest.GetWantAgent());
this->SetGeofenceTransitionEventList(geofenceRequest.GetGeofenceTransitionEventList());
#ifdef NOTIFICATION_ENABLE
this->SetNotificationRequestList(geofenceRequest.GetNotificationRequestList());
#endif
this->SetGeofenceTransitionCallback(geofenceRequest.GetGeofenceTransitionCallback());
this->SetFenceId(geofenceRequest.GetFenceId());
this->SetBundleName(geofenceRequest.GetBundleName());
}
GeofenceRequest::~GeofenceRequest() {}
GeoFence GeofenceRequest::GetGeofence()
{
return geofence_;
}
void GeofenceRequest::SetGeofence(GeoFence geofence)
{
geofence_ = geofence;
}
int GeofenceRequest::GetScenario()
{
return scenario_;
}
void GeofenceRequest::SetScenario(int scenario)
{
scenario_ = scenario;
}
void GeofenceRequest::SetWantAgent(const AbilityRuntime::WantAgent::WantAgent wantAgent)
{
wantAgent_ = wantAgent;
}
AbilityRuntime::WantAgent::WantAgent GeofenceRequest::GetWantAgent()
{
return wantAgent_;
}
std::vector<GeofenceTransitionEvent> GeofenceRequest::GetGeofenceTransitionEventList()
{
std::unique_lock<std::mutex> lock(geofenceRequestMutex_);
return transitionStatusList_;
}
void GeofenceRequest::SetGeofenceTransitionEvent(GeofenceTransitionEvent status)
{
std::unique_lock<std::mutex> lock(geofenceRequestMutex_);
transitionStatusList_.push_back(status);
}
void GeofenceRequest::SetGeofenceTransitionEventList(std::vector<GeofenceTransitionEvent> statusList)
{
std::unique_lock<std::mutex> lock(geofenceRequestMutex_);
for (auto it = statusList.begin(); it != statusList.end(); ++it) {
transitionStatusList_.push_back(*it);
}
}
#ifdef NOTIFICATION_ENABLE
std::vector<OHOS::Notification::NotificationRequest> GeofenceRequest::GetNotificationRequestList()
{
std::unique_lock<std::mutex> lock(geofenceRequestMutex_);
return notificationRequestList_;
}
void GeofenceRequest::SetNotificationRequest(OHOS::Notification::NotificationRequest request)
{
std::unique_lock<std::mutex> lock(geofenceRequestMutex_);
notificationRequestList_.push_back(request);
}
void GeofenceRequest::SetNotificationRequestList(std::vector<OHOS::Notification::NotificationRequest> requestList)
{
std::unique_lock<std::mutex> lock(geofenceRequestMutex_);
for (auto it = requestList.begin(); it != requestList.end(); ++it) {
notificationRequestList_.push_back(*it);
}
}
#endif
void GeofenceRequest::SetGeofenceTransitionCallback(const sptr<IRemoteObject>& callback)
{
callback_ = callback;
}
sptr<IRemoteObject> GeofenceRequest::GetGeofenceTransitionCallback()
{
return callback_;
}
int GeofenceRequest::GetFenceId()
{
return fenceId_;
}
void GeofenceRequest::SetFenceId(int fenceId)
{
fenceId_ = fenceId;
}
std::string GeofenceRequest::GetBundleName()
{
return bundleName_;
}
void GeofenceRequest::SetBundleName(std::string bundleName)
{
bundleName_ = bundleName;
}
void GeofenceRequest::ReadFromParcel(Parcel& data)
{
std::unique_lock<std::mutex> lock(geofenceRequestMutex_);

View File

@ -35,10 +35,27 @@ GeofenceManager::GeofenceManager()
GeofenceManager::~GeofenceManager()
{}
void GeofenceManager::ResetGeofenceSdkProxy(const wptr<IRemoteObject> &remote)
{
if (remote == nullptr) {
LBSLOGE(GEOFENCE_SDK, "%{public}s: remote is nullptr.", __func__);
return;
}
if (client_ == nullptr || !isServerExist_) {
LBSLOGE(GEOFENCE_SDK, "%{public}s: proxy is nullptr.", __func__);
return;
}
if (remote.promote() != nullptr) {
remote.promote()->RemoveDeathRecipient(recipient_);
}
isServerExist_ = false;
LBSLOGI(GEOFENCE_SDK, "%{public}s: finish.", __func__);
}
sptr<GeofenceSdk> GeofenceManager::GetProxy()
{
std::unique_lock<std::mutex> lock(mutex_);
if (client_ != nullptr) {
if (client_ != nullptr && isServerExist_) {
return client_;
}
@ -52,6 +69,12 @@ sptr<GeofenceSdk> GeofenceManager::GetProxy()
LBSLOGE(GEOFENCE_SDK, "%{public}s: get remote service failed.", __func__);
return nullptr;
}
recipient_ = sptr<GeofenceManagerDeathRecipient>(new (std::nothrow) GeofenceManagerDeathRecipient(*this));
if ((obj->IsProxyObject()) && (!obj->AddDeathRecipient(recipient_))) {
LBSLOGE(GEOFENCE_SDK, "%{public}s: deathRecipient add failed.", __func__);
return nullptr;
}
isServerExist_ = true;
client_ = sptr<GeofenceSdk>(new (std::nothrow) GeofenceSdk(obj));
return client_;
}
@ -91,7 +114,6 @@ LocationErrCode GeofenceManager::AddGnssGeofence(std::shared_ptr<GeofenceRequest
if (!LocationSaLoadManager::InitLocationSa(LOCATION_LOCATOR_SA_ID)) {
return ERRCODE_SERVICE_UNAVAILABLE;
}
LBSLOGD(GEOFENCE_SDK, "GeofenceManager::AddGnssGeofence()");
sptr<GeofenceSdk> proxy = GetProxy();
if (proxy == nullptr) {
LBSLOGE(GEOFENCE_SDK, "%{public}s get proxy failed.", __func__);
@ -160,7 +182,7 @@ LocationErrCode GeofenceSdk::HandleGnssfenceRequest(
}
request->Marshalling(data);
LocationErrCode errorCode = SendMsgWithDataReplyV9(static_cast<int>(code), data, reply);
LBSLOGD(GEOFENCE_SDK, "Transact ErrCodes = %{public}d", errorCode);
LBSLOGI(GEOFENCE_SDK, "Transact ErrCodes = %{public}d", errorCode);
return errorCode;
}
@ -182,7 +204,7 @@ LocationErrCode GeofenceSdk::RemoveGnssGeofence(std::shared_ptr<GeofenceRequest>
data.WriteInt32(request->GetFenceId());
LocationErrCode errorCode = SendMsgWithDataReplyV9(
static_cast<int>(LocatorInterfaceCode::REMOVE_GNSS_GEOFENCE), data, reply);
LBSLOGD(GEOFENCE_SDK, "Transact ErrCodes = %{public}d", errorCode);
LBSLOGI(GEOFENCE_SDK, "Transact ErrCodes = %{public}d", errorCode);
return errorCode;
}
@ -214,12 +236,12 @@ LocationErrCode GeofenceSdk::SendMsgWithDataReplyV9(const int msgId, MessageParc
LBSLOGE(GEOFENCE_SDK, "SendMsgWithDataReply remote is null");
return ERRCODE_SERVICE_UNAVAILABLE;
}
LBSLOGI(GEOFENCE_SDK, "%{public}s: %{public}d", __func__, msgId);
int error = remote->SendRequest(msgId, data, reply, option);
if (error != NO_ERROR) {
LBSLOGE(GEOFENCE_SDK, "msgid = %{public}d, send request error: %{public}d", msgId, error);
return ERRCODE_SERVICE_UNAVAILABLE;
}
LBSLOGD(GEOFENCE_SDK, "Proxy::SendMsgWithDataReply result from server.");
return LocationErrCode(reply.ReadInt32());
}
}

View File

@ -38,17 +38,27 @@ ohos_shared_library("locator_agent") {
cfi_cross_dso = true
debug = false
}
branch_protector_ret = "pac_ret"
deps = [ "$LOCATION_COMMON_DIR:lbsservice_common" ]
external_deps = [
"c_utils:utils",
"hilog:libhilog",
"ipc:ipc_single",
"samgr:samgr_proxy",
]
ldflags = [
"-Wl,--as-needed",
"-Wl,--gc-sections",
]
cflags_cc = [
"-ffunction-sections",
"-fdata-sections",
]
defines = []
if (is_emulator) {
defines += [ "EMULATOR_ENABLED" ]

View File

@ -1,4 +1,4 @@
# Copyright (C) 2022 Huawei Device Co., Ltd.
# Copyright (C) 2022-2024 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
@ -21,9 +21,26 @@ config("locator_sdk_config") {
include_dirs = [
"$LOCATION_ROOT_DIR/interfaces/inner_api/include",
"$LOCATION_ROOT_DIR/frameworks/js/napi/include",
"$LOCATION_ROOT_DIR/services/utils/lbsutils/include",
"$LOCATION_ROOT_DIR/services/utils/inner_api",
"$LOCATION_ROOT_DIR/frameworks/native/locator_sdk/include",
]
}
local_base_sources = [
"$LOCATION_NATIVE_DIR/locator_sdk/source/country_code_callback_host.cpp",
"$LOCATION_NATIVE_DIR/locator_sdk/source/country_code_manager.cpp",
"$LOCATION_NATIVE_DIR/locator_sdk/source/location_data_manager.cpp",
"$LOCATION_NATIVE_DIR/locator_sdk/source/location_data_rdb_observer.cpp",
"$LOCATION_NATIVE_DIR/locator_sdk/source/location_switch_callback_host.cpp",
"$LOCATION_NATIVE_DIR/locator_sdk/source/locator.cpp",
"$LOCATION_NATIVE_DIR/locator_sdk/source/locator_callback_host.cpp",
"$LOCATION_NATIVE_DIR/locator_sdk/source/locator_impl.cpp",
"$LOCATION_NATIVE_DIR/locator_sdk/source/locator_proxy.cpp",
"$LOCATION_NATIVE_DIR/locator_sdk/source/switch_callback_proxy.cpp",
"$LOCATION_ROOT_DIR/services/utils/lbsutils/source/lbs_res_loader.cpp",
]
ohos_shared_library("locator_sdk") {
install_enable = true
@ -34,48 +51,93 @@ ohos_shared_library("locator_sdk") {
cfi_cross_dso = true
debug = false
}
branch_protector_ret = "pac_ret"
sources = [
"$LOCATION_NATIVE_DIR/locator_sdk/source/cached_locations_callback_host.cpp",
"$LOCATION_NATIVE_DIR/locator_sdk/source/country_code_callback_host.cpp",
"$LOCATION_NATIVE_DIR/locator_sdk/source/country_code_manager.cpp",
"$LOCATION_NATIVE_DIR/locator_sdk/source/gnss_status_callback_host.cpp",
"$LOCATION_NATIVE_DIR/locator_sdk/source/locating_required_data_callback_host.cpp",
"$LOCATION_NATIVE_DIR/locator_sdk/source/location_data_manager.cpp",
"$LOCATION_NATIVE_DIR/locator_sdk/source/location_data_rdb_observer.cpp",
"$LOCATION_NATIVE_DIR/locator_sdk/source/location_error_callback_host.cpp",
"$LOCATION_NATIVE_DIR/locator_sdk/source/location_switch_callback_host.cpp",
"$LOCATION_NATIVE_DIR/locator_sdk/source/locator.cpp",
"$LOCATION_NATIVE_DIR/locator_sdk/source/locator_callback_host.cpp",
"$LOCATION_NATIVE_DIR/locator_sdk/source/locator_impl.cpp",
"$LOCATION_NATIVE_DIR/locator_sdk/source/locator_proxy.cpp",
"$LOCATION_NATIVE_DIR/locator_sdk/source/napi_util.cpp",
"$LOCATION_NATIVE_DIR/locator_sdk/source/nmea_message_callback_host.cpp",
"$LOCATION_NATIVE_DIR/locator_sdk/source/switch_callback_proxy.cpp",
]
sources = local_base_sources
deps = [ "$LOCATION_COMMON_DIR:lbsservice_common" ]
public_external_deps = [
"ability_runtime:dataobs_manager",
"data_share:datashare_consumer",
"hilog:libhilog",
"init:libbeget_proxy",
"ipc:ipc_single",
"samgr:samgr_proxy",
]
defines = []
if (i18n_enable) {
defines += [ "I18N_ENABLE" ]
}
if (telephony_core_service_enable) {
public_external_deps += [ "core_service:tel_core_service_api" ]
defines += [ "TEL_CORE_SERVICE_ENABLE" ]
}
if (telephony_cellular_data_enable) {
public_external_deps += [ "cellular_data:tel_cellular_data_api" ]
defines += [ "TEL_CELLULAR_DATA_ENABLE" ]
}
if (is_emulator) {
defines += [ "EMULATOR_ENABLED" ]
}
cflags_cc = [
"-std=c++17",
"-fno-rtti",
"-ffunction-sections",
"-fdata-sections",
"-flto=thin",
"-Os",
]
ldflags = [
"-fPIC",
"-Wl,-E",
"-Wl,--as-needed",
"-Wl,--gc-sections",
]
# Used to control the export of dynamic library symbols.
version_script = "liblocator_sdk_version_script.txt"
innerapi_tags = [ "platformsdk" ]
part_name = "location"
subsystem_name = "location"
}
ohos_static_library("locator_sdk_static") {
public_configs = [ ":locator_sdk_config" ]
sanitize = {
cfi = true
cfi_cross_dso = true
debug = false
}
branch_protector_ret = "pac_ret"
sources = local_base_sources
deps = [ "$LOCATION_COMMON_DIR:lbsservice_common" ]
public_external_deps = [
"ability_base:zuri",
"ability_runtime:dataobs_manager",
"ability_runtime:wantagent_innerkits",
"c_utils:utils",
"common_event_service:cesfwk_innerkits",
"data_share:datashare_consumer",
"hilog:libhilog",
"init:libbeget_proxy",
"ipc:ipc_single",
"libuv:uv",
"napi:ace_napi",
"samgr:samgr_proxy",
]
defines = []
if (i18n_enable) {
public_external_deps += [ "i18n:intl_util" ]
defines += [ "I18N_ENABLE" ]
}
@ -103,7 +165,6 @@ ohos_shared_library("locator_sdk") {
"-Wl,-E",
]
innerapi_tags = [ "platformsdk" ]
part_name = "location"
subsystem_name = "location"
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2022 Huawei Device Co., Ltd.
* Copyright (C) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -18,28 +18,15 @@
#include "i_country_code_callback.h"
#include "iremote_stub.h"
#include "napi/native_api.h"
#include "uv.h"
#include "country_code.h"
namespace OHOS {
namespace Location {
class CountryCodeCallbackHost : public IRemoteStub<ICountryCodeCallback> {
public:
CountryCodeCallbackHost();
virtual ~CountryCodeCallbackHost();
virtual int OnRemoteRequest(uint32_t code,
MessageParcel& data, MessageParcel& reply, MessageOption& option) override;
void OnCountryCodeChange(const std::shared_ptr<CountryCode>& country) override;
bool Send(const std::shared_ptr<CountryCode>& country);
void SetEnv(napi_env env);
void SetCallback(napi_ref cb);
void DeleteHandler();
void UvQueueWork(uv_loop_s* loop, uv_work_t* work);
private:
napi_env env_;
napi_ref handlerCb_;
std::mutex mutex_;
};
} // namespace Location
} // namespace OHOS

View File

@ -0,0 +1,33 @@
/*
* Copyright (C) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef LOCATION_SWITCH_CALLBACK_HOST_H
#define LOCATION_SWITCH_CALLBACK_HOST_H
#include "i_switch_callback.h"
#include "iremote_stub.h"
namespace OHOS {
namespace Location {
class LocationSwitchCallbackHost : public IRemoteStub<ISwitchCallback> {
public:
virtual int OnRemoteRequest(
uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) override;
void OnSwitchChange(int switchState) override;
};
} // namespace Location
} // namespace OHOS
#endif // LOCATION_SWITCH_CALLBACK_HOST_H

View File

@ -0,0 +1,34 @@
/*
* Copyright (C) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef LOCATOR_CALLBACK_HOST_H
#define LOCATOR_CALLBACK_HOST_H
#include "iremote_stub.h"
#include "i_locator_callback.h"
namespace OHOS {
namespace Location {
class LocatorCallbackHost : public IRemoteStub<ILocatorCallback> {
public:
virtual int OnRemoteRequest(uint32_t code,
MessageParcel& data, MessageParcel& reply, MessageOption& option) override;
void OnLocationReport(const std::unique_ptr<Location>& location) override;
void OnLocatingStatusChange(const int status) override;
void OnErrorReport(const int errorCode) override;
};
} // namespace Location
} // namespace OHOS
#endif // LOCATOR_CALLBACK_HOST_H

View File

@ -0,0 +1,11 @@
{
global:
"*LocatorImpl*";
"*GetInstance*";
"*LocatorProxy*";
"*LocationSwitchCallbackHost*";
"*LocatorCallbackHost*";
"*CountryCodeCallbackHost*";
local:
*;
};

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2022 Huawei Device Co., Ltd.
* Copyright (C) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -14,25 +14,10 @@
*/
#include "country_code_callback_host.h"
#include "common_utils.h"
#include "ipc_skeleton.h"
#include "location_log.h"
#include "napi/native_api.h"
#include "country_code.h"
#include "napi_util.h"
namespace OHOS {
namespace Location {
CountryCodeCallbackHost::CountryCodeCallbackHost()
{
env_ = nullptr;
handlerCb_ = nullptr;
}
CountryCodeCallbackHost::~CountryCodeCallbackHost()
{
}
int CountryCodeCallbackHost::OnRemoteRequest(
uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option)
{
@ -56,128 +41,8 @@ int CountryCodeCallbackHost::OnRemoteRequest(
return 0;
}
bool CountryCodeCallbackHost::Send(const std::shared_ptr<CountryCode>& country)
{
std::unique_lock<std::mutex> guard(mutex_);
uv_loop_s *loop = nullptr;
if (env_ == nullptr) {
LBSLOGE(COUNTRY_CODE_CALLBACK, "env_ == nullptr.");
return false;
}
if (country == nullptr) {
LBSLOGE(COUNTRY_CODE_CALLBACK, "country == nullptr.");
return false;
}
NAPI_CALL_BASE(env_, napi_get_uv_event_loop(env_, &loop), false);
if (loop == nullptr) {
LBSLOGE(COUNTRY_CODE_CALLBACK, "loop == nullptr.");
return false;
}
uv_work_t *work = new (std::nothrow) uv_work_t;
if (work == nullptr) {
LBSLOGE(COUNTRY_CODE_CALLBACK, "work == nullptr.");
return false;
}
auto context = new (std::nothrow) CountryCodeContext(env_);
if (context == nullptr) {
LBSLOGE(COUNTRY_CODE_CALLBACK, "context == nullptr.");
delete work;
return false;
}
context->env = env_;
context->callback[SUCCESS_CALLBACK] = handlerCb_;
context->country = country;
work->data = context;
UvQueueWork(loop, work);
return true;
}
void CountryCodeCallbackHost::UvQueueWork(uv_loop_s* loop, uv_work_t* work)
{
uv_queue_work(
loop,
work,
[](uv_work_t *work) {},
[](uv_work_t *work, int status) {
CountryCodeContext *context = nullptr;
napi_handle_scope scope = nullptr;
if (work == nullptr) {
LBSLOGE(LOCATOR_CALLBACK, "work is nullptr!");
return;
}
context = static_cast<CountryCodeContext *>(work->data);
if (context == nullptr || context->env == nullptr) {
LBSLOGE(LOCATOR_CALLBACK, "context is nullptr!");
delete work;
return;
}
NAPI_CALL_RETURN_VOID(context->env, napi_open_handle_scope(context->env, &scope));
if (scope == nullptr) {
LBSLOGE(COUNTRY_CODE_CALLBACK, "scope is nullptr");
delete context;
delete work;
return;
}
napi_value jsEvent;
CHK_NAPI_ERR_CLOSE_SCOPE(context->env, napi_create_object(context->env, &jsEvent),
scope, context, work);
if (context->country) {
CountryCodeToJs(context->env, context->country, jsEvent);
} else {
LBSLOGE(LOCATOR_STANDARD, "country is nullptr!");
}
if (context->callback[0] != nullptr) {
napi_value undefine;
napi_value handler = nullptr;
CHK_NAPI_ERR_CLOSE_SCOPE(context->env,
napi_get_undefined(context->env, &undefine), scope, context, work);
CHK_NAPI_ERR_CLOSE_SCOPE(context->env,
napi_get_reference_value(context->env, context->callback[SUCCESS_CALLBACK], &handler),
scope, context, work);
if (napi_call_function(context->env, nullptr, handler, 1, &jsEvent, &undefine) != napi_ok) {
LBSLOGE(COUNTRY_CODE_CALLBACK, "Report event failed");
}
}
NAPI_CALL_RETURN_VOID(context->env, napi_close_handle_scope(context->env, scope));
delete context;
delete work;
});
}
void CountryCodeCallbackHost::OnCountryCodeChange(const std::shared_ptr<CountryCode>& country)
{
LBSLOGD(COUNTRY_CODE_CALLBACK, "CountryCodeCallbackHost::OnCountryCodeChange");
Send(country);
}
void CountryCodeCallbackHost::SetEnv(napi_env env)
{
std::unique_lock<std::mutex> guard(mutex_);
env_ = env;
}
void CountryCodeCallbackHost::SetCallback(napi_ref cb)
{
std::unique_lock<std::mutex> guard(mutex_);
handlerCb_ = cb;
}
void CountryCodeCallbackHost::DeleteHandler()
{
std::unique_lock<std::mutex> guard(mutex_);
if (handlerCb_ == nullptr || env_ == nullptr) {
LBSLOGE(COUNTRY_CODE_CALLBACK, "handler or env is nullptr.");
return;
}
auto context = new (std::nothrow) AsyncContext(env_);
if (context == nullptr) {
LBSLOGE(COUNTRY_CODE_CALLBACK, "context == nullptr.");
return;
}
context->env = env_;
context->callback[SUCCESS_CALLBACK] = handlerCb_;
DeleteQueueWork(context);
handlerCb_ = nullptr;
}
} // namespace Location
} // namespace OHOS

View File

@ -19,11 +19,7 @@
#ifdef TEL_CORE_SERVICE_ENABLE
#include "core_service_client.h"
#endif
#ifdef I18N_ENABLE
#include "locale_config.h"
#endif
#include "parameter.h"
#include "common_event_manager.h"
#include "common_event_support.h"
#include "common_utils.h"
@ -31,6 +27,7 @@
#include "country_code.h"
#include "location_log.h"
#include "locator_impl.h"
#include "lbs_res_loader.h"
namespace OHOS {
namespace Location {
@ -44,7 +41,6 @@ CountryCodeManager::CountryCodeManager()
{
lastCountryByLocation_ = std::make_shared<CountryCode>();
lastCountry_ = std::make_shared<CountryCode>();
countryCodeCallback_ = std::make_unique<std::map<pid_t, sptr<ICountryCodeCallback>>>();
simSubscriber_ = nullptr;
networkSubscriber_ = nullptr;
SubscribeLocaleConfigEvent();
@ -57,13 +53,12 @@ CountryCodeManager::~CountryCodeManager()
void CountryCodeManager::NotifyAllListener()
{
std::unique_lock lock(countryCodeCallbackMutex_);
if (lastCountry_ == nullptr || countryCodeCallback_ == nullptr) {
if (lastCountry_ == nullptr) {
LBSLOGE(COUNTRY_CODE, "NotifyAllListener cancel, para is invalid");
return;
}
auto country = std::make_shared<CountryCode>(*lastCountry_);
for (auto iter = countryCodeCallback_->begin(); iter != countryCodeCallback_->end(); iter++) {
sptr<ICountryCodeCallback> callback = (iter->second);
for (auto callback : countryCodeCallbacks_) {
if (callback) {
callback->OnCountryCodeChange(country);
}
@ -74,7 +69,7 @@ void CountryCodeManager::RegisterCountryCodeCallback(const sptr<IRemoteObject>&
{
std::unique_lock<std::mutex> lock(countryCodeCallbackMutex_, std::defer_lock);
lock.lock();
if (callback == nullptr || countryCodeCallback_ == nullptr) {
if (callback == nullptr) {
LBSLOGE(COUNTRY_CODE, "callback is invalid");
lock.unlock();
return;
@ -86,11 +81,10 @@ void CountryCodeManager::RegisterCountryCodeCallback(const sptr<IRemoteObject>&
lock.unlock();
return;
}
countryCodeCallback_->erase(uid);
countryCodeCallback_->insert(std::make_pair(uid, countryCodeCallback));
LBSLOGD(COUNTRY_CODE, "after uid:%{public}d register, countryCodeCallback_ size:%{public}s",
uid, std::to_string(countryCodeCallback_->size()).c_str());
if (countryCodeCallback_->size() != 1) {
countryCodeCallbacks_.push_back(countryCodeCallback);
LBSLOGD(COUNTRY_CODE, "after uid:%{public}d register, countryCodeCallbacks_ size:%{public}s",
uid, std::to_string(countryCodeCallbacks_.size()).c_str());
if (countryCodeCallbacks_.size() != 1) {
lock.unlock();
return;
}
@ -103,7 +97,7 @@ void CountryCodeManager::UnregisterCountryCodeCallback(const sptr<IRemoteObject>
{
std::unique_lock<std::mutex> lock(countryCodeCallbackMutex_, std::defer_lock);
lock.lock();
if (callback == nullptr || countryCodeCallback_ == nullptr) {
if (callback == nullptr) {
LBSLOGE(COUNTRY_CODE, "unregister an invalid callback");
lock.unlock();
return;
@ -114,19 +108,27 @@ void CountryCodeManager::UnregisterCountryCodeCallback(const sptr<IRemoteObject>
lock.unlock();
return;
}
pid_t uid = -1;
for (auto iter = countryCodeCallback_->begin(); iter != countryCodeCallback_->end(); iter++) {
sptr<IRemoteObject> remoteObject = (iter->second)->AsObject();
size_t i = 0;
for (; i < countryCodeCallbacks_.size(); i++) {
if (countryCodeCallbacks_[i] == nullptr) {
continue;
}
sptr<IRemoteObject> remoteObject = countryCodeCallbacks_[i]->AsObject();
if (remoteObject == callback) {
uid = iter->first;
break;
}
}
countryCodeCallback_->erase(uid);
LBSLOGD(COUNTRY_CODE, "after uid:%{public}d unregister, countryCodeCallback_ size:%{public}s",
uid, std::to_string(countryCodeCallback_->size()).c_str());
if (countryCodeCallback_->size() != 0) {
if (i >= countryCodeCallbacks_.size()) {
LBSLOGD(GNSS, "countryCode callback is not in vector");
lock.unlock();
return;
}
if (countryCodeCallbacks_.size() > 0) {
countryCodeCallbacks_.erase(countryCodeCallbacks_.begin() + i);
}
LBSLOGD(COUNTRY_CODE, "after unregister, countryCodeCallbacks_ size:%{public}s",
std::to_string(countryCodeCallbacks_.size()).c_str());
if (countryCodeCallbacks_.size() != 0) {
lock.unlock();
return;
}
@ -138,7 +140,7 @@ void CountryCodeManager::UnregisterCountryCodeCallback(const sptr<IRemoteObject>
bool CountryCodeManager::IsCountryCodeRegistered()
{
std::unique_lock lock(countryCodeCallbackMutex_);
return countryCodeCallback_->size() != 0;
return countryCodeCallbacks_.size() != 0;
}
std::string CountryCodeManager::GetCountryCodeByLastLocation()
@ -257,7 +259,8 @@ std::shared_ptr<CountryCode> CountryCodeManager::GetIsoCountryCode()
#endif
#ifdef I18N_ENABLE
if (countryCodeStr8.empty()) {
countryCodeStr8 = Global::I18n::LocaleConfig::GetSystemRegion();
LbsResLoader resLoader;
countryCodeStr8 = resLoader.GetSystemRegion();
type = COUNTRY_CODE_FROM_LOCALE;
}
#endif
@ -276,16 +279,16 @@ std::shared_ptr<CountryCode> CountryCodeManager::GetIsoCountryCode()
bool CountryCodeManager::SubscribeSimEvent()
{
LBSLOGD(COUNTRY_CODE, "SubscribeSimEvent");
OHOS::EventFwk::MatchingSkills matchingSkills;
matchingSkills.AddEvent(SIM_STATE_CHANGE_ACTION);
OHOS::EventFwk::CommonEventSubscribeInfo subscriberInfo(matchingSkills);
EventFwk::MatchingSkills matchingSkills;
matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_SIM_STATE_CHANGED);
EventFwk::CommonEventSubscribeInfo subscriberInfo(matchingSkills);
std::unique_lock<std::mutex> lock(simSubscriberMutex_, std::defer_lock);
lock.lock();
if (simSubscriber_ == nullptr) {
simSubscriber_ = std::make_shared<SimSubscriber>(subscriberInfo);
}
lock.unlock();
bool result = OHOS::EventFwk::CommonEventManager::SubscribeCommonEvent(simSubscriber_);
bool result = EventFwk::CommonEventManager::SubscribeCommonEvent(simSubscriber_);
if (!result) {
LBSLOGE(COUNTRY_CODE, "SubscribeSimEvent failed.");
}
@ -295,16 +298,16 @@ bool CountryCodeManager::SubscribeSimEvent()
bool CountryCodeManager::SubscribeNetworkStatusEvent()
{
LBSLOGD(COUNTRY_CODE, "SubscribeNetworkStatusEvent");
OHOS::EventFwk::MatchingSkills matchingSkills;
matchingSkills.AddEvent(SEARCH_NET_WORK_STATE_CHANGE_ACTION);
OHOS::EventFwk::CommonEventSubscribeInfo subscriberInfo(matchingSkills);
EventFwk::MatchingSkills matchingSkills;
matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_NETWORK_STATE_CHANGED);
EventFwk::CommonEventSubscribeInfo subscriberInfo(matchingSkills);
std::unique_lock<std::mutex> lock(networkSubscriberMutex_, std::defer_lock);
lock.lock();
if (networkSubscriber_ == nullptr) {
networkSubscriber_ = std::make_shared<NetworkSubscriber>(subscriberInfo);
}
lock.unlock();
bool result = OHOS::EventFwk::CommonEventManager::SubscribeCommonEvent(networkSubscriber_);
bool result = EventFwk::CommonEventManager::SubscribeCommonEvent(networkSubscriber_);
if (!result) {
LBSLOGE(COUNTRY_CODE, "SubscribeNetworkStatusEvent failed.");
}
@ -323,7 +326,7 @@ bool CountryCodeManager::SubscribeLocaleConfigEvent()
manager->GetIsoCountryCode();
};
int ret = WatchParameter(LOCALE_KEY.c_str(), eventCallback, nullptr);
int ret = WatchParameter(LOCALE_KEY, eventCallback, nullptr);
if (ret != SUCCESS) {
LBSLOGD(COUNTRY_CODE, "WatchParameter fail");
return false;
@ -419,7 +422,7 @@ void CountryCodeManager::ReSubscribeEvent()
{
std::unique_lock<std::mutex> lock(countryCodeCallbackMutex_, std::defer_lock);
lock.lock();
if (countryCodeCallback_->size() <= 0) {
if (countryCodeCallbacks_.size() <= 0) {
LBSLOGD(COUNTRY_CODE, "no valid callback registed, no need to subscribe");
lock.unlock();
return;
@ -433,7 +436,7 @@ void CountryCodeManager::ReUnsubscribeEvent()
{
std::unique_lock<std::mutex> lock(countryCodeCallbackMutex_, std::defer_lock);
lock.lock();
if (countryCodeCallback_->size() <= 0) {
if (countryCodeCallbacks_.size() <= 0) {
LBSLOGE(COUNTRY_CODE, "no valid callback registed, no need to unsubscribe");
lock.unlock();
return;

View File

@ -38,7 +38,6 @@ LocationDataManager* LocationDataManager::GetInstance()
LocationDataManager::LocationDataManager()
{
switchCallbacks_ = std::make_unique<std::map<pid_t, sptr<ISwitchCallback>>>();
sptr<ISystemAbilityManager> sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (sam == nullptr) {
LBSLOGE(LOCATOR_STANDARD, "%{public}s: get samgr failed.", __func__);
@ -59,15 +58,10 @@ LocationDataManager::~LocationDataManager()
LocationErrCode LocationDataManager::ReportSwitchState(bool isEnabled)
{
if (switchCallbacks_ == nullptr) {
LBSLOGE(LOCATOR, "switchCallbacks_ is nullptr");
return ERRCODE_INVALID_PARAM;
}
int state = isEnabled ? ENABLED : DISABLED;
std::unique_lock<std::mutex> lock(mutex_);
for (auto iter = switchCallbacks_->begin(); iter != switchCallbacks_->end(); iter++) {
sptr<IRemoteObject> remoteObject = (iter->second)->AsObject();
for (auto switchCallback : switchCallbacks_) {
sptr<IRemoteObject> remoteObject = switchCallback->AsObject();
auto callback = std::make_unique<SwitchCallbackProxy>(remoteObject);
callback->OnSwitchChange(state);
}
@ -76,7 +70,7 @@ LocationErrCode LocationDataManager::ReportSwitchState(bool isEnabled)
LocationErrCode LocationDataManager::RegisterSwitchCallback(const sptr<IRemoteObject>& callback, pid_t uid)
{
if (callback == nullptr || switchCallbacks_ == nullptr) {
if (callback == nullptr) {
LBSLOGE(LOCATOR, "register an invalid switch callback");
return ERRCODE_INVALID_PARAM;
}
@ -86,16 +80,15 @@ LocationErrCode LocationDataManager::RegisterSwitchCallback(const sptr<IRemoteOb
return ERRCODE_INVALID_PARAM;
}
std::unique_lock<std::mutex> lock(mutex_);
switchCallbacks_->erase(uid);
switchCallbacks_->insert(std::make_pair(uid, switchCallback));
switchCallbacks_.push_back(switchCallback);
LBSLOGD(LOCATOR, "after uid:%{public}d register, switch callback size:%{public}s",
uid, std::to_string(switchCallbacks_->size()).c_str());
uid, std::to_string(switchCallbacks_.size()).c_str());
return ERRCODE_SUCCESS;
}
LocationErrCode LocationDataManager::UnregisterSwitchCallback(const sptr<IRemoteObject>& callback)
{
if (callback == nullptr || switchCallbacks_ == nullptr) {
if (callback == nullptr) {
LBSLOGE(LOCATOR, "unregister an invalid switch callback");
return ERRCODE_INVALID_PARAM;
}
@ -105,18 +98,26 @@ LocationErrCode LocationDataManager::UnregisterSwitchCallback(const sptr<IRemote
return ERRCODE_INVALID_PARAM;
}
pid_t uid = -1;
std::unique_lock<std::mutex> lock(mutex_);
for (auto iter = switchCallbacks_->begin(); iter != switchCallbacks_->end(); iter++) {
sptr<IRemoteObject> remoteObject = (iter->second)->AsObject();
size_t i = 0;
for (; i < switchCallbacks_.size(); i++) {
if (switchCallbacks_[i] == nullptr) {
continue;
}
sptr<IRemoteObject> remoteObject = switchCallbacks_[i]->AsObject();
if (remoteObject == callback) {
uid = iter->first;
break;
}
}
switchCallbacks_->erase(uid);
LBSLOGD(LOCATOR, "after uid:%{public}d unregister, switch callback size:%{public}s",
uid, std::to_string(switchCallbacks_->size()).c_str());
if (i >= switchCallbacks_.size()) {
LBSLOGD(GNSS, "switch callback is not in vector");
return ERRCODE_SUCCESS;
}
if (switchCallbacks_.size() > 0) {
switchCallbacks_.erase(switchCallbacks_.begin() + i);
}
LBSLOGD(LOCATOR, "after unregister, switch callback size:%{public}s",
std::to_string(switchCallbacks_.size()).c_str());
return ERRCODE_SUCCESS;
}
@ -130,7 +131,7 @@ void LocationDataManager::SetCachedSwitchState(int state)
bool LocationDataManager::IsSwitchStateReg()
{
std::unique_lock<std::mutex> lock(mutex_);
return (switchCallbacks_->size() > 0);
return (switchCallbacks_.size() > 0);
}
void LocationDataManager::ResetIsObserverReg()

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2022 Huawei Device Co., Ltd.
* Copyright (C) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -14,35 +14,18 @@
*/
#include "location_switch_callback_host.h"
#include "common_utils.h"
#include "ipc_skeleton.h"
#include "location_log.h"
namespace OHOS {
namespace Location {
LocationSwitchCallbackHost::LocationSwitchCallbackHost()
{
env_ = nullptr;
handlerCb_ = nullptr;
remoteDied_ = false;
}
LocationSwitchCallbackHost::~LocationSwitchCallbackHost()
{
}
int LocationSwitchCallbackHost::OnRemoteRequest(
uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option)
{
LBSLOGD(SWITCH_CALLBACK, "LocatorCallbackHost::OnRemoteRequest!");
LBSLOGD(SWITCH_CALLBACK, "LocationSwitchCallbackHost::OnRemoteRequest!");
if (data.ReadInterfaceToken() != GetDescriptor()) {
LBSLOGE(SWITCH_CALLBACK, "invalid token.");
return -1;
}
if (remoteDied_) {
LBSLOGD(SWITCH_CALLBACK, "Failed to `%{public}s`,Remote service is died!", __func__);
return -1;
}
switch (code) {
case RECEIVE_SWITCH_STATE_EVENT: {
@ -56,116 +39,8 @@ int LocationSwitchCallbackHost::OnRemoteRequest(
}
return 0;
}
bool LocationSwitchCallbackHost::IsRemoteDied()
{
return remoteDied_;
}
napi_value LocationSwitchCallbackHost::PackResult(bool switchState)
{
napi_value result;
NAPI_CALL(env_, napi_get_boolean(env_, switchState, &result));
return result;
}
bool LocationSwitchCallbackHost::Send(int switchState)
{
std::unique_lock<std::mutex> guard(mutex_);
uv_loop_s *loop = nullptr;
NAPI_CALL_BASE(env_, napi_get_uv_event_loop(env_, &loop), false);
if (loop == nullptr) {
LBSLOGE(SWITCH_CALLBACK, "loop == nullptr.");
return false;
}
uv_work_t *work = new (std::nothrow) uv_work_t;
if (work == nullptr) {
LBSLOGE(SWITCH_CALLBACK, "work == nullptr.");
return false;
}
SwitchAsyncContext *context = new (std::nothrow) SwitchAsyncContext(env_);
if (context == nullptr) {
LBSLOGE(SWITCH_CALLBACK, "context == nullptr.");
delete work;
return false;
}
context->env = env_;
context->callback[SUCCESS_CALLBACK] = handlerCb_;
context->enable = (switchState == 1 ? true : false);
work->data = context;
UvQueueWork(loop, work);
return true;
}
void LocationSwitchCallbackHost::UvQueueWork(uv_loop_s* loop, uv_work_t* work)
{
uv_queue_work(
loop,
work,
[](uv_work_t *work) {},
[](uv_work_t *work, int status) {
SwitchAsyncContext *context = nullptr;
napi_handle_scope scope = nullptr;
if (work == nullptr) {
LBSLOGE(LOCATOR_CALLBACK, "work is nullptr!");
return;
}
context = static_cast<SwitchAsyncContext *>(work->data);
if (context == nullptr || context->env == nullptr) {
LBSLOGE(LOCATOR_CALLBACK, "context is nullptr!");
delete work;
return;
}
NAPI_CALL_RETURN_VOID(context->env, napi_open_handle_scope(context->env, &scope));
napi_value jsEvent;
CHK_NAPI_ERR_CLOSE_SCOPE(context->env, napi_get_boolean(context->env, context->enable, &jsEvent),
scope, context, work);
if (scope == nullptr) {
LBSLOGE(SWITCH_CALLBACK, "scope is nullptr");
delete context;
delete work;
return;
}
if (context->callback[0] != nullptr) {
napi_value undefine;
napi_value handler = nullptr;
CHK_NAPI_ERR_CLOSE_SCOPE(context->env, napi_get_undefined(context->env, &undefine),
scope, context, work);
CHK_NAPI_ERR_CLOSE_SCOPE(context->env,
napi_get_reference_value(context->env, context->callback[0], &handler), scope, context, work);
if (napi_call_function(context->env, nullptr, handler, 1,
&jsEvent, &undefine) != napi_ok) {
LBSLOGE(SWITCH_CALLBACK, "Report event failed");
}
}
NAPI_CALL_RETURN_VOID(context->env, napi_close_handle_scope(context->env, scope));
delete context;
delete work;
});
}
void LocationSwitchCallbackHost::OnSwitchChange(int switchState)
{
LBSLOGD(SWITCH_CALLBACK, "LocatorCallbackHost::OnSwitchChange");
Send(switchState);
}
void LocationSwitchCallbackHost::DeleteHandler()
{
std::unique_lock<std::mutex> guard(mutex_);
if (handlerCb_ == nullptr || env_ == nullptr) {
LBSLOGE(SWITCH_CALLBACK, "handler or env is nullptr.");
return;
}
auto context = new (std::nothrow) AsyncContext(env_);
if (context == nullptr) {
LBSLOGE(SWITCH_CALLBACK, "context == nullptr.");
return;
}
context->env = env_;
context->callback[SUCCESS_CALLBACK] = handlerCb_;
DeleteQueueWork(context);
handlerCb_ = nullptr;
}
} // namespace Location
} // namespace OHOS

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2022 Huawei Device Co., Ltd.
* Copyright (C) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -14,54 +14,14 @@
*/
#include "locator_callback_host.h"
#include "ipc_object_stub.h"
#include "ipc_skeleton.h"
#include "js_native_api.h"
#include "message_option.h"
#include "message_parcel.h"
#include "napi/native_common.h"
#include "uv.h"
#include "common_utils.h"
#include "constant_definition.h"
#include "i_locator_callback.h"
#include "location.h"
#include "location_async_context.h"
#include "location_log.h"
#include "napi_util.h"
namespace OHOS {
namespace Location {
LocatorCallbackHost::LocatorCallbackHost()
{
env_ = nullptr;
handlerCb_ = nullptr;
successHandlerCb_ = nullptr;
failHandlerCb_ = nullptr;
completeHandlerCb_ = nullptr;
deferred_ = nullptr;
fixNumber_ = 0;
inHdArea_ = true;
singleLocation_ = nullptr;
locationPriority_ = 0;
InitLatch();
}
void LocatorCallbackHost::InitLatch()
{
latch_ = new CountDownLatch();
latch_->SetCount(1);
}
LocatorCallbackHost::~LocatorCallbackHost()
{
delete latch_;
}
int LocatorCallbackHost::OnRemoteRequest(uint32_t code,
MessageParcel& data, MessageParcel& reply, MessageOption& option)
{
LBSLOGD(LOCATOR_CALLBACK, "LocatorCallbackHost::OnRemoteRequest!");
if (data.ReadInterfaceToken() != GetDescriptor()) {
LBSLOGE(LOCATOR_CALLBACK, "invalid token.");
return -1;
@ -71,16 +31,6 @@ int LocatorCallbackHost::OnRemoteRequest(uint32_t code,
case RECEIVE_LOCATION_INFO_EVENT: {
std::unique_ptr<Location> location = Location::Unmarshalling(data);
OnLocationReport(location);
if (location->GetLocationSourceType() == LocationSourceType::NETWORK_TYPE &&
location->GetAdditionsMap()["inHdArea"] != "") {
inHdArea_ = (location->GetAdditionsMap()["inHdArea"] == "true");
}
if (NeedSetSingleLocation(location)) {
SetSingleLocation(location);
}
if (IfReportAccuracyLocation()) {
CountDown();
}
break;
}
case RECEIVE_LOCATION_STATUS_EVENT: {
@ -91,14 +41,7 @@ int LocatorCallbackHost::OnRemoteRequest(uint32_t code,
case RECEIVE_ERROR_INFO_EVENT: {
int errorCode = data.ReadInt32();
LBSLOGI(LOCATOR_STANDARD, "CallbackSutb receive ERROR_EVENT. errorCode:%{public}d", errorCode);
if (errorCode == LOCATING_FAILED_INTERNET_ACCESS_FAILURE) {
inHdArea_ = false;
if (GetSingleLocation() != nullptr) {
CountDown();
}
} else {
OnErrorReport(errorCode);
}
OnErrorReport(errorCode);
break;
}
default: {
@ -108,167 +51,8 @@ int LocatorCallbackHost::OnRemoteRequest(uint32_t code,
}
return 0;
}
void LocatorCallbackHost::DoSendWork(uv_loop_s*& loop, uv_work_t*& work)
{
uv_queue_work(loop, work, [](uv_work_t* work) {}, [](uv_work_t* work, int status) {
if (work == nullptr) {
return;
}
napi_handle_scope scope = nullptr;
auto context = static_cast<LocationAsyncContext*>(work->data);
if (context == nullptr) {
delete work;
return;
}
if (context->env == nullptr || context->loc == nullptr) {
delete context;
delete work;
return;
}
napi_open_handle_scope(context->env, &scope);
if (scope == nullptr) {
DELETE_SCOPE_CONTEXT_WORK(context->env, scope, context, work);
return;
}
napi_value jsEvent = nullptr;
CHK_NAPI_ERR_CLOSE_SCOPE(context->env, napi_create_object(context->env, &jsEvent), scope, context, work);
if (context->callback[1]) {
SystemLocationToJs(context->env, context->loc, jsEvent);
} else {
LocationToJs(context->env, context->loc, jsEvent);
}
if (context->callback[0] != nullptr) {
napi_value undefine = nullptr;
napi_value handler = nullptr;
CHK_NAPI_ERR_CLOSE_SCOPE(context->env, napi_get_undefined(context->env, &undefine),
scope, context, work);
CHK_NAPI_ERR_CLOSE_SCOPE(context->env,
napi_get_reference_value(context->env, context->callback[0], &handler), scope, context, work);
if (napi_call_function(context->env, nullptr, handler, 1, &jsEvent, &undefine) != napi_ok) {
LBSLOGE(LOCATOR_CALLBACK, "Report location failed");
}
} else if (context->deferred != nullptr) {
CHK_NAPI_ERR_CLOSE_SCOPE(context->env,
((jsEvent != nullptr) ? napi_resolve_deferred(context->env, context->deferred, jsEvent) :
napi_reject_deferred(context->env, context->deferred, jsEvent)),
scope, context, work);
}
DELETE_SCOPE_CONTEXT_WORK(context->env, scope, context, work);
});
}
void LocatorCallbackHost::DoSendErrorCode(uv_loop_s *&loop, uv_work_t *&work)
{
uv_queue_work(loop, work, [](uv_work_t *work) {},
[](uv_work_t *work, int status) {
AsyncContext *context = nullptr;
napi_handle_scope scope = nullptr;
if (work == nullptr) {
LBSLOGE(LOCATOR_CALLBACK, "work is nullptr");
return;
}
context = static_cast<AsyncContext *>(work->data);
if (context == nullptr || context->env == nullptr) {
LBSLOGE(LOCATOR_CALLBACK, "context is nullptr");
delete work;
return;
}
NAPI_CALL_RETURN_VOID(context->env, napi_open_handle_scope(context->env, &scope));
if (scope == nullptr) {
LBSLOGE(LOCATOR_CALLBACK, "scope is nullptr");
delete context;
delete work;
return;
}
if (context->callback[FAIL_CALLBACK] != nullptr) {
napi_value undefine;
napi_value handler = nullptr;
CHK_NAPI_ERR_CLOSE_SCOPE(context->env, napi_get_undefined(context->env, &undefine),
scope, context, work);
CHK_NAPI_ERR_CLOSE_SCOPE(context->env,
napi_get_reference_value(context->env, context->callback[FAIL_CALLBACK], &handler),
scope, context, work);
std::string msg = GetErrorMsgByCode(context->errCode);
CreateFailCallBackParams(*context, msg, context->errCode);
if (napi_call_function(context->env, nullptr, handler, RESULT_SIZE,
context->result, &undefine) != napi_ok) {
LBSLOGE(LOCATOR_CALLBACK, "Report system error failed");
}
}
NAPI_CALL_RETURN_VOID(context->env, napi_close_handle_scope(context->env, scope));
delete context;
delete work;
});
}
bool LocatorCallbackHost::SendErrorCode(const int& errorCode)
{
std::unique_lock<std::mutex> guard(mutex_);
if (!IsSystemGeoLocationApi() && !IsSingleLocationRequest()) {
LBSLOGE(LOCATOR_CALLBACK, "this is Callback type,cant send error msg.");
return false;
}
if (env_ == nullptr) {
LBSLOGE(LOCATOR_CALLBACK, "env_ is nullptr.");
return false;
}
uv_loop_s *loop = nullptr;
NAPI_CALL_BASE(env_, napi_get_uv_event_loop(env_, &loop), false);
if (loop == nullptr) {
LBSLOGE(LOCATOR_CALLBACK, "loop == nullptr.");
return false;
}
uv_work_t *work = new (std::nothrow) uv_work_t;
if (work == nullptr) {
LBSLOGE(LOCATOR_CALLBACK, "work == nullptr.");
return false;
}
AsyncContext *context = new (std::nothrow) AsyncContext(env_);
if (context == nullptr) {
LBSLOGE(LOCATOR_CALLBACK, "context == nullptr.");
delete work;
return false;
}
if (!InitContext(context)) {
LBSLOGE(LOCATOR_CALLBACK, "InitContext fail");
}
context->errCode = errorCode;
work->data = context;
DoSendErrorCode(loop, work);
return true;
}
void LocatorCallbackHost::OnLocationReport(const std::unique_ptr<Location>& location)
{
std::unique_lock<std::mutex> guard(mutex_);
uv_loop_s *loop = nullptr;
if (env_ == nullptr) {
LBSLOGD(LOCATOR_CALLBACK, "env_ is nullptr.");
return;
}
NAPI_CALL_RETURN_VOID(env_, napi_get_uv_event_loop(env_, &loop));
if (loop == nullptr) {
LBSLOGE(LOCATOR_CALLBACK, "loop == nullptr.");
return;
}
uv_work_t *work = new (std::nothrow) uv_work_t;
if (work == nullptr) {
LBSLOGE(LOCATOR_CALLBACK, "work == nullptr.");
return;
}
auto context = new (std::nothrow) LocationAsyncContext(env_);
if (context == nullptr) {
LBSLOGE(LOCATOR_CALLBACK, "context == nullptr.");
delete work;
return;
}
if (!InitContext(context)) {
LBSLOGE(LOCATOR_CALLBACK, "InitContext fail");
}
context->loc = std::make_unique<Location>(*location);
work->data = context;
DoSendWork(loop, work);
}
void LocatorCallbackHost::OnLocatingStatusChange(const int status)
@ -277,106 +61,6 @@ void LocatorCallbackHost::OnLocatingStatusChange(const int status)
void LocatorCallbackHost::OnErrorReport(const int errorCode)
{
SendErrorCode(errorCode);
}
void LocatorCallbackHost::DeleteAllCallbacks()
{
DeleteHandler();
}
void LocatorCallbackHost::DeleteHandler()
{
LBSLOGD(LOCATOR_CALLBACK, "before DeleteHandler");
std::unique_lock<std::mutex> guard(mutex_);
if (env_ == nullptr) {
LBSLOGE(LOCATOR_CALLBACK, "env is nullptr.");
return;
}
auto context = new (std::nothrow) AsyncContext(env_);
if (context == nullptr) {
LBSLOGE(LOCATOR_CALLBACK, "context == nullptr.");
return;
}
if (!InitContext(context)) {
LBSLOGE(LOCATOR_CALLBACK, "InitContext fail");
}
DeleteQueueWork(context);
if (IsSystemGeoLocationApi()) {
successHandlerCb_ = nullptr;
failHandlerCb_ = nullptr;
completeHandlerCb_ = nullptr;
} else {
handlerCb_ = nullptr;
}
}
bool LocatorCallbackHost::IsSystemGeoLocationApi()
{
return (successHandlerCb_ != nullptr) ? true : false;
}
bool LocatorCallbackHost::IsSingleLocationRequest()
{
return (fixNumber_ == 1);
}
void LocatorCallbackHost::CountDown()
{
if (IsSingleLocationRequest() && latch_ != nullptr) {
latch_->CountDown();
}
}
void LocatorCallbackHost::Wait(int time)
{
if (IsSingleLocationRequest() && latch_ != nullptr) {
latch_->Wait(time);
}
}
int LocatorCallbackHost::GetCount()
{
if (IsSingleLocationRequest() && latch_ != nullptr) {
return latch_->GetCount();
}
return 0;
}
void LocatorCallbackHost::SetCount(int count)
{
if (IsSingleLocationRequest() && latch_ != nullptr) {
return latch_->SetCount(count);
}
}
bool LocatorCallbackHost::NeedSetSingleLocation(const std::unique_ptr<Location>& location)
{
if (locationPriority_ == LOCATION_PRIORITY_ACCURACY &&
singleLocation_ != nullptr &&
location->GetLocationSourceType() == LocationSourceType::NETWORK_TYPE) {
return false;
} else {
return true;
}
}
bool LocatorCallbackHost::IfReportAccuracyLocation()
{
if (locationPriority_ == LOCATION_PRIORITY_ACCURACY &&
(((singleLocation_->GetLocationSourceType() == LocationSourceType::GNSS_TYPE ||
singleLocation_->GetLocationSourceType() == LocationSourceType::RTK_TYPE) && inHdArea_) ||
singleLocation_->GetLocationSourceType() == LocationSourceType::NETWORK_TYPE)) {
return false;
} else {
return true;
}
}
void LocatorCallbackHost::SetSingleLocation(const std::unique_ptr<Location>& location)
{
std::unique_lock<std::mutex> guard(mutex_);
singleLocation_ = std::make_shared<Location>(*location);
}
} // namespace Location
} // namespace OHOS

View File

@ -39,7 +39,8 @@ std::mutex g_locationCallbackMapMutex;
std::mutex g_gnssStatusInfoCallbacksMutex;
std::mutex g_nmeaCallbacksMutex;
std::shared_ptr<CallbackResumeManager> g_callbackResumer = std::make_shared<CallbackResumeManager>();
std::map<std::string, void(CallbackResumeManager::*)()> g_resumeFuncMap;
using CallbackResumeHandle = std::function<void()>;
std::map<std::string, CallbackResumeHandle> g_resumeFuncMap;
std::map<sptr<ILocatorCallback>, RequestConfig> g_locationCallbackMap;
std::set<sptr<IRemoteObject>> g_gnssStatusInfoCallbacks;
std::set<sptr<IRemoteObject>> g_nmeaCallbacks;
@ -1364,9 +1365,9 @@ void CallbackResumeManager::InitResumeCallbackFuncMap()
if (g_resumeFuncMap.size() != 0) {
return;
}
g_resumeFuncMap.insert(std::make_pair("satelliteStatusChange", &CallbackResumeManager::ResumeGnssStatusCallback));
g_resumeFuncMap.insert(std::make_pair("nmeaMessage", &CallbackResumeManager::ResumeNmeaMessageCallback));
g_resumeFuncMap.insert(std::make_pair("locationChange", &CallbackResumeManager::ResumeLocating));
g_resumeFuncMap.insert(std::make_pair("satelliteStatusChange", [this]() { return ResumeGnssStatusCallback(); }));
g_resumeFuncMap.insert(std::make_pair("nmeaMessage", [this]() { return ResumeNmeaMessageCallback(); }));
g_resumeFuncMap.insert(std::make_pair("locationChange", [this]() { return ResumeLocating(); }));
}
void CallbackResumeManager::ResumeCallback()
@ -1375,7 +1376,7 @@ void CallbackResumeManager::ResumeCallback()
std::unique_lock<std::mutex> lock(g_resumeFuncMapMutex);
for (auto iter = g_resumeFuncMap.begin(); iter != g_resumeFuncMap.end(); iter++) {
auto resumeFunc = iter->second;
(this->*resumeFunc)();
resumeFunc();
}
}
@ -1426,6 +1427,7 @@ void CallbackResumeManager::ResumeLocating()
}
auto requestConfig = std::make_unique<RequestConfig>();
requestConfig->Set(iter->second);
LBSLOGI(LOCATOR_STANDARD, "ResumeLocating requestConfig = %{public}s", requestConfig->ToString().c_str());
proxy->StartLocatingV9(requestConfig, locatorCallback);
}
}

View File

@ -27,6 +27,7 @@ public:
napi_async_work work;
napi_deferred deferred;
napi_ref callback[MAX_CALLBACK_NUM] = { 0 };
bool* callbackValid;
std::function<void(void*)> executeFunc;
std::function<void(void*)> completeFunc;
napi_value resourceName;
@ -43,6 +44,7 @@ public:
resourceName = nullptr;
result[PARAM0] = nullptr;
result[PARAM1] = nullptr;
callbackValid = nullptr;
errCode = 0;
}

View File

@ -40,16 +40,16 @@ const std::string DEFAULT_ABILITY = "default";
const std::string LOCATION_DIR = "/data/service/el1/public/location/";
const std::string SWITCH_CONFIG_NAME = "location_switch";
const std::string PRIVACY_CONFIG_NAME = "location_privacy";
const std::string NLP_SERVICE_NAME = "const.location.nlp_service_name";
const std::string NLP_ABILITY_NAME = "const.location.nlp_ability_name";
const std::string GEOCODE_SERVICE_NAME = "const.location.geocode_service_name";
const std::string GEOCODE_ABILITY_NAME = "const.location.geocode_ability_name";
const std::string SUPL_MODE_NAME = "const.location.supl_mode";
const std::string EDM_POLICY_NAME = "persist.edm.location_policy";
const std::string AGNSS_SERVER_ADDR = "const.location.agnss_server_addr";
const std::string AGNSS_SERVER_PORT = "const.location.agnss_server_port";
constexpr const char* NLP_SERVICE_NAME = "const.location.nlp_service_name";
constexpr const char* NLP_ABILITY_NAME = "const.location.nlp_ability_name";
constexpr const char* GEOCODE_SERVICE_NAME = "const.location.geocode_service_name";
constexpr const char* GEOCODE_ABILITY_NAME = "const.location.geocode_ability_name";
constexpr const char* SUPL_MODE_NAME = "const.location.supl_mode";
constexpr const char* EDM_POLICY_NAME = "persist.edm.location_policy";
constexpr const char* AGNSS_SERVER_ADDR = "const.location.agnss_server_addr";
constexpr const char* AGNSS_SERVER_PORT = "const.location.agnss_server_port";
const std::string BUILD_INFO = "ro.build.characteristics";
constexpr const char* BUILD_INFO = "ro.build.characteristics";
const int SA_NUM = 3;
const int DEFAULT_UID = 10001;
const int SYSTEM_UID = 1000;

View File

@ -47,12 +47,10 @@ const int32_t UNKNOW_USER_ID = -1;
const int32_t SUBSCRIBE_TIME = 5;
const int32_t DEFAULT_TIME_INTERVAL = 30 * 60; // app receive location every 30 minutes in frozen state
const int32_t REQUESTS_NUM_MAX = 1;
const std::string FEATURE_SWITCH_PROP = "ro.config.locator_background";
const std::string TIME_INTERVAL_PROP = "ro.config.locator_background.timeInterval";
const std::string PROC_NAME = "system";
const std::string SEARCH_NET_WORK_STATE_CHANGE_ACTION = "com.hos.action.SEARCH_NET_WORK_STATE_CHANGE";
const std::string SIM_STATE_CHANGE_ACTION = "com.hos.action.SIM_STATE_CHANGE";
const std::string LOCALE_KEY = "persist.global.locale";
constexpr const char* FEATURE_SWITCH_PROP = "ro.config.locator_background";
constexpr const char* TIME_INTERVAL_PROP = "ro.config.locator_background.timeInterval";
constexpr const char* PROC_NAME = "system";
constexpr const char* LOCALE_KEY = "persist.global.locale";
const int MODE_STANDALONE = 1;
const int MODE_MS_BASED = 2;
const int MODE_MS_ASSISTED = 3;

View File

@ -80,7 +80,7 @@ private:
std::shared_ptr<CountryCode> lastCountryByLocation_;
std::shared_ptr<CountryCode> lastCountry_;
std::unique_ptr<std::map<pid_t, sptr<ICountryCodeCallback>>> countryCodeCallback_;
std::vector<sptr<ICountryCodeCallback>> countryCodeCallbacks_;
std::shared_ptr<SimSubscriber> simSubscriber_;
std::shared_ptr<NetworkSubscriber> networkSubscriber_;
std::mutex simSubscriberMutex_;

View File

@ -25,7 +25,7 @@
#include "async_context.h"
#include "constant_definition.h"
#include "location_log.h"
#include "location_gnss_geofence_callback_host.h"
#include "location_gnss_geofence_callback_napi.h"
#include "geofence_definition.h"
#include "geofence_request.h"
@ -35,7 +35,7 @@ class GnssGeofenceAsyncContext : public AsyncContext {
public:
int code_{-1};
GeofenceTransition transition_{-1, GEOFENCE_TRANSITION_INIT};
sptr<LocationGnssGeofenceCallbackHost> callbackHost_ = nullptr;
sptr<LocationGnssGeofenceCallbackNapi> callbackHost_ = nullptr;
std::shared_ptr<GeofenceRequest> request_;
int fenceId_{-1};

View File

@ -19,7 +19,9 @@
#include <mutex>
#include <vector>
#include "geofence_definition.h"
#ifdef NOTIFICATION_ENABLE
#include "notification_request.h"
#endif
#include "want_agent_helper.h"
#include <parcel.h>
@ -35,135 +37,57 @@ typedef struct {
class GeofenceRequest : public Parcelable {
public:
GeofenceRequest()
{
callback_ = nullptr;
scenario_ = -1;
fenceId_ = -1;
}
GeofenceRequest();
GeofenceRequest(GeofenceRequest& geofenceRequest)
{
this->SetGeofence(geofenceRequest.GetGeofence());
this->SetScenario(geofenceRequest.GetScenario());
this->SetWantAgent(geofenceRequest.GetWantAgent());
this->SetGeofenceTransitionEventList(geofenceRequest.GetGeofenceTransitionEventList());
this->SetNotificationRequestList(geofenceRequest.GetNotificationRequestList());
this->SetGeofenceTransitionCallback(geofenceRequest.GetGeofenceTransitionCallback());
this->SetFenceId(geofenceRequest.GetFenceId());
this->SetBundleName(geofenceRequest.GetBundleName());
}
GeofenceRequest(GeofenceRequest& geofenceRequest);
~GeofenceRequest() {}
~GeofenceRequest();
inline GeoFence GetGeofence()
{
return geofence_;
}
GeoFence GetGeofence();
void SetGeofence(GeoFence geofence);
inline void SetGeofence(GeoFence geofence)
{
geofence_ = geofence;
}
int GetScenario();
inline int GetScenario()
{
return scenario_;
}
void SetScenario(int scenario);
inline void SetScenario(int scenario)
{
scenario_ = scenario;
}
void SetWantAgent(const AbilityRuntime::WantAgent::WantAgent wantAgent);
inline void SetWantAgent(const AbilityRuntime::WantAgent::WantAgent wantAgent)
{
wantAgent_ = wantAgent;
}
AbilityRuntime::WantAgent::WantAgent GetWantAgent();
inline AbilityRuntime::WantAgent::WantAgent GetWantAgent()
{
return wantAgent_;
}
std::vector<GeofenceTransitionEvent> GetGeofenceTransitionEventList();
inline std::vector<GeofenceTransitionEvent> GetGeofenceTransitionEventList()
{
std::unique_lock<std::mutex> lock(geofenceRequestMutex_);
return transitionStatusList_;
}
void SetGeofenceTransitionEvent(GeofenceTransitionEvent status);
inline void SetGeofenceTransitionEvent(GeofenceTransitionEvent status)
{
std::unique_lock<std::mutex> lock(geofenceRequestMutex_);
transitionStatusList_.push_back(status);
}
void SetGeofenceTransitionEventList(std::vector<GeofenceTransitionEvent> statusList);
inline void SetGeofenceTransitionEventList(std::vector<GeofenceTransitionEvent> statusList)
{
std::unique_lock<std::mutex> lock(geofenceRequestMutex_);
for (auto it = statusList.begin(); it != statusList.end(); ++it) {
transitionStatusList_.push_back(*it);
}
}
#ifdef NOTIFICATION_ENABLE
std::vector<OHOS::Notification::NotificationRequest> GetNotificationRequestList();
inline std::vector<OHOS::Notification::NotificationRequest> GetNotificationRequestList()
{
std::unique_lock<std::mutex> lock(geofenceRequestMutex_);
return notificationRequestList_;
}
void SetNotificationRequest(OHOS::Notification::NotificationRequest request);
inline void SetNotificationRequest(OHOS::Notification::NotificationRequest request)
{
std::unique_lock<std::mutex> lock(geofenceRequestMutex_);
notificationRequestList_.push_back(request);
}
void SetNotificationRequestList(std::vector<OHOS::Notification::NotificationRequest> requestList);
#endif
inline void SetNotificationRequestList(std::vector<OHOS::Notification::NotificationRequest> requestList)
{
std::unique_lock<std::mutex> lock(geofenceRequestMutex_);
for (auto it = requestList.begin(); it != requestList.end(); ++it) {
notificationRequestList_.push_back(*it);
}
}
void SetGeofenceTransitionCallback(const sptr<IRemoteObject>& callback);
inline void SetGeofenceTransitionCallback(const sptr<IRemoteObject>& callback)
{
callback_ = callback;
}
sptr<IRemoteObject> GetGeofenceTransitionCallback();
inline sptr<IRemoteObject> GetGeofenceTransitionCallback()
{
return callback_;
}
int GetFenceId();
inline int GetFenceId()
{
return fenceId_;
}
void SetFenceId(int fenceId);
inline void SetFenceId(int fenceId)
{
fenceId_ = fenceId;
}
std::string GetBundleName();
inline std::string GetBundleName()
{
return bundleName_;
}
inline void SetBundleName(std::string bundleName)
{
bundleName_ = bundleName;
}
void SetBundleName(std::string bundleName);
void ReadFromParcel(Parcel& parcel);
bool Marshalling(Parcel& parcel) const override;
static std::shared_ptr<GeofenceRequest> Unmarshalling(Parcel& parcel);
private:
std::vector<GeofenceTransitionEvent> transitionStatusList_;
#ifdef NOTIFICATION_ENABLE
std::vector<OHOS::Notification::NotificationRequest> notificationRequestList_;
#endif
sptr<IRemoteObject> callback_ = nullptr;
GeoFence geofence_{0.0, 0.0, 0.0, WGS84};
int scenario_;

View File

@ -67,11 +67,27 @@ public:
LocationErrCode RemoveGnssGeofence(std::shared_ptr<GeofenceRequest>& request);
LocationErrCode GetGeofenceSupportedCoordTypes(
std::vector<CoordinateSystemType>& coordinateSystemTypes);
void ResetGeofenceSdkProxy(const wptr<IRemoteObject> &remote);
private:
sptr<GeofenceSdk> GetProxy();
sptr<GeofenceSdk> client_ { nullptr };
sptr<IRemoteObject::DeathRecipient> recipient_ { nullptr };
std::mutex mutex_;
bool isServerExist_ = false;
private:
class GeofenceManagerDeathRecipient : public IRemoteObject::DeathRecipient {
public:
explicit GeofenceManagerDeathRecipient(GeofenceManager &impl) : impl_(impl) {}
~GeofenceManagerDeathRecipient() override = default;
void OnRemoteDied(const wptr<IRemoteObject> &remote) override
{
impl_.ResetGeofenceSdkProxy(remote);
}
private:
GeofenceManager &impl_;
};
};
} // namespace Location
} // namespace OHOS

View File

@ -116,7 +116,7 @@ public:
inline void SetAdditions(std::vector<std::string> additions, bool ifAppend)
{
if (!ifAppend) {
additions_.clear();
std::vector<std::string>().swap(additions_);
}
for (auto it = additions.begin(); it != additions.end(); ++it) {
additions_.push_back(*it);

View File

@ -28,14 +28,14 @@
#include "geo_address.h"
#include "geo_coding_mock_info.h"
#include "locating_required_data.h"
#include "locating_required_data_callback_host.h"
#include "locating_required_data_callback_napi.h"
#include "locating_required_data_config.h"
#include "location.h"
#include "location_log.h"
#include "locator_callback_host.h"
#include "locator_callback_napi.h"
#include "request_config.h"
#include "satellite_status.h"
#include "location_gnss_geofence_callback_host.h"
#include "location_gnss_geofence_callback_napi.h"
namespace OHOS {
namespace Location {
@ -219,7 +219,7 @@ public:
class SingleLocationAsyncContext : public AsyncContext {
public:
int timeout_;
sptr<LocatorCallbackHost> callbackHost_;
sptr<LocatorCallbackNapi> callbackHost_;
std::unique_ptr<RequestConfig> request_;
explicit SingleLocationAsyncContext(napi_env env, napi_async_work work = nullptr, napi_deferred deferred = nullptr)
@ -260,7 +260,7 @@ public:
class SingleScanAsyncContext : public AsyncContext {
public:
int timeout_;
sptr<LocatingRequiredDataCallbackHost> callbackHost_;
sptr<LocatingRequiredDataCallbackNapi> callbackHost_;
explicit SingleScanAsyncContext(napi_env env, napi_async_work work = nullptr, napi_deferred deferred = nullptr)
: AsyncContext(env, work, deferred), timeout_(0), callbackHost_(nullptr) {}

View File

@ -47,7 +47,7 @@ public:
private:
std::mutex mutex_;
std::mutex switchStateMutex_;
std::unique_ptr<std::map<pid_t, sptr<ISwitchCallback>>> switchCallbacks_;
std::vector<sptr<ISwitchCallback>> switchCallbacks_;
int32_t cachedSwitchState_ = DISABLED;
bool isStateCached_ = false;
bool isObserverReg_ = false;

View File

@ -23,15 +23,10 @@
namespace OHOS {
namespace Location {
const std::string LOCATION_DATA_ABILITY_PREFIX = "datashare://";
const std::string LOCATION_DATA_URI_ID =
"/com.ohos.settingsdata/entry/settingsdata/SETTINGSDATA?Proxy=true&key=location_enable";
const std::string LOCATION_DATA_URI = LOCATION_DATA_ABILITY_PREFIX + LOCATION_DATA_URI_ID;
const std::string LOCATION_DATA_COLUMN_KEYWORD = "KEYWORD";
const std::string LOCATION_DATA_COLUMN_VALUE = "VALUE";
const std::string LOCATION_DATA_COLUMN_ENABLE = "location_switch_enable";
const std::string LOCATION_WORKING_STATE = "location_working_state";
const std::string LOCATION_ENHANCE_STATUS = "location_enhance_status";
const std::string LOCATION_DATA_URI =
"datashare:///com.ohos.settingsdata/entry/settingsdata/SETTINGSDATA?Proxy=true&key=location_enable";
class LocationDataRdbManager {
public:
static std::string GetLocationDataUri(std::string key);

View File

@ -13,8 +13,8 @@
* limitations under the License.
*/
#ifndef LOCATION_GNSS_GEOFENCE_CALLBACK_HOST_H
#define LOCATION_GNSS_GEOFENCE_CALLBACK_HOST_H
#ifndef LOCATION_GNSS_GEOFENCE_CALLBACK_NAPI_H
#define LOCATION_GNSS_GEOFENCE_CALLBACK_NAPI_H
#include "iremote_stub.h"
#include "message_option.h"
@ -27,10 +27,10 @@
namespace OHOS {
namespace Location {
class LocationGnssGeofenceCallbackHost : public IRemoteStub<IGnssGeofenceCallback> {
class LocationGnssGeofenceCallbackNapi : public IRemoteStub<IGnssGeofenceCallback> {
public:
LocationGnssGeofenceCallbackHost();
virtual ~LocationGnssGeofenceCallbackHost();
LocationGnssGeofenceCallbackNapi();
virtual ~LocationGnssGeofenceCallbackNapi();
virtual int OnRemoteRequest(
uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) override;
bool IsRemoteDied();
@ -50,6 +50,20 @@ public:
void OnTransitionStatusChange(GeofenceTransition transition) override;
void OnReportOperationResult(int fenceId, int type, int result) override;
template <typename T>
bool InitContext(T* context)
{
if (context == nullptr) {
LBSLOGE(LOCATION_GNSS_GEOFENCE_CALLBACK, "context == nullptr.");
return false;
}
context->env = env_;
callbackValid_ = handlerCb_ == nullptr ? false : true;
context->callbackValid = &callbackValid_;
context->callback[SUCCESS_CALLBACK] = handlerCb_;
return true;
}
inline napi_env GetEnv() const
{
return env_;
@ -91,9 +105,10 @@ private:
std::mutex operationResultMutex_;
CountDownLatch* latch_;
int fenceId_;
bool callbackValid_;
GnssGeofenceOperateType type_;
GnssGeofenceOperateResult result_;
};
} // namespace Location
} // namespace OHOS
#endif // LOCATION_GNSS_GEOFENCE_CALLBACK_HOST_H
#endif // LOCATION_GNSS_GEOFENCE_CALLBACK_NAPI_H

View File

@ -83,6 +83,9 @@ static constexpr OHOS::HiviewDFX::HiLogLabel COUNTRY_CODE_CALLBACK = {
static constexpr OHOS::HiviewDFX::HiLogLabel LOCATING_DATA_CALLBACK = {
LOG_CORE, LOCATION_LOG_DOMAIN, "LocatingDataCallback"
};
static constexpr OHOS::HiviewDFX::HiLogLabel LOCATION_ERR_CALLBACK = {
LOG_CORE, LOCATION_LOG_DOMAIN, "LocationErrorCallback"
};
static constexpr OHOS::HiviewDFX::HiLogLabel LOCATOR_CALLBACK = {LOG_CORE, LOCATION_LOG_DOMAIN, "LocatorCallback"};
static constexpr OHOS::HiviewDFX::HiLogLabel GNSS = {LOG_CORE, LOCATION_LOG_DOMAIN, "GnssAbility"};
static constexpr OHOS::HiviewDFX::HiLogLabel GNSS_TEST = {LOG_CORE, LOCATION_LOG_DOMAIN, "GnssAbilityTest"};
@ -114,6 +117,7 @@ static constexpr OHOS::HiviewDFX::HiLogLabel NAPI_UTILS = {LOG_CORE, LOCATION_LO
static constexpr OHOS::HiviewDFX::HiLogLabel GEOFENCE_SDK = {
LOG_CORE, LOCATION_LOG_DOMAIN, "geofenceSdk"
};
static constexpr OHOS::HiviewDFX::HiLogLabel GEOFENCE_SDK_TEST = {LOG_CORE, LOCATION_LOG_DOMAIN, "GeofenceSdkTest"};
} // namespace Location
} // namespace OHOS
#endif // LOCATION_LOG_H

View File

@ -68,6 +68,8 @@ public:
void SetNlpRequestType();
void SetLocationErrorCallBack(const sptr<ILocatorCallback>& callback);
sptr<ILocatorCallback> GetLocationErrorCallBack();
void SetLocatorCallbackRecipient(const sptr<IRemoteObject::DeathRecipient>& recipient);
sptr<IRemoteObject::DeathRecipient> GetLocatorCallbackRecipient();
private:
void GetProxyNameByPriority(std::shared_ptr<std::list<std::string>> proxys);
@ -88,6 +90,7 @@ private:
bool isUsingBackgroundPerm_;
bool isUsingApproximatelyPerm_;
int permUsedType_;
sptr<IRemoteObject::DeathRecipient> locatorCallbackRecipient_;
};
} // namespace Location
} // namespace OHOS

View File

@ -12,7 +12,7 @@
"name" : "locationhub",
"path" : ["/system/bin/sa_main", "/system/profile/locationhub.json"],
"uid" : "gps",
"gid" : ["gps", "shell"],
"gid" : ["gps", "shell", "netsys_socket"],
"secon" : "u:r:locationhub:s0",
"permission" : [
"ohos.permission.PERMISSION_USED_STATS",

View File

@ -14,14 +14,16 @@
import("//base/location/config.gni")
import("//build/ohos.gni")
local_base_sources = [
"$LOCATION_GEOCONVERT_ROOT/source/geo_convert_callback_host.cpp",
"$LOCATION_GEOCONVERT_ROOT/source/geo_convert_service.cpp",
"$LOCATION_GEOCONVERT_ROOT/source/geo_convert_skeleton.cpp",
"$LOCATION_LOCATOR_ROOT/source/location_config_manager.cpp",
]
if (location_feature_with_geocode) {
ohos_shared_library("lbsservice_geocode") {
sources = [
"$LOCATION_GEOCONVERT_ROOT/source/geo_convert_callback_host.cpp",
"$LOCATION_GEOCONVERT_ROOT/source/geo_convert_service.cpp",
"$LOCATION_GEOCONVERT_ROOT/source/geo_convert_skeleton.cpp",
"$LOCATION_LOCATOR_ROOT/source/location_config_manager.cpp",
]
sources = local_base_sources
include_dirs = [
"$LOCATION_GEOCONVERT_ROOT/include",
@ -40,6 +42,67 @@ if (location_feature_with_geocode) {
"$LOCATION_ROOT_DIR/frameworks/location_common/common:lbsservice_common",
]
ldflags = [
"-Wl,--as-needed",
"-Wl,--gc-sections",
]
cflags_cc = [
"-ffunction-sections",
"-fdata-sections",
"-Os",
]
defines = []
if (location_feature_with_geocode) {
defines += [ "FEATURE_GEOCODE_SUPPORT" ]
}
external_deps = [
"ability_base:want",
"ability_runtime:ability_manager",
"hilog:libhilog",
"ipc:ipc_single",
"safwk:system_ability_fwk",
]
# Used to control the export of dynamic library symbols.
version_script = "liblbsservice_geocode_version_script.txt"
part_name = "location"
subsystem_name = "location"
}
ohos_static_library("lbsservice_geocode_static") {
sources = local_base_sources
include_dirs = [
"$LOCATION_GEOCONVERT_ROOT/include",
"$LOCATION_LOCATOR_ROOT/include",
"$LOCATION_ROOT_DIR/interfaces/inner_api/include",
]
sanitize = {
cfi = true
cfi_cross_dso = true
debug = false
}
branch_protector_ret = "pac_ret"
deps = [
"$LOCATION_ROOT_DIR/frameworks/location_common/common:lbsservice_common",
]
ldflags = [
"-Wl,--as-needed",
"-Wl,--gc-sections",
]
cflags_cc = [
"-ffunction-sections",
"-fdata-sections",
]
defines = []
if (location_feature_with_geocode) {
defines += [ "FEATURE_GEOCODE_SUPPORT" ]
@ -47,11 +110,8 @@ if (location_feature_with_geocode) {
external_deps = [
"ability_base:want",
"ability_runtime:ability_connect_callback_stub",
"ability_runtime:ability_manager",
"c_utils:utils",
"hilog:libhilog",
"init:libbegetutil",
"ipc:ipc_single",
"safwk:system_ability_fwk",
]
@ -64,4 +124,9 @@ if (location_feature_with_geocode) {
part_name = "location"
subsystem_name = "location"
}
ohos_static_library("lbsservice_geocode_static") {
part_name = "location"
subsystem_name = "location"
}
}

View File

@ -42,8 +42,7 @@ public:
class GeoConvertServiceStub : public IRemoteStub<IGeoConvert> {
public:
using GeoConvertMsgHandle = int (GeoConvertServiceStub::*)(
MessageParcel &data, MessageParcel &reply, AppIdentity &identity);
using GeoConvertMsgHandle = std::function<int(MessageParcel &, MessageParcel &, AppIdentity &)>;
using GeoConvertMsgHandleMap = std::map<int, GeoConvertMsgHandle>;
GeoConvertServiceStub();
virtual ~GeoConvertServiceStub() = default;

View File

@ -0,0 +1,5 @@
{
global:
local:
*;
};

View File

@ -29,17 +29,29 @@ void GeoConvertServiceStub::InitGeoConvertHandleMap()
return;
}
geoConvertMsgHandleMap_[static_cast<uint32_t>(GeoConvertInterfaceCode::IS_AVAILABLE)] =
&GeoConvertServiceStub::IsGeoConvertAvailableInner;
[this](MessageParcel &data, MessageParcel &reply, AppIdentity &identity) {
return IsGeoConvertAvailableInner(data, reply, identity);
};
geoConvertMsgHandleMap_[static_cast<uint32_t>(GeoConvertInterfaceCode::GET_FROM_COORDINATE)] =
&GeoConvertServiceStub::GetAddressByCoordinateInner;
[this](MessageParcel &data, MessageParcel &reply, AppIdentity &identity) {
return GetAddressByCoordinateInner(data, reply, identity);
};
geoConvertMsgHandleMap_[static_cast<uint32_t>(GeoConvertInterfaceCode::GET_FROM_LOCATION_NAME_BY_BOUNDARY)] =
&GeoConvertServiceStub::GetAddressByLocationNameInner;
[this](MessageParcel &data, MessageParcel &reply, AppIdentity &identity) {
return GetAddressByLocationNameInner(data, reply, identity);
};
geoConvertMsgHandleMap_[static_cast<uint32_t>(GeoConvertInterfaceCode::ENABLE_REVERSE_GEOCODE_MOCK)] =
&GeoConvertServiceStub::EnableReverseGeocodingMockInner;
[this](MessageParcel &data, MessageParcel &reply, AppIdentity &identity) {
return EnableReverseGeocodingMockInner(data, reply, identity);
};
geoConvertMsgHandleMap_[static_cast<uint32_t>(GeoConvertInterfaceCode::DISABLE_REVERSE_GEOCODE_MOCK)] =
&GeoConvertServiceStub::DisableReverseGeocodingMockInner;
[this](MessageParcel &data, MessageParcel &reply, AppIdentity &identity) {
return DisableReverseGeocodingMockInner(data, reply, identity);
};
geoConvertMsgHandleMap_[static_cast<uint32_t>(GeoConvertInterfaceCode::SET_REVERSE_GEOCODE_MOCKINFO)] =
&GeoConvertServiceStub::SetGeocodingMockInfoInner;
[this](MessageParcel &data, MessageParcel &reply, AppIdentity &identity) {
return SetGeocodingMockInfoInner(data, reply, identity);
};
}
GeoConvertServiceStub::GeoConvertServiceStub()
@ -138,7 +150,6 @@ int GeoConvertServiceStub::OnRemoteRequest(uint32_t code,
code, option.GetFlags(), callingPid, callingUid, std::to_string(CommonUtils::GetCurrentTimeStamp()).c_str());
if (data.ReadInterfaceToken() != GetDescriptor()) {
LBSLOGE(GEO_CONVERT, "invalid token.");
reply.WriteInt32(ERRCODE_SERVICE_UNAVAILABLE);
return ERRCODE_SERVICE_UNAVAILABLE;
}
@ -146,12 +157,9 @@ int GeoConvertServiceStub::OnRemoteRequest(uint32_t code,
auto handleFunc = geoConvertMsgHandleMap_.find(code);
if (handleFunc != geoConvertMsgHandleMap_.end() && handleFunc->second != nullptr) {
auto memberFunc = handleFunc->second;
ret = (this->*memberFunc)(data, reply, identity);
ret = memberFunc(data, reply, identity);
} else {
LBSLOGE(GEO_CONVERT, "OnReceived cmd = %{public}u, unsupport service.", code);
#if !defined(FEATURE_GNSS_SUPPORT) || !defined(FEATURE_GEOCODE_SUPPORT)
reply.WriteInt32(ERRCODE_NOT_SUPPORTED);
#endif
ret = IPCObjectStub::OnRemoteRequest(code, data, reply, option);
}
UnloadGeoConvertSystemAbility();

View File

@ -15,21 +15,23 @@ import("//base/location/config.gni")
import("//build/ohos.gni")
if (location_feature_with_gnss) {
local_base_sources = [
"$LOCATION_GNSS_ROOT/source/agnss_event_callback.cpp",
"$LOCATION_GNSS_ROOT/source/agnss_ni_manager.cpp",
"$LOCATION_GNSS_ROOT/source/geofence_event_callback.cpp",
"$LOCATION_GNSS_ROOT/source/gnss_ability.cpp",
"$LOCATION_GNSS_ROOT/source/gnss_ability_skeleton.cpp",
"$LOCATION_GNSS_ROOT/source/gnss_common_event_subscriber.cpp",
"$LOCATION_GNSS_ROOT/source/gnss_event_callback.cpp",
"$LOCATION_GNSS_ROOT/source/string_utils.cpp",
"$LOCATION_LOCATOR_ROOT/source/location_config_manager.cpp",
"$LOCATION_LOCATOR_ROOT/source/subability_common.cpp",
"$LOCATION_LOCATOR_ROOT/source/work_record.cpp",
"$LOCATION_LOCATOR_ROOT/source/work_record_statistic.cpp",
]
ohos_shared_library("lbsservice_gnss") {
sources = [
"$LOCATION_GNSS_ROOT/source/agnss_event_callback.cpp",
"$LOCATION_GNSS_ROOT/source/agnss_ni_manager.cpp",
"$LOCATION_GNSS_ROOT/source/geofence_event_callback.cpp",
"$LOCATION_GNSS_ROOT/source/gnss_ability.cpp",
"$LOCATION_GNSS_ROOT/source/gnss_ability_skeleton.cpp",
"$LOCATION_GNSS_ROOT/source/gnss_common_event_subscriber.cpp",
"$LOCATION_GNSS_ROOT/source/gnss_event_callback.cpp",
"$LOCATION_GNSS_ROOT/source/string_utils.cpp",
"$LOCATION_LOCATOR_ROOT/source/location_config_manager.cpp",
"$LOCATION_LOCATOR_ROOT/source/subability_common.cpp",
"$LOCATION_LOCATOR_ROOT/source/work_record.cpp",
"$LOCATION_LOCATOR_ROOT/source/work_record_statistic.cpp",
]
sources = local_base_sources
include_dirs = [
"$LOCATION_ROOT_DIR/interfaces/inner_api/include",
@ -51,13 +53,132 @@ if (location_feature_with_gnss) {
external_deps = [
"ability_base:want",
"ability_runtime:ability_connect_callback_stub",
"c_utils:utils",
"eventhandler:libeventhandler",
"ffrt:libffrt",
"hdf_core:libhdi",
"hilog:libhilog",
"init:libbegetutil",
"ipc:ipc_single",
"relational_store:native_rdb",
"safwk:system_ability_fwk",
"samgr:samgr_proxy",
]
defines = []
ldflags = [
"-Wl,--as-needed",
"-Wl,--gc-sections",
]
cflags_cc = [
"-ffunction-sections",
"-fdata-sections",
"-flto=thin",
"-Os",
]
if (telephony_core_service_enable) {
external_deps += [ "core_service:tel_core_service_api" ]
defines += [ "TEL_CORE_SERVICE_ENABLE" ]
}
if (telephony_cellular_data_enable) {
external_deps += [ "cellular_data:tel_cellular_data_api" ]
defines += [ "TEL_CELLULAR_DATA_ENABLE" ]
}
if (hdf_drivers_interface_location_agnss_enable) {
external_deps +=
[ "drivers_interface_location_agnss:liblocation_agnss_proxy_2.0" ]
defines += [ "HDF_DRIVERS_INTERFACE_AGNSS_ENABLE" ]
}
if (location_feature_with_gnss &&
hdf_drivers_interface_location_gnss_enable) {
external_deps +=
[ "drivers_interface_location_gnss:liblocation_gnss_proxy_2.0" ]
defines += [ "FEATURE_GNSS_SUPPORT" ]
}
if (location_feature_with_passive) {
defines += [ "FEATURE_PASSIVE_SUPPORT" ]
}
if (communication_wifi_enable) {
external_deps += [ "wifi:wifi_sdk" ]
defines += [ "WIFI_ENABLE" ]
}
if (call_manager_enable) {
external_deps += [ "call_manager:tel_call_manager_api" ]
defines += [ "CALL_MANAGER_ENABLE" ]
}
if (common_event_service_enable) {
external_deps += [
"ability_runtime:extension_manager",
"common_event_service:cesfwk_innerkits",
]
defines += [ "COMMON_EVENT_SERVICE_ENABLE" ]
}
if (sms_mms_enable) {
external_deps += [ "sms_mms:tel_sms_mms_api" ]
defines += [ "SMS_MMS_ENABLE" ]
}
if (notification_distributed_notification_service_enable) {
defines += [ "NOTIFICATION_ENABLE" ]
}
if (hdf_drivers_interface_location_geofence_enable) {
external_deps += [
"drivers_interface_location_geofence:liblocation_geofence_proxy_2.0",
]
defines += [ "HDF_DRIVERS_INTERFACE_GEOFENCE_ENABLE" ]
}
if (time_service_enable) {
external_deps += [ "time_service:time_client" ]
defines += [ "TIME_SERVICE_ENABLE" ]
}
# Used to control the export of dynamic library symbols.
version_script = "liblbsservice_gnss_version_script.txt"
part_name = "location"
subsystem_name = "location"
}
ohos_static_library("lbsservice_gnss_static") {
sources = local_base_sources
include_dirs = [
"$LOCATION_ROOT_DIR/interfaces/inner_api/include",
"$LOCATION_GNSS_ROOT/include",
"$LOCATION_LOCATOR_ROOT/include",
]
sanitize = {
cfi = true
cfi_cross_dso = true
debug = false
}
branch_protector_ret = "pac_ret"
deps = [
"$LOCATION_ROOT_DIR/frameworks/location_common/common:lbsservice_common",
"$LOCATION_ROOT_DIR/frameworks/native/geofence_sdk:geofence_sdk",
]
external_deps = [
"ability_base:want",
"eventhandler:libeventhandler",
"ffrt:libffrt",
"hdf_core:libhdi",
"hilog:libhilog",
"ipc:ipc_single",
"relational_store:native_rdb",
"safwk:system_ability_fwk",
"samgr:samgr_proxy",
]
@ -115,7 +236,6 @@ if (location_feature_with_gnss) {
}
if (notification_distributed_notification_service_enable) {
external_deps += [ "distributed_notification_service:ans_innerkits" ]
defines += [ "NOTIFICATION_ENABLE" ]
}
@ -139,4 +259,9 @@ if (location_feature_with_gnss) {
part_name = "location"
subsystem_name = "location"
}
ohos_static_library("lbsservice_gnss_static") {
part_name = "location"
subsystem_name = "location"
}
}

View File

@ -19,8 +19,10 @@
#ifdef HDF_DRIVERS_INTERFACE_AGNSS_ENABLE
#include <v2_0/ia_gnss_callback.h>
#ifdef TEL_CORE_SERVICE_ENABLE
#include "core_service_client.h"
#include "cell_information.h"
#endif
namespace OHOS {
namespace Location {
@ -31,7 +33,10 @@ using HDI::Location::Agnss::V2_0::SubscriberSetIdType;
using HDI::Location::Agnss::V2_0::AGnssRefInfo;
using HDI::Location::Agnss::V2_0::AGnssRefInfoType;
using HDI::Location::Agnss::V2_0::AGnssUserPlaneProtocol;
#ifdef TEL_CORE_SERVICE_ENABLE
using OHOS::Telephony::CellInformation;
#endif
class AGnssEventCallback : public IAGnssCallback {
public:
@ -40,10 +45,12 @@ public:
int32_t RequestSubscriberSetId(SubscriberSetIdType type) override;
int32_t RequestAgnssRefInfo(AGnssRefInfoType type) override;
private:
#ifdef TEL_CORE_SERVICE_ENABLE
void JudgmentDataGsm(AGnssRefInfo& refInfo, sptr<CellInformation> infoItem);
void JudgmentDataUmts(AGnssRefInfo& refInfo, sptr<CellInformation> infoItem);
void JudgmentDataLte(AGnssRefInfo& refInfo, sptr<CellInformation> infoItem);
void JudgmentDataNr(AGnssRefInfo& refInfo, sptr<CellInformation> infoItem);
#endif
__attribute__((no_sanitize("cfi"))) void GetWiFiRefInfo(AGnssRefInfo& refInfo);
void GetCellRefInfo(AGnssRefInfo& refInfo);
};

View File

@ -28,6 +28,7 @@
#endif
#include "event_handler.h"
#include "ffrt.h"
#include "system_ability.h"
#ifdef HDF_DRIVERS_INTERFACE_AGNSS_ENABLE
#include "agnss_event_callback.h"
@ -43,10 +44,6 @@
#include "locationhub_ipc_interface_code.h"
#include "geofence_event_callback.h"
#include "ipc_skeleton.h"
#ifdef NOTIFICATION_ENABLE
#include "notification_request.h"
#include "notification_helper.h"
#endif
namespace OHOS {
namespace Location {
@ -130,7 +127,7 @@ private:
void HandleRemoveGeofence(const AppExecFwk::InnerEvent::Pointer& event);
void HandleSendNetworkLocation(const AppExecFwk::InnerEvent::Pointer& event);
using GnssEventProcessHandle = void (GnssHandler::*)(const AppExecFwk::InnerEvent::Pointer& event);
using GnssEventProcessHandle = std::function<void(const AppExecFwk::InnerEvent::Pointer &)>;
using GnssEventProcessMap = std::map<uint32_t, GnssEventProcessHandle>;
GnssEventProcessMap gnssEventProcessMap_;
};
@ -191,9 +188,6 @@ public:
void SetSetIdImpl(const SubscriberSetId &id);
void SetRefInfo(const AGnssRefInfo& refInfo);
void SetRefInfoImpl(const AGnssRefInfo &refInfo);
#endif
#ifdef HDF_DRIVERS_INTERFACE_GEOFENCE_ENABLE
bool SetGeofenceCallback();
#endif
void ReConnectHdiImpl();
bool IsMockEnabled();
@ -233,33 +227,40 @@ private:
int32_t GenerateFenceId();
bool IsGnssfenceRequestMapExist();
bool CheckBundleNameInGnssGeofenceRequestMap(std::string bundleName, int fenceId);
bool ConnectGnssHdi();
#ifdef HDF_DRIVERS_INTERFACE_AGNSS_ENABLE
bool ConnectAgnssHdi();
#endif
#ifdef HDF_DRIVERS_INTERFACE_GEOFENCE_ENABLE
bool SetGeofenceCallback();
bool ConnectGeofenceHdi();
#endif
bool IsDeviceLoaded(const std::string &servName);
size_t mockLocationIndex_ = 0;
bool registerToAbility_ = false;
int gnssWorkingStatus_ = 0;
std::shared_ptr<GnssHandler> gnssHandler_;
ServiceRunningState state_ = ServiceRunningState::STATE_NOT_START;
std::mutex gnssMutex_;
std::mutex nmeaMutex_;
std::mutex hdiMutex_;
std::mutex statusMutex_;
ffrt::mutex gnssMutex_;
ffrt::mutex nmeaMutex_;
ffrt::mutex hdiMutex_;
ffrt::mutex statusMutex_;
std::vector<sptr<IGnssStatusCallback>> gnssStatusCallback_;
std::vector<sptr<INmeaMessageCallback>> nmeaCallback_;
sptr<IGnssInterface> gnssInterface_;
sptr<IGnssCallback> gnssCallback_;
Location nlpLocation_;
#ifdef HDF_DRIVERS_INTERFACE_AGNSS_ENABLE
sptr<IAGnssCallback> agnssCallback_;
sptr<IAGnssInterface> agnssInterface_;
#endif
#ifdef HDF_DRIVERS_INTERFACE_GEOFENCE_ENABLE
sptr<IGeofenceInterface> geofenceInterface_;
sptr<IGeofenceCallback> geofenceCallback_;
#endif
int32_t fenceId_;
std::mutex fenceIdMutex_;
std::mutex gnssGeofenceRequestMapMutex_;
std::map<std::shared_ptr<GeofenceRequest>, sptr<IRemoteObject>> gnssGeofenceRequestMap_;
ffrt::mutex fenceIdMutex_;
ffrt::mutex gnssGeofenceRequestMapMutex_;
std::map<std::shared_ptr<GeofenceRequest>,
std::pair<sptr<IRemoteObject>, sptr<IRemoteObject::DeathRecipient>>> gnssGeofenceRequestMap_;
};
class LocationHdiDeathRecipient : public IRemoteObject::DeathRecipient {

View File

@ -56,12 +56,12 @@ public:
class GnssAbilityStub : public IRemoteStub<IGnssAbility> {
public:
using GnssMsgHandle = int (GnssAbilityStub::*)(
MessageParcel &data, MessageParcel &reply, AppIdentity &identity);
using GnssMsgHandle = std::function<int(MessageParcel &, MessageParcel &, AppIdentity &)>;
using GnssMsgHandleMap = std::map<int, GnssMsgHandle>;
GnssAbilityStub();
virtual ~GnssAbilityStub() = default;
void InitGnssMsgHandleMap();
void InitGnssEnhanceMsgHandleMap();
int32_t OnRemoteRequest(uint32_t code,
MessageParcel &data, MessageParcel &reply, MessageOption &option) override;
virtual void SendMessage(uint32_t code, MessageParcel &data, MessageParcel &reply) = 0;

View File

@ -27,8 +27,8 @@ using namespace EventFwk;
using CommonEventSubscriber = OHOS::EventFwk::CommonEventSubscriber;
using CommonEventData = OHOS::EventFwk::CommonEventData;
using CommonEventSubscribeInfo = OHOS::EventFwk::CommonEventSubscribeInfo;
const std::string AGNSS_NI_ACCEPT_EVENT = "usual.event.AGNSS_NI_ACCEPT";
const std::string AGNSS_NI_REJECT_EVENT = "usual.event.AGNSS_NI_REJECT";
constexpr const char* AGNSS_NI_ACCEPT_EVENT = "usual.event.AGNSS_NI_ACCEPT";
constexpr const char* AGNSS_NI_REJECT_EVENT = "usual.event.AGNSS_NI_REJECT";
class GnssCommonEventSubscriber : public OHOS::EventFwk::CommonEventSubscriber {
public:

View File

@ -36,7 +36,7 @@ public:
int32_t ReportLocation(const LocationInfo& location) override;
int32_t ReportGnssWorkingStatus(GnssWorkingStatus status) override;
int32_t ReportNmea(int64_t timestamp, const std::string& nmea, int32_t length) override;
int32_t ReportGnssCapabilities(GnssCapabilities capabilities) override;
int32_t ReportGnssCapabilities(unsigned int capabilities) override;
int32_t ReportSatelliteStatusInfo(const SatelliteStatusInfo& info) override;
int32_t RequestGnssReferenceInfo(GnssRefInfoType type) override;
int32_t RequestPredictGnssData() override;

View File

@ -0,0 +1,5 @@
{
global:
local:
*;
};

View File

@ -153,6 +153,7 @@ int32_t AGnssEventCallback::RequestAgnssRefInfo(AGnssRefInfoType type)
return ERR_OK;
}
#ifdef TEL_CORE_SERVICE_ENABLE
void AGnssEventCallback::JudgmentDataGsm(AGnssRefInfo& refInfo, sptr<CellInformation> infoItem)
{
auto gsmCellInfo = static_cast<Telephony::GsmCellInformation *>(infoItem.GetRefPtr());
@ -203,6 +204,7 @@ void AGnssEventCallback::JudgmentDataUmts(AGnssRefInfo& refInfo, sptr<CellInform
refInfo.cellId.cid = static_cast<unsigned int>(wcdmaCellInfo->GetCellId());
}
}
#endif
} // namespace Location
} // namespace OHOS
#endif

View File

@ -23,7 +23,9 @@
#include "location_data_rdb_manager.h"
#include "location_log.h"
#include "nlohmann/json.hpp"
#ifdef NOTIFICATION_ENABLE
#include "notification_helper.h"
#endif
#include "securec.h"
#include "sms_service_manager_client.h"
#include "string_utils.h"
@ -40,10 +42,12 @@ constexpr uint32_t TIME_AFTER_EMERGENCY_CALL = 10 * 1000;
constexpr int32_t INVALID_SUBID = -1;
const std::string URN_APPLICATION_ID = "x-oma-application:ulp.ua";
const std::string AGNSS_NI_SERVICE_NAME = "agnss_ni";
const int32_t GNSS_AGNSS_NI_NOTIFICATION_ID = LOCATION_GNSS_SA_ID * 100;
const std::string LOCATION_DIALOG_BUNDLE_NAME = "com.ohos.locationdialog";
const std::string AGNSS_NI_DIALOG_ABILITY_NAME = "ConfirmUIExtAbility";
#ifdef NOTIFICATION_ENABLE
const int32_t GNSS_AGNSS_NI_NOTIFICATION_ID = LOCATION_GNSS_SA_ID * 100;
constexpr uint32_t NOTIFICATION_AUTO_DELETED_TIME = 1000;
#endif
AGnssNiManager* AGnssNiManager::GetInstance()
{
@ -325,6 +329,7 @@ std::string AGnssNiManager::DecodeNiString(std::string original, int coding)
void AGnssNiManager::SendNiNotification(const GnssNiNotificationRequest &notif)
{
#ifdef NOTIFICATION_ENABLE
std::shared_ptr<Notification::NotificationNormalContent> notificationNormalContent =
std::make_shared<Notification::NotificationNormalContent>();
std::string title = "Location Request";
@ -353,15 +358,18 @@ void AGnssNiManager::SendNiNotification(const GnssNiNotificationRequest &notif)
return;
}
LBSLOGI(GNSS, "GNSS service publish notification success");
#else
LBSLOGI(GNSS, "GNSS service publish notification not support");
#endif
}
void AGnssNiManager::SendUserResponse(GnssNiResponseCmd responseCmd)
{
std::unique_lock<std::mutex> lock(mutex_);
if (gnssInterface_ == nullptr) {
LBSLOGE(GNSS, "gnssInterfacev1_0 is nullptr");
return;
}
std::unique_lock<std::mutex> lock(mutex_);
gnssInterface_->SendNiUserResponse(niNotificationId_, responseCmd);
}

View File

@ -42,6 +42,11 @@
#include "location_log_event_ids.h"
#include "location_data_rdb_manager.h"
#ifdef NOTIFICATION_ENABLE
#include "notification_request.h"
#include "notification_helper.h"
#endif
#include "hook_utils.h"
#include "geofence_definition.h"
@ -57,12 +62,17 @@ const uint32_t EVENT_INTERVAL_UNITE = 1000;
#ifdef HDF_DRIVERS_INTERFACE_AGNSS_ENABLE
constexpr const char *AGNSS_SERVICE_NAME = "agnss_interface_service";
#endif
constexpr const char *LOCATION_HOST_NAME = "location_host";
constexpr const char *GNSS_SERVICE_NAME = "gnss_interface_service";
#ifdef HDF_DRIVERS_INTERFACE_GEOFENCE_ENABLE
constexpr const char *GEOFENCE_SERVICE_NAME = "geofence_interface_service";
const std::string UNLOAD_GNSS_TASK = "gnss_sa_unload";
#endif
constexpr const char *UNLOAD_GNSS_TASK = "gnss_sa_unload";
const uint32_t RETRY_INTERVAL_OF_UNLOAD_SA = 4 * 60 * EVENT_INTERVAL_UNITE;
constexpr int32_t FENCE_MAX_ID = 1000000;
#ifdef TIME_SERVICE_ENABLE
constexpr int DEFAULT_UNCERTAINTY = 30;
#endif
constexpr int NLP_FIX_VALID_TIME = 2;
}
@ -77,15 +87,13 @@ GnssAbility* GnssAbility::GetInstance()
GnssAbility::GnssAbility() : SystemAbility(LOCATION_GNSS_SA_ID, true)
{
gnssInterface_ = nullptr;
gnssCallback_ = nullptr;
#ifdef HDF_DRIVERS_INTERFACE_AGNSS_ENABLE
agnssCallback_ = nullptr;
agnssInterface_ = nullptr;
#endif
gnssWorkingStatus_ = GNSS_WORKING_STATUS_NONE;
SetAbility(GNSS_ABILITY);
gnssHandler_ = std::make_shared<GnssHandler>(AppExecFwk::EventRunner::Create(true));
gnssHandler_ = std::make_shared<GnssHandler>(AppExecFwk::EventRunner::Create(true, AppExecFwk::ThreadMode::FFRT));
if (gnssHandler_ != nullptr) {
AppExecFwk::InnerEvent::Pointer event = AppExecFwk::InnerEvent::Get(
static_cast<uint32_t>(GnssAbilityInterfaceCode::INIT_HDI), 0);
@ -105,10 +113,19 @@ GnssAbility::~GnssAbility()
bool GnssAbility::CheckIfHdiConnected()
{
if (!IsDeviceLoaded(GNSS_SERVICE_NAME)) {
return false;
}
#ifdef HDF_DRIVERS_INTERFACE_AGNSS_ENABLE
return gnssInterface_ != nullptr && agnssInterface_ != nullptr;
#else
return gnssInterface_ != nullptr;
if (!IsDeviceLoaded(AGNSS_SERVICE_NAME)) {
return false;
}
#endif
#ifdef HDF_DRIVERS_INTERFACE_GEOFENCE_ENABLE
if (!IsDeviceLoaded(GEOFENCE_SERVICE_NAME)) {
return false;
}
return true;
#endif
}
@ -131,6 +148,13 @@ void GnssAbility::OnStop()
{
state_ = ServiceRunningState::STATE_NOT_START;
registerToAbility_ = false;
if (CheckIfHdiConnected()) {
auto startTime = CommonUtils::GetCurrentTimeStamp();
auto ret = RemoveHdi();
auto endTime = CommonUtils::GetCurrentTimeStamp();
WriteLocationInnerEvent(HDI_EVENT, {"ret", std::to_string(ret), "type", "DisConnectHdi",
"startTime", std::to_string(startTime), "endTime", std::to_string(endTime)});
}
LBSLOGI(GNSS, "OnStop ability stopped.");
}
@ -155,10 +179,6 @@ LocationErrCode GnssAbility::SendLocationRequest(WorkRecord &workrecord)
LocationErrCode GnssAbility::SetEnable(bool state)
{
if (!CheckIfHdiConnected()) {
LBSLOGE(GNSS, "no need start or stop gnss");
return ERRCODE_SUCCESS;
}
if (state) {
EnableGnss();
StartGnss();
@ -180,13 +200,6 @@ void GnssAbility::UnloadGnssSystemAbility()
return;
}
auto task = [this]() {
if (CheckIfHdiConnected()) {
auto startTime = CommonUtils::GetCurrentTimeStamp();
auto ret = RemoveHdi();
auto endTime = CommonUtils::GetCurrentTimeStamp();
WriteLocationInnerEvent(HDI_EVENT, {"ret", std::to_string(ret), "type", "DisConnectHdi",
"startTime", std::to_string(startTime), "endTime", std::to_string(endTime)});
}
LocationSaLoadManager::UnInitLocationSa(LOCATION_GNSS_SA_ID);
};
if (gnssHandler_ != nullptr) {
@ -201,7 +214,7 @@ bool GnssAbility::CheckIfGnssConnecting()
bool GnssAbility::IsGnssfenceRequestMapExist()
{
std::unique_lock<std::mutex> lock(gnssGeofenceRequestMapMutex_);
std::unique_lock<ffrt::mutex> lock(gnssGeofenceRequestMapMutex_);
return gnssGeofenceRequestMap_.size() != 0;
}
@ -224,7 +237,7 @@ LocationErrCode GnssAbility::RegisterGnssStatusCallback(const sptr<IRemoteObject
LBSLOGE(GNSS, "cast switch callback fail!");
return ERRCODE_INVALID_PARAM;
}
std::unique_lock<std::mutex> lock(gnssMutex_);
std::unique_lock<ffrt::mutex> lock(gnssMutex_);
gnssStatusCallback_.push_back(gnssStatusCallback);
LBSLOGD(GNSS, "after uid:%{public}d register, gnssStatusCallback size:%{public}s",
uid, std::to_string(gnssStatusCallback_.size()).c_str());
@ -243,7 +256,7 @@ LocationErrCode GnssAbility::UnregisterGnssStatusCallback(const sptr<IRemoteObje
return ERRCODE_INVALID_PARAM;
}
std::unique_lock<std::mutex> lock(gnssMutex_);
std::unique_lock<ffrt::mutex> lock(gnssMutex_);
size_t i = 0;
for (; i < gnssStatusCallback_.size(); i++) {
sptr<IRemoteObject> remoteObject = gnssStatusCallback_[i]->AsObject();
@ -276,7 +289,7 @@ LocationErrCode GnssAbility::RegisterNmeaMessageCallback(const sptr<IRemoteObjec
LBSLOGE(GNSS, "cast nmea callback fail!");
return ERRCODE_INVALID_PARAM;
}
std::unique_lock<std::mutex> lock(nmeaMutex_);
std::unique_lock<ffrt::mutex> lock(nmeaMutex_);
nmeaCallback_.push_back(nmeaCallback);
LBSLOGD(GNSS, "after uid:%{public}d register, nmeaCallback size:%{public}s",
uid, std::to_string(nmeaCallback_.size()).c_str());
@ -295,7 +308,7 @@ LocationErrCode GnssAbility::UnregisterNmeaMessageCallback(const sptr<IRemoteObj
return ERRCODE_INVALID_PARAM;
}
std::unique_lock<std::mutex> lock(nmeaMutex_);
std::unique_lock<ffrt::mutex> lock(nmeaMutex_);
size_t i = 0;
for (; i < nmeaCallback_.size(); i++) {
sptr<IRemoteObject> remoteObject = nmeaCallback_[i]->AsObject();
@ -367,7 +380,7 @@ void GnssAbility::RequestRecord(WorkRecord &workRecord, bool isAdded)
StartGnss();
} else {
// GNSS will stop only if all requests have stopped
if (CheckIfHdiConnected() && GetRequestNum() == 0) {
if (GetRequestNum() == 0) {
StopGnss();
}
}
@ -448,23 +461,25 @@ bool GnssAbility::GetCommandFlags(std::unique_ptr<LocationCommand>& commands, Gn
LocationErrCode GnssAbility::SendCommand(std::unique_ptr<LocationCommand>& commands)
{
if (gnssInterface_ == nullptr) {
LBSLOGE(GNSS, "gnssInterface_ is nullptr");
sptr<IGnssInterface> gnssInterface = IGnssInterface::Get();
if (gnssInterface == nullptr) {
LBSLOGE(GNSS, "gnssInterface is nullptr");
return ERRCODE_SERVICE_UNAVAILABLE;
}
GnssAuxiliaryDataType flags;
bool result = GetCommandFlags(commands, flags);
LBSLOGE(GNSS, "GetCommandFlags,flags = %{public}d", flags);
if (result) {
gnssInterface_->DeleteAuxiliaryData(flags);
gnssInterface->DeleteAuxiliaryData(flags);
}
return ERRCODE_SUCCESS;
}
LocationErrCode GnssAbility::SetPositionMode()
{
if (gnssInterface_ == nullptr) {
LBSLOGE(GNSS, "gnssInterface_ is nullptr");
sptr<IGnssInterface> gnssInterface = IGnssInterface::Get();
if (gnssInterface == nullptr) {
LBSLOGE(GNSS, "gnssInterface is nullptr");
return ERRCODE_SERVICE_UNAVAILABLE;
}
GnssConfigPara para;
@ -479,7 +494,7 @@ LocationErrCode GnssAbility::SetPositionMode()
LBSLOGE(GNSS, "unknow mode");
return ERRCODE_SUCCESS;
}
int ret = gnssInterface_->SetGnssConfigPara(para);
int ret = gnssInterface->SetGnssConfigPara(para);
if (ret != ERRCODE_SUCCESS) {
LBSLOGE(GNSS, "SetGnssConfigPara failed , ret =%{public}d", ret);
}
@ -489,8 +504,9 @@ LocationErrCode GnssAbility::SetPositionMode()
LocationErrCode GnssAbility::InjectTime()
{
#ifdef TIME_SERVICE_ENABLE
if (gnssInterface_ == nullptr) {
LBSLOGE(GNSS, "gnssInterface_ is nullptr");
sptr<IGnssInterface> gnssInterface = IGnssInterface::Get();
if (gnssInterface == nullptr) {
LBSLOGE(GNSS, "gnssInterface is nullptr");
return ERRCODE_SERVICE_UNAVAILABLE;
}
@ -505,7 +521,7 @@ LocationErrCode GnssAbility::InjectTime()
refInfo.time.time = wallTime;
refInfo.time.elapsedRealtime = elapsedTime;
refInfo.time.uncertaintyOfTime = DEFAULT_UNCERTAINTY;
gnssInterface_->SetGnssReferenceInfo(refInfo);
gnssInterface->SetGnssReferenceInfo(refInfo);
#endif
return ERRCODE_SUCCESS;
}
@ -522,8 +538,9 @@ LocationErrCode GnssAbility::SendNetworkLocation(const std::unique_ptr<Location>
LocationErrCode GnssAbility::InjectLocation()
{
if (gnssInterface_ == nullptr) {
LBSLOGE(GNSS, "gnssInterface_ or location is nullptr");
sptr<IGnssInterface> gnssInterface = IGnssInterface::Get();
if (gnssInterface == nullptr) {
LBSLOGE(GNSS, "gnssInterface or location is nullptr");
return ERRCODE_SERVICE_UNAVAILABLE;
}
if (nlpLocation_.GetAccuracy() < 1e-9 || nlpLocation_.GetTimeStamp() == 0) {
@ -537,7 +554,8 @@ LocationErrCode GnssAbility::InjectLocation()
}
GnssRefInfo refInfo;
refInfo.type = GnssRefInfoType::GNSS_REF_INFO_LOCATION;
refInfo.gnssLocation.fieldValidity = GnssLocationValidity::GNSS_LOCATION_LAT_VALID;
refInfo.gnssLocation.fieldValidity =
GnssLocationValidity::GNSS_LOCATION_LAT_VALID | GnssLocationValidity::GNSS_LOCATION_LONG_VALID;
refInfo.gnssLocation.latitude = nlpLocation_.GetLatitude();
refInfo.gnssLocation.longitude = nlpLocation_.GetLongitude();
refInfo.gnssLocation.altitude = nlpLocation_.GetAltitude();
@ -550,7 +568,7 @@ LocationErrCode GnssAbility::InjectLocation()
refInfo.gnssLocation.timeForFix = nlpLocation_.GetTimeStamp();
refInfo.gnssLocation.timeSinceBoot = nlpLocation_.GetTimeSinceBoot();
refInfo.gnssLocation.timeUncertainty = nlpLocation_.GetUncertaintyOfTimeSinceBoot();
gnssInterface_->SetGnssReferenceInfo(refInfo);
gnssInterface->SetGnssReferenceInfo(refInfo);
return ERRCODE_SUCCESS;
}
@ -559,11 +577,12 @@ LocationErrCode GnssAbility::AddFence(std::shared_ptr<GeofenceRequest>& request)
int fenceId = GenerateFenceId();
request->SetFenceId(fenceId);
#ifdef HDF_DRIVERS_INTERFACE_GEOFENCE_ENABLE
auto geofence = request->GetGeofence();
if (geofenceInterface_ == nullptr) {
LBSLOGE(GNSS, "geofenceInterface_ is nullptr");
sptr<IGeofenceInterface> geofenceInterface = IGeofenceInterface::Get();
if (geofenceInterface == nullptr) {
LBSLOGE(GNSS, "geofenceInterface is nullptr");
return ERRCODE_SERVICE_UNAVAILABLE;
}
auto geofence = request->GetGeofence();
GeofenceInfo fenceInfo;
fenceInfo.fenceIndex = fenceId;
fenceInfo.latitude = geofence.latitude;
@ -571,7 +590,7 @@ LocationErrCode GnssAbility::AddFence(std::shared_ptr<GeofenceRequest>& request)
fenceInfo.radius = geofence.radius;
int monitorEvent = static_cast<int>(GeofenceTransitionEvent::GEOFENCE_TRANSITION_EVENT_ENTER) |
static_cast<int>(GeofenceTransitionEvent::GEOFENCE_TRANSITION_EVENT_EXIT);
int32_t ret = geofenceInterface_->AddGnssGeofence(fenceInfo, static_cast<GeofenceEvent>(monitorEvent));
int32_t ret = geofenceInterface->AddGnssGeofence(fenceInfo, monitorEvent);
LBSLOGD(GNSS, "Successfully AddFence!, %{public}d", ret);
#endif
if (ExecuteFenceProcess(GnssInterfaceCode::ADD_FENCE_INFO, request)) {
@ -582,12 +601,17 @@ LocationErrCode GnssAbility::AddFence(std::shared_ptr<GeofenceRequest>& request)
LocationErrCode GnssAbility::RemoveFence(std::shared_ptr<GeofenceRequest>& request)
{
if (request == nullptr) {
LBSLOGE(GNSS, "request is nullptr");
return ERRCODE_GEOFENCE_FAIL;
}
#ifdef HDF_DRIVERS_INTERFACE_GEOFENCE_ENABLE
if (geofenceInterface_ == nullptr || request == nullptr) {
LBSLOGE(GNSS, "geofenceInterface_ is nullptr");
sptr<IGeofenceInterface> geofenceInterface = IGeofenceInterface::Get();
if (geofenceInterface == nullptr) {
LBSLOGE(GNSS, "geofenceInterface is nullptr");
return ERRCODE_SERVICE_UNAVAILABLE;
}
int32_t ret = geofenceInterface_->DeleteGnssGeofence(request->GetFenceId());
int32_t ret = geofenceInterface->DeleteGnssGeofence(request->GetFenceId());
LBSLOGD(GNSS, "Successfully RemoveFence!, %{public}d", ret);
#endif
if (ExecuteFenceProcess(GnssInterfaceCode::REMOVE_FENCE_INFO, request)) {
@ -599,7 +623,7 @@ LocationErrCode GnssAbility::RemoveFence(std::shared_ptr<GeofenceRequest>& reque
int32_t GnssAbility::GenerateFenceId()
{
LBSLOGD(GNSS, "GenerateFenceId");
std::lock_guard<std::mutex> lock(fenceIdMutex_);
std::lock_guard<ffrt::mutex> lock(fenceIdMutex_);
if (fenceId_ > FENCE_MAX_ID) {
fenceId_ = 0;
}
@ -613,11 +637,12 @@ LocationErrCode GnssAbility::AddGnssGeofence(std::shared_ptr<GeofenceRequest>& r
int fenceId = GenerateFenceId();
request->SetFenceId(fenceId);
#ifdef HDF_DRIVERS_INTERFACE_GEOFENCE_ENABLE
auto geofence = request->GetGeofence();
if (geofenceInterface_ == nullptr) {
LBSLOGE(GNSS, "geofenceInterface_ is nullptr");
sptr<IGeofenceInterface> geofenceInterface = IGeofenceInterface::Get();
if (geofenceInterface == nullptr) {
LBSLOGE(GNSS, "geofenceInterface is nullptr");
return ERRCODE_SERVICE_UNAVAILABLE;
}
auto geofence = request->GetGeofence();
GeofenceInfo fenceInfo;
fenceInfo.fenceIndex = fenceId;
fenceInfo.latitude = geofence.latitude;
@ -629,7 +654,7 @@ LocationErrCode GnssAbility::AddGnssGeofence(std::shared_ptr<GeofenceRequest>& r
GeofenceTransitionEvent status = transitionList[i];
monitorEvent |= static_cast<uint32_t>(status);
}
int32_t ret = geofenceInterface_->AddGnssGeofence(fenceInfo, static_cast<GeofenceEvent>(monitorEvent));
int32_t ret = geofenceInterface->AddGnssGeofence(fenceInfo, monitorEvent);
LBSLOGD(GNSS, "Successfully AddGnssGeofence!, %{public}d", ret);
#endif
RegisterGnssGeofenceCallback(request, request->GetGeofenceTransitionCallback());
@ -650,10 +675,10 @@ bool GnssAbility::RegisterGnssGeofenceCallback(std::shared_ptr<GeofenceRequest>
LBSLOGE(GNSS, "register an invalid callback");
return false;
}
std::unique_lock<std::mutex> lock(gnssGeofenceRequestMapMutex_);
std::unique_lock<ffrt::mutex> lock(gnssGeofenceRequestMapMutex_);
sptr<IRemoteObject::DeathRecipient> death(new (std::nothrow) GnssGeofenceCallbackDeathRecipient());
callback->AddDeathRecipient(death);
gnssGeofenceRequestMap_.insert(std::make_pair(request, callback));
gnssGeofenceRequestMap_.insert(std::make_pair(request, std::make_pair(callback, death)));
return true;
}
@ -668,11 +693,12 @@ LocationErrCode GnssAbility::RemoveGnssGeofence(std::shared_ptr<GeofenceRequest>
return ERRCODE_GEOFENCE_INCORRECT_ID;
}
#ifdef HDF_DRIVERS_INTERFACE_GEOFENCE_ENABLE
if (geofenceInterface_ == nullptr) {
LBSLOGE(GNSS, "geofenceInterface_ is nullptr");
sptr<IGeofenceInterface> geofenceInterface = IGeofenceInterface::Get();
if (geofenceInterface == nullptr) {
LBSLOGE(GNSS, "geofenceInterface is nullptr");
return ERRCODE_SERVICE_UNAVAILABLE;
}
int32_t ret = geofenceInterface_->DeleteGnssGeofence(request->GetFenceId());
int32_t ret = geofenceInterface->DeleteGnssGeofence(request->GetFenceId());
LBSLOGD(GNSS, "Successfully DeleteGnssGeofence!, %{public}d", ret);
#endif
@ -687,7 +713,10 @@ bool GnssAbility::UnregisterGnssGeofenceCallback(int fenceId)
for (auto iter = gnssGeofenceRequestMap_.begin(); iter != gnssGeofenceRequestMap_.end();) {
auto requestInMap = iter->first;
auto fenceIdInMap = requestInMap->GetFenceId();
auto callbackPair = iter->second;
auto callback = callbackPair.first;
if (fenceId == fenceIdInMap) {
callback->RemoveDeathRecipient(callbackPair.second);
iter = gnssGeofenceRequestMap_.erase(iter);
break;
} else {
@ -701,7 +730,7 @@ bool GnssAbility::UnregisterGnssGeofenceCallback(int fenceId)
bool GnssAbility::CheckBundleNameInGnssGeofenceRequestMap(std::string bundleName, int fenceId)
{
std::unique_lock<std::mutex> lock(gnssGeofenceRequestMapMutex_);
std::unique_lock<ffrt::mutex> lock(gnssGeofenceRequestMapMutex_);
for (auto iter = gnssGeofenceRequestMap_.begin();
iter != gnssGeofenceRequestMap_.end(); iter++) {
auto requestInMap = iter->first;
@ -719,10 +748,12 @@ bool GnssAbility::RemoveGnssGeofenceRequestByCallback(sptr<IRemoteObject> callba
if (callbackObj == nullptr) {
return false;
}
std::unique_lock<std::mutex> lock(gnssGeofenceRequestMapMutex_);
std::unique_lock<ffrt::mutex> lock(gnssGeofenceRequestMapMutex_);
for (auto iter = gnssGeofenceRequestMap_.begin(); iter != gnssGeofenceRequestMap_.end();) {
auto callback = iter->second;
auto callbackPair = iter->second;
auto callback = callbackPair.first;
if (callback == callbackObj) {
callback->RemoveDeathRecipient(callbackPair.second);
iter = gnssGeofenceRequestMap_.erase(iter);
break;
} else {
@ -738,7 +769,7 @@ bool GnssAbility::RemoveGnssGeofenceRequestByCallback(sptr<IRemoteObject> callba
void GnssAbility::ReportGeofenceOperationResult(
int fenceId, GeofenceOperateType type, GeofenceOperateResult result)
{
std::unique_lock<std::mutex> lock(gnssGeofenceRequestMapMutex_);
std::unique_lock<ffrt::mutex> lock(gnssGeofenceRequestMapMutex_);
auto geofenceRequest = GetGeofenceRequestByFenceId(fenceId);
if (geofenceRequest == nullptr) {
LBSLOGE(GNSS, "request is nullptr");
@ -761,7 +792,7 @@ void GnssAbility::ReportGeofenceOperationResult(
#ifdef HDF_DRIVERS_INTERFACE_GEOFENCE_ENABLE
void GnssAbility::ReportGeofenceEvent(int fenceIndex, GeofenceEvent event)
{
std::unique_lock<std::mutex> lock(gnssGeofenceRequestMapMutex_);
std::unique_lock<ffrt::mutex> lock(gnssGeofenceRequestMapMutex_);
auto request = GetGeofenceRequestByFenceId(fenceIndex);
if (request == nullptr) {
LBSLOGE(GNSS, "request is nullptr");
@ -774,9 +805,6 @@ void GnssAbility::ReportGeofenceEvent(int fenceIndex, GeofenceEvent event)
}
sptr<IGnssGeofenceCallback> gnssGeofenceCallback = iface_cast<IGnssGeofenceCallback>(callback);
auto transitionStatusList = request->GetGeofenceTransitionEventList();
#ifdef NOTIFICATION_ENABLE
auto notificationRequestList = request->GetNotificationRequestList();
#endif
for (size_t i = 0; i < transitionStatusList.size(); i++) {
if (transitionStatusList[i] !=
static_cast<GeofenceTransitionEvent>(event)) {
@ -787,6 +815,7 @@ void GnssAbility::ReportGeofenceEvent(int fenceIndex, GeofenceEvent event)
geofenceTransition.event = transitionStatusList[i];
gnssGeofenceCallback->OnTransitionStatusChange(geofenceTransition);
#ifdef NOTIFICATION_ENABLE
auto notificationRequestList = request->GetNotificationRequestList();
if (transitionStatusList.size() == notificationRequestList.size()) {
auto notificationRequest = notificationRequestList[i];
notificationRequest.SetCreatorUid(IPCSkeleton::GetCallingUid());
@ -818,7 +847,10 @@ bool GnssAbility::ExecuteFenceProcess(
fenceStruct.requestCode = static_cast<int>(code);
fenceStruct.retCode = true;
#ifdef HDF_DRIVERS_INTERFACE_GEOFENCE_ENABLE
std::unique_lock<ffrt::mutex> lock(hdiMutex_, std::defer_lock);
lock.lock();
fenceStruct.callback = geofenceCallback_;
lock.unlock();
#endif
HookUtils::ExecuteHook(
LocationProcessStage::FENCE_REQUEST_PROCESS, (void *)&fenceStruct, nullptr);
@ -832,12 +864,16 @@ bool GnssAbility::SetGeofenceCallback()
LBSLOGE(GNSS, "QuerySwitchState is DISABLED");
return false;
}
if (geofenceInterface_ == nullptr || geofenceCallback_ == nullptr) {
LBSLOGE(GNSS, "geofenceInterface_ or geofenceCallback_ is nullptr");
sptr<IGeofenceInterface> geofenceInterface = IGeofenceInterface::Get();
if (geofenceInterface == nullptr) {
LBSLOGE(GNSS, "geofenceInterface get failed");
return false;
}
int32_t ret = geofenceInterface_->SetGeofenceCallback(geofenceCallback_);
int32_t ret = geofenceInterface->SetGeofenceCallback(geofenceCallback_);
LBSLOGD(GNSS, "set geofence callback, ret:%{public}d", ret);
if (!ret) {
return false;
}
return true;
}
#endif
@ -848,7 +884,7 @@ void GnssAbility::ReportGnssSessionStatus(int status)
void GnssAbility::ReportNmea(int64_t timestamp, const std::string &nmea)
{
std::unique_lock<std::mutex> lock(nmeaMutex_);
std::unique_lock<ffrt::mutex> lock(nmeaMutex_);
for (auto nmeaCallback : nmeaCallback_) {
nmeaCallback->OnMessageChange(timestamp, nmea);
}
@ -856,7 +892,7 @@ void GnssAbility::ReportNmea(int64_t timestamp, const std::string &nmea)
void GnssAbility::ReportSv(const std::unique_ptr<SatelliteStatus> &sv)
{
std::unique_lock<std::mutex> lock(gnssMutex_);
std::unique_lock<ffrt::mutex> lock(gnssMutex_);
for (auto gnssStatusCallback : gnssStatusCallback_) {
gnssStatusCallback->OnStatusChange(sv);
}
@ -868,15 +904,24 @@ bool GnssAbility::EnableGnss()
LBSLOGE(GNSS, "QuerySwitchState is DISABLED");
return false;
}
if (gnssInterface_ == nullptr || gnssCallback_ == nullptr) {
LBSLOGE(GNSS, "gnssInterface_ or gnssCallback_ is nullptr");
sptr<IGnssInterface> gnssInterface = IGnssInterface::Get();
if (gnssInterface == nullptr) {
LBSLOGE(GNSS, "gnssInterface is nullptr");
return false;
}
if (IsGnssEnabled()) {
LBSLOGE(GNSS, "gnss has been enabled");
return false;
}
int32_t ret = gnssInterface_->EnableGnss(gnssCallback_);
std::unique_lock<ffrt::mutex> lock(hdiMutex_, std::defer_lock);
lock.lock();
if (gnssCallback_ == nullptr) {
LBSLOGE(GNSS, "gnssCallback_ is nullptr");
lock.unlock();
return false;
}
int32_t ret = gnssInterface->EnableGnss(gnssCallback_);
lock.unlock();
LBSLOGD(GNSS, "Successfully enable_gnss!, %{public}d", ret);
if (ret == 0) {
gnssWorkingStatus_ = GNSS_WORKING_STATUS_ENGINE_ON;
@ -890,15 +935,16 @@ bool GnssAbility::EnableGnss()
void GnssAbility::DisableGnss()
{
if (gnssInterface_ == nullptr) {
LBSLOGE(GNSS, "gnssInterface_ is nullptr");
sptr<IGnssInterface> gnssInterface = IGnssInterface::Get();
if (gnssInterface == nullptr) {
LBSLOGE(GNSS, "gnssInterface is nullptr");
return;
}
if (!IsGnssEnabled()) {
LBSLOGE(GNSS, "%{public}s gnss has been disabled", __func__);
return;
}
int ret = gnssInterface_->DisableGnss();
int ret = gnssInterface->DisableGnss();
if (ret == 0) {
gnssWorkingStatus_ = GNSS_WORKING_STATUS_ENGINE_OFF;
} else {
@ -915,7 +961,7 @@ bool GnssAbility::IsGnssEnabled()
void GnssAbility::RestGnssWorkStatus()
{
std::unique_lock<std::mutex> uniqueLock(statusMutex_);
std::unique_lock<ffrt::mutex> uniqueLock(statusMutex_);
gnssWorkingStatus_ = GNSS_WORKING_STATUS_NONE;
}
@ -925,8 +971,9 @@ void GnssAbility::StartGnss()
LBSLOGE(GNSS, "QuerySwitchState is DISABLED");
return;
}
if (gnssInterface_ == nullptr) {
LBSLOGE(GNSS, "gnssInterface_ is nullptr");
sptr<IGnssInterface> gnssInterface = IGnssInterface::Get();
if (gnssInterface == nullptr) {
LBSLOGE(GNSS, "gnssInterface is nullptr");
return;
}
if (!IsGnssEnabled()) {
@ -941,7 +988,7 @@ void GnssAbility::StartGnss()
return;
}
SetPositionMode();
int ret = gnssInterface_->StartGnss(GNSS_START_TYPE_NORMAL);
int ret = gnssInterface->StartGnss(GNSS_START_TYPE_NORMAL);
if (ret == 0) {
gnssWorkingStatus_ = GNSS_WORKING_STATUS_SESSION_BEGIN;
WriteLocationInnerEvent(START_GNSS, {});
@ -957,16 +1004,17 @@ void GnssAbility::StartGnss()
void GnssAbility::StopGnss()
{
if (gnssInterface_ == nullptr) {
LBSLOGE(GNSS, "gnssInterface_ is nullptr");
sptr<IGnssInterface> gnssInterface = IGnssInterface::Get();
if (gnssInterface == nullptr) {
LBSLOGE(GNSS, "gnssInterface is nullptr");
return;
}
if (!IsGnssEnabled()) {
LBSLOGE(GNSS, "%{public}s gnss has been disabled", __func__);
return;
}
int ret = gnssInterface_->StopGnss(GNSS_START_TYPE_NORMAL);
int ret = gnssInterface->StopGnss(GNSS_START_TYPE_NORMAL);
if (ret == 0) {
gnssWorkingStatus_ = GNSS_WORKING_STATUS_SESSION_END;
WriteLocationInnerEvent(STOP_GNSS, {});
@ -980,59 +1028,150 @@ void GnssAbility::StopGnss()
}
}
bool GnssAbility::ConnectHdi()
bool GnssAbility::IsDeviceLoaded(const std::string &servName)
{
auto devmgr = HDI::DeviceManager::V1_0::IDeviceManager::Get();
if (devmgr == nullptr) {
LBSLOGE(GNSS, "fail to get devmgr.");
return false;
}
if (devmgr->LoadDevice(GNSS_SERVICE_NAME) != 0) {
LBSLOGE(GNSS, "Load gnss service failed!");
std::vector<OHOS::HDI::DeviceManager::V1_0::HdiDevHostInfo> deviceInfos;
int ret = devmgr->ListAllDevice(deviceInfos);
if (ret != HDF_SUCCESS) {
LBSLOGE(GNSS, "get listAllDevice failed");
return false;
}
#ifdef HDF_DRIVERS_INTERFACE_AGNSS_ENABLE
if (devmgr->LoadDevice(AGNSS_SERVICE_NAME) != 0) {
LBSLOGE(GNSS, "Load agnss service failed!");
return false;
}
#endif
if (devmgr->LoadDevice(GEOFENCE_SERVICE_NAME) != 0) {
LBSLOGE(GNSS, "Load gnss service failed!");
return false;
}
std::unique_lock<std::mutex> lock(hdiMutex_, std::defer_lock);
lock.lock();
gnssInterface_ = IGnssInterface::Get();
#ifdef HDF_DRIVERS_INTERFACE_GEOFENCE_ENABLE
geofenceInterface_ = IGeofenceInterface::Get();
if (geofenceInterface_ != nullptr) {
geofenceCallback_ = sptr<GeofenceEventCallback>(new (std::nothrow) GeofenceEventCallback);
SetGeofenceCallback();
}
#endif
#ifdef HDF_DRIVERS_INTERFACE_AGNSS_ENABLE
agnssInterface_ = IAGnssInterface::Get();
if (agnssInterface_ != nullptr) {
agnssCallback_ = new (std::nothrow) AGnssEventCallback();
}
#endif
if (gnssInterface_ != nullptr) {
LBSLOGD(GNSS, "connect v2_0 hdi success.");
if (gnssCallback_ == nullptr) {
gnssCallback_ = new (std::nothrow) GnssEventCallback();
auto itDevicesInfo = deviceInfos.begin();
for (;itDevicesInfo != deviceInfos.end(); itDevicesInfo++) {
if (itDevicesInfo->hostName == LOCATION_HOST_NAME) {
break;
}
RegisterLocationHdiDeathRecipient();
lock.unlock();
return true;
}
if (itDevicesInfo == deviceInfos.end()) {
LBSLOGE(GNSS, "The host is not found:%{public}s", LOCATION_HOST_NAME);
return false;
}
auto itDevInfo = itDevicesInfo->devInfo.begin();
for (;itDevInfo != itDevicesInfo->devInfo.end(); itDevInfo++) {
if (itDevInfo->servName == servName) {
break;
}
}
if (itDevInfo == itDevicesInfo->devInfo.end()) {
LBSLOGE(GNSS, "The devices is not found:%{public}s in host %{public}s", servName.c_str(), LOCATION_HOST_NAME);
return false;
}
std::unique_lock<ffrt::mutex> lock(hdiMutex_, std::defer_lock);
LBSLOGI(GNSS, "check host:%{public}s dev:%{public}s loaded",
itDevicesInfo->hostName.c_str(), itDevInfo->servName.c_str());
return true;
}
bool GnssAbility::ConnectGnssHdi()
{
auto devmgr = HDI::DeviceManager::V1_0::IDeviceManager::Get();
if (devmgr == nullptr) {
LBSLOGE(GNSS, "fail to get devmgr.");
return false;
}
if (!IsDeviceLoaded(GNSS_SERVICE_NAME)) {
if (devmgr->LoadDevice(GNSS_SERVICE_NAME) != HDF_SUCCESS) {
LBSLOGE(GNSS, "Load gnss service failed!");
return false;
}
}
sptr<IGnssInterface> gnssInterface = IGnssInterface::Get();
if (gnssInterface == nullptr) {
LBSLOGE(GNSS, "gnssInterface get failed");
return false;
}
std::unique_lock<ffrt::mutex> lock(hdiMutex_, std::defer_lock);
lock.lock();
if (gnssCallback_ == nullptr) {
gnssCallback_ = new (std::nothrow) GnssEventCallback();
}
lock.unlock();
LBSLOGE(GNSS, "connect v2_0 hdi failed.");
return false;
RegisterLocationHdiDeathRecipient();
LBSLOGI(GNSS, "ConnectGnssHdi success");
return true;
}
#ifdef HDF_DRIVERS_INTERFACE_AGNSS_ENABLE
bool GnssAbility::ConnectAgnssHdi()
{
auto devmgr = HDI::DeviceManager::V1_0::IDeviceManager::Get();
if (devmgr == nullptr) {
LBSLOGE(GNSS, "fail to get devmgr.");
return false;
}
if (!IsDeviceLoaded(AGNSS_SERVICE_NAME)) {
if (devmgr->LoadDevice(AGNSS_SERVICE_NAME) != HDF_SUCCESS) {
LBSLOGE(GNSS, "Load agnss service failed!");
return false;
}
}
sptr<IAGnssInterface> agnssInterface = IAGnssInterface::Get();
if (agnssInterface == nullptr) {
LBSLOGE(GNSS, "agnssInterface get failed");
return false;
}
std::unique_lock<ffrt::mutex> lock(hdiMutex_);
if (agnssCallback_ == nullptr) {
agnssCallback_ = new (std::nothrow) AGnssEventCallback();
}
LBSLOGI(GNSS, "ConnectAgnssHdi success");
return true;
}
#endif
#ifdef HDF_DRIVERS_INTERFACE_GEOFENCE_ENABLE
bool GnssAbility::ConnectGeofenceHdi()
{
auto devmgr = HDI::DeviceManager::V1_0::IDeviceManager::Get();
if (devmgr == nullptr) {
LBSLOGE(GNSS, "fail to get devmgr.");
return false;
}
if (!IsDeviceLoaded(GEOFENCE_SERVICE_NAME)) {
if (devmgr->LoadDevice(GEOFENCE_SERVICE_NAME) != HDF_SUCCESS) {
LBSLOGE(GNSS, "Load geofence service failed!");
return false;
}
}
std::unique_lock<ffrt::mutex> lock(hdiMutex_);
if (geofenceCallback_ == nullptr) {
geofenceCallback_ = sptr<GeofenceEventCallback>(new (std::nothrow) GeofenceEventCallback);
}
bool ret = SetGeofenceCallback();
if (!ret) {
LBSLOGE(GNSS, "ConnectGeofenceHdi fail");
return false;
}
LBSLOGI(GNSS, "ConnectGeofenceHdi success");
return true;
}
#endif
bool GnssAbility::ConnectHdi()
{
if (!ConnectGnssHdi()) {
return false;
}
#ifdef HDF_DRIVERS_INTERFACE_AGNSS_ENABLE
if (!ConnectAgnssHdi()) {
return false;
}
#endif
#ifdef HDF_DRIVERS_INTERFACE_GEOFENCE_ENABLE
if (!ConnectGeofenceHdi()) {
return false;
}
#endif
LBSLOGI(GNSS, "connect v2_0 hdi success.");
return true;
}
bool GnssAbility::RemoveHdi()
{
std::unique_lock<ffrt::mutex> lock(hdiMutex_);
auto devmgr = HDI::DeviceManager::V1_0::IDeviceManager::Get();
if (devmgr == nullptr) {
LBSLOGE(GNSS, "fail to get devmgr.");
@ -1043,14 +1182,12 @@ bool GnssAbility::RemoveHdi()
return false;
}
gnssCallback_ = nullptr;
gnssInterface_ = nullptr;
#ifdef HDF_DRIVERS_INTERFACE_AGNSS_ENABLE
if (devmgr->UnloadDevice(AGNSS_SERVICE_NAME) != 0) {
LBSLOGE(GNSS, "Unload agnss service failed!");
return false;
}
agnssCallback_ = nullptr;
agnssInterface_ = nullptr;
#endif
#ifdef HDF_DRIVERS_INTERFACE_GEOFENCE_ENABLE
if (devmgr->UnloadDevice(GEOFENCE_SERVICE_NAME) != 0) {
@ -1058,7 +1195,6 @@ bool GnssAbility::RemoveHdi()
return false;
}
geofenceCallback_ = nullptr;
geofenceInterface_ = nullptr;
#endif
LBSLOGI(GNSS, "RemoveHdi success.");
return true;
@ -1067,10 +1203,6 @@ bool GnssAbility::RemoveHdi()
#ifdef HDF_DRIVERS_INTERFACE_AGNSS_ENABLE
void GnssAbility::SetAgnssServer()
{
if (agnssInterface_ == nullptr) {
LBSLOGE(GNSS, "agnssInterface_ is nullptr");
return;
}
if (!IsGnssEnabled()) {
LBSLOGE(GNSS, "%{public}s gnss has been disabled", __func__);
return;
@ -1082,25 +1214,32 @@ void GnssAbility::SetAgnssServer()
return;
}
int port = LocationConfigManager::GetInstance()->GetAgnssServerPort();
sptr<IAGnssInterface> agnssInterface = IAGnssInterface::Get();
if (agnssInterface == nullptr) {
LBSLOGE(GNSS, "agnssInterface is nullptr");
return;
}
AGnssServerInfo info;
info.type = AGNSS_TYPE_SUPL;
info.server = addrName;
info.port = port;
agnssInterface_->SetAgnssServer(info);
agnssInterface->SetAgnssServer(info);
}
void GnssAbility::SetAgnssCallback()
{
LBSLOGD(GNSS, "enter SetAgnssCallback");
if (agnssInterface_ == nullptr || agnssCallback_ == nullptr) {
LBSLOGE(GNSS, "agnssInterface_ or agnssCallback_ is nullptr");
std::unique_lock<ffrt::mutex> lock(hdiMutex_);
sptr<IAGnssInterface> agnssInterface = IAGnssInterface::Get();
if (agnssInterface == nullptr || agnssCallback_ == nullptr) {
LBSLOGE(GNSS, "agnssInterface or agnssCallback_ is nullptr");
return;
}
if (!IsGnssEnabled()) {
LBSLOGE(GNSS, "%{public}s gnss has been disabled", __func__);
return;
}
agnssInterface_->SetAgnssCallback(agnssCallback_);
agnssInterface->SetAgnssCallback(agnssCallback_);
}
void GnssAbility::SetSetId(const SubscriberSetId& id)
@ -1117,15 +1256,16 @@ void GnssAbility::SetSetId(const SubscriberSetId& id)
void GnssAbility::SetSetIdImpl(const SubscriberSetId& id)
{
if (agnssInterface_ == nullptr) {
LBSLOGE(GNSS, "agnssInterface_ is nullptr");
sptr<IAGnssInterface> agnssInterface = IAGnssInterface::Get();
if (agnssInterface == nullptr) {
LBSLOGE(GNSS, "agnssInterface is nullptr");
return;
}
if (!IsGnssEnabled()) {
LBSLOGE(GNSS, "%{public}s gnss has been disabled", __func__);
return;
}
agnssInterface_->SetSubscriberSetId(id);
agnssInterface->SetSubscriberSetId(id);
}
void GnssAbility::SetRefInfo(const AGnssRefInfo& refInfo)
@ -1141,15 +1281,16 @@ void GnssAbility::SetRefInfo(const AGnssRefInfo& refInfo)
void GnssAbility::SetRefInfoImpl(const AGnssRefInfo &refInfo)
{
if (agnssInterface_ == nullptr) {
LBSLOGE(GNSS, "agnssInterface_ is nullptr");
sptr<IAGnssInterface> agnssInterface = IAGnssInterface::Get();
if (agnssInterface == nullptr) {
LBSLOGE(GNSS, "agnssInterface is nullptr");
return;
}
if (!IsGnssEnabled()) {
LBSLOGE(GNSS, "%{public}s gnss has been disabled", __func__);
return;
}
agnssInterface_->SetAgnssRefInfo(refInfo);
agnssInterface->SetAgnssRefInfo(refInfo);
}
AGnssRefInfo AgnssRefInfoMessage::GetAgnssRefInfo()
@ -1330,6 +1471,7 @@ void GnssAbility::SendMessage(uint32_t code, MessageParcel &data, MessageParcel
SendEvent(event, reply);
break;
}
#ifdef NOTIFICATION_ENABLE
case static_cast<uint32_t>(GnssAbilityInterfaceCode::ADD_FENCE): {
auto request = GeofenceRequest::Unmarshalling(data);
AppExecFwk::InnerEvent::Pointer event = AppExecFwk::InnerEvent::Get(code, request);
@ -1356,6 +1498,7 @@ void GnssAbility::SendMessage(uint32_t code, MessageParcel &data, MessageParcel
SendEvent(event, reply);
break;
}
#endif
case static_cast<uint32_t>(GnssInterfaceCode::SEND_NETWORK_LOCATION): {
auto request = Location::Unmarshalling(data);
AppExecFwk::InnerEvent::Pointer event = AppExecFwk::InnerEvent::Get(code, request);
@ -1382,11 +1525,12 @@ void GnssAbility::SendEvent(AppExecFwk::InnerEvent::Pointer& event, MessageParce
void GnssAbility::RegisterLocationHdiDeathRecipient()
{
if (gnssInterface_ == nullptr) {
LBSLOGE(GNSS, "%{public}s: gnssInterface_ is nullptr", __func__);
sptr<IGnssInterface> gnssInterface = IGnssInterface::Get();
if (gnssInterface == nullptr) {
LBSLOGE(GNSS, "%{public}s: gnssInterface is nullptr", __func__);
return;
}
sptr<IRemoteObject> obj = OHOS::HDI::hdi_objcast<IGnssInterface>(gnssInterface_);
sptr<IRemoteObject> obj = OHOS::HDI::hdi_objcast<IGnssInterface>(gnssInterface);
if (obj == nullptr) {
LBSLOGE(GNSS, "%{public}s: hdi obj is nullptr", __func__);
return;
@ -1406,35 +1550,35 @@ void GnssHandler::InitGnssEventProcessMap()
return;
}
gnssEventProcessMap_[static_cast<uint32_t>(GnssAbilityInterfaceCode::EVENT_REPORT_MOCK_LOCATION)] =
&GnssHandler::HandleReportMockLocation;
[this](const AppExecFwk::InnerEvent::Pointer& event) { HandleReportMockLocation(event); };
gnssEventProcessMap_[static_cast<uint32_t>(GnssInterfaceCode::SEND_LOCATION_REQUEST)] =
&GnssHandler::HandleSendLocationRequest;
[this](const AppExecFwk::InnerEvent::Pointer& event) { HandleSendLocationRequest(event); };
gnssEventProcessMap_[static_cast<uint32_t>(GnssInterfaceCode::SET_MOCKED_LOCATIONS)] =
&GnssHandler::HandleSetMockedLocations;
[this](const AppExecFwk::InnerEvent::Pointer& event) { HandleSetMockedLocations(event); };
gnssEventProcessMap_[static_cast<uint32_t>(GnssInterfaceCode::SEND_COMMANDS)] =
&GnssHandler::HandleSendCommands;
[this](const AppExecFwk::InnerEvent::Pointer& event) { HandleSendCommands(event); };
#ifdef HDF_DRIVERS_INTERFACE_AGNSS_ENABLE
gnssEventProcessMap_[static_cast<uint32_t>(GnssAbilityInterfaceCode::SET_SUBSCRIBER_SET_ID)] =
&GnssHandler::HandleSetSubscriberSetId;
[this](const AppExecFwk::InnerEvent::Pointer& event) { HandleSetSubscriberSetId(event); };
gnssEventProcessMap_[static_cast<uint32_t>(GnssAbilityInterfaceCode::SET_AGNSS_REF_INFO)] =
&GnssHandler::HandleSetAgnssRefInfo;
[this](const AppExecFwk::InnerEvent::Pointer& event) { HandleSetAgnssRefInfo(event); };
#endif
gnssEventProcessMap_[static_cast<uint32_t>(GnssAbilityInterfaceCode::RECONNECT_HDI)] =
&GnssHandler::HandleReconnectHdi;
[this](const AppExecFwk::InnerEvent::Pointer& event) { HandleReconnectHdi(event); };
gnssEventProcessMap_[static_cast<uint32_t>(GnssInterfaceCode::SET_ENABLE)] =
&GnssHandler::HandleSetEnable;
[this](const AppExecFwk::InnerEvent::Pointer& event) { HandleSetEnable(event); };
gnssEventProcessMap_[static_cast<uint32_t>(GnssAbilityInterfaceCode::INIT_HDI)] =
&GnssHandler::HandleInitHdi;
[this](const AppExecFwk::InnerEvent::Pointer& event) { HandleInitHdi(event); };
gnssEventProcessMap_[static_cast<uint32_t>(GnssAbilityInterfaceCode::ADD_FENCE)] =
&GnssHandler::HandleAddFence;
[this](const AppExecFwk::InnerEvent::Pointer& event) { HandleAddFence(event); };
gnssEventProcessMap_[static_cast<uint32_t>(GnssAbilityInterfaceCode::REMOVE_FENCE)] =
&GnssHandler::HandleRemoveFence;
[this](const AppExecFwk::InnerEvent::Pointer& event) { HandleRemoveFence(event); };
gnssEventProcessMap_[static_cast<uint32_t>(GnssAbilityInterfaceCode::ADD_GEOFENCE)] =
&GnssHandler::HandleAddGeofence;
[this](const AppExecFwk::InnerEvent::Pointer& event) { HandleAddGeofence(event); };
gnssEventProcessMap_[static_cast<uint32_t>(GnssAbilityInterfaceCode::REMOVE_GEOFENCE)] =
&GnssHandler::HandleRemoveGeofence;
[this](const AppExecFwk::InnerEvent::Pointer& event) { HandleRemoveGeofence(event); };
gnssEventProcessMap_[static_cast<uint32_t>(GnssInterfaceCode::SEND_NETWORK_LOCATION)] =
&GnssHandler::HandleSendNetworkLocation;
[this](const AppExecFwk::InnerEvent::Pointer& event) { HandleSendNetworkLocation(event); };
}
GnssHandler::~GnssHandler() {}
@ -1451,7 +1595,7 @@ void GnssHandler::ProcessEvent(const AppExecFwk::InnerEvent::Pointer& event)
auto handleFunc = gnssEventProcessMap_.find(eventId);
if (handleFunc != gnssEventProcessMap_.end() && handleFunc->second != nullptr) {
auto memberFunc = handleFunc->second;
(this->*memberFunc)(event);
memberFunc(event);
}
gnssAbility->UnloadGnssSystemAbility();
}
@ -1566,9 +1710,7 @@ void GnssHandler::HandleInitHdi(const AppExecFwk::InnerEvent::Pointer& event)
LBSLOGE(GNSS, "ProcessEvent: gnss ability is nullptr");
return;
}
if (!gnssAbility->CheckIfHdiConnected()) {
gnssAbility->ConnectHdi();
}
gnssAbility->ConnectHdi();
gnssAbility->EnableGnss();
#ifdef HDF_DRIVERS_INTERFACE_AGNSS_ENABLE
gnssAbility->SetAgnssCallback();

View File

@ -33,52 +33,99 @@ void GnssAbilityStub::InitGnssMsgHandleMap()
return;
}
GnssMsgHandleMap_[static_cast<uint32_t>(GnssInterfaceCode::SEND_LOCATION_REQUEST)] =
&GnssAbilityStub::SendLocationRequestInner;
GnssMsgHandleMap_[static_cast<uint32_t>(GnssInterfaceCode::SET_MOCKED_LOCATIONS)] =
&GnssAbilityStub::SetMockLocationsInner;
[this](MessageParcel &data, MessageParcel &reply, AppIdentity &identity) {
return SendLocationRequestInner(data, reply, identity);
};
GnssMsgHandleMap_[static_cast<uint32_t>(GnssInterfaceCode::SET_ENABLE)] =
&GnssAbilityStub::SetEnableInner;
[this](MessageParcel &data, MessageParcel &reply, AppIdentity &identity) {
return SetEnableInner(data, reply, identity);
};
GnssMsgHandleMap_[static_cast<uint32_t>(GnssInterfaceCode::REFRESH_REQUESTS)] =
&GnssAbilityStub::RefreshRequirementsInner;
[this](MessageParcel &data, MessageParcel &reply, AppIdentity &identity) {
return RefreshRequirementsInner(data, reply, identity);
};
GnssMsgHandleMap_[static_cast<uint32_t>(GnssInterfaceCode::REG_GNSS_STATUS)] =
&GnssAbilityStub::RegisterGnssStatusCallbackInner;
[this](MessageParcel &data, MessageParcel &reply, AppIdentity &identity) {
return RegisterGnssStatusCallbackInner(data, reply, identity);
};
GnssMsgHandleMap_[static_cast<uint32_t>(GnssInterfaceCode::UNREG_GNSS_STATUS)] =
&GnssAbilityStub::UnregisterGnssStatusCallbackInner;
[this](MessageParcel &data, MessageParcel &reply, AppIdentity &identity) {
return UnregisterGnssStatusCallbackInner(data, reply, identity);
};
GnssMsgHandleMap_[static_cast<uint32_t>(GnssInterfaceCode::REG_NMEA)] =
&GnssAbilityStub::RegisterNmeaMessageCallbackInner;
[this](MessageParcel &data, MessageParcel &reply, AppIdentity &identity) {
return RegisterNmeaMessageCallbackInner(data, reply, identity);
};
GnssMsgHandleMap_[static_cast<uint32_t>(GnssInterfaceCode::UNREG_NMEA)] =
&GnssAbilityStub::UnregisterNmeaMessageCallbackInner;
[this](MessageParcel &data, MessageParcel &reply, AppIdentity &identity) {
return UnregisterNmeaMessageCallbackInner(data, reply, identity);
};
GnssMsgHandleMap_[static_cast<uint32_t>(GnssInterfaceCode::REG_CACHED)] =
&GnssAbilityStub::RegisterCachedCallbackInner;
[this](MessageParcel &data, MessageParcel &reply, AppIdentity &identity) {
return RegisterCachedCallbackInner(data, reply, identity);
};
GnssMsgHandleMap_[static_cast<uint32_t>(GnssInterfaceCode::UNREG_CACHED)] =
&GnssAbilityStub::UnregisterCachedCallbackInner;
[this](MessageParcel &data, MessageParcel &reply, AppIdentity &identity) {
return UnregisterCachedCallbackInner(data, reply, identity);
};
GnssMsgHandleMap_[static_cast<uint32_t>(GnssInterfaceCode::GET_CACHED_SIZE)] =
&GnssAbilityStub::GetCachedGnssLocationsSizeInner;
[this](MessageParcel &data, MessageParcel &reply, AppIdentity &identity) {
return GetCachedGnssLocationsSizeInner(data, reply, identity);
};
GnssMsgHandleMap_[static_cast<uint32_t>(GnssInterfaceCode::FLUSH_CACHED)] =
&GnssAbilityStub::FlushCachedGnssLocationsInner;
[this](MessageParcel &data, MessageParcel &reply, AppIdentity &identity) {
return FlushCachedGnssLocationsInner(data, reply, identity);
};
}
void GnssAbilityStub::InitGnssEnhanceMsgHandleMap()
{
GnssMsgHandleMap_[static_cast<uint32_t>(GnssInterfaceCode::SEND_COMMANDS)] =
&GnssAbilityStub::SendCommandInner;
[this](MessageParcel &data, MessageParcel &reply, AppIdentity &identity) {
return SendCommandInner(data, reply, identity);
};
GnssMsgHandleMap_[static_cast<uint32_t>(GnssInterfaceCode::SET_MOCKED_LOCATIONS)] =
[this](MessageParcel &data, MessageParcel &reply, AppIdentity &identity) {
return SetMockLocationsInner(data, reply, identity);
};
GnssMsgHandleMap_[static_cast<uint32_t>(GnssInterfaceCode::ENABLE_LOCATION_MOCK)] =
&GnssAbilityStub::EnableMockInner;
[this](MessageParcel &data, MessageParcel &reply, AppIdentity &identity) {
return EnableMockInner(data, reply, identity);
};
GnssMsgHandleMap_[static_cast<uint32_t>(GnssInterfaceCode::DISABLE_LOCATION_MOCK)] =
&GnssAbilityStub::DisableMockInner;
[this](MessageParcel &data, MessageParcel &reply, AppIdentity &identity) {
return DisableMockInner(data, reply, identity);
};
GnssMsgHandleMap_[static_cast<uint32_t>(GnssInterfaceCode::ADD_FENCE_INFO)] =
&GnssAbilityStub::AddFenceInner;
[this](MessageParcel &data, MessageParcel &reply, AppIdentity &identity) {
return AddFenceInner(data, reply, identity);
};
GnssMsgHandleMap_[static_cast<uint32_t>(GnssInterfaceCode::REMOVE_FENCE_INFO)] =
&GnssAbilityStub::RemoveFenceInner;
[this](MessageParcel &data, MessageParcel &reply, AppIdentity &identity) {
return RemoveFenceInner(data, reply, identity);
};
GnssMsgHandleMap_[static_cast<uint32_t>(GnssInterfaceCode::ADD_GNSS_GEOFENCE)] =
&GnssAbilityStub::AddGnssGeofenceInner;
[this](MessageParcel &data, MessageParcel &reply, AppIdentity &identity) {
return AddGnssGeofenceInner(data, reply, identity);
};
GnssMsgHandleMap_[static_cast<uint32_t>(GnssInterfaceCode::REMOVE_GNSS_GEOFENCE)] =
&GnssAbilityStub::RemoveGnssGeofenceInner;
[this](MessageParcel &data, MessageParcel &reply, AppIdentity &identity) {
return RemoveGnssGeofenceInner(data, reply, identity);
};
GnssMsgHandleMap_[static_cast<uint32_t>(GnssInterfaceCode::GET_GEOFENCE_SUPPORT_COORDINATE_SYSTEM_TYPE)] =
&GnssAbilityStub::QuerySupportCoordinateSystemTypeInner;
[this](MessageParcel &data, MessageParcel &reply, AppIdentity &identity) {
return QuerySupportCoordinateSystemTypeInner(data, reply, identity);
};
GnssMsgHandleMap_[static_cast<uint32_t>(GnssInterfaceCode::SEND_NETWORK_LOCATION)] =
&GnssAbilityStub::SendNetworkLocationInner;
[this](MessageParcel &data, MessageParcel &reply, AppIdentity &identity) {
return SendNetworkLocationInner(data, reply, identity);
};
}
GnssAbilityStub::GnssAbilityStub()
{
InitGnssMsgHandleMap();
InitGnssEnhanceMsgHandleMap();
}
int GnssAbilityStub::SendLocationRequestInner(MessageParcel &data, MessageParcel &reply, AppIdentity &identity)
@ -318,7 +365,6 @@ int GnssAbilityStub::OnRemoteRequest(uint32_t code,
if (data.ReadInterfaceToken() != GetDescriptor()) {
LBSLOGE(GNSS, "invalid token.");
reply.WriteInt32(ERRCODE_SERVICE_UNAVAILABLE);
return ERRCODE_SERVICE_UNAVAILABLE;
}
int ret = ERRCODE_SUCCESS;
@ -326,10 +372,9 @@ int GnssAbilityStub::OnRemoteRequest(uint32_t code,
auto handleFunc = GnssMsgHandleMap_.find(code);
if (handleFunc != GnssMsgHandleMap_.end() && handleFunc->second != nullptr) {
auto memberFunc = handleFunc->second;
ret = (this->*memberFunc)(data, reply, identity);
ret = memberFunc(data, reply, identity);
} else {
LBSLOGE(GNSS, "OnReceived cmd = %{public}u, unsupport service.", code);
reply.WriteInt32(ERRCODE_NOT_SUPPORTED);
ret = IPCObjectStub::OnRemoteRequest(code, data, reply, option);
}
if (!isMessageRequest_) {

View File

@ -52,8 +52,12 @@ int32_t GnssEventCallback::ReportLocation(const LocationInfo& location)
locationNew->SetAccuracy(location.horizontalAccuracy);
locationNew->SetSpeed(location.speed);
locationNew->SetDirection(location.bearing);
locationNew->SetAltitudeAccuracy(location.verticalAccuracy);
locationNew->SetSpeedAccuracy(location.speedAccuracy);
locationNew->SetDirectionAccuracy(location.bearingAccuracy);
locationNew->SetTimeStamp(location.timeForFix);
locationNew->SetTimeSinceBoot(location.timeSinceBoot);
locationNew->SetUncertaintyOfTimeSinceBoot(location.timeUncertainty);
locationNew->SetIsFromMock(false);
locationNew->SetLocationSourceType(LocationSourceType::GNSS_TYPE);
if (gnssAbility->IsMockEnabled()) {
@ -103,7 +107,7 @@ int32_t GnssEventCallback::ReportNmea(int64_t timestamp, const std::string& nmea
return ERR_OK;
}
int32_t GnssEventCallback::ReportGnssCapabilities(GnssCapabilities capabilities)
int32_t GnssEventCallback::ReportGnssCapabilities(unsigned int capabilities)
{
return ERR_OK;
}

View File

@ -13,6 +13,37 @@
import("//base/location/config.gni")
import("//build/ohos.gni")
local_base_sources = [
"$SUBSYSTEM_DIR/location_locator/callback/source/cached_locations_callback_proxy.cpp",
"$SUBSYSTEM_DIR/location_locator/callback/source/country_code_callback_proxy.cpp",
"$SUBSYSTEM_DIR/location_locator/callback/source/gnss_status_callback_proxy.cpp",
"$SUBSYSTEM_DIR/location_locator/callback/source/locating_required_data_callback_proxy.cpp",
"$SUBSYSTEM_DIR/location_locator/callback/source/location_gnss_geofence_callback_proxy.cpp",
"$SUBSYSTEM_DIR/location_locator/callback/source/locator_callback_proxy.cpp",
"$SUBSYSTEM_DIR/location_locator/callback/source/locator_msdp_state_change_cb.cpp",
"$SUBSYSTEM_DIR/location_locator/callback/source/nmea_message_callback_proxy.cpp",
"$SUBSYSTEM_DIR/location_locator/locator/source/fusion_controller.cpp",
"$SUBSYSTEM_DIR/location_locator/locator/source/geo_convert_proxy.cpp",
"$SUBSYSTEM_DIR/location_locator/locator/source/gnss_ability_proxy.cpp",
"$SUBSYSTEM_DIR/location_locator/locator/source/location_config_manager.cpp",
"$SUBSYSTEM_DIR/location_locator/locator/source/locator_ability.cpp",
"$SUBSYSTEM_DIR/location_locator/locator/source/locator_background_proxy.cpp",
"$SUBSYSTEM_DIR/location_locator/locator/source/locator_event_manager.cpp",
"$SUBSYSTEM_DIR/location_locator/locator/source/locator_event_subscriber.cpp",
"$SUBSYSTEM_DIR/location_locator/locator/source/locator_msdp_monitor_manager.cpp",
"$SUBSYSTEM_DIR/location_locator/locator/source/locator_required_data_manager.cpp",
"$SUBSYSTEM_DIR/location_locator/locator/source/locator_skeleton.cpp",
"$SUBSYSTEM_DIR/location_locator/locator/source/network_ability_proxy.cpp",
"$SUBSYSTEM_DIR/location_locator/locator/source/passive_ability_proxy.cpp",
"$SUBSYSTEM_DIR/location_locator/locator/source/permission_status_change_cb.cpp",
"$SUBSYSTEM_DIR/location_locator/locator/source/report_manager.cpp",
"$SUBSYSTEM_DIR/location_locator/locator/source/request_manager.cpp",
"$SUBSYSTEM_DIR/location_locator/locator/source/subability_common.cpp",
"$SUBSYSTEM_DIR/location_locator/locator/source/work_record.cpp",
"$SUBSYSTEM_DIR/location_locator/locator/source/work_record_statistic.cpp",
]
ohos_shared_library("lbsservice_locator") {
sanitize = {
cfi = true
@ -21,35 +52,7 @@ ohos_shared_library("lbsservice_locator") {
}
branch_protector_ret = "pac_ret"
sources = [
"$SUBSYSTEM_DIR/location_locator/callback/source/cached_locations_callback_proxy.cpp",
"$SUBSYSTEM_DIR/location_locator/callback/source/country_code_callback_proxy.cpp",
"$SUBSYSTEM_DIR/location_locator/callback/source/gnss_status_callback_proxy.cpp",
"$SUBSYSTEM_DIR/location_locator/callback/source/locating_required_data_callback_proxy.cpp",
"$SUBSYSTEM_DIR/location_locator/callback/source/location_gnss_geofence_callback_proxy.cpp",
"$SUBSYSTEM_DIR/location_locator/callback/source/locator_callback_proxy.cpp",
"$SUBSYSTEM_DIR/location_locator/callback/source/locator_msdp_state_change_cb.cpp",
"$SUBSYSTEM_DIR/location_locator/callback/source/nmea_message_callback_proxy.cpp",
"$SUBSYSTEM_DIR/location_locator/locator/source/fusion_controller.cpp",
"$SUBSYSTEM_DIR/location_locator/locator/source/geo_convert_proxy.cpp",
"$SUBSYSTEM_DIR/location_locator/locator/source/gnss_ability_proxy.cpp",
"$SUBSYSTEM_DIR/location_locator/locator/source/location_config_manager.cpp",
"$SUBSYSTEM_DIR/location_locator/locator/source/locator_ability.cpp",
"$SUBSYSTEM_DIR/location_locator/locator/source/locator_background_proxy.cpp",
"$SUBSYSTEM_DIR/location_locator/locator/source/locator_event_manager.cpp",
"$SUBSYSTEM_DIR/location_locator/locator/source/locator_event_subscriber.cpp",
"$SUBSYSTEM_DIR/location_locator/locator/source/locator_msdp_monitor_manager.cpp",
"$SUBSYSTEM_DIR/location_locator/locator/source/locator_required_data_manager.cpp",
"$SUBSYSTEM_DIR/location_locator/locator/source/locator_skeleton.cpp",
"$SUBSYSTEM_DIR/location_locator/locator/source/network_ability_proxy.cpp",
"$SUBSYSTEM_DIR/location_locator/locator/source/passive_ability_proxy.cpp",
"$SUBSYSTEM_DIR/location_locator/locator/source/permission_status_change_cb.cpp",
"$SUBSYSTEM_DIR/location_locator/locator/source/report_manager.cpp",
"$SUBSYSTEM_DIR/location_locator/locator/source/request_manager.cpp",
"$SUBSYSTEM_DIR/location_locator/locator/source/subability_common.cpp",
"$SUBSYSTEM_DIR/location_locator/locator/source/work_record.cpp",
"$SUBSYSTEM_DIR/location_locator/locator/source/work_record_statistic.cpp",
]
sources = local_base_sources
include_dirs = [
"$LOCATION_ROOT_DIR/interfaces/inner_api/include",
@ -71,11 +74,128 @@ ohos_shared_library("lbsservice_locator") {
"ability_runtime:app_manager",
"access_token:libaccesstoken_sdk",
"access_token:libprivacy_sdk",
"c_utils:utils",
"common_event_service:cesfwk_innerkits",
"eventhandler:libeventhandler",
"ffrt:libffrt",
"hilog:libhilog",
"ipc:ipc_single",
"os_account:os_account_innerkits",
"safwk:system_ability_fwk",
"samgr:samgr_proxy",
]
defines = []
ldflags = [
"-Wl,--as-needed",
"-Wl,--gc-sections",
]
cflags_cc = [
"-ffunction-sections",
"-fdata-sections",
"-flto=thin",
"-Os",
]
if (communication_wifi_enable) {
external_deps += [ "wifi:wifi_sdk" ]
defines += [ "WIFI_ENABLE" ]
}
if (communication_bluetooth_enable) {
external_deps += [ "bluetooth:btframework" ]
defines += [ "BLUETOOTH_ENABLE" ]
}
if (location_feature_with_geocode) {
defines += [ "FEATURE_GEOCODE_SUPPORT" ]
}
if (location_feature_with_gnss) {
defines += [ "FEATURE_GNSS_SUPPORT" ]
}
if (location_feature_with_network) {
defines += [ "FEATURE_NETWORK_SUPPORT" ]
}
if (location_feature_with_passive) {
defines += [ "FEATURE_PASSIVE_SUPPORT" ]
}
if (resourceschedule_background_task_mgr_enable) {
external_deps += [ "background_task_mgr:bgtaskmgr_innerkits" ]
defines += [ "BGTASKMGR_SUPPORT" ]
}
if (is_emulator) {
defines += [ "EMULATOR_ENABLED" ]
}
if (ability_form_fwk_enable) {
external_deps += [ "form_fwk:fmskit_native" ]
defines += [ "FMSKIT_NATIVE_SUPPORT" ]
}
if (resourceschedule_schedule_service_enable) {
external_deps += [ "resource_schedule_service:ressched_client" ]
defines += [ "RES_SCHED_SUPPROT" ]
}
if (notification_distributed_notification_service_enable) {
defines += [ "NOTIFICATION_ENABLE" ]
}
if (movement_client_enable) {
external_deps += [ "movement:movement_client" ]
defines += [ "MOVEMENT_CLIENT_ENABLE" ]
}
if (location_device_standby_enable) {
external_deps += [ "device_standby:standby_innerkits" ]
defines += [ "DEVICE_STANDBY_ENABLE" ]
}
# Used to control the export of dynamic library symbols.
version_script = "liblbsservice_locator_version_script.txt"
part_name = "location"
subsystem_name = "location"
}
ohos_static_library("lbsservice_locator_static") {
sanitize = {
cfi = true
cfi_cross_dso = true
debug = false
}
branch_protector_ret = "pac_ret"
sources = local_base_sources
include_dirs = [
"$LOCATION_ROOT_DIR/interfaces/inner_api/include",
"$SUBSYSTEM_DIR/location_geocode/geocode/include",
"$SUBSYSTEM_DIR/location_gnss/gnss/include",
"$SUBSYSTEM_DIR/location_locator/callback/include",
"$SUBSYSTEM_DIR/location_locator/locator/include",
"$SUBSYSTEM_DIR/location_network/network/include",
"$SUBSYSTEM_DIR/location_passive/passive/include",
]
deps = [
"$LOCATION_COMMON_DIR:lbsservice_common",
"$LOCATION_ROOT_DIR/frameworks/native/geofence_sdk:geofence_sdk",
]
external_deps = [
"ability_base:want",
"ability_runtime:app_manager",
"access_token:libaccesstoken_sdk",
"access_token:libprivacy_sdk",
"eventhandler:libeventhandler",
"ffrt:libffrt",
"hilog:libhilog",
"init:libbegetutil",
"ipc:ipc_single",
"os_account:os_account_innerkits",
"safwk:system_ability_fwk",
@ -129,7 +249,6 @@ ohos_shared_library("lbsservice_locator") {
}
if (notification_distributed_notification_service_enable) {
external_deps += [ "distributed_notification_service:ans_innerkits" ]
defines += [ "NOTIFICATION_ENABLE" ]
}

View File

@ -21,6 +21,7 @@
#include <singleton.h>
#include "event_handler.h"
#include "ffrt.h"
#include "system_ability.h"
#include "app_identity.h"
@ -45,8 +46,7 @@ namespace OHOS {
namespace Location {
class LocatorHandler : public AppExecFwk::EventHandler {
public:
using LocatorEventHandle = void (LocatorHandler::*)(
const AppExecFwk::InnerEvent::Pointer& event);
using LocatorEventHandle = std::function<void(const AppExecFwk::InnerEvent::Pointer &)>;
using LocatorEventHandleMap = std::map<int, LocatorEventHandle>;
explicit LocatorHandler(const std::shared_ptr<AppExecFwk::EventRunner>& runner);
~LocatorHandler() override;
@ -178,7 +178,7 @@ public:
int permUsedType, int succCnt, int failCnt);
LocationErrCode RemoveInvalidRequests();
bool IsInvalidRequest(std::shared_ptr<Request>& request);
bool IsProcessRunning(pid_t pid);
bool IsProcessRunning(pid_t pid, const uint32_t tokenId);
#ifdef FEATURE_GNSS_SUPPORT
LocationErrCode QuerySupportCoordinateSystemType(
std::vector<CoordinateSystemType>& coordinateSystemTypes);
@ -214,11 +214,11 @@ private:
ServiceRunningState state_ = ServiceRunningState::STATE_NOT_START;
std::shared_ptr<LocatorEventSubscriber> locatorEventSubscriber_;
std::mutex switchMutex_;
std::mutex requestsMutex_;
std::mutex receiversMutex_;
ffrt::mutex requestsMutex_;
ffrt::mutex receiversMutex_;
std::mutex proxyMapMutex_;
std::mutex permissionMapMutex_;
std::mutex loadedSaMapMutex_;
ffrt::mutex permissionMapMutex_;
ffrt::mutex loadedSaMapMutex_;
std::unique_ptr<std::map<pid_t, sptr<ISwitchCallback>>> switchCallbacks_;
std::shared_ptr<std::map<std::string, std::list<std::shared_ptr<Request>>>> requests_;
std::shared_ptr<std::map<sptr<IRemoteObject>, std::list<std::shared_ptr<Request>>>> receivers_;
@ -265,6 +265,15 @@ private:
std::string uuid_;
int32_t errCode_;
};
class LocatorCallbackDeathRecipient : public IRemoteObject::DeathRecipient {
public:
void OnRemoteDied(const wptr<IRemoteObject> &remote) override;
LocatorCallbackDeathRecipient(int32_t tokenId);
~LocatorCallbackDeathRecipient() override;
private:
int32_t tokenId_;
};
} // namespace Location
} // namespace OHOS
#endif // LOCATOR_ABILITY_H

View File

@ -22,11 +22,9 @@
namespace OHOS {
namespace Location {
const std::string MODE_CHANGED_EVENT = "usual.event.location.MODE_STATE_CHANGED";
const std::string LOCATION_PRIVACY_ACCEPT_EVENT = "usual.event.LOCATION_PRIVACY_ACCEPT";
const std::string LOCATION_PRIVACY_REJECT_EVENT = "usual.event.LOCATION_PRIVACY_REJECT";
const std::string LOCATOR_STANDBY_NAP = "napped";
const std::string LOCATOR_STANDBY_SLEEPING = "sleeping";
constexpr const char* MODE_CHANGED_EVENT = "usual.event.location.MODE_STATE_CHANGED";
constexpr const char* LOCATION_PRIVACY_ACCEPT_EVENT = "usual.event.LOCATION_PRIVACY_ACCEPT";
constexpr const char* LOCATION_PRIVACY_REJECT_EVENT = "usual.event.LOCATION_PRIVACY_REJECT";
class LocatorEventSubscriber : public OHOS::EventFwk::CommonEventSubscriber {
public:
explicit LocatorEventSubscriber(const OHOS::EventFwk::CommonEventSubscribeInfo &info);

View File

@ -39,8 +39,7 @@ public:
class LocatorAbilityStub : public IRemoteStub<ILocator> {
public:
using LocatorMsgHandle = int (LocatorAbilityStub::*)(
MessageParcel &data, MessageParcel &reply, AppIdentity &identity);
using LocatorMsgHandle = std::function<int(MessageParcel &, MessageParcel &, AppIdentity &)>;
using LocatorMsgHandleMap = std::map<LocatorInterfaceCode, LocatorMsgHandle>;
LocatorAbilityStub();
@ -113,22 +112,16 @@ private:
int DoProcessFenceRequest(
LocatorInterfaceCode code, MessageParcel &data, MessageParcel &reply, AppIdentity &identity);
void ConstructLocatorHandleMap();
void ConstructLocatorEnhanceHandleMap();
void ConstructLocatorMockHandleMap();
void ConstructGeocodeHandleMap();
bool IsStopAction(uint32_t code);
bool CheckRequestAvailable(uint32_t code, AppIdentity &identity);
void ConstructGnssHandleMap();
void ConstructGnssEnhanceHandleMap();
sptr<IRemoteObject::DeathRecipient> scanRecipient_ = new (std::nothrow) ScanCallbackDeathRecipient();
};
class LocatorCallbackDeathRecipient : public IRemoteObject::DeathRecipient {
public:
void OnRemoteDied(const wptr<IRemoteObject> &remote) override;
LocatorCallbackDeathRecipient(int32_t tokenId);
~LocatorCallbackDeathRecipient() override;
private:
int32_t tokenId_;
};
class SwitchCallbackDeathRecipient : public IRemoteObject::DeathRecipient {
public:
void OnRemoteDied(const wptr<IRemoteObject> &remote) override;

View File

@ -22,6 +22,7 @@
#include <singleton.h>
#include <string>
#include "ffrt.h"
#include "iremote_object.h"
#include "i_locator_callback.h"
@ -40,7 +41,7 @@ public:
void HandlePowerSuspendChanged(int32_t pid, int32_t uid, int32_t flag);
void UpdateRequestRecord(std::shared_ptr<Request> request, bool shouldInsert);
void HandleRequest();
void UpdateUsingPermission(std::shared_ptr<Request> request);
void UpdateUsingPermission(std::shared_ptr<Request> request, const bool isStart);
void HandlePermissionChanged(uint32_t tokenId);
void UpdateLocationErrorCallbackToRequest(sptr<ILocatorCallback> callback, uint32_t tokenId, bool state);
void SyncStillMovementState(bool state);
@ -56,8 +57,7 @@ private:
void ProxySendLocationRequest(std::string abilityName, WorkRecord& workRecord);
sptr<IRemoteObject> GetRemoteObject(std::string abilityName);
bool IsUidInProcessing(int32_t uid);
void UpdateUsingApproximatelyPermission(std::shared_ptr<Request> request);
void UpdateUsingApproximatelyStatus(std::shared_ptr<Request> request, bool isActive);
void UpdateUsingApproximatelyPermission(std::shared_ptr<Request> request, const bool isStart);
bool ActiveLocatingStrategies(const std::shared_ptr<Request>& request);
bool AddRequestToWorkRecord(std::string abilityName, std::shared_ptr<Request>& request,
std::shared_ptr<WorkRecord>& workRecord);
@ -66,9 +66,9 @@ private:
void ReportDataToResSched(std::string state, const pid_t uid);
void IsStandby();
std::map<int32_t, int32_t> runningUidMap_;
static std::mutex requestMutex_;
std::mutex runningUidsMutex_;
std::mutex permissionRecordMutex_;
static ffrt::mutex requestMutex_;
ffrt::mutex runningUidsMutex_;
ffrt::mutex permissionRecordMutex_;
std::atomic_bool isDeviceIdleMode_;
std::atomic_bool isDeviceStillState_;
};

View File

@ -0,0 +1,5 @@
{
global:
local:
*;
};

View File

@ -104,6 +104,8 @@ LocatorAbility* LocatorAbility::GetInstance()
LocatorAbility::LocatorAbility() : SystemAbility(LOCATION_LOCATOR_SA_ID, true)
{
locatorHandler_ = std::make_shared<LocatorHandler>(AppExecFwk::EventRunner::Create(true,
AppExecFwk::ThreadMode::FFRT));
switchCallbacks_ = std::make_unique<std::map<pid_t, sptr<ISwitchCallback>>>();
requests_ = std::make_shared<std::map<std::string, std::list<std::shared_ptr<Request>>>>();
receivers_ = std::make_shared<std::map<sptr<IRemoteObject>, std::list<std::shared_ptr<Request>>>>();
@ -112,6 +114,11 @@ LocatorAbility::LocatorAbility() : SystemAbility(LOCATION_LOCATOR_SA_ID, true)
permissionMap_ = std::make_shared<std::map<uint32_t, std::shared_ptr<PermissionStatusChangeCb>>>();
InitRequestManagerMap();
reportManager_ = ReportManager::GetInstance();
deviceId_ = CommonUtils::InitDeviceId();
#ifdef MOVEMENT_CLIENT_ENABLE
LocatorMsdpMonitorManager::GetInstance();
#endif
requestManager_ = RequestManager::GetInstance();
LBSLOGI(LOCATOR, "LocatorAbility constructed.");
}
@ -180,13 +187,6 @@ bool LocatorAbility::Init()
LBSLOGE(LOCATOR, "Init add system ability failed!");
return false;
}
deviceId_ = CommonUtils::InitDeviceId();
requestManager_ = RequestManager::GetInstance();
#ifdef MOVEMENT_CLIENT_ENABLE
LocatorMsdpMonitorManager::GetInstance();
#endif
locatorHandler_ = std::make_shared<LocatorHandler>(AppExecFwk::EventRunner::Create(true));
InitSaAbility();
if (locatorHandler_ != nullptr) {
locatorHandler_->SendHighPriorityEvent(EVENT_INIT_REQUEST_MANAGER, 0, RETRY_INTERVAL_OF_INIT_REQUEST_MANAGER);
@ -198,7 +198,7 @@ bool LocatorAbility::Init()
void LocatorAbility::InitRequestManagerMap()
{
std::unique_lock<std::mutex> lock(requestsMutex_);
std::unique_lock<ffrt::mutex> lock(requestsMutex_);
if (requests_ != nullptr) {
#ifdef FEATURE_GNSS_SUPPORT
std::list<std::shared_ptr<Request>> gnssList;
@ -217,13 +217,13 @@ void LocatorAbility::InitRequestManagerMap()
std::shared_ptr<std::map<std::string, std::list<std::shared_ptr<Request>>>> LocatorAbility::GetRequests()
{
std::unique_lock<std::mutex> lock(requestsMutex_);
std::unique_lock<ffrt::mutex> lock(requestsMutex_);
return requests_;
}
int LocatorAbility::GetActiveRequestNum()
{
std::unique_lock<std::mutex> lock(requestsMutex_);
std::unique_lock<ffrt::mutex> lock(requestsMutex_);
int num = 0;
#ifdef FEATURE_GNSS_SUPPORT
auto gpsListIter = requests_->find(GNSS_ABILITY);
@ -244,7 +244,7 @@ int LocatorAbility::GetActiveRequestNum()
std::shared_ptr<std::map<sptr<IRemoteObject>, std::list<std::shared_ptr<Request>>>> LocatorAbility::GetReceivers()
{
std::unique_lock<std::mutex> lock(receiversMutex_);
std::unique_lock<ffrt::mutex> lock(receiversMutex_);
return receivers_;
}
@ -319,7 +319,7 @@ void LocatorAbility::UpdateSaAbilityHandler()
}
locatorBackgroundProxy->OnSaStateChange(isEnabled);
UpdateLoadedSaMap();
std::unique_lock<std::mutex> lock(loadedSaMapMutex_);
std::unique_lock<ffrt::mutex> lock(loadedSaMapMutex_);
for (auto iter = loadedSaMap_->begin(); iter != loadedSaMap_->end(); iter++) {
sptr<IRemoteObject> remoteObject = iter->second;
MessageParcel data;
@ -410,6 +410,7 @@ LocationErrCode LocatorAbility::EnableAbility(bool isEnabled)
LocationDataRdbManager::SetSwitchMode(isEnabled ? ENABLED : DISABLED);
}
UpdateSaAbility();
ApplyRequests(0);
std::string state = isEnabled ? "enable" : "disable";
ReportDataToResSched(state);
WriteLocationSwitchStateEvent(state);
@ -787,7 +788,7 @@ LocationErrCode LocatorAbility::ProcessLocationMockMsg(
void LocatorAbility::UpdateLoadedSaMap()
{
std::unique_lock<std::mutex> lock(loadedSaMapMutex_);
std::unique_lock<ffrt::mutex> lock(loadedSaMapMutex_);
loadedSaMap_->clear();
if (LocationSaLoadManager::CheckIfSystemAbilityAvailable(LOCATION_GNSS_SA_ID)) {
sptr<IRemoteObject> objectGnss =
@ -888,6 +889,9 @@ LocationErrCode LocatorAbility::StartLocating(std::unique_ptr<RequestConfig>& re
}
reportManager_->UpdateRandom();
std::shared_ptr<Request> request = std::make_shared<Request>(requestConfig, callback, identity);
sptr<IRemoteObject::DeathRecipient> death(new (std::nothrow) LocatorCallbackDeathRecipient(identity.GetTokenId()));
callback->AsObject()->AddDeathRecipient(death);
request->SetLocatorCallbackRecipient(death);
HookUtils::ExecuteHookWhenStartLocation(request);
OHOS::Security::AccessToken::PermUsedTypeEnum type =
Security::AccessToken::AccessTokenKit::GetUserGrantedPermissionUsedType(request->GetTokenId(),
@ -900,6 +904,7 @@ LocationErrCode LocatorAbility::StartLocating(std::unique_ptr<RequestConfig>& re
#else
if (NeedReportCacheLocation(request, callback)) {
LBSLOGI(LOCATOR, "report cache location to %{public}s", identity.GetBundleName().c_str());
callback->AsObject()->RemoveDeathRecipient(death);
} else {
HandleStartLocating(request, callback);
}
@ -1046,8 +1051,8 @@ LocationErrCode LocatorAbility::GetCacheLocation(std::unique_ptr<Location>& loc,
bool LocatorAbility::CheckIsReportPermitted(AppIdentity &identity)
{
auto requests = GetRequests();
if (requests == nullptr || requests->empty()) {
std::unique_lock<ffrt::mutex> lock(requestsMutex_);
if (requests_ == nullptr || requests_->empty()) {
LBSLOGE(LOCATOR, "requests map is empty");
return false;
}
@ -1055,7 +1060,7 @@ bool LocatorAbility::CheckIsReportPermitted(AppIdentity &identity)
bool isPermitted = true;
int switchState = DISABLED;
GetSwitchState(switchState);
for (auto mapIter = requests->begin(); mapIter != requests->end(); mapIter++) {
for (auto mapIter = requests_->begin(); mapIter != requests_->end(); mapIter++) {
auto list = mapIter->second;
for (auto request : list) {
if (request == nullptr || request->GetTokenId() != identity.GetTokenId()) {
@ -1379,7 +1384,7 @@ bool LocatorAbility::IsProxyPid(int32_t pid)
void LocatorAbility::RegisterPermissionCallback(const uint32_t callingTokenId,
const std::vector<std::string>& permissionNameList)
{
std::unique_lock<std::mutex> lock(permissionMapMutex_);
std::unique_lock<ffrt::mutex> lock(permissionMapMutex_);
if (permissionMap_ == nullptr) {
LBSLOGE(LOCATOR, "permissionMap is null.");
return;
@ -1400,7 +1405,7 @@ void LocatorAbility::RegisterPermissionCallback(const uint32_t callingTokenId,
void LocatorAbility::UnregisterPermissionCallback(const uint32_t callingTokenId)
{
std::unique_lock<std::mutex> lock(permissionMapMutex_);
std::unique_lock<ffrt::mutex> lock(permissionMapMutex_);
if (permissionMap_ == nullptr) {
LBSLOGE(LOCATOR, "permissionMap is null.");
return;
@ -1523,7 +1528,7 @@ LocationErrCode LocatorAbility::RemoveInvalidRequests()
int32_t requestNum = 0;
int32_t invalidRequestNum = 0;
{
std::unique_lock<std::mutex> lock(requestsMutex_);
std::unique_lock<ffrt::mutex> lock(requestsMutex_);
#ifdef FEATURE_GNSS_SUPPORT
auto gpsListIter = requests_->find(GNSS_ABILITY);
if (gpsListIter != requests_->end()) {
@ -1570,15 +1575,19 @@ bool LocatorAbility::IsInvalidRequest(std::shared_ptr<Request>& request)
return true;
}
if (timeDiff > REQUEST_DEFAULT_TIMEOUT_SECOUND && !IsProcessRunning(request->GetPid())) {
if (timeDiff > REQUEST_DEFAULT_TIMEOUT_SECOUND && !IsProcessRunning(request->GetPid(), request->GetTokenId())) {
LBSLOGI(LOCATOR, "request process is not running");
return true;
}
return false;
}
bool LocatorAbility::IsProcessRunning(pid_t pid)
bool LocatorAbility::IsProcessRunning(pid_t pid, const uint32_t tokenId)
{
auto tokenType = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(tokenId);
if (tokenType == Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE) {
return true;
}
sptr<ISystemAbilityManager> samgrClient = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (samgrClient == nullptr) {
LBSLOGE(LOCATOR, "Get system ability manager failed.");
@ -1702,23 +1711,42 @@ void LocatorHandler::InitLocatorHandlerEventMap()
if (locatorHandlerEventMap_.size() != 0) {
return;
}
locatorHandlerEventMap_[EVENT_UPDATE_SA] = &LocatorHandler::UpdateSaEvent;
locatorHandlerEventMap_[EVENT_INIT_REQUEST_MANAGER] = &LocatorHandler::InitRequestManagerEvent;
locatorHandlerEventMap_[EVENT_APPLY_REQUIREMENTS] = &LocatorHandler::ApplyRequirementsEvent;
locatorHandlerEventMap_[EVENT_RETRY_REGISTER_ACTION] = &LocatorHandler::RetryRegisterActionEvent;
locatorHandlerEventMap_[EVENT_REPORT_LOCATION_MESSAGE] = &LocatorHandler::ReportLocationMessageEvent;
locatorHandlerEventMap_[EVENT_SEND_SWITCHSTATE_TO_HIFENCE] = &LocatorHandler::SendSwitchStateToHifenceEvent;
locatorHandlerEventMap_[EVENT_START_LOCATING] = &LocatorHandler::StartLocatingEvent;
locatorHandlerEventMap_[EVENT_STOP_LOCATING] = &LocatorHandler::StopLocatingEvent;
locatorHandlerEventMap_[EVENT_UPDATE_LASTLOCATION_REQUESTNUM] = &LocatorHandler::UpdateLastLocationRequestNum;
locatorHandlerEventMap_[EVENT_UNLOAD_SA] = &LocatorHandler::UnloadSaEvent;
locatorHandlerEventMap_[EVENT_GET_CACHED_LOCATION_SUCCESS] = &LocatorHandler::GetCachedLocationSuccess;
locatorHandlerEventMap_[EVENT_GET_CACHED_LOCATION_FAILED] = &LocatorHandler::GetCachedLocationFailed;
locatorHandlerEventMap_[EVENT_REG_LOCATION_ERROR] = &LocatorHandler::RegLocationErrorEvent;
locatorHandlerEventMap_[EVENT_UNREG_LOCATION_ERROR] = &LocatorHandler::UnRegLocationErrorEvent;
locatorHandlerEventMap_[EVENT_REPORT_LOCATION_ERROR] = &LocatorHandler::ReportLocationErrorEvent;
locatorHandlerEventMap_[EVENT_SYNC_STILL_MOVEMENT_STATE] = &LocatorHandler::SyncStillMovementState;
locatorHandlerEventMap_[EVENT_SYNC_IDLE_STATE] = &LocatorHandler::SyncIdleState;
locatorHandlerEventMap_[EVENT_UPDATE_SA] =
[this](const AppExecFwk::InnerEvent::Pointer& event) { UpdateSaEvent(event); };
locatorHandlerEventMap_[EVENT_INIT_REQUEST_MANAGER] =
[this](const AppExecFwk::InnerEvent::Pointer& event) { InitRequestManagerEvent(event); };
locatorHandlerEventMap_[EVENT_APPLY_REQUIREMENTS] =
[this](const AppExecFwk::InnerEvent::Pointer& event) { ApplyRequirementsEvent(event); };
locatorHandlerEventMap_[EVENT_RETRY_REGISTER_ACTION] =
[this](const AppExecFwk::InnerEvent::Pointer& event) { RetryRegisterActionEvent(event); };
locatorHandlerEventMap_[EVENT_REPORT_LOCATION_MESSAGE] =
[this](const AppExecFwk::InnerEvent::Pointer& event) { ReportLocationMessageEvent(event); };
locatorHandlerEventMap_[EVENT_SEND_SWITCHSTATE_TO_HIFENCE] =
[this](const AppExecFwk::InnerEvent::Pointer& event) { SendSwitchStateToHifenceEvent(event); };
locatorHandlerEventMap_[EVENT_START_LOCATING] =
[this](const AppExecFwk::InnerEvent::Pointer& event) { StartLocatingEvent(event); };
locatorHandlerEventMap_[EVENT_STOP_LOCATING] =
[this](const AppExecFwk::InnerEvent::Pointer& event) { StopLocatingEvent(event); };
locatorHandlerEventMap_[EVENT_UPDATE_LASTLOCATION_REQUESTNUM] =
[this](const AppExecFwk::InnerEvent::Pointer& event) { UpdateLastLocationRequestNum(event); };
locatorHandlerEventMap_[EVENT_UNLOAD_SA] =
[this](const AppExecFwk::InnerEvent::Pointer& event) { UnloadSaEvent(event); };
locatorHandlerEventMap_[EVENT_GET_CACHED_LOCATION_SUCCESS] =
[this](const AppExecFwk::InnerEvent::Pointer& event) { GetCachedLocationSuccess(event); };
locatorHandlerEventMap_[EVENT_GET_CACHED_LOCATION_FAILED] =
[this](const AppExecFwk::InnerEvent::Pointer& event) { GetCachedLocationFailed(event); };
locatorHandlerEventMap_[EVENT_REG_LOCATION_ERROR] =
[this](const AppExecFwk::InnerEvent::Pointer& event) { RegLocationErrorEvent(event); };
locatorHandlerEventMap_[EVENT_UNREG_LOCATION_ERROR] =
[this](const AppExecFwk::InnerEvent::Pointer& event) { UnRegLocationErrorEvent(event); };
locatorHandlerEventMap_[EVENT_REPORT_LOCATION_ERROR] =
[this](const AppExecFwk::InnerEvent::Pointer& event) { ReportLocationErrorEvent(event); };
locatorHandlerEventMap_[EVENT_PERIODIC_CHECK] =
[this](const AppExecFwk::InnerEvent::Pointer& event) { RequestCheckEvent(event); };
locatorHandlerEventMap_[EVENT_SYNC_STILL_MOVEMENT_STATE] =
[this](const AppExecFwk::InnerEvent::Pointer& event) { SyncStillMovementState(event); };
locatorHandlerEventMap_[EVENT_SYNC_IDLE_STATE] =
[this](const AppExecFwk::InnerEvent::Pointer& event) { SyncIdleState(event); };
}
void LocatorHandler::GetCachedLocationSuccess(const AppExecFwk::InnerEvent::Pointer& event)
@ -1945,7 +1973,7 @@ void LocatorHandler::ProcessEvent(const AppExecFwk::InnerEvent::Pointer& event)
auto handleFunc = locatorHandlerEventMap_.find(eventId);
if (handleFunc != locatorHandlerEventMap_.end() && handleFunc->second != nullptr) {
auto memberFunc = handleFunc->second;
(this->*memberFunc)(event);
memberFunc(event);
} else {
LBSLOGE(LOCATOR, "ProcessEvent event:%{public}d, unsupport service.", eventId);
}
@ -1977,5 +2005,26 @@ void LocatorHandler::SyncIdleState(const AppExecFwk::InnerEvent::Pointer& event)
requestManager->SyncIdleState(state);
}
}
LocatorCallbackDeathRecipient::LocatorCallbackDeathRecipient(int32_t tokenId)
{
tokenId_ = tokenId;
}
LocatorCallbackDeathRecipient::~LocatorCallbackDeathRecipient()
{
}
void LocatorCallbackDeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &remote)
{
sptr<ILocatorCallback> callback = iface_cast<ILocatorCallback>(remote.promote());
auto locatorAbility = LocatorAbility::GetInstance();
if (locatorAbility != nullptr) {
locatorAbility->RemoveUnloadTask(DEFAULT_CODE);
locatorAbility->StopLocating(callback);
locatorAbility->PostUnloadTask(DEFAULT_CODE);
LBSLOGI(LOCATOR, "locator callback OnRemoteDied tokenId = %{public}d", tokenId_);
}
}
} // namespace Location
} // namespace OHOS

View File

@ -172,22 +172,6 @@ void LocatorBackgroundProxy::StartLocator()
void LocatorBackgroundProxy::UpdateListOnRequestChange(const std::shared_ptr<Request>& request)
{
if (request == nullptr) {
LBSLOGE(LOCATOR_BACKGROUND_PROXY, "request is null");
return;
}
int32_t uid = request->GetUid();
std::string bundleName;
if (!CommonUtils::GetBundleNameByUid(uid, bundleName)) {
LBSLOGE(LOCATOR_BACKGROUND_PROXY, "Fail to Get bundle name: uid = %{public}d.", uid);
return;
}
UpdateListOnSuspend(request, !IsAppBackground(bundleName));
if (requestsList_->empty()) {
StopLocator();
} else {
StartLocator();
}
}
// called when the app freezes or wakes up
@ -201,12 +185,6 @@ void LocatorBackgroundProxy::OnSuspend(const std::shared_ptr<Request>& request,
if (!isUserSwitchSubscribed_) {
isUserSwitchSubscribed_ = LocatorBackgroundProxy::UserSwitchSubscriber::Subscribe();
}
UpdateListOnSuspend(request, active);
if (requestsList_->empty()) {
StopLocator();
} else {
StartLocator();
}
}
// called when SA switch on or switch off
@ -259,41 +237,6 @@ bool LocatorBackgroundProxy::CheckPermission(const std::shared_ptr<Request>& req
void LocatorBackgroundProxy::UpdateListOnSuspend(const std::shared_ptr<Request>& request, bool active)
{
if (request == nullptr) {
return;
}
auto requestManager = RequestManager::GetInstance();
if (requestManager == nullptr) {
LBSLOGE(LOCATOR_BACKGROUND_PROXY, "UpdateListOnSuspend: RequestManager is nullptr.");
return;
}
requestManager->UpdateUsingPermission(request);
std::unique_lock lock(requestListMutex_);
auto userId = GetUserId(request->GetUid());
auto iter = requestsMap_->find(userId);
if (iter == requestsMap_->end()) {
return;
}
auto requestsList = iter->second;
auto it = find(requestsList->begin(), requestsList->end(), request);
if (it != requestsList->end()) {
if (active || !CheckPermission(request)) {
LBSLOGD(LOCATOR_BACKGROUND_PROXY, "remove request:%{public}s from User:%{public}d",
request->ToString().c_str(), userId);
requestsList->remove(request);
}
} else {
if (request->GetRequestConfig() == nullptr) {
return;
}
//App in Location ContinuousTasks or app has visible cards are not add to requestList of LocatorBackgroundProxy
if (!active && CheckPermission(request) && request->GetRequestConfig()->GetFixNumber() == 0
&& CheckMaxRequestNum(request->GetUid(), request->GetPackageName())) {
LBSLOGD(LOCATOR_BACKGROUND_PROXY, "add request:%{public}s from User:%{public}d",
request->ToString().c_str(), userId);
requestsList->push_back(request);
}
}
}
void LocatorBackgroundProxy::UpdateListOnUserSwitch(int32_t userId)
@ -570,9 +513,6 @@ bool LocatorBackgroundProxy::IsAppInLocationContinuousTasks(pid_t uid)
bool LocatorBackgroundProxy::IsAppHasFormVisible(uint32_t tokenId, uint64_t tokenIdEx)
{
bool ret = false;
if (!PermissionManager::CheckSystemPermission(tokenId, tokenIdEx)) {
return ret;
}
auto tokenType = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(tokenId);
if (tokenType != Security::AccessToken::ATokenTypeEnum::TOKEN_HAP) {
return ret;

Some files were not shown because too many files have changed in this diff Show More