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-08-02 04:06:08 +00:00 committed by Gitee
commit 4f235ffac9
61 changed files with 1224 additions and 319 deletions

View File

@ -76,7 +76,8 @@
"image_framework",
"movement",
"device_standby",
"time_service"
"time_service",
"netmanager_base"
]
},
"build": {

View File

@ -59,6 +59,7 @@ declare_args() {
movement_client_enable = true
location_device_standby_enable = true
time_service_enable = true
net_manager_enable = true
if (defined(global_parts_info) && !defined(global_parts_info.global_i18n)) {
i18n_enable = false
@ -152,4 +153,9 @@ declare_args() {
!defined(global_parts_info.time_time_service)) {
time_service_enable = false
}
if (defined(global_parts_info) &&
!defined(global_parts_info.communication_netmanager_base)) {
net_manager_enable = false
}
}

View File

@ -44,6 +44,7 @@ if (notification_distributed_notification_service_enable) {
]
notification_external_deps = [
"ability_base:session_info",
"ability_base:want",
"ability_runtime:napi_common",
"distributed_notification_service:ans_innerkits",

View File

@ -28,6 +28,7 @@
#include "constant_definition.h"
#include "parameter.h"
#include "location_sa_load_manager.h"
#include "hook_utils.h"
#include "accesstoken_kit.h"
#include "os_account_manager.h"
@ -40,6 +41,7 @@ static std::random_device g_randomDevice;
static std::mt19937 g_gen(g_randomDevice());
static std::uniform_int_distribution<> g_dis(0, 15); // random between 0 and 15
static std::uniform_int_distribution<> g_dis2(8, 11); // random between 8 and 11
const int64_t SEC_TO_NANO = 1000 * 1000 * 1000;
int CommonUtils::AbilityConvertToId(const std::string ability)
{
@ -127,7 +129,7 @@ bool CommonUtils::GetCurrentUserId(int &userId)
std::vector<int> activeIds;
int ret = AccountSA::OsAccountManager::QueryActiveOsAccountIds(activeIds);
if (ret != 0) {
LBSLOGE(COMMON_UTILS, "QueryActiveOsAccountIds failed ret:%{public}d", ret);
LBSLOGI(COMMON_UTILS, "GetCurrentUserId failed ret:%{public}d", ret);
return false;
}
if (activeIds.empty()) {
@ -401,5 +403,35 @@ std::string CommonUtils::GenerateUuid()
};
return ss.str();
}
bool CommonUtils::CheckAppForUser(int32_t uid)
{
int currentUserId = 0;
int userId = 0;
bool ret = GetCurrentUserId(currentUserId);
if (!ret) {
return true;
}
auto result = AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(uid, userId);
if (result != ERR_OK) {
return true;
}
if (userId != currentUserId) {
return false;
}
return true;
}
int64_t CommonUtils::GetSinceBootTime()
{
int result;
struct timespec ts;
result = clock_gettime(CLOCK_BOOTTIME, &ts);
if (result == 0) {
return ts.tv_sec * SEC_TO_NANO + ts.tv_nsec;
} else {
return 0;
}
}
} // namespace Location
} // namespace OHOS

View File

@ -21,9 +21,11 @@
namespace OHOS {
namespace Location {
const int DEFAULT_USERID = 100;
const int DEFAULT_SWITCHMODE = 2;
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)
@ -99,6 +101,7 @@ int LocationDataRdbManager::GetSwitchMode()
{
char result[MAX_SIZE] = {0};
std::string value = "";
std::unique_lock<std::mutex> lock(mutex_);
auto res = GetParameter(LOCATION_SWITCH_MODE, "", result, MAX_SIZE);
if (res < 0 || strlen(result) == 0) {
LBSLOGE(COMMON_UTILS, "%{public}s get para value failed, res: %{public}d", __func__, res);
@ -121,6 +124,7 @@ bool LocationDataRdbManager::SetSwitchMode(int value)
{
char valueArray[MAX_SIZE] = {0};
(void)sprintf_s(valueArray, sizeof(valueArray), "%d", value);
std::unique_lock<std::mutex> lock(mutex_);
int res = SetParameter(LOCATION_SWITCH_MODE, valueArray);
if (res < 0) {
LBSLOGE(COMMON_UTILS, "%{public}s failed, res: %{public}d", __func__, res);
@ -129,6 +133,21 @@ bool LocationDataRdbManager::SetSwitchMode(int value)
return true;
}
bool LocationDataRdbManager::ClearSwitchMode()
{
char valueArray[MAX_SIZE] = {0};
int code = sprintf_s(valueArray, sizeof(valueArray), "%d", DEFAULT_SWITCHMODE);
if (code <= 0) {
return false;
}
std::unique_lock<std::mutex> lock(mutex_);
int res = SetParameter(LOCATION_SWITCH_MODE, valueArray);
if (res < 0) {
return false;
}
return true;
}
bool LocationDataRdbManager::SetLocationEnhanceStatus(int32_t state)
{
Uri locationWorkingStateUri(GetLocationDataSecureUri(LOCATION_ENHANCE_STATUS));

View File

@ -176,6 +176,8 @@ public:
static bool GetStringParameter(const std::string& type, std::string& value);
static bool GetEdmPolicy(std::string& name);
static std::string GenerateUuid();
static bool CheckAppForUser(int32_t uid);
static int64_t GetSinceBootTime();
};
class CountDownLatch {

View File

@ -17,6 +17,7 @@
#define LOCATION_DATA_RDB_MANAGER_H
#include <unistd.h>
#include <string>
#include <mutex>
#include "constant_definition.h"
@ -35,9 +36,12 @@ public:
static bool GetLocationWorkingState(int32_t& state);
static int GetSwitchMode();
static bool SetSwitchMode(int value);
static bool ClearSwitchMode();
static std::string GetLocationDataSecureUri(std::string key);
static bool SetLocationEnhanceStatus(int32_t state);
static bool GetLocationEnhanceStatus(int32_t& state);
private:
static std::mutex mutex_;
};
} // namespace Location
} // namespace OHOS

View File

@ -20,6 +20,8 @@
"ohos.permission.MANAGE_SECURE_SETTINGS",
"ohos.permission.GET_TELEPHONY_STATE",
"ohos.permission.LOCATION",
"ohos.permission.APPROXIMATELY_LOCATION",
"ohos.permission.LOCATION_IN_BACKGROUND",
"ohos.permission.GET_WIFI_INFO",
"ohos.permission.SET_WIFI_INFO",
"ohos.permission.GET_RUNNING_INFO",
@ -32,7 +34,10 @@
"ohos.permission.ACCESS_PROTOCOL_DFX_STATE",
"ohos.permission.MANAGE_SETTINGS",
"ohos.permission.ACTIVITY_MOTION",
"ohos.permission.INTERNET"
"ohos.permission.INTERNET",
"ohos.permission.GET_NETWORK_INFO",
"ohos.permission.RECEIVE_SMS",
"ohos.permission.MANAGE_LOCAL_ACCOUNTS"
],
"permission_acls" : ["ohos.permission.GET_SENSITIVE_PERMISSIONS"],
"critical" : [0, 5, 10],

View File

@ -81,7 +81,7 @@ private:
double minLatitude_;
double minLongitude_;
std::string bundleName_;
sptr<IRemoteObject> callback_ = nullptr;
sptr<IRemoteObject> callback_;
std::string transId_;
std::string country_;
GeoCodeType requestType_;

View File

@ -86,6 +86,7 @@ public:
bool ConnectService();
void NotifyConnected(const sptr<IRemoteObject>& remoteObject);
void DisconnectAbilityConnect();
void NotifyDisConnected();
bool ResetServiceProxy();
bool SendGeocodeRequest(int code, MessageParcel& dataParcel, MessageParcel& replyParcel, MessageOption& option);

View File

@ -18,7 +18,23 @@
namespace OHOS {
namespace Location {
GeoConvertRequest::GeoConvertRequest() {}
GeoConvertRequest::GeoConvertRequest()
{
locale_ = "";
latitude_ = 0.0;
longitude_ = 0.0;
maxItems_ = 0;
description_ = "";
maxLatitude_ = 0.0;
maxLongitude_ = 0.0;
minLatitude_ = 0.0;
minLongitude_ = 0.0;
bundleName_ = "";
callback_ = nullptr;
transId_ = "";
country_ = "";
requestType_ = GeoCodeType::REQUEST_GEOCODE;
}
GeoConvertRequest::~GeoConvertRequest() {}

View File

@ -32,7 +32,10 @@ namespace Location {
const bool REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(
GeoConvertService::GetInstance());
const uint32_t EVENT_SEND_GEOREQUEST = 0x0100;
const char* UNLOAD_GEOCONVERT_TASK = "geoconvert_sa_unload";
const int GEOCONVERT_CONNECT_TIME_OUT = 1;
const uint32_t EVENT_INTERVAL_UNITE = 1000;
const int UNLOAD_GEOCONVERT_DELAY_TIME = 5 * EVENT_INTERVAL_UNITE;
GeoConvertService* GeoConvertService::GetInstance()
{
static GeoConvertService data;
@ -48,6 +51,9 @@ GeoConvertService::GeoConvertService() : SystemAbility(LOCATION_GEO_CONVERT_SA_I
GeoConvertService::~GeoConvertService()
{
if (geoConvertHandler_ != nullptr) {
geoConvertHandler_->RemoveTask(UNLOAD_GEOCONVERT_TASK);
}
conn_ = nullptr;
}
@ -320,8 +326,27 @@ bool GeoConvertService::CancelIdleState()
void GeoConvertService::UnloadGeoConvertSystemAbility()
{
if (!CheckIfGeoConvertConnecting()) {
if (geoConvertHandler_ == nullptr) {
LBSLOGE(GEO_CONVERT, "%{public}s geoConvertHandler_ is nullptr", __func__);
return;
}
geoConvertHandler_->RemoveTask(UNLOAD_GEOCONVERT_TASK);
if (CheckIfGeoConvertConnecting()) {
return;
}
auto task = [this]() {
LocationSaLoadManager::UnInitLocationSa(LOCATION_GEO_CONVERT_SA_ID);
GeoConvertService::GetInstance()->DisconnectAbilityConnect();
};
geoConvertHandler_->PostTask(task, UNLOAD_GEOCONVERT_TASK, UNLOAD_GEOCONVERT_DELAY_TIME);
}
void GeoConvertService::DisconnectAbilityConnect()
{
if (conn_ != nullptr) {
AAFwk::AbilityManagerClient::GetInstance()->DisconnectAbility(conn_);
SetServiceConnectState(ServiceConnectState::STATE_DISCONNECT);
LBSLOGI(GEO_CONVERT, "UnloadGeoConvert OnStop and disconnect");
}
}

View File

@ -23,6 +23,12 @@ if (location_feature_with_gnss) {
"$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/ntp/elapsed_real_time_check.cpp",
"$LOCATION_GNSS_ROOT/source/ntp/gps_time_manager.cpp",
"$LOCATION_GNSS_ROOT/source/ntp/net_conn_observer.cpp",
"$LOCATION_GNSS_ROOT/source/ntp/ntp_time_check.cpp",
"$LOCATION_GNSS_ROOT/source/ntp/ntp_time_helper.cpp",
"$LOCATION_GNSS_ROOT/source/ntp/time_manager.cpp",
"$LOCATION_GNSS_ROOT/source/string_utils.cpp",
"$LOCATION_LOCATOR_ROOT/source/location_config_manager.cpp",
"$LOCATION_LOCATOR_ROOT/source/subability_common.cpp",
@ -36,6 +42,7 @@ if (location_feature_with_gnss) {
include_dirs = [
"$LOCATION_ROOT_DIR/interfaces/inner_api/include",
"$LOCATION_GNSS_ROOT/include",
"$LOCATION_GNSS_ROOT/include/ntp",
"$LOCATION_LOCATOR_ROOT/include",
]
@ -143,6 +150,11 @@ if (location_feature_with_gnss) {
defines += [ "TIME_SERVICE_ENABLE" ]
}
if (net_manager_enable) {
external_deps += [ "netmanager_base:net_conn_manager_if" ]
defines += [ "NET_MANAGER_ENABLE" ]
}
# Used to control the export of dynamic library symbols.
version_script = "liblbsservice_gnss_version_script.txt"
@ -156,6 +168,7 @@ if (location_feature_with_gnss) {
include_dirs = [
"$LOCATION_ROOT_DIR/interfaces/inner_api/include",
"$LOCATION_GNSS_ROOT/include",
"$LOCATION_GNSS_ROOT/include/ntp",
"$LOCATION_LOCATOR_ROOT/include",
]
@ -251,6 +264,11 @@ if (location_feature_with_gnss) {
defines += [ "TIME_SERVICE_ENABLE" ]
}
if (net_manager_enable) {
external_deps += [ "netmanager_base:net_conn_manager_if" ]
defines += [ "NET_MANAGER_ENABLE" ]
}
part_name = "location"
subsystem_name = "location"
}

View File

@ -45,6 +45,15 @@
#include "geofence_event_callback.h"
#include "ipc_skeleton.h"
#ifdef TIME_SERVICE_ENABLE
#include "time_manager.h"
#endif
#ifdef NET_MANAGER_ENABLE
#include "net_conn_observer.h"
#include "net_conn_client.h"
#include "net_specifier.h"
#endif
namespace OHOS {
namespace Location {
#ifdef __aarch64__
@ -211,6 +220,8 @@ public:
LocationErrCode SendNetworkLocation(const std::unique_ptr<Location>& location) override;
LocationErrCode InjectLocation();
LocationErrCode InjectTime();
LocationErrCode UpdateNtpTime(int64_t ntpTime, int64_t elapsedTime);
void MonitorNetwork();
private:
bool Init();
@ -251,6 +262,12 @@ private:
std::vector<sptr<INmeaMessageCallback>> nmeaCallback_;
sptr<IGnssCallback> gnssCallback_;
Location nlpLocation_;
#ifdef TIME_SERVICE_ENABLE
TimeManager ntpTime_;
#endif
#ifdef NET_MANAGER_ENABLE
sptr<NetConnObserver> netWorkObserver_ = nullptr;
#endif
#ifdef HDF_DRIVERS_INTERFACE_AGNSS_ENABLE
sptr<IAGnssCallback> agnssCallback_;
#endif

View File

@ -0,0 +1,46 @@
/*
* 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 ELAPSED_REAL_TIME_CHECK_H
#define ELAPSED_REAL_TIME_CHECK_H
#ifdef FEATURE_GNSS_SUPPORT
#ifdef TIME_SERVICE_ENABLE
#include <cstdint>
namespace OHOS {
namespace Location {
class ElapsedRealTimeCheck {
public:
static ElapsedRealTimeCheck* GetInstance();
void CheckRealTime(int64_t time);
bool CanTrustElapsedRealTime();
private:
ElapsedRealTimeCheck();
~ElapsedRealTimeCheck();
int64_t timeBegin_;
int64_t timeBeginElapsed_;
int64_t timeCheck_;
int64_t timeCheckElapsed_;
bool canTrustElapsedRealTime_ = true; // default is true, usually we trust this time.
};
} // namespace Location
} // namespace OHOS
#endif // TIME_SERVICE_ENABLE
#endif // FEATURE_GNSS_SUPPORT
#endif // ELAPSED_REAL_TIME_CHECK_H

View File

@ -0,0 +1,43 @@
/*
* 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 GPS_TIME_MANAGER_H
#define GPS_TIME_MANAGER_H
#ifdef FEATURE_GNSS_SUPPORT
#ifdef TIME_SERVICE_ENABLE
#include "time_manager.h"
namespace OHOS {
namespace Location {
class GpsTimeManager {
public:
GpsTimeManager();
~GpsTimeManager();
int64_t GetGpsTime();
void SetGpsTime(int64_t gpsTime, int64_t bootTimeMs);
private:
bool CheckValid(int64_t gpsTime, int64_t lastSystemTime);
TimeManager timeManager_;
bool validFlag_ {false};
int64_t lastSystemTime_;
};
} // namespace Location
} // namespace OHOS
#endif // TIME_SERVICE_ENABLE
#endif // FEATURE_GNSS_SUPPORT
#endif // GPS_TIME_MANAGER_H

View File

@ -0,0 +1,47 @@
/*
* 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 NETMANAGER_BASE_NET_CONN_CALLBACK_OBSERVER_H
#define NETMANAGER_BASE_NET_CONN_CALLBACK_OBSERVER_H
#ifdef FEATURE_GNSS_SUPPORT
#ifdef NET_MANAGER_ENABLE
#include "net_all_capabilities.h"
#include "net_conn_callback_stub.h"
namespace OHOS {
namespace Location {
class NetConnObserver : public NetManagerStandard::NetConnCallbackStub {
public:
int32_t NetAvailable(sptr<NetManagerStandard::NetHandle> &netHandle) override;
int32_t NetCapabilitiesChange(sptr<NetManagerStandard::NetHandle> &netHandle,
const sptr<NetManagerStandard::NetAllCapabilities> &netAllCap) override;
int32_t NetConnectionPropertiesChange(sptr<NetManagerStandard::NetHandle> &netHandle,
const sptr<NetManagerStandard::NetLinkInfo> &info) override;
int32_t NetLost(sptr<NetManagerStandard::NetHandle> &netHandle) override;
int32_t NetUnavailable() override;
int32_t NetBlockStatusChange(sptr<NetManagerStandard::NetHandle> &netHandle, bool blocked) override;
};
} // namespace Location
} // namespace OHOS
#endif
#endif // NET_MANAGER_ENABLE
#endif // NETMANAGER_BASE_NET_CONN_CALLBACK_OBSERVER_H

View File

@ -0,0 +1,45 @@
/*
* 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 GPS_NTP_TIME_CHECK_H
#define GPS_NTP_TIME_CHECK_H
#ifdef FEATURE_GNSS_SUPPORT
#ifdef TIME_SERVICE_ENABLE
#include "gps_time_manager.h"
namespace OHOS {
namespace Location {
const int64_t DEFAULT_UNCERTAINTY = 30;
class NtpTimeCheck {
public:
static NtpTimeCheck* GetInstance();
bool CheckNtpTime(int64_t ntpMsTime, int64_t msTimeSynsBoot);
int GetUncertainty();
void SetGpsTime(int64_t gpsMsTime, int64_t bootTimeMs);
private:
NtpTimeCheck();
~NtpTimeCheck();
bool CompareTime(int64_t currentNtpTime, int64_t compareTime);
GpsTimeManager gpsTimeManager_;
int difference_ = DEFAULT_UNCERTAINTY;
};
} // namespace Location
} // namespace OHOS
#endif // TIME_SERVICE_ENABLE
#endif // FEATURE_GNSS_SUPPORT
#endif // GPS_NTP_TIME_CHECK_H

View File

@ -0,0 +1,49 @@
/*
* 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 NTP_TIME_HELPER_H
#define NTP_TIME_HELPER_H
#ifdef FEATURE_GNSS_SUPPORT
#ifdef TIME_SERVICE_ENABLE
#include <string>
#include "time_manager.h"
namespace OHOS {
namespace Location {
struct NtpTrustedTime {
int64_t ntpTime = 0;
int64_t ageMillis = 0;
int64_t elapsedRealTime = 0;
};
class NtpTimeHelper {
public:
static NtpTimeHelper* GetInstance();
void RetrieveAndInjectNtpTime();
private:
NtpTimeHelper() = default;
~NtpTimeHelper() = default;
NtpTrustedTime ntpResult_;
};
} // namespace Location
} // namespace OHOS
#endif // TIME_SERVICE_ENABLE
#endif // FEATURE_GNSS_SUPPORT
#endif // NTP_TIME_HELPER_H

View File

@ -0,0 +1,46 @@
/*
* 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 TIME_MANAGER_H
#define TIME_MANAGER_H
#ifdef FEATURE_GNSS_SUPPORT
#ifdef TIME_SERVICE_ENABLE
#include <string>
namespace OHOS {
namespace Location {
const int64_t EXPIRT_TIME = 14 * 24 * 60 * 60 * 1000L; // 14 day, two week
class TimeManager {
public:
TimeManager() = default;
explicit TimeManager(int64_t expireTime) : expireTime_(expireTime) {}
~TimeManager() = default;
int64_t GetCurrentTime();
void SetCurrentTime(int64_t msTime, int64_t msTimeSynsBoot);
int64_t GetTimestamp();
private:
int64_t timestamp_ = 0;
int64_t timeSynsBoot_ = 0;
int64_t expireTime_ = EXPIRT_TIME;
};
} // namespace Location
} // namespace OHOS
#endif // TIME_SERVICE_ENABLE
#endif // FEATURE_GNSS_SUPPORT
#endif // TIME_MANAGER_H

View File

@ -52,6 +52,7 @@
#ifdef TIME_SERVICE_ENABLE
#include "time_service_client.h"
#include "ntp_time_check.h"
#endif
namespace OHOS {
@ -70,10 +71,8 @@ constexpr const char *GEOFENCE_SERVICE_NAME = "geofence_interface_service";
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;
const int64_t INVALID_TIME = 0;
}
const bool REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(
@ -104,11 +103,17 @@ GnssAbility::GnssAbility() : SystemAbility(LOCATION_GNSS_SA_ID, true)
if (agnssNiManager != nullptr) {
agnssNiManager->SubscribeSaStatusChangeListerner();
}
MonitorNetwork();
LBSLOGI(GNSS, "ability constructed.");
}
GnssAbility::~GnssAbility()
{
#ifdef NET_MANAGER_ENABLE
if (netWorkObserver_ != nullptr) {
NetManagerStandard::NetConnClient::GetInstance().UnregisterNetConnCallback(netWorkObserver_);
}
#endif
}
bool GnssAbility::CheckIfHdiConnected()
@ -515,27 +520,69 @@ LocationErrCode GnssAbility::SetPositionMode()
return ERRCODE_SUCCESS;
}
void GnssAbility::MonitorNetwork()
{
#ifdef NET_MANAGER_ENABLE
NetManagerStandard::NetSpecifier netSpecifier;
NetManagerStandard::NetAllCapabilities netAllCapabilities;
netAllCapabilities.netCaps_.insert(NetManagerStandard::NetCap::NET_CAPABILITY_INTERNET);
netSpecifier.netCapabilities_ = netAllCapabilities;
sptr<NetManagerStandard::NetSpecifier> specifier(
new (std::nothrow) NetManagerStandard::NetSpecifier(netSpecifier));
if (specifier == nullptr) {
LBSLOGE(GNSS, "new operator error.specifier is nullptr");
return;
}
netWorkObserver_ = sptr<NetConnObserver>((new (std::nothrow) NetConnObserver()));
if (netWorkObserver_ == nullptr) {
LBSLOGE(GNSS, "new operator error.netWorkObserver_ is nullptr");
return;
}
int ret = NetManagerStandard::NetConnClient::GetInstance().RegisterNetConnCallback(specifier, netWorkObserver_, 0);
LBSLOGI(GNSS, "RegisterNetConnCallback retcode= %{public}d", ret);
#endif
return;
}
LocationErrCode GnssAbility::InjectTime()
{
#ifdef TIME_SERVICE_ENABLE
sptr<IGnssInterface> gnssInterface = IGnssInterface::Get();
if (gnssInterface == nullptr) {
LBSLOGE(GNSS, "gnssInterface is nullptr");
LBSLOGD(GNSS, "InjectTime");
int64_t currentTime = ntpTime_.GetCurrentTime();
if (currentTime == INVALID_TIME) {
return ERRCODE_SERVICE_UNAVAILABLE;
}
GnssRefInfo refInfo;
refInfo.type = GnssRefInfoType::GNSS_REF_INFO_TIME;
auto wallTime = MiscServices::TimeServiceClient::GetInstance()->GetWallTimeMs();
auto elapsedTime = MiscServices::TimeServiceClient::GetInstance()->GetBootTimeMs();
if (wallTime < 0 || elapsedTime < 0) {
LBSLOGE(GNSS, "get time failed");
if (elapsedTime < 0) {
LBSLOGE(GNSS, "get boot time failed");
return ERRCODE_SERVICE_UNAVAILABLE;
}
refInfo.time.time = wallTime;
refInfo.time.elapsedRealtime = elapsedTime;
refInfo.time.uncertaintyOfTime = DEFAULT_UNCERTAINTY;
gnssInterface->SetGnssReferenceInfo(refInfo);
auto ntpTimeCheck = NtpTimeCheck::GetInstance();
if (ntpTimeCheck != nullptr && ntpTimeCheck->CheckNtpTime(currentTime, elapsedTime)) {
GnssRefInfo refInfo;
refInfo.type = GnssRefInfoType::GNSS_REF_INFO_TIME;
refInfo.time.time = currentTime;
refInfo.time.elapsedRealtime = elapsedTime;
refInfo.time.uncertaintyOfTime = ntpTimeCheck->GetUncertainty();
auto gnssInterface = IGnssInterface::Get();
if (gnssInterface != nullptr) {
LBSLOGI(GNSS, "inject ntp time: %{public}s unert %{public}d",
std::to_string(currentTime).c_str(), ntpTimeCheck->GetUncertainty());
gnssInterface->SetGnssReferenceInfo(refInfo);
}
}
#endif
return ERRCODE_SUCCESS;
}
LocationErrCode GnssAbility::UpdateNtpTime(int64_t ntpTime, int64_t elapsedTime)
{
#ifdef TIME_SERVICE_ENABLE
if (ntpTime <= 0 || elapsedTime <= 0) {
LBSLOGE(GNSS, "failed to UpdateNtpTime");
return ERRCODE_SERVICE_UNAVAILABLE;
}
ntpTime_.SetCurrentTime(ntpTime, elapsedTime);
#endif
return ERRCODE_SUCCESS;
}
@ -569,7 +616,9 @@ LocationErrCode GnssAbility::InjectLocation()
GnssRefInfo refInfo;
refInfo.type = GnssRefInfoType::GNSS_REF_INFO_LOCATION;
refInfo.gnssLocation.fieldValidity =
GnssLocationValidity::GNSS_LOCATION_LAT_VALID | GnssLocationValidity::GNSS_LOCATION_LONG_VALID;
GnssLocationValidity::GNSS_LOCATION_LAT_VALID |
GnssLocationValidity::GNSS_LOCATION_LONG_VALID |
GnssLocationValidity::GNSS_LOCATION_HORIZONTAL_ACCURACY_VALID;
refInfo.gnssLocation.latitude = nlpLocation_.GetLatitude();
refInfo.gnssLocation.longitude = nlpLocation_.GetLongitude();
refInfo.gnssLocation.altitude = nlpLocation_.GetAltitude();
@ -1430,6 +1479,9 @@ int32_t GnssAbility::ReportMockedLocation(const std::shared_ptr<Location> locati
LBSLOGE(GNSS, "location mock is enabled, do not report gnss location!");
return ERR_OK;
}
location->SetTimeSinceBoot(CommonUtils::GetSinceBootTime());
location->SetTimeStamp(CommonUtils::GetCurrentTimeStamp() * MICRO_PER_MILLI);
location->SetLocationSourceType(LocationSourceType::GNSS_TYPE);
ReportLocationInfo(GNSS_ABILITY, location);
#ifdef FEATURE_PASSIVE_SUPPORT
ReportLocationInfo(PASSIVE_ABILITY, location);

View File

@ -25,6 +25,10 @@
#include "common_hisysevent.h"
#include "agnss_ni_manager.h"
#ifdef TIME_SERVICE_ENABLE
#include "ntp_time_check.h"
#include "time_service_client.h"
#endif
namespace OHOS {
namespace Location {
using namespace OHOS::HiviewDFX;
@ -37,6 +41,17 @@ bool g_hasLocation = false;
bool g_svIncrease = false;
std::unique_ptr<SatelliteStatus> g_svInfo = nullptr;
static void SetGpsTime(int64_t gpsTime)
{
#ifdef TIME_SERVICE_ENABLE
auto ntpTimeCheck = NtpTimeCheck::GetInstance();
if (ntpTimeCheck != nullptr) {
auto elapsedRealTime = MiscServices::TimeServiceClient::GetInstance()->GetBootTimeMs();
ntpTimeCheck->SetGpsTime(gpsTime, elapsedRealTime);
}
#endif
}
int32_t GnssEventCallback::ReportLocation(const LocationInfo& location)
{
auto gnssAbility = GnssAbility::GetInstance();
@ -80,6 +95,7 @@ int32_t GnssEventCallback::ReportLocation(const LocationInfo& location)
#ifdef FEATURE_PASSIVE_SUPPORT
gnssAbility->ReportLocationInfo(PASSIVE_ABILITY, locationNew);
#endif
SetGpsTime(locationNew->GetTimeStamp());
IPCSkeleton::SetCallingIdentity(identity);
return ERR_OK;
}

View File

@ -0,0 +1,84 @@
/*
* 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.
*/
#ifdef FEATURE_GNSS_SUPPORT
#ifdef TIME_SERVICE_ENABLE
#include "elapsed_real_time_check.h"
#include <cmath>
#include <string>
#include "common_utils.h"
#include "location_log.h"
#include "time_service_client.h"
namespace OHOS {
namespace Location {
const int64_t MAX_MISS_MS = 24 * 1000; // we only allow 24s misstake
ElapsedRealTimeCheck *ElapsedRealTimeCheck::GetInstance()
{
static ElapsedRealTimeCheck data;
return &data;
}
ElapsedRealTimeCheck::ElapsedRealTimeCheck() {}
ElapsedRealTimeCheck::~ElapsedRealTimeCheck() {}
void ElapsedRealTimeCheck::CheckRealTime(int64_t time)
{
if (timeBegin_ == 0) {
timeBegin_ = time;
timeBeginElapsed_ = MiscServices::TimeServiceClient::GetInstance()->GetBootTimeMs();
} else if (timeCheck_ == 0) {
timeCheck_ = time;
timeCheckElapsed_ = MiscServices::TimeServiceClient::GetInstance()->GetBootTimeMs();
} else {
LBSLOGD(GNSS, "checkRealTime");
}
if ((timeBegin_ != 0) && (timeCheck_ != 0)) {
int64_t missTime = (timeCheck_ - timeBegin_) - (timeCheckElapsed_ - timeBeginElapsed_);
LBSLOGD(GNSS,
"checkRealTime timeBegin_:%{public}s, timeCheck_:%{public}s, timeBeginElapsed_:%{public}s, "
"timeCheckElapsed_:%{public}s",
std::to_string(timeBegin_).c_str(), std::to_string(timeCheck_).c_str(),
std::to_string(timeBeginElapsed_).c_str(), std::to_string(timeCheckElapsed_).c_str());
LBSLOGI(GNSS, "checkRealTime missTime:%{public}s", std::to_string(missTime).c_str());
// we found missTime usually should not grow, results should be simillar on any moment.
// so if very high missTime should be problem.
if (std::abs(missTime) >= MAX_MISS_MS) {
LBSLOGI(GNSS, "checkRealTime false");
canTrustElapsedRealTime_ = false;
} else {
// sometimes just once system communication block, this could recover automaticly,
// elapsedRealtime still be ok.
canTrustElapsedRealTime_ = true;
}
timeCheck_ = 0;
timeCheckElapsed_ = 0;
}
}
bool ElapsedRealTimeCheck::CanTrustElapsedRealTime()
{
return canTrustElapsedRealTime_;
}
} // namespace Location
} // namespace OHOS
#endif // TIME_SERVICE_ENABLE
#endif

View File

@ -0,0 +1,72 @@
/*
* 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.
*/
#ifdef FEATURE_GNSS_SUPPORT
#ifdef TIME_SERVICE_ENABLE
#include "gps_time_manager.h"
#include "elapsed_real_time_check.h"
#include "location_log.h"
#include "time_service_client.h"
namespace OHOS {
namespace Location {
const int64_t INVALID_TIME = 0L;
const int64_t MAX_MISSTAKE_TIME = 10 * 1000L;
GpsTimeManager::GpsTimeManager()
{
timeManager_ = TimeManager(EXPIRT_TIME);
}
GpsTimeManager::~GpsTimeManager() {}
bool GpsTimeManager::CheckValid(int64_t gpsTime, int64_t lastSystemTime)
{
int64_t bootTimeDiff = gpsTime - timeManager_.GetTimestamp();
int64_t systemTimeDiff = MiscServices::TimeServiceClient::GetInstance()->GetWallTimeMs() - lastSystemTime;
if (abs(bootTimeDiff - systemTimeDiff) > MAX_MISSTAKE_TIME) {
return false;
}
return true;
}
int64_t GpsTimeManager::GetGpsTime()
{
int64_t tmpTime = timeManager_.GetCurrentTime();
if ((!validFlag_) && (tmpTime > 0)) {
if (!CheckValid(tmpTime, lastSystemTime_)) {
return INVALID_TIME;
}
}
return tmpTime;
}
void GpsTimeManager::SetGpsTime(int64_t gpsMsTime, int64_t bootTimeMs)
{
validFlag_ = true;
lastSystemTime_ = MiscServices::TimeServiceClient::GetInstance()->GetWallTimeMs();
timeManager_.SetCurrentTime(gpsMsTime, bootTimeMs);
auto elapsedRealTimeCheck = ElapsedRealTimeCheck::GetInstance();
if (elapsedRealTimeCheck != nullptr) {
elapsedRealTimeCheck->CheckRealTime(gpsMsTime);
}
}
} // namespace Location
} // namespace OHOS
#endif // TIME_SERVICE_ENABLE
#endif

View File

@ -0,0 +1,75 @@
/*
* 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.
*/
#ifdef FEATURE_GNSS_SUPPORT
#ifdef NET_MANAGER_ENABLE
#include "net_conn_observer.h"
#include "location_log.h"
#include "ntp_time_helper.h"
using namespace OHOS::NetManagerStandard;
namespace OHOS {
namespace Location {
int32_t NetConnObserver::NetAvailable(sptr<NetHandle> &netHandle)
{
return ERR_OK;
}
int32_t NetConnObserver::NetCapabilitiesChange(sptr<NetHandle> &netHandle,
const sptr<NetAllCapabilities> &netAllCap)
{
LBSLOGI(GNSS, "Observe network capabilities change");
if (netAllCap == nullptr) {
LBSLOGE(GNSS, "Observe network netAllCap is null");
return -1;
}
if (netAllCap->netCaps_.count(NetCap::NET_CAPABILITY_INTERNET)) {
#ifdef TIME_SERVICE_ENABLE
auto npTimeHelper = NtpTimeHelper::GetInstance();
if (npTimeHelper != nullptr) {
npTimeHelper->RetrieveAndInjectNtpTime();
}
#endif
}
return ERR_OK;
}
int32_t NetConnObserver::NetConnectionPropertiesChange(sptr<NetHandle> &netHandle,
const sptr<NetLinkInfo> &info)
{
return ERR_OK;
}
int32_t NetConnObserver::NetLost(sptr<NetHandle> &netHandle)
{
return ERR_OK;
}
int32_t NetConnObserver::NetUnavailable()
{
return ERR_OK;
}
int32_t NetConnObserver::NetBlockStatusChange(sptr<NetHandle> &netHandle, bool blocked)
{
return ERR_OK;
}
} // namespace Location
} // namespace OHOS
#endif
#endif

View File

@ -0,0 +1,86 @@
/*
* 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.
*/
#ifdef FEATURE_GNSS_SUPPORT
#ifdef TIME_SERVICE_ENABLE
#include "ntp_time_check.h"
#include <cmath>
#include <string>
#include "common_utils.h"
#include "location_log.h"
#include "time_service_client.h"
namespace OHOS {
namespace Location {
const int64_t INVALID_TIME = 0;
const int64_t MISSTAKE_TIME = 50 * 1000; // 50s
NtpTimeCheck::NtpTimeCheck() {}
NtpTimeCheck::~NtpTimeCheck() {}
NtpTimeCheck *NtpTimeCheck::GetInstance()
{
static NtpTimeCheck data;
return &data;
}
bool NtpTimeCheck::CheckNtpTime(int64_t ntpMsTime, int64_t msTimeSynsBoot)
{
int64_t currentNtpTime =
ntpMsTime + MiscServices::TimeServiceClient::GetInstance()->GetBootTimeMs() - msTimeSynsBoot;
if (gpsTimeManager_.GetGpsTime() != INVALID_TIME) {
return CompareTime(currentNtpTime, gpsTimeManager_.GetGpsTime());
}
LBSLOGI(GNSS, "checkNtpTime return false");
return false;
}
bool NtpTimeCheck::CompareTime(int64_t currentNtpTime, int64_t compareTime)
{
LBSLOGI(GNSS, "compareTime currentNtpTime:%{public}s, compareTime:%{public}s",
std::to_string(currentNtpTime).c_str(), std::to_string(compareTime).c_str());
int64_t misstake = std::abs(currentNtpTime - compareTime);
if (misstake > MISSTAKE_TIME) {
LBSLOGI(GNSS, "find error ntp time:%{public}s", std::to_string(misstake).c_str());
return false;
} else {
difference_ = misstake;
return true;
}
}
void NtpTimeCheck::SetGpsTime(int64_t gpsMsTime, int64_t bootTimeMs)
{
if (gpsMsTime <= 0 || bootTimeMs <= 0) {
LBSLOGE(GNSS, "set gps time failed :%{public}s, %{public}s", std::to_string(gpsMsTime).c_str(),
std::to_string(bootTimeMs).c_str());
return;
}
gpsTimeManager_.SetGpsTime(gpsMsTime, bootTimeMs);
}
int NtpTimeCheck::GetUncertainty()
{
return (difference_ > DEFAULT_UNCERTAINTY) ? difference_ : DEFAULT_UNCERTAINTY;
}
} // namespace Location
} // namespace OHOS
#endif // TIME_SERVICE_ENABLE
#endif

View File

@ -0,0 +1,67 @@
/*
* 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.
*/
#ifdef FEATURE_GNSS_SUPPORT
#ifdef TIME_SERVICE_ENABLE
#include "ntp_time_helper.h"
#include <string>
#include "gnss_ability.h"
#include "location_log.h"
#include "ntp_time_check.h"
#include "time_service_client.h"
namespace OHOS {
namespace Location {
static const int64_t NTP_INTERVAL = 24 * 60 * 60 * 1000;
NtpTimeHelper *NtpTimeHelper::GetInstance()
{
static NtpTimeHelper data;
return &data;
}
void NtpTimeHelper::RetrieveAndInjectNtpTime()
{
if (ntpResult_.elapsedRealTime > 0) {
ntpResult_.ageMillis =
MiscServices::TimeServiceClient::GetInstance()->GetBootTimeMs() - ntpResult_.elapsedRealTime;
LBSLOGD(GNSS, "ntp age millis %{public}s", std::to_string(ntpResult_.ageMillis).c_str());
}
auto gnssAbility = GnssAbility::GetInstance();
if (ntpResult_.ntpTime == 0 || ntpResult_.ageMillis > NTP_INTERVAL) {
auto ret = MiscServices::TimeServiceClient::GetInstance()->GetNtpTimeMs(ntpResult_.ntpTime);
if (ret != ERR_OK) {
ntpResult_.ntpTime = 0;
LBSLOGE(GNSS, "failed to get ntp time %{public}d", ret);
return;
}
LBSLOGI(GNSS, "get ntp time %{public}s", std::to_string(ntpResult_.ntpTime).c_str());
ntpResult_.elapsedRealTime = MiscServices::TimeServiceClient::GetInstance()->GetBootTimeMs();
ntpResult_.ageMillis = 0;
if (gnssAbility != nullptr) {
gnssAbility->UpdateNtpTime(ntpResult_.ntpTime, ntpResult_.elapsedRealTime);
}
}
if (gnssAbility != nullptr) {
gnssAbility->InjectTime();
}
}
} // namespace Location
} // namespace OHOS
#endif // TIME_SERVICE_ENABLE
#endif

View File

@ -0,0 +1,68 @@
/*
* 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.
*/
#ifdef FEATURE_GNSS_SUPPORT
#ifdef TIME_SERVICE_ENABLE
#include "time_manager.h"
#include <string>
#include "common_utils.h"
#include "elapsed_real_time_check.h"
#include "location_log.h"
#include "time_service_client.h"
namespace OHOS {
namespace Location {
const int64_t INVALID_TIME = 0;
const int64_t GPS_UTC_REFERENCE_TIME = 946656000; // 946656000:UTC time of 2000-01-01 00:00:00
int64_t TimeManager::GetCurrentTime()
{
LBSLOGI(GNSS, "beginning timestamp_ is %{public}s", std::to_string(timestamp_).c_str());
if (timestamp_ < GPS_UTC_REFERENCE_TIME) {
return INVALID_TIME;
}
if (!ElapsedRealTimeCheck::GetInstance()->CanTrustElapsedRealTime()) {
LBSLOGI(GNSS, "getCurrentTime ElapsedRealTime INVALID_TIME");
return INVALID_TIME;
}
int64_t timeTillNow = MiscServices::TimeServiceClient::GetInstance()->GetBootTimeMs() - timeSynsBoot_;
if (timeTillNow >= expireTime_) {
LBSLOGI(GNSS, "getCurrentTime INVALID_TIME");
return INVALID_TIME;
} else {
LBSLOGI(GNSS, "getCurrentTime:%{public}s", std::to_string(timestamp_ + timeTillNow).c_str());
return timestamp_ + timeTillNow;
}
}
void TimeManager::SetCurrentTime(int64_t msTime, int64_t msTimeSynsBoot)
{
timestamp_ = msTime;
timeSynsBoot_ = msTimeSynsBoot;
LBSLOGI(GNSS, "setCurrentTime timestamp_:%{public}s, mTimeReference:%{public}s",
std::to_string(timestamp_).c_str(), std::to_string(timeSynsBoot_).c_str());
}
int64_t TimeManager::GetTimestamp()
{
return timestamp_;
}
} // namespace Location
} // namespace OHOS
#endif // TIME_SERVICE_ENABLE
#endif

View File

@ -27,8 +27,6 @@ namespace Location {
class FusionController {
public:
void ActiveFusionStrategies(int type);
void Process(std::string abilityName);
void FuseResult(std::string abilityName, const std::unique_ptr<Location>& location);
std::unique_ptr<Location> chooseBestLocation(const std::unique_ptr<Location>& gnssLocation,
const std::unique_ptr<Location>& networkLocation);
std::unique_ptr<Location> GetFuseLocation(
@ -36,9 +34,6 @@ public:
static FusionController* GetInstance();
private:
#ifdef FEATURE_NETWORK_SUPPORT
void RequestQuickFix(bool state);
#endif
bool CheckIfLastIndoorLocationValid(const std::unique_ptr<Location>& location,
const std::unique_ptr<Location>& lastFuseLocation);
bool CheckIfLastGnssLocationValid(const std::unique_ptr<Location>& location,

View File

@ -116,6 +116,8 @@ private:
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();

View File

@ -36,7 +36,6 @@ public:
~NetworkAbilityProxy() = default;
LocationErrCode SendLocationRequest(WorkRecord &workrecord) override;
LocationErrCode SetEnable(bool state) override;
LocationErrCode SelfRequest(bool state) override;
LocationErrCode EnableMock() override;
LocationErrCode DisableMock() override;
LocationErrCode SetMocked(const int timeInterval, const std::vector<std::shared_ptr<Location>> &location) override;

View File

@ -24,6 +24,7 @@
#include "i_locator_callback.h"
#include "location.h"
#include "request.h"
#include <mutex>
namespace OHOS {
namespace Location {
@ -49,9 +50,10 @@ public:
private:
struct timespec lastUpdateTime_;
double offsetRandom_;
Location lastLocation_;
std::map<int, std::shared_ptr<Location>> lastLocationsMap_;
Location cacheGnssLocation_;
Location cacheNlpLocation_;
std::mutex lastLocationMutex_;
std::unique_ptr<Location> ApproximatelyLocation(const std::unique_ptr<Location>& location);
bool ProcessRequestForReport(std::shared_ptr<Request>& request,
std::unique_ptr<std::list<std::shared_ptr<Request>>>& deadRequests,
@ -60,6 +62,7 @@ private:
const std::unique_ptr<Location>& location);
std::unique_ptr<Location> ExecuteReportProcess(std::shared_ptr<Request>& request,
std::unique_ptr<Location>& location, std::string abilityName);
void UpdateLastLocation(const std::unique_ptr<Location>& location);
};
} // namespace OHOS
} // namespace Location

View File

@ -45,7 +45,6 @@ public:
void SetAbility(std::string name);
void LocationRequest(WorkRecord &workrecord);
void Enable(bool state, const sptr<IRemoteObject> ability);
void HandleSelfRequest(pid_t pid, pid_t uid, bool state);
void HandleRefrashRequirements();
int GetRequestNum();
bool EnableLocationMock();

View File

@ -31,7 +31,6 @@ const uint32_t REPORT_FUSED_LOCATION_FLAG = FUSION_BASE_FLAG;
#ifdef FEATURE_NETWORK_SUPPORT
const uint32_t QUICK_FIX_FLAG = FUSION_BASE_FLAG << 1;
const uint32_t NETWORK_SELF_REQUEST = 4;
#endif
const long NANOS_PER_MILLI = 1000000L;
const long MAX_GNSS_LOCATION_COMPARISON_MS = 30 * MILLI_PER_SEC;
@ -62,46 +61,6 @@ void FusionController::ActiveFusionStrategies(int type)
}
}
void FusionController::Process(std::string abilityName)
{
needReset_ = true;
if (GNSS_ABILITY.compare(abilityName) != 0) {
return;
}
LBSLOGD(FUSION_CONTROLLER, "fused flag:%{public}u", fusedFlag_);
#ifdef FEATURE_NETWORK_SUPPORT
RequestQuickFix(fusedFlag_ & QUICK_FIX_FLAG);
#endif
}
void FusionController::FuseResult(std::string abilityName, const std::unique_ptr<Location>& location)
{
if (GNSS_ABILITY.compare(abilityName) == 0) {
#ifdef FEATURE_NETWORK_SUPPORT
RequestQuickFix(false);
#endif
}
}
#ifdef FEATURE_NETWORK_SUPPORT
void FusionController::RequestQuickFix(bool state)
{
sptr<IRemoteObject> remoteObject = CommonUtils::GetRemoteObject(LOCATION_NETWORK_LOCATING_SA_ID);
if (remoteObject == nullptr) {
LBSLOGW(FUSION_CONTROLLER, "can not get network ability remote object");
return;
}
MessageParcel data;
MessageParcel reply;
MessageOption option;
if (!data.WriteInterfaceToken(NetworkAbilityProxy::GetDescriptor())) {
return;
}
data.WriteBool(state);
remoteObject->SendRequest(NETWORK_SELF_REQUEST, data, reply, option);
}
#endif
std::unique_ptr<Location> FusionController::chooseBestLocation(const std::unique_ptr<Location>& location,
const std::unique_ptr<Location>& lastFuseLocation)
{

View File

@ -332,6 +332,9 @@ void LocatorAbility::UpdateSaAbilityHandler()
int state = LocationDataRdbManager::QuerySwitchState();
LBSLOGI(LOCATOR, "update location subability enable state, switch state=%{public}d, action registered=%{public}d",
state, isActionRegistered);
if (state == DEFAULT_STATE) {
return;
}
bool isEnabled = (state == ENABLED);
auto locatorBackgroundProxy = LocatorBackgroundProxy::GetInstance();
if (locatorBackgroundProxy == nullptr) {

View File

@ -30,6 +30,7 @@
#include "locator_ability.h"
#include "request_manager.h"
#include "permission_manager.h"
#include "location_data_rdb_manager.h"
#include "accesstoken_kit.h"
#include "tokenid_kit.h"
@ -284,6 +285,11 @@ int32_t LocatorBackgroundProxy::GetUserId(int32_t uid) const
void LocatorBackgroundProxy::OnUserSwitch(int32_t userId)
{
UpdateListOnUserSwitch(userId);
LocationDataRdbManager::ClearSwitchMode();
auto locatorAbility = LocatorAbility::GetInstance();
if (locatorAbility != nullptr) {
locatorAbility->ApplyRequests(1);
}
if (!requestsList_->empty()) {
StartLocator();
} else {

View File

@ -1307,25 +1307,52 @@ int LocatorAbilityStub::PreReportLocationError(MessageParcel &data, MessageParce
return ERRCODE_SUCCESS;
}
bool LocatorAbilityStub::IsStopAction(uint32_t code)
{
if (code == static_cast<uint32_t>(LocatorInterfaceCode::UNREG_SWITCH_CALLBACK) ||
code == static_cast<uint32_t>(LocatorInterfaceCode::STOP_LOCATING) ||
code == static_cast<uint32_t>(LocatorInterfaceCode::STOP_LOCATING) ||
code == static_cast<uint32_t>(LocatorInterfaceCode::DISABLE_LOCATION_MOCK) ||
code == static_cast<uint32_t>(LocatorInterfaceCode::UNREG_LOCATION_ERROR) ||
code == static_cast<uint32_t>(LocatorInterfaceCode::UNREG_LOCATING_REQUIRED_DATA_CALLBACK)) {
return true;
}
return false;
}
bool LocatorAbilityStub::CheckRequestAvailable(uint32_t code, AppIdentity &identity)
{
if (IsStopAction(code)) {
return true;
}
if (PermissionManager::CheckSystemPermission(identity.GetTokenId(), identity.GetTokenIdEx())) {
return true;
}
if (!CommonUtils::CheckAppForUser(identity.GetUid())) {
return false;
}
return true;
}
int32_t LocatorAbilityStub::OnRemoteRequest(uint32_t code,
MessageParcel &data, MessageParcel &reply, MessageOption &option)
{
int ret = ERRCODE_SUCCESS;
pid_t callingPid = IPCSkeleton::GetCallingPid();
pid_t callingUid = IPCSkeleton::GetCallingUid();
uint32_t callingTokenId = IPCSkeleton::GetCallingTokenID();
uint64_t callingTokenIdEx = IPCSkeleton::GetCallingFullTokenID();
uint32_t callingFirstTokenid = IPCSkeleton::GetFirstTokenID();
AppIdentity identity;
identity.SetPid(callingPid);
identity.SetUid(callingUid);
identity.SetTokenId(callingTokenId);
identity.SetTokenIdEx(callingTokenIdEx);
identity.SetFirstTokenId(callingFirstTokenid);
identity.SetPid(IPCSkeleton::GetCallingPid());
identity.SetUid(IPCSkeleton::GetCallingUid());
identity.SetTokenId(IPCSkeleton::GetCallingTokenID());
identity.SetTokenIdEx(IPCSkeleton::GetCallingFullTokenID());
identity.SetFirstTokenId(IPCSkeleton::GetFirstTokenID());
// first token id is invalid
if (identity.GetUid() == identity.GetFirstTokenId() && identity.GetUid() == static_cast<pid_t>(getuid())
&& identity.GetPid() == getpid()) {
identity.SetFirstTokenId(0);
}
std::string bundleName = "";
if (!CommonUtils::GetBundleNameByUid(callingUid, bundleName)) {
LBSLOGD(LOCATOR, "Fail to Get bundle name: uid = %{public}d.", callingUid);
if (!CommonUtils::GetBundleNameByUid(identity.GetUid(), bundleName)) {
LBSLOGD(LOCATOR, "Fail to Get bundle name: uid = %{public}d.", identity.GetUid());
}
identity.SetBundleName(bundleName);
if (code != static_cast<uint32_t>(LocatorInterfaceCode::PROXY_PID_FOR_FREEZE)) {
@ -1335,15 +1362,18 @@ int32_t LocatorAbilityStub::OnRemoteRequest(uint32_t code,
std::to_string(CommonUtils::GetCurrentTimeStamp()).c_str());
}
std::string callingIdentity = IPCSkeleton::ResetCallingIdentity();
if (data.ReadInterfaceToken() != GetDescriptor()) {
LBSLOGE(LOCATOR, "invalid token.");
IPCSkeleton::SetCallingIdentity(callingIdentity);
return ERRCODE_SERVICE_UNAVAILABLE;
}
if (!CheckRequestAvailable(code, identity)) {
IPCSkeleton::SetCallingIdentity(callingIdentity);
reply.WriteInt32(ERRCODE_PERMISSION_DENIED);
return ERRCODE_PERMISSION_DENIED;
}
CancelIdleState();
RemoveUnloadTask(code);
auto handleFunc = locatorHandleMap_.find(static_cast<LocatorInterfaceCode>(code));
if (handleFunc != locatorHandleMap_.end() && handleFunc->second != nullptr) {
auto memberFunc = handleFunc->second;

View File

@ -68,24 +68,6 @@ LocationErrCode NetworkAbilityProxy::SetEnable(bool state)
return LocationErrCode(reply.ReadInt32());
}
LocationErrCode NetworkAbilityProxy::SelfRequest(bool state)
{
MessageParcel data;
MessageParcel reply;
MessageOption option;
if (!data.WriteInterfaceToken(GetDescriptor())) {
LBSLOGE(NETWORK, "write interfaceToken fail!");
return ERRCODE_SERVICE_UNAVAILABLE;
}
data.WriteBool(state);
int error =
Remote()->SendRequest(static_cast<uint32_t>(NetworkInterfaceCode::SELF_REQUEST), data, reply, option);
if (error != ERR_OK) {
LBSLOGI(NETWORK, "%{public}s Transact Error = %{public}d", __func__, error);
}
return LocationErrCode(reply.ReadInt32());
}
LocationErrCode NetworkAbilityProxy::EnableMock()
{
MessageParcel data;

View File

@ -58,7 +58,6 @@ bool ReportManager::OnReportLocation(const std::unique_ptr<Location>& location,
if (fusionController == nullptr) {
return false;
}
fusionController->FuseResult(abilityName, location);
UpdateCacheLocation(location, abilityName);
auto locatorAbility = LocatorAbility::GetInstance();
if (locatorAbility == nullptr) {
@ -77,12 +76,12 @@ bool ReportManager::OnReportLocation(const std::unique_ptr<Location>& location,
for (auto iter = requestList.begin(); iter != requestList.end(); iter++) {
auto request = *iter;
WriteNetWorkReportEvent(abilityName, request, location);
if (abilityName == NETWORK_ABILITY && (request->GetUuid() == location->GetUuid())) {
ProcessRequestForReport(request, deadRequests, location, abilityName);
break;
} else if (abilityName == NETWORK_ABILITY && (request->GetUuid() != location->GetUuid())) {
continue;
} else {
if (abilityName == NETWORK_ABILITY) {
if (request->GetUuid() == location->GetUuid() || location->GetIsFromMock()) {
ProcessRequestForReport(request, deadRequests, location, abilityName);
break;
}
} else if (abilityName == GNSS_ABILITY || abilityName == PASSIVE_ABILITY) {
ProcessRequestForReport(request, deadRequests, location, abilityName);
}
}
@ -209,6 +208,10 @@ std::unique_ptr<Location> ReportManager::GetPermittedLocation(const std::shared_
}
return nullptr;
}
if (!PermissionManager::CheckSystemPermission(tokenId, tokenIdEx) &&
!CommonUtils::CheckAppForUser(uid)) {
return nullptr;
}
std::unique_ptr<Location> finalLocation = std::make_unique<Location>(*location);
// for api8 and previous version, only ACCESS_LOCATION permission granted also report original location info.
if (PermissionManager::CheckLocationPermission(tokenId, firstTokenId)) {
@ -272,7 +275,8 @@ bool ReportManager::ResultCheck(const std::unique_ptr<Location>& location,
LBSLOGE(REPORT_MANAGER, "accuracy check fail, do not report location");
return false;
}
if (CommonUtils::DoubleEqual(request->GetLastLocation()->GetLatitude(), MIN_LATITUDE - 1)) {
if (CommonUtils::DoubleEqual(request->GetLastLocation()->GetLatitude(), MIN_LATITUDE - 1) ||
request->GetLastLocation()->GetIsFromMock() != location->GetIsFromMock()) {
LBSLOGD(REPORT_MANAGER, "no valid cache location, no need to check");
return true;
}
@ -301,25 +305,42 @@ void ReportManager::UpdateCacheLocation(const std::unique_ptr<Location>& locatio
if (abilityName == GNSS_ABILITY) {
if (HookUtils::CheckGnssLocationValidity(location)) {
cacheGnssLocation_ = *location;
lastLocation_ = *location;
UpdateLastLocation(location);
}
} else if (abilityName == NETWORK_ABILITY &&
location->GetLocationSourceType() != LocationSourceType::INDOOR_TYPE) {
cacheNlpLocation_ = *location;
lastLocation_ = *location;
UpdateLastLocation(location);
} else {
lastLocation_ = *location;
UpdateLastLocation(location);
}
}
void ReportManager::UpdateLastLocation(const std::unique_ptr<Location>& location)
{
int currentUserId = 0;
if (CommonUtils::GetCurrentUserId(currentUserId)) {
std::unique_lock<std::mutex> lock(lastLocationMutex_);
lastLocationsMap_.insert(std::make_pair(currentUserId, std::make_shared<Location>(*location)));
}
}
std::unique_ptr<Location> ReportManager::GetLastLocation()
{
auto lastLocation = std::make_unique<Location>(lastLocation_);
if (CommonUtils::DoubleEqual(lastLocation->GetLatitude(), MIN_LATITUDE - 1)) {
LBSLOGE(REPORT_MANAGER, "%{public}s no valid cache location", __func__);
return nullptr;
int currentUserId = 0;
if (CommonUtils::GetCurrentUserId(currentUserId)) {
std::unique_lock<std::mutex> lock(lastLocationMutex_);
auto iter = lastLocationsMap_.find(currentUserId);
if (iter == lastLocationsMap_.end()) {
return nullptr;
}
std::unique_ptr<Location> lastLocation = std::make_unique<Location>(*(iter->second));
if (CommonUtils::DoubleEqual(lastLocation->GetLatitude(), MIN_LATITUDE - 1)) {
return nullptr;
}
return lastLocation;
}
return lastLocation;
return nullptr;
}
std::unique_ptr<Location> ReportManager::GetCacheLocation(const std::shared_ptr<Request>& request)

View File

@ -403,6 +403,9 @@ bool RequestManager::ActiveLocatingStrategies(const std::shared_ptr<Request>& re
*/
bool RequestManager::IsRequestAvailable(std::shared_ptr<Request>& request)
{
if (!request->GetIsRequesting()) {
return false;
}
// for frozen app, do not add to workRecord
if (LocatorAbility::GetInstance()->IsProxyPid(request->GetPid())) {
return false;
@ -441,13 +444,9 @@ bool RequestManager::AddRequestToWorkRecord(std::string abilityName, std::shared
if (request == nullptr) {
return false;
}
if (!request->GetIsRequesting()) {
return false;
}
if (!IsRequestAvailable(request)) {
return false;
}
auto locationErrorCallback = request->GetLocationErrorCallBack();
int switchState = DISABLED;
auto locatorAbility = LocatorAbility::GetInstance();
@ -493,6 +492,13 @@ bool RequestManager::AddRequestToWorkRecord(std::string abilityName, std::shared
if (requestConfig == nullptr) {
return false;
}
if (!PermissionManager::CheckSystemPermission(tokenId, request->GetTokenIdEx()) &&
!CommonUtils::CheckAppForUser(uid)) {
LBSLOGD(REPORT_MANAGER, "AddRequestToWorkRecord uid: %{public}d ,CheckAppIsCurrentUser fail", uid);
return false;
}
if (HookUtils::ExecuteHookWhenAddWorkRecord(isDeviceStillState_.load(), isDeviceIdleMode_.load(),
abilityName, bundleName)) {
LBSLOGI(REQUEST_MANAGER, "Enter idle and still status, not add request");
@ -517,6 +523,8 @@ void RequestManager::ProxySendLocationRequest(std::string abilityName, WorkRecor
LBSLOGE(LOCATOR, "%{public}s: remote obj is nullptr", __func__);
return;
}
LBSLOGI(LOCATOR, "%{public}s: %{public}s workRecord uid_ size %{public}d",
__func__, abilityName.c_str(), workRecord.Size());
workRecord.SetDeviceId(CommonUtils::InitDeviceId());
if (abilityName == GNSS_ABILITY) {
#ifdef FEATURE_GNSS_SUPPORT
@ -534,10 +542,6 @@ void RequestManager::ProxySendLocationRequest(std::string abilityName, WorkRecor
passiveProxy->SendLocationRequest(workRecord);
#endif
}
auto fusionController = FusionController::GetInstance();
if (fusionController != nullptr) {
fusionController->Process(abilityName);
}
}
sptr<IRemoteObject> RequestManager::GetRemoteObject(std::string abilityName)

View File

@ -153,30 +153,6 @@ void SubAbility::Enable(bool state, const sptr<IRemoteObject> ability)
}
}
void SubAbility::HandleSelfRequest(pid_t pid, pid_t uid, bool state)
{
std::unique_ptr<WorkRecord> records = std::make_unique<WorkRecord>();
std::string name = Str16ToStr8(u"ohos");
std::string uuid = std::to_string(CommonUtils::IntRandom(MIN_INT_RANDOM, MAX_INT_RANDOM));
records->Set(*lastRecord_);
if (state) {
std::unique_ptr<RequestConfig> requestConfig = std::make_unique<RequestConfig>();
requestConfig->SetTimeInterval(interval_);
std::shared_ptr<Request> request = std::make_shared<Request>();
request->SetUid(uid);
request->SetPid(pid);
request->SetPackageName(name);
request->SetRequestConfig(*requestConfig);
request->SetUuid(uuid);
request->SetNlpRequestType(NlpRequestType::PRIORITY_TYPE_BALANCED_POWER_ACCURACY);
records->Add(request);
} else {
records->Remove(uid, pid, name, uuid);
}
LocationRequest(*records);
records->Clear();
}
bool SubAbility::EnableLocationMock()
{
LBSLOGI(label_, "EnableLocationMock current state is %{public}d", mockEnabled_);

View File

@ -283,12 +283,12 @@ bool WorkRecord::Find(int uid, std::string name, std::string uuid)
void WorkRecord::Clear()
{
std::unique_lock<std::mutex> lock(workRecordMutex_);
uids_.clear();
pids_.clear();
names_.clear();
timeInterval_.clear();
uuid_.clear();
nlpRequestType_.clear();
std::vector<int>().swap(uids_);
std::vector<int>().swap(pids_);
std::vector<std::string>().swap(names_);
std::vector<int>().swap(timeInterval_);
std::vector<std::string>().swap(uuid_);
std::vector<int>().swap(nlpRequestType_);
num_ = 0;
}

View File

@ -58,7 +58,6 @@ public:
}
LocationErrCode SendLocationRequest(WorkRecord &workrecord) override;
LocationErrCode SetEnable(bool state) override;
LocationErrCode SelfRequest(bool state) override;
int32_t Dump(int32_t fd, const std::vector<std::u16string>& args) override;
void RequestRecord(WorkRecord &workRecord, bool isAdded) override;
LocationErrCode EnableMock() override;

View File

@ -29,7 +29,6 @@ namespace Location {
class INetworkAbility : public ISubAbility {
public:
DECLARE_INTERFACE_DESCRIPTOR(u"location.INetworkAbility");
virtual LocationErrCode SelfRequest(bool state) = 0;
};
class NetworkAbilityStub : public IRemoteStub<INetworkAbility> {
@ -47,7 +46,6 @@ public:
private:
int SendLocationRequestInner(MessageParcel &data, MessageParcel &reply, AppIdentity &identity);
int SetMockLocationsInner(MessageParcel &data, MessageParcel &reply, AppIdentity &identity);
int SelfRequestInner(MessageParcel &data, MessageParcel &reply, AppIdentity &identity);
int SetEnableInner(MessageParcel &data, MessageParcel &reply, AppIdentity &identity);
int EnableMockInner(MessageParcel &data, MessageParcel &reply, AppIdentity &identity);
int DisableMockInner(MessageParcel &data, MessageParcel &reply, AppIdentity &identity);

View File

@ -255,13 +255,6 @@ bool NetworkAbility::CheckIfNetworkConnecting()
return IsMockEnabled() || !GetLocationMock().empty() || GetRequestNum() != 0;
}
LocationErrCode NetworkAbility::SelfRequest(bool state)
{
LBSLOGD(NETWORK, "SelfRequest %{public}d", state);
HandleSelfRequest(IPCSkeleton::GetCallingPid(), IPCSkeleton::GetCallingUid(), state);
return ERRCODE_SUCCESS;
}
void NetworkAbility::RequestRecord(WorkRecord &workRecord, bool isAdded)
{
if (!IsConnect()) {
@ -285,7 +278,7 @@ void NetworkAbility::RequestRecord(WorkRecord &workRecord, bool isAdded)
} else {
RemoveNetworkLocation(workRecord);
if (GetRequestNum() == 0 && conn_ != nullptr) {
LBSLOGD(NETWORK, "RequestRecord disconnect");
LBSLOGI(NETWORK, "RequestRecord disconnect");
AAFwk::AbilityManagerClient::GetInstance()->DisconnectAbility(conn_);
}
}
@ -301,7 +294,7 @@ bool NetworkAbility::RequestNetworkLocation(WorkRecord &workRecord)
LBSLOGE(NETWORK, "QuerySwitchState is DISABLED");
return false;
}
LBSLOGD(NETWORK, "start network location");
LBSLOGI(NETWORK, "start network location, uuid: %{public}s", workRecord.GetUuid(0).c_str());
sptr<NetworkCallbackHost> callback = new (std::nothrow) NetworkCallbackHost();
if (callback == nullptr) {
LBSLOGE(NETWORK, "can not get valid callback.");
@ -333,7 +326,7 @@ bool NetworkAbility::RemoveNetworkLocation(WorkRecord &workRecord)
LBSLOGE(NETWORK, "nlpProxy is nullptr.");
return false;
}
LBSLOGD(NETWORK, "stop network location");
LBSLOGI(NETWORK, "stop network location, uuid: %{public}s", workRecord.GetUuid(0).c_str());
MessageParcel data;
MessageParcel reply;
MessageOption option;
@ -407,6 +400,9 @@ int32_t NetworkAbility::ReportMockedLocation(const std::shared_ptr<Location> loc
LBSLOGE(NETWORK, "location mock is enabled, do not report network location!");
return ERR_OK;
}
location->SetTimeSinceBoot(CommonUtils::GetSinceBootTime());
location->SetTimeStamp(CommonUtils::GetCurrentTimeStamp() * MICRO_PER_MILLI);
location->SetLocationSourceType(LocationSourceType::NETWORK_TYPE);
ReportLocationInfo(NETWORK_ABILITY, location);
#ifdef FEATURE_PASSIVE_SUPPORT
ReportLocationInfo(PASSIVE_ABILITY, location);
@ -478,12 +474,6 @@ void NetworkAbility::SendMessage(uint32_t code, MessageParcel &data, MessageParc
}
break;
}
case static_cast<uint32_t>(NetworkInterfaceCode::SELF_REQUEST): {
int64_t param = data.ReadBool() ? 1 : 0;
networkHandler_->SendEvent(code, param, 0) ? reply.WriteInt32(ERRCODE_SUCCESS) :
reply.WriteInt32(ERRCODE_SERVICE_UNAVAILABLE);
break;
}
default:
break;
}
@ -569,12 +559,6 @@ void NetworkHandler::ProcessEvent(const AppExecFwk::InnerEvent::Pointer& event)
}
break;
}
case static_cast<uint32_t>(NetworkInterfaceCode::SELF_REQUEST): {
bool state = event->GetParam();
networkAbility->SelfRequest(state);
// no need unload sa, return
return;
}
default:
break;
}

View File

@ -45,10 +45,6 @@ void NetworkAbilityStub::InitNetworkMsgHandleMap()
[this](MessageParcel &data, MessageParcel &reply, AppIdentity &identity) {
return SetMockLocationsInner(data, reply, identity);
};
NetworkMsgHandleMap_[static_cast<uint32_t>(NetworkInterfaceCode::SELF_REQUEST)] =
[this](MessageParcel &data, MessageParcel &reply, AppIdentity &identity) {
return SelfRequestInner(data, reply, identity);
};
NetworkMsgHandleMap_[static_cast<uint32_t>(NetworkInterfaceCode::SET_ENABLE)] =
[this](MessageParcel &data, MessageParcel &reply, AppIdentity &identity) {
return SetEnableInner(data, reply, identity);
@ -88,19 +84,6 @@ int NetworkAbilityStub::SetMockLocationsInner(MessageParcel &data, MessageParcel
return ERRCODE_SUCCESS;
}
int NetworkAbilityStub::SelfRequestInner(MessageParcel &data, MessageParcel &reply, AppIdentity &identity)
{
if (!PermissionManager::CheckCallingPermission(identity.GetUid(), identity.GetPid(), reply)) {
return ERRCODE_PERMISSION_DENIED;
}
if (CheckLocationSwitchState(reply)) {
return ERRCODE_SWITCH_OFF;
}
SendMessage(static_cast<uint32_t>(NetworkInterfaceCode::SELF_REQUEST), data, reply);
isMessageRequest_ = true;
return ERRCODE_SUCCESS;
}
int NetworkAbilityStub::SetEnableInner(MessageParcel &data, MessageParcel &reply, AppIdentity &identity)
{
if (!PermissionManager::CheckCallingPermission(identity.GetUid(), identity.GetPid(), reply)) {

View File

@ -63,9 +63,20 @@ int NetworkCallbackHost::OnRemoteRequest(
void NetworkCallbackHost::OnLocationReport(const std::unique_ptr<Location>& location)
{
LBSLOGD(NETWORK, "NetworkCallbackHost::OnLocationReport");
auto networkAbility = NetworkAbility::GetInstance();
if (networkAbility == nullptr) {
LBSLOGE(NETWORK, "ReportLocation: network ability is nullptr.");
return;
}
if (networkAbility->IsMockEnabled()) {
LBSLOGE(NETWORK, "location mock is enabled, do not report network location!");
return;
}
std::shared_ptr<Location> locationNew = std::make_shared<Location>(*location);
NetworkAbility::GetInstance()->ReportLocationInfo(NETWORK_ABILITY, locationNew);
NetworkAbility::GetInstance()->ReportLocationInfo(PASSIVE_ABILITY, locationNew);
if (locationNew->GetLocationSourceType() == LocationSourceType::NETWORK_TYPE) {
NetworkAbility::GetInstance()->ReportLocationInfo(PASSIVE_ABILITY, locationNew);
}
WriteLocationInnerEvent(NETWORK_CALLBACK_LOCATION, {"speed", std::to_string(location->GetSpeed()),
"accuracy", std::to_string(location->GetAccuracy()),
"locationTimestamp", std::to_string(location->GetTimeStamp() / MILLI_PER_SEC),

View File

@ -2,8 +2,8 @@
"app": {
"bundleName": "com.ohos.locationdialog",
"vendor": "example",
"versionCode": 1000000,
"versionName": "1.0.0",
"versionCode": 1000001,
"versionName": "1.0.1",
"icon": "$media:app_icon",
"label": "$string:app_name",
"distributedNotificationEnabled": true,

View File

@ -28,6 +28,7 @@ struct dialogPlusPage {
@State secondaryButtonValue: Resource = $r('app.string.wifi_cdd_notify_yes_button');
private WIFI_DIALOG_CDD: number = 0;
private WIFI_DIALOG_THREE_VAP: number = 1;
private WIFI_DIALOG_CANDIDATE_CONNECT: number = 2;
aboutToAppear() {
console.info(TAG, 'aboutToAppear')
@ -44,6 +45,11 @@ struct dialogPlusPage {
this.primaryButtonValue = $r('app.string.wifi_three_vap_notify_no_button');
this.secondaryButtonValue = $r('app.string.wifi_three_vap_notify_yes_button');
break;
case this.WIFI_DIALOG_CANDIDATE_CONNECT:
this.title = $r('app.string.wifi_candidate_connect_notify_title');
this.primaryButtonValue = $r('app.string.wifi_candidate_connect_notify_no_button');
this.secondaryButtonValue = $r('app.string.wifi_candidate_connect_notify_yes_button');
break;
default:
break;
}

View File

@ -107,6 +107,18 @@
{
"name": "wifi_three_vap_notify_yes_button",
"value": "Disconnect"
},
{
"name": "wifi_candidate_connect_notify_title",
"value": "Connect to a specified candidate WLAN?"
},
{
"name": "wifi_candidate_connect_notify_no_button",
"value": "Cancel"
},
{
"name": "wifi_candidate_connect_notify_yes_button",
"value": "Connect"
}
]
}

View File

@ -99,6 +99,18 @@
{
"name": "wifi_three_vap_notify_yes_button",
"value": "断开"
},
{
"name": "wifi_candidate_connect_notify_title",
"value": "连接到指定的候选WLAN?"
},
{
"name": "wifi_candidate_connect_notify_no_button",
"value": "取消"
},
{
"name": "wifi_candidate_connect_notify_yes_button",
"value": "连接"
}
]
}

View File

@ -29,10 +29,6 @@ namespace OHOS {
std::make_shared<FusionController>();
int index = 0;
fusionController->ActiveFusionStrategies(data[index++]);
std::string abilityName((const char*) data, size);
fusionController->Process(abilityName);
auto location = std::make_unique<OHOS::Location::Location>();
fusionController->FuseResult(abilityName, location);
return true;
}
}

View File

@ -69,10 +69,6 @@ bool NetworkAbilityProxy001FuzzTest(const uint8_t* data, size_t size)
std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_TIMES));
proxy->SetEnable(false);
std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_TIMES));
proxy->SelfRequest(true);
std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_TIMES));
proxy->SelfRequest(false);
std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_TIMES));
std::vector<std::shared_ptr<OHOS::Location::Location>> locations;
proxy->EnableMock();
std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_TIMES));

View File

@ -26,6 +26,7 @@ if (location_feature_with_gnss) {
"$GNSS_UNIT_TEST_DIR/source/gnss_ability_test.cpp",
"$GNSS_UNIT_TEST_DIR/source/gnss_event_callback_test.cpp",
"$GNSS_UNIT_TEST_DIR/source/gnss_interface_test.cpp",
"$GNSS_UNIT_TEST_DIR/source/ntp_time_test.cpp",
"$LOCATION_ROOT_DIR/test/mock/src/mock_service_registry.cpp",
]

View File

@ -0,0 +1,30 @@
/*
* 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 NTP_TIME_TEST_H
#define NTP_TIME_TEST_H
#include <gtest/gtest.h>
namespace OHOS {
namespace Location {
class NtpTimeTest : public testing::Test {
public:
void SetUp();
void TearDown();
};
} // namespace Location
} // namespace OHOS
#endif // NTP_TIME_TEST_H

View File

@ -1471,17 +1471,6 @@ HWTEST_F(GnssAbilityTest, SubAbilityCommonGetRequestNum001, TestSize.Level1)
LBSLOGI(LOCATOR, "[SubAbilityCommonTest] GetRequestNum001 end");
}
HWTEST_F(GnssAbilityTest, SubAbilityCommonHandleSelfRequest001, TestSize.Level1)
{
GTEST_LOG_(INFO)
<< "SubAbilityCommonTest, HandleSelfRequest001, TestSize.Level1";
LBSLOGI(LOCATOR, "[SubAbilityCommonTest] HandleSelfRequest001 begin");
ability_->HandleSelfRequest(0, 0, false);
ability_->GetTimeIntervalMock();
LBSLOGI(LOCATOR, "[SubAbilityCommonTest] HandleSelfRequest001 end");
}
HWTEST_F(GnssAbilityTest, GetCommandFlags001, TestSize.Level1)
{
GTEST_LOG_(INFO)

View File

@ -0,0 +1,62 @@
/*
* Copyright (c) 2023 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 "ntp_time_test.h"
#include "location_log.h"
#include "ntp_time_check.h"
using namespace testing::ext;
namespace OHOS {
namespace Location {
void NtpTimeTest::SetUp()
{
}
void NtpTimeTest::TearDown()
{
}
HWTEST_F(NtpTimeTest, NtpTimeCheckSetGpsTimeTest001, TestSize.Level1)
{
GTEST_LOG_(INFO)
<< "NtpTimeTest, NtpTimeCheckSetGpsTimeTest001, TestSize.Level1";
LBSLOGI(GNSS_TEST, "[NtpTimeTest] NtpTimeCheckSetGpsTimeTest001 begin");
auto ntpTimeCheck = NtpTimeCheck::GetInstance();
EXPECT_NE(nullptr, ntpTimeCheck);
int64_t gpsMsTime = -1;
int64_t bootTimeMs = -1;
ntpTimeCheck->SetGpsTime(gpsMsTime, bootTimeMs);
LBSLOGI(GNSS_TEST, "[NtpTimeTest] NtpTimeCheckSetGpsTimeTest001 end");
}
HWTEST_F(NtpTimeTest, NtpTimeCheckCheckNtpTimeTest001, TestSize.Level1)
{
GTEST_LOG_(INFO)
<< "NtpTimeTest, NtpTimeCheckCheckNtpTimeTest001, TestSize.Level1";
LBSLOGI(GNSS_TEST, "[NtpTimeTest] NtpTimeCheckCheckNtpTimeTest001 begin");
auto ntpTimeCheck = NtpTimeCheck::GetInstance();
EXPECT_NE(nullptr, ntpTimeCheck);
int64_t gpsMsTime = 1720522730000;
int64_t bootTimeMs = 1;
ntpTimeCheck->SetGpsTime(gpsMsTime, bootTimeMs);
int64_t ntpMsTime = 1720522730000;
int64_t msTimeSynsBoot = 1;
ntpTimeCheck->CheckNtpTime(ntpMsTime, msTimeSynsBoot);
LBSLOGI(GNSS_TEST, "[NtpTimeTest] NtpTimeCheckCheckNtpTimeTest001 end");
}
}
}

View File

@ -93,48 +93,6 @@ HWTEST_F(FusionControllerTest, ActiveFusionStrategies005, TestSize.Level1)
LBSLOGI(FUSION_CONTROLLER, "[FusionControllerTest] ActiveFusionStrategies005 end");
}
HWTEST_F(FusionControllerTest, Process001, TestSize.Level1)
{
GTEST_LOG_(INFO)
<< "FusionControllerTest, Process001, TestSize.Level1";
LBSLOGI(FUSION_CONTROLLER, "[FusionControllerTest] Process001 begin");
fusionController_->Process(GNSS_ABILITY);
EXPECT_EQ(true, fusionController_->needReset_);
LBSLOGI(FUSION_CONTROLLER, "[FusionControllerTest] Process001 end");
}
HWTEST_F(FusionControllerTest, Process002, TestSize.Level1)
{
GTEST_LOG_(INFO)
<< "FusionControllerTest, Process002, TestSize.Level1";
LBSLOGI(FUSION_CONTROLLER, "[FusionControllerTest] Process002 begin");
fusionController_->Process(PASSIVE_ABILITY); // is not gnss ability
EXPECT_EQ(true, fusionController_->needReset_);
LBSLOGI(FUSION_CONTROLLER, "[FusionControllerTest] Process002 end");
}
HWTEST_F(FusionControllerTest, FuseResult001, TestSize.Level1)
{
GTEST_LOG_(INFO)
<< "FusionControllerTest, FuseResult001, TestSize.Level1";
LBSLOGI(FUSION_CONTROLLER, "[FusionControllerTest] FuseResult001 begin");
auto location = std::make_unique<Location>();
ASSERT_TRUE(fusionController_ != nullptr);
fusionController_->FuseResult(GNSS_ABILITY, location);
LBSLOGI(FUSION_CONTROLLER, "[FusionControllerTest] FuseResult001 end");
}
HWTEST_F(FusionControllerTest, FuseResult002, TestSize.Level1)
{
GTEST_LOG_(INFO)
<< "FusionControllerTest, FuseResult002, TestSize.Level1";
LBSLOGI(FUSION_CONTROLLER, "[FusionControllerTest] FuseResult002 begin");
auto location = std::make_unique<Location>();
ASSERT_TRUE(fusionController_ != nullptr);
fusionController_->FuseResult(NETWORK_ABILITY, location); // is not gnss ability
LBSLOGI(FUSION_CONTROLLER, "[FusionControllerTest] FuseResult002 end");
}
HWTEST_F(FusionControllerTest, ChooseBestLocation001, TestSize.Level1)
{
GTEST_LOG_(INFO)

View File

@ -36,7 +36,6 @@ public:
MockNetworkAbilityStub() {}
~MockNetworkAbilityStub() {}
MOCK_METHOD(void, SendMessage, (uint32_t code, MessageParcel &data, MessageParcel &reply));
MOCK_METHOD(LocationErrCode, SelfRequest, (bool state));
MOCK_METHOD(LocationErrCode, SendLocationRequest, (WorkRecord &workrecord));
MOCK_METHOD(LocationErrCode, SetEnable, (bool state));
MOCK_METHOD(LocationErrCode, EnableMock, ());

View File

@ -78,23 +78,6 @@ HWTEST_F(NetworkAbilityStubTest, NetworkAbilityStubTest002, TestSize.Level1)
LBSLOGI(NETWORK, "[NetworkAbilityStubTest] NetworkAbilityStubTest002 end");
}
HWTEST_F(NetworkAbilityStubTest, NetworkAbilityStubTest003, TestSize.Level1)
{
GTEST_LOG_(INFO)
<< "NetworkAbilityStubTest, NetworkAbilityStubTest003, TestSize.Level1";
LBSLOGI(NETWORK, "[NetworkAbilityStubTest] NetworkAbilityStubTest003 begin");
auto networkAbilityStub = sptr<MockNetworkAbilityStub>(new (std::nothrow) MockNetworkAbilityStub());
EXPECT_CALL(*networkAbilityStub, SendMessage(_, _, _)).WillOnce(DoAll(Return()));
MessageParcel parcel;
parcel.WriteInterfaceToken(NetworkAbilityProxy::GetDescriptor());
MessageParcel reply;
MessageOption option;
EXPECT_EQ(ERRCODE_SUCCESS,
networkAbilityStub->OnRemoteRequest(static_cast<uint32_t>(NetworkInterfaceCode::SELF_REQUEST),
parcel, reply, option));
LBSLOGI(NETWORK, "[NetworkAbilityStubTest] NetworkAbilityStubTest003 end");
}
HWTEST_F(NetworkAbilityStubTest, NetworkAbilityStubTest004, TestSize.Level1)
{
GTEST_LOG_(INFO)

View File

@ -178,42 +178,6 @@ HWTEST_F(NetworkAbilityTest, SetEnableAndDisable001, TestSize.Level1)
LBSLOGI(NETWORK_TEST, "[NetworkAbilityTest] SetEnableAndDisable001 end");
}
/*
* @tc.name: SelfRequest001
* @tc.desc: test self request function
* @tc.type: FUNC
*/
HWTEST_F(NetworkAbilityTest, SelfRequest001, TestSize.Level1)
{
GTEST_LOG_(INFO)
<< "NetworkAbilityTest, SelfRequest001, TestSize.Level1";
LBSLOGI(NETWORK_TEST, "[NetworkAbilityTest] SelfRequest001 begin");
/*
* @tc.steps: step1. send location request
* @tc.expected: step1. no exception happens.
*/
EXPECT_EQ(ERRCODE_SWITCH_OFF, proxy_->SelfRequest(true));
LBSLOGI(NETWORK_TEST, "[NetworkAbilityTest] SelfRequest001 end");
}
/*
* @tc.name: SelfRequest002
* @tc.desc: test self request function
* @tc.type: FUNC
*/
HWTEST_F(NetworkAbilityTest, SelfRequest002, TestSize.Level1)
{
GTEST_LOG_(INFO)
<< "NetworkAbilityTest, SelfRequest002, TestSize.Level1";
LBSLOGI(NETWORK_TEST, "[NetworkAbilityTest] SelfRequest002 begin");
/*
* @tc.steps: step1. send location request
* @tc.expected: step1. no exception happens.
*/
EXPECT_EQ(ERRCODE_SWITCH_OFF, proxy_->SelfRequest(false));
LBSLOGI(NETWORK_TEST, "[NetworkAbilityTest] SelfRequest002 end");
}
HWTEST_F(NetworkAbilityTest, NetworkLocationMock001, TestSize.Level1)
{
GTEST_LOG_(INFO)