!18 完善代码,兼容第三方依赖需求

Merge pull request !18 from guduhanyan/master
This commit is contained in:
openharmony_ci
2021-09-23 13:29:33 +00:00
committed by Gitee
53 changed files with 876 additions and 910 deletions
+1
View File
@@ -24,6 +24,7 @@ group("time_native_packages") {
"interfaces/kits/js/napi/system_timer:systemtimer",
"profile:miscservices_time_sa_profiles",
"services:time_service",
"services:timezone_json",
]
}
}
+1 -1
View File
@@ -22,7 +22,7 @@
├── etc # 组件包含的进程的配置文件
├── figures # 构架图
├── interfaces # 组件对外提供的接口代码
└── innerkits # 服务间接口
└── innerkits # 服务间接口
│ └── kits # 对应用提供的接口
├── profile # 组件包含的系统服务的配置文件
└── services # 时间服务实现
+1 -1
View File
@@ -11,7 +11,7 @@
"path" : ["/system/bin/sa_main", "/system/profile/time_service.xml"],
"uid" : "system",
"gid" : ["system", "shell"],
"caps" : ["SYS_TIME","WAKE_ALARM"]
"caps" : ["SYS_TIME", "WAKE_ALARM"]
}
]
}
+4 -2
View File
@@ -12,13 +12,14 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef I_TIMER_INFO_H
#define I_TIMER_INFO_H
#include <mutex>
#include "want_agent.h"
namespace OHOS {
namespace MiscServices {
class ITimerInfo {
public:
ITimerInfo();
@@ -70,9 +71,10 @@ public:
*/
virtual void SetInterval(const uint64_t &interval) = 0;
virtual void SetWantAgent(std::shared_ptr<OHOS::Notification::WantAgent::WantAgent> wantAgent) = 0;
virtual void OnTrigger() = 0;
virtual void OnTrigger() = 0;
};
} // MiscServices
} // OHOS
#endif // I_TIMER_INFO_H
@@ -20,29 +20,24 @@
#include "time_service_interface.h"
#include "iremote_object.h"
#include "timer_call_back.h"
#include <mutex>
namespace OHOS {
namespace MiscServices {
constexpr int64_t ERROR_OPREATION_FAILED = -1;
class TimeSaDeathRecipient : public IRemoteObject::DeathRecipient {
public:
explicit TimeSaDeathRecipient();
explicit TimeSaDeathRecipient();
~TimeSaDeathRecipient() = default;
void OnRemoteDied(const wptr<IRemoteObject> &object) override;
private:
DISALLOW_COPY_AND_MOVE(TimeSaDeathRecipient);
DISALLOW_COPY_AND_MOVE(TimeSaDeathRecipient);
};
class TimeServiceClient : public RefBase{
class TimeServiceClient : public RefBase {
public:
DISALLOW_COPY_AND_MOVE(TimeServiceClient);
static sptr<TimeServiceClient> GetInstance();
/**
@@ -172,15 +167,12 @@ public:
private:
TimeServiceClient();
~TimeServiceClient();
static sptr<ITimeService> ConnectService();
static std::mutex instanceLock_;
static sptr<TimeServiceClient> instance_;
static sptr<ITimeService> timeServiceProxy_;
static sptr<TimeSaDeathRecipient> deathRecipient_;
};
} // MiscServices
} // OHOS
@@ -44,7 +44,6 @@ declare namespace systemTime {
*/
function setTimezone(timezone: string, callback: AsyncCallback<boolean>): void;
function setTimezone(timezone: string): Promise<boolean>;
}
export default systemTime;
@@ -26,17 +26,15 @@ constexpr int REJECT = 0;
constexpr int NONE_PARAMETER = 0;
constexpr int ONE_PARAMETER = 1;
constexpr int TWO_PARAMETER = 2;
constexpr int THREE_PARAMETER = 3;
constexpr int TWO_PARAMETERS = 2;
constexpr int THREE_PARAMETERS = 3;
constexpr int MAX_TIME_ZONE_ID = 1024;
#define GET_PARAMS(env, info, num) \
#define GET_PARAMS(env, info, num) \
size_t argc = num; \
napi_value argv[num]; \
napi_value thisVar; \
void* data; \
napi_value argv[num] = {0}; \
napi_value thisVar = nullptr; \
void *data; \
napi_get_cb_info(env, info, &argc, argv, &thisVar, &data)
typedef struct AsyncContext {
@@ -20,30 +20,28 @@
#include "napi/native_api.h"
#include "napi/native_node_api.h"
#include "js_native_api.h"
#include "time_common.h"
#include <initializer_list>
using namespace OHOS::MiscServices;
static napi_value JSSystemTimeSetTime(napi_env env, napi_callback_info info)
{
TIME_HILOGI(TIME_MODULE_JS_NAPI,"JSSystemTimeSetTime start");
GET_PARAMS(env, info, 2);
NAPI_ASSERT(env, argc == ONE_PARAMETER || argc == TWO_PARAMETER, "type mismatch");
TIME_HILOGI(TIME_MODULE_JS_NAPI, "JSSystemTimeSetTime start");
GET_PARAMS(env, info, TWO_PARAMETERS);
NAPI_ASSERT(env, argc == ONE_PARAMETER || argc == TWO_PARAMETERS, "type mismatch");
AsyncContext* asyncContext = new (std::nothrow)AsyncContext();
asyncContext->env = env;
for (size_t i = 0; i < argc; i++) {
napi_valuetype valueType;
napi_valuetype valueType = napi_undefined;
napi_typeof(env, argv[i], &valueType);
if (i == 0 && valueType == napi_number) {
napi_get_value_int64(env, argv[i], &asyncContext->time);
} else if (i == 0 && valueType == napi_object){
} else if (i == 0 && valueType == napi_object) {
bool hasProperty = false;
napi_valuetype resValueType;
napi_valuetype resValueType = napi_undefined;
NAPI_CALL(env, napi_has_named_property(env, argv[i], "getTime", &hasProperty));
NAPI_ASSERT(env, hasProperty, "type expected.");
napi_value getTimeFunc = nullptr;
@@ -73,12 +71,9 @@ static napi_value JSSystemTimeSetTime(napi_env env, napi_callback_info info)
napi_value resource = nullptr;
napi_create_string_utf8(env, "JSSystemTimeSetTime", NAPI_AUTO_LENGTH, &resource);
napi_create_async_work(env, nullptr, resource,[](napi_env env, void* data) {
AsyncContext* asyncContext = (AsyncContext*)data;
bool setTimeResult;
setTimeResult = TimeServiceClient::GetInstance()->SetTime(asyncContext->time);
auto setTimeResult = TimeServiceClient::GetInstance()->SetTime(asyncContext->time);
if (setTimeResult) {
asyncContext->status = RESOLVED;
} else {
@@ -119,23 +114,28 @@ static napi_value JSSystemTimeSetTime(napi_env env, napi_callback_info info)
return result;
}
static napi_value JSSystemTimeSetTimeZone(napi_env env, napi_callback_info info){
TIME_HILOGI(TIME_MODULE_JS_NAPI,"JSSystemTimeSetTimeZone start");
GET_PARAMS(env, info, 2);
NAPI_ASSERT(env, argc == ONE_PARAMETER || argc == TWO_PARAMETER, "type mismatch");
static napi_value JSSystemTimeSetTimeZone(napi_env env, napi_callback_info info)
{
TIME_HILOGI(TIME_MODULE_JS_NAPI, "JSSystemTimeSetTimeZone start");
GET_PARAMS(env, info, TWO_PARAMETERS);
NAPI_ASSERT(env, argc == ONE_PARAMETER || argc == TWO_PARAMETERS, "type mismatch");
AsyncContext* asyncContext = new AsyncContext();
asyncContext->env = env;
for (size_t i = 0; i < argc; i++) {
napi_valuetype valueType;
napi_valuetype valueType = napi_undefined;
napi_typeof(env, argv[i], &valueType);
if (i == 0 && valueType == napi_string) {
char timeZoneChars[MAX_TIME_ZONE_ID];
size_t timeZoneCharsSize;
if (napi_ok != napi_get_value_string_utf8(env, argv[i], timeZoneChars, MAX_TIME_ZONE_ID-1, &timeZoneCharsSize)){
delete asyncContext;
NAPI_ASSERT(env, false, "input para invalid");
if (napi_ok != napi_get_value_string_utf8(env,
argv[i],
timeZoneChars,
MAX_TIME_ZONE_ID-1,
&timeZoneCharsSize)) {
delete asyncContext;
NAPI_ASSERT(env, false, "input para invalid");
}
std::string timeZoneStr(timeZoneChars, timeZoneCharsSize);
asyncContext->timeZone = timeZoneStr;
@@ -156,7 +156,6 @@ static napi_value JSSystemTimeSetTimeZone(napi_env env, napi_callback_info info)
}
napi_value resource = nullptr;
napi_create_string_utf8(env, "JSSystemTimeSetTimeZone", NAPI_AUTO_LENGTH, &resource);
napi_create_async_work(env, nullptr, resource,
[](napi_env env, void* data) {
AsyncContext* asyncContext = (AsyncContext*)data;
@@ -43,8 +43,8 @@ ohos_shared_library("systemtimer") {
configs = [ ":native_module_config" ]
sources = [
"src/init.cpp",
"src/system_timer.cpp",
"src/timer_init.cpp",
"src/timer_type.cpp",
]
@@ -24,6 +24,11 @@ namespace OHOS {
namespace MiscServicesNapi {
using namespace OHOS::MiscServices;
constexpr int NONE_PARAMETER = 0;
constexpr int ONE_PARAMETER = 1;
constexpr int TWO_PARAMETERS = 2;
constexpr int THREE_PARAMETERS = 3;
class ITimerInfoInstance : public ITimerInfo {
public:
ITimerInfoInstance();
@@ -49,8 +54,6 @@ napi_value CreateTimer(napi_env env, napi_callback_info info);
napi_value StartTimer(napi_env env, napi_callback_info info);
napi_value StopTimer(napi_env env, napi_callback_info info);
napi_value DestroyTimer(napi_env env, napi_callback_info info);
} // namespace MiscServicesNapi
} // namespace OHOS
#endif // SYSTEM_TIMER_H
@@ -0,0 +1,29 @@
/*
* Copyright (c); 2021 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 TIMER_INIT_H
#define TIMER_INIT_H
#include "system_timer.h"
#include "napi/native_api.h"
#include "napi/native_node_api.h"
namespace OHOS {
namespace MiscServicesNapi {
} // OHOS
} // MiscServicesNapi
#endif // TIMER_INIT_H
@@ -21,6 +21,11 @@
namespace OHOS {
namespace MiscServicesNapi {
constexpr int TIMER_TYPE_REALTIME = 0;
constexpr int TIMER_TYPE_WAKEUP = 1;
constexpr int TIMER_TYPE_EXACT = 2;
constexpr int TIMER_TYPE_IDLE = 3;
napi_value TimerTypeInit(napi_env env, napi_value exports);
} // namespace MiscServicesNapi
} // namespace OHOS
@@ -24,7 +24,6 @@
namespace OHOS {
namespace MiscServicesNapi {
const int NO_ERROR = 0;
const int ERROR = -1;
const int CREATE_MAX_PARA = 2;
@@ -96,7 +95,7 @@ static std::vector<AsyncCallbackInfoCreate *> asyncCallbackInfoCreateInfo;
napi_value NapiGetNull(napi_env env)
{
napi_value result = 0;
napi_value result = nullptr;
napi_get_null(env, &result);
return result;
}
@@ -118,11 +117,11 @@ void SetPromise(const napi_env &env, const napi_deferred &deferred, const napi_v
void SetCallback(const napi_env &env, const napi_ref &callbackIn, const int &errorCode, const napi_value &result)
{
napi_value undefined;
napi_value undefined = nullptr;
napi_get_undefined(env, &undefined);
napi_value callback;
napi_value resultout;
napi_value callback = nullptr;
napi_value resultout = nullptr;
napi_get_reference_value(env, callbackIn, &callback);
napi_value results[ARGS_TWO] = {0};
results[PARAM0] = GetCallbackErrorValue(env, errorCode);
@@ -135,7 +134,7 @@ napi_value JSParaError(const napi_env &env, const napi_ref &callback)
if (callback) {
return NapiGetNull(env);
} else {
napi_value promise = 0;
napi_value promise = nullptr;
napi_deferred deferred = nullptr;
napi_create_promise(env, &deferred, &promise);
SetPromise(env, deferred, NapiGetNull(env));
@@ -153,6 +152,7 @@ void ReturnCallbackPromise(const napi_env &env, const CallbackPromiseInfo &info,
}
ITimerInfoInstance::ITimerInfoInstance()
: callbackInfo_ {}
{}
ITimerInfoInstance::~ITimerInfoInstance()
@@ -178,10 +178,15 @@ void ITimerInfoInstance::OnTrigger()
uv_work_t *work = new (std::nothrow) uv_work_t;
if (!work) {
delete dataWorker;
return;
}
if (!loop) {
delete dataWorker;
delete work;
return;
}
work->data = (void *)dataWorker;
uv_queue_work(loop,
work,
[](uv_work_t *work) {},
@@ -191,8 +196,10 @@ void ITimerInfoInstance::OnTrigger()
return;
}
SetCallback(dataWorkerData->env, dataWorkerData->ref, NO_ERROR, NapiGetNull(dataWorkerData->env));
SetCallback(dataWorkerData->env,
dataWorkerData->ref,
NO_ERROR,
NapiGetNull(dataWorkerData->env));
delete dataWorkerData;
dataWorkerData = nullptr;
delete work;
@@ -227,8 +234,8 @@ void ITimerInfoInstance::SetWantAgent(std::shared_ptr<OHOS::Notification::WantAg
napi_value GetTimerOptions(const napi_env &env, const napi_value &value,
std::shared_ptr<ITimerInfoInstance> &iTimerInfoInstance)
{
napi_valuetype valuetype;
napi_value result;
napi_valuetype valuetype = napi_undefined;
napi_value result = nullptr;
OHOS::Notification::WantAgent::WantAgent *wantAgent = nullptr;
bool hasProperty = false;
@@ -274,7 +281,8 @@ napi_value GetTimerOptions(const napi_env &env, const napi_value &value,
if (wantAgent == nullptr) {
return nullptr;
}
std::shared_ptr<OHOS::Notification::WantAgent::WantAgent> sWantAgent = std::make_shared<OHOS::Notification::WantAgent::WantAgent>(*wantAgent);
std::shared_ptr<OHOS::Notification::WantAgent::WantAgent> sWantAgent =
std::make_shared<OHOS::Notification::WantAgent::WantAgent>(*wantAgent);
iTimerInfoInstance->SetWantAgent(sWantAgent);
}
@@ -296,7 +304,7 @@ napi_value ParseParametersByCreateTimer(const napi_env &env, const napi_value (&
const size_t &argc, std::shared_ptr<ITimerInfoInstance> &iTimerInfoInstance, napi_ref &callback)
{
NAPI_ASSERT(env, argc >= CREATE_MAX_PARA - 1, "Wrong number of arguments");
napi_valuetype valuetype;
napi_valuetype valuetype = napi_undefined;
// argv[0]: TimerOptions
NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype));
@@ -342,17 +350,19 @@ napi_value CreateTimer(napi_env env, napi_callback_info info)
if (ParseParametersByCreateTimer(env, argv, argc, iTimerInfoInstance, callback) == nullptr) {
return JSParaError(env, callback);
}
AsyncCallbackInfoCreate *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoCreate{.env = env,
AsyncCallbackInfoCreate *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoCreate {
.env = env,
.asyncWork = nullptr,
.iTimerInfoInstance = iTimerInfoInstance};
.iTimerInfoInstance = iTimerInfoInstance
};
if (!asynccallbackinfo) {
return JSParaError(env, callback);
}
napi_value promise = 0;
napi_value promise = nullptr;
PaddingAsyncCallbackInfoIsByCreateTimer(env, asynccallbackinfo, callback, promise);
napi_value resourceName;
napi_value resourceName = nullptr;
napi_create_string_latin1(env, "createTimer", NAPI_AUTO_LENGTH, &resourceName);
// Asynchronous function call
napi_create_async_work(env,
@@ -362,10 +372,9 @@ napi_value CreateTimer(napi_env env, napi_callback_info info)
AsyncCallbackInfoCreate *asynccallbackinfo = (AsyncCallbackInfoCreate *)data;
asynccallbackinfo->timerId =
TimeServiceClient::GetInstance()->CreateTimer(asynccallbackinfo->iTimerInfoInstance);
if (asynccallbackinfo->timerId > 0){
if (asynccallbackinfo->timerId > 0) {
asyncCallbackInfoCreateInfo.emplace_back(asynccallbackinfo);
}
},
[](napi_env env, napi_status status, void *data) {
AsyncCallbackInfoCreate *asynccallbackinfo = (AsyncCallbackInfoCreate *)data;
@@ -377,7 +386,7 @@ napi_value CreateTimer(napi_env env, napi_callback_info info)
info.errorCode = asynccallbackinfo->errorCode;
// timerId: number
napi_value result;
napi_value result = nullptr;
napi_create_int64(env, asynccallbackinfo->timerId, &result);
ReturnCallbackPromise(env, info, result);
napi_delete_async_work(env, asynccallbackinfo->asyncWork);
@@ -398,7 +407,7 @@ napi_value ParseParametersByStartTimer(const napi_env &env, const napi_value (&a
const size_t &argc, uint64_t &uintTimerId, uint64_t &uintTriggerTime, napi_ref &callback)
{
NAPI_ASSERT(env, argc >= START_MAX_PARA - 1, "Wrong number of arguments");
napi_valuetype valuetype;
napi_valuetype valuetype = napi_undefined;
// argv[0]: timer
NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype));
@@ -418,9 +427,9 @@ napi_value ParseParametersByStartTimer(const napi_env &env, const napi_value (&a
// argv[2]:callback
if (argc >= START_MAX_PARA) {
NAPI_CALL(env, napi_typeof(env, argv[2], &valuetype));
NAPI_CALL(env, napi_typeof(env, argv[TWO_PARAMETERS], &valuetype));
NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected.");
napi_create_reference(env, argv[2], 1, &callback);
napi_create_reference(env, argv[TWO_PARAMETERS], 1, &callback);
}
return NapiGetNull(env);
@@ -460,10 +469,10 @@ napi_value StartTimer(napi_env env, napi_callback_info info)
return JSParaError(env, callback);
}
napi_value promise = 0;
napi_value promise = nullptr;
PaddingAsyncCallbackInfoIsByStartTimer(env, asynccallbackinfo, callback, promise);
napi_value resourceName;
napi_value resourceName = nullptr;
napi_create_string_latin1(env, "startTimer", NAPI_AUTO_LENGTH, &resourceName);
// Asynchronous function call
napi_create_async_work(env,
@@ -488,7 +497,7 @@ napi_value StartTimer(napi_env env, napi_callback_info info)
info.errorCode = asynccallbackinfo->errorCode;
// result: bool
napi_value result;
napi_value result = nullptr;
napi_get_boolean(env, asynccallbackinfo->isOK, &result);
ReturnCallbackPromise(env, info, result);
@@ -514,7 +523,7 @@ napi_value ParseParametersByStopTimer(const napi_env &env, const napi_value (&ar
uint64_t &uintTimerId, napi_ref &callback)
{
NAPI_ASSERT(env, argc >= STOP_MAX_PARA - 1, "Wrong number of arguments");
napi_valuetype valuetype;
napi_valuetype valuetype = napi_undefined;
// argv[0]: timer
NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype));
@@ -567,10 +576,10 @@ napi_value StopTimer(napi_env env, napi_callback_info info)
return JSParaError(env, callback);
}
napi_value promise = 0;
napi_value promise = nullptr;
PaddingAsyncCallbackInfoIsByStopTimer(env, asynccallbackinfo, callback, promise);
napi_value resourceName;
napi_value resourceName = nullptr;
napi_create_string_latin1(env, "stopTimer", NAPI_AUTO_LENGTH, &resourceName);
// Asynchronous function call
napi_create_async_work(env,
@@ -593,7 +602,7 @@ napi_value StopTimer(napi_env env, napi_callback_info info)
info.errorCode = asynccallbackinfo->errorCode;
// result: bool
napi_value result;
napi_value result = nullptr;
napi_get_boolean(env, asynccallbackinfo->isOK, &result);
ReturnCallbackPromise(env, info, result);
@@ -619,7 +628,7 @@ napi_value ParseParametersByDestroyTimer(const napi_env &env, const napi_value (
const size_t &argc, uint64_t &uintTimerId, napi_ref &callback)
{
NAPI_ASSERT(env, argc >= DESTROY_MAX_PARA - 1, "Wrong number of arguments");
napi_valuetype valuetype;
napi_valuetype valuetype = napi_undefined;
// argv[0]: timer
NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype));
@@ -672,10 +681,10 @@ napi_value DestroyTimer(napi_env env, napi_callback_info info)
return JSParaError(env, callback);
}
napi_value promise = 0;
napi_value promise = nullptr;
PaddingAsyncCallbackInfoIsByDestroyTimer(env, asynccallbackinfo, callback, promise);
napi_value resourceName;
napi_value resourceName = nullptr;
napi_create_string_latin1(env, "destroyTimer", NAPI_AUTO_LENGTH, &resourceName);
// Asynchronous function call
napi_create_async_work(env,
@@ -706,7 +715,7 @@ napi_value DestroyTimer(napi_env env, napi_callback_info info)
info.errorCode = asynccallbackinfo->errorCode;
// result: bool
napi_value result;
napi_value result = nullptr;
napi_get_boolean(env, asynccallbackinfo->isOK, &result);
ReturnCallbackPromise(env, info, result);
@@ -742,6 +751,5 @@ napi_value SystemtimerInit(napi_env env, napi_value exports)
OHOS::MiscServicesNapi::TimerTypeInit(env, exports);
return exports;
}
} // namespace MiscServicesNapi
} // namespace OHOS
@@ -13,14 +13,11 @@
* limitations under the License.
*/
#include "system_timer.h"
#include "napi/native_api.h"
#include "napi/native_node_api.h"
#include "timer_init.h"
namespace OHOS {
namespace MiscServicesNapi {
EXTERN_C_START
/*
* Module export function
*/
@@ -30,7 +27,6 @@ static napi_value Init(napi_env env, napi_value exports)
* Propertise define
*/
SystemtimerInit(env, exports);
return exports;
}
EXTERN_C_END
@@ -30,16 +30,15 @@ napi_value TimerTypeInit(napi_env env, napi_value exports)
napi_value obj = nullptr;
napi_create_object(env, &obj);
SetNamedPropertyByInteger(env, obj, 1 << 0, "TIMER_TYPE_REALTIME");
SetNamedPropertyByInteger(env, obj, 1 << 1, "TIMER_TYPE_WAKEUP");
SetNamedPropertyByInteger(env, obj, 1 << 2, "TIMER_TYPE_EXACT");
SetNamedPropertyByInteger(env, obj, 1 << 3, "TIMER_TYPE_IDLE");
SetNamedPropertyByInteger(env, obj, 1 << TIMER_TYPE_REALTIME, "TIMER_TYPE_REALTIME");
SetNamedPropertyByInteger(env, obj, 1 << TIMER_TYPE_WAKEUP, "TIMER_TYPE_WAKEUP");
SetNamedPropertyByInteger(env, obj, 1 << TIMER_TYPE_EXACT, "TIMER_TYPE_EXACT");
SetNamedPropertyByInteger(env, obj, 1 << TIMER_TYPE_IDLE, "TIMER_TYPE_IDLE");
napi_property_descriptor exportFuncs[] = {DECLARE_NAPI_PROPERTY("systemTimer", obj)};
napi_define_properties(env, exports, sizeof(exportFuncs) / sizeof(*exportFuncs), exportFuncs);
return exports;
}
} // namespace MiscServicesNapi
} // namespace OHOS
+10 -3
View File
@@ -46,11 +46,10 @@ ohos_shared_library("time_service") {
"timer/src/timer_info.cpp",
"timer/src/timer_manager.cpp",
]
configs = [ "${time_utils_path}:utils_config" ]
public_configs = [
"//utils/native/base:utils_config",
"//third_party/jsoncpp:jsoncpp_public_config",
":time_service_config",
]
deps = [
@@ -60,6 +59,7 @@ ohos_shared_library("time_service") {
"//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_appdatafwk:native_appdatafwk",
"//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_preferences:native_preferences",
"//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_rdb:native_rdb",
"//third_party/jsoncpp:jsoncpp",
"//utils/native/base:utils",
]
external_deps = [
@@ -74,6 +74,13 @@ ohos_shared_library("time_service") {
"safwk:system_ability_fwk",
"samgr_L2:samgr_proxy",
]
subsystem_name = "miscservices"
part_name = "time_native"
subsystem_name = "miscservices"
}
ohos_prebuilt_etc("timezone_json") {
source = "time_manager/src/timezone.json"
module_install_dir = "/data/misc/zoneinfo/"
part_name = "time_native"
subsystem_name = "miscservices"
}
@@ -20,7 +20,6 @@
namespace OHOS {
namespace MiscServices {
class ITimerCallback : public IRemoteBroker {
public:
DECLARE_INTERFACE_DESCRIPTOR(u"ohos.miscservices.time.ITimerCallback");
@@ -36,9 +35,7 @@ public:
enum Message {
NOTIFY_TIMER = 1
};
};
} // namespace MiscServices
} // namespace OHOS
+8 -10
View File
@@ -18,7 +18,6 @@
#include "time_service_stub.h"
#include "time_service_notify.h"
#include "time_rdb_handler.h"
#include "timer_manager.h"
#include "time_permission.h"
#include "system_ability.h"
@@ -28,6 +27,7 @@
#include <mutex>
#include <inttypes.h>
namespace OHOS {
namespace MiscServices {
enum class ServiceRunningState {
@@ -35,19 +35,10 @@ enum class ServiceRunningState {
STATE_RUNNING
};
const int TIMER_TYPE_REALTIME_MASK = 1 << 0;
const int TIMER_TYPE_REALTIME_WAKEUP_MASK = 1 << 1;
const int TIMER_TYPE_EXACT_MASK = 1 << 2;
const int TIMER_TYPE_IDLE_MASK = 1 << 3;
class TimeService : public SystemAbility, public TimeServiceStub {
DECLARE_SYSTEM_ABILITY(TimeService);
public:
DISALLOW_COPY_AND_MOVE(TimeService);
TimeService(int32_t systemAbilityId, bool runOnCreate);
TimeService();
~TimeService();
@@ -74,11 +65,18 @@ protected:
void OnStop() override;
private:
struct TimerPara {
int timerType;
int64_t windowLength;
uint64_t interval;
int flag;
};
int32_t Init();
void InitServiceHandler();
void InitNotifyHandler();
void InitTimeZone();
void InitTimerHandler();
void PaserTimerPara(int32_t type, bool repeat, uint64_t interval, TimerPara &paras);
bool GetTimeByClockid(clockid_t clockID, struct timespec* tv);
int set_rtc_time(time_t sec);
@@ -21,10 +21,8 @@
namespace OHOS {
namespace MiscServices {
class ITimeService : public IRemoteBroker {
public:
// remote method code
enum {
SET_TIME = 0,
@@ -168,7 +166,6 @@ public:
DECLARE_INTERFACE_DESCRIPTOR(u"ohos.miscservices.time.ITimeService");
};
} // namespace MiscServices
} // namespace OHOS
#endif // SERVICES_INCLUDE_TIME_SERVICE_INTERFACE_H
@@ -23,9 +23,7 @@
namespace OHOS {
namespace MiscServices {
class TimeServiceNotify {
public:
TimeServiceNotify() = default;
~TimeServiceNotify() = default;
@@ -42,7 +40,6 @@ private:
sptr<IntentWant> timeZoneChangeWant_;
sptr<OHOS::EventFwk::CommonEventPublishInfo> publishInfo_;
};
} // namespace MiscServices
} // namespace OHOS
+20 -19
View File
@@ -15,37 +15,38 @@
#ifndef SERVICES_INCLUDE_TIME_ZONE_INFO_H
#define SERVICES_INCLUDE_TIME_ZONE_INFO_H
#include <singleton.h>
#include <map>
#include <mutex>
#include "refbase.h"
#include "time.h"
#include <sys/time.h>
#include "time_common.h"
#include <vector>
#include "json/json.h"
#include <fstream>
namespace OHOS{
namespace MiscServices{
using namespace std;
struct zoneInfoEntry
{
namespace OHOS {
namespace MiscServices {
struct zoneInfoEntry {
std::string ID;
std::string alias;
int utcOffsetHours;
std::string description;
float utcOffsetHours;
};
class TimeZoneInfo : public RefBase{
TimeZoneInfo();
~TimeZoneInfo();
class TimeZoneInfo {
DECLARE_DELAYED_SINGLETON(TimeZoneInfo)
public:
static sptr<TimeZoneInfo> GetInstance();
bool GetTimezone(std::string &timezoneId);
bool SetTimezone(std::string timezoneId);
void Init();
int32_t GetOffset(const std::string timezoneId, int &offset);
int32_t GetTimezoneId(std::string &timezoneId);
private:
const std::string TIMEZONE_FILE_PATH = "/data/misc/zoneinfo/timezone.json";
bool SetOffsetToKernel(float offset);
bool GetOffsetById(const std::string timezoneId, float &offset);
bool GetTimezoneFromFile(std::string &timezoneId);
bool SaveTimezoneToFile(std::string timezoneId);
std::string curTimezoneId_;
int32_t lastOffset_;
static std::mutex instanceLock_;
static sptr<TimeZoneInfo> instance_;
std::map<std::string, struct zoneInfoEntry> timezoneInfoMap_;
};
} // MiscServices
@@ -25,13 +25,10 @@
namespace OHOS {
namespace MiscServices {
class TimerCallback : public TimerCallbackStub {
public:
DISALLOW_COPY_AND_MOVE(TimerCallback);
static sptr<TimerCallback> GetInstance();
virtual void NotifyTimer(const uint64_t timerId) override;
/**
* Get timer callback info.
@@ -41,7 +38,6 @@ public:
* @return Get timer callback info success or not
*/
bool InsertTimerCallbackInfo(const uint64_t timerId, const std::shared_ptr<ITimerInfo> &timerInfo);
bool RemoveTimerCallbackInfo(const uint64_t timerId);
private:
@@ -50,11 +46,9 @@ private:
static std::mutex instanceLock_;
static sptr<TimerCallback> instance_;
static std::map<uint64_t, std::shared_ptr<ITimerInfo>> TimerInfoMap_;
static std::mutex timerInfoMutex_;
};
} // namespace MiscServices
} // namespace OHOS
@@ -30,12 +30,11 @@ public:
~TimerCallbackProxy();
DISALLOW_COPY_AND_MOVE(TimerCallbackProxy);
virtual void NotifyTimer(uint64_t timerId) override;
virtual void NotifyTimer(const uint64_t timerId) override;
private:
static inline BrokerDelegator<TimerCallbackProxy> delegator_;
};
} // namespace PowerMgr
} // namespace OHOS
@@ -23,7 +23,6 @@
#include <inttypes.h>
namespace OHOS {
namespace MiscServices {
class TimerCallbackStub : public IRemoteStub<ITimerCallback> {
public:
DISALLOW_COPY_AND_MOVE(TimerCallbackStub);
+2 -4
View File
@@ -17,16 +17,14 @@
namespace OHOS {
namespace MiscServices {
ITimerInfo::ITimerInfo()
: type {0}, repeat {false}, interval {0}
{
}
ITimerInfo::~ITimerInfo()
{
}
} // MiscServices
} // OHOS
+156 -190
View File
@@ -22,8 +22,8 @@
#include "system_ability_definition.h"
#include "iservice_registry.h"
#include <time.h>
#include <stdio.h>
#include <ctime>
#include <cstdio>
#include <string>
#include <unistd.h>
#include <sys/time.h>
@@ -33,7 +33,7 @@
#include <sys/ioctl.h>
#include <linux/rtc.h>
#include <dirent.h>
#include <string.h>
#include <cstring>
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/types.h>
@@ -43,21 +43,23 @@
namespace OHOS {
namespace MiscServices {
namespace{
// Unit of measure conversion , BASE: second
static const int MILLI_TO_BASE = 1000LL;
static const int MICR_TO_BASE = 1000000LL;
static const int NANO_TO_BASE = 1000000000LL;
//constexpr int MILLI_TO_NANO = NANO_TO_BASE / MILLI_TO_BASE;
constexpr int MILLI_TO_MICR = MICR_TO_BASE / MILLI_TO_BASE;
//constexpr int MICR_TO_MILLI = MILLI_TO_BASE / MICR_TO_BASE;
constexpr int NANO_TO_MILLI = NANO_TO_BASE / MILLI_TO_BASE;
static const int FIVE_THOUSANDS = 5000LL;
static const std::int32_t INIT_INTERVAL = 10000L;
static const uint32_t TIMER_TYPE_REALTIME_MASK = 1 << 0;
static const uint32_t TIMER_TYPE_REALTIME_WAKEUP_MASK = 1 << 1;
static const uint32_t TIMER_TYPE_EXACT_MASK = 1 << 2;
constexpr int MILLI_TO_MICR = MICR_TO_BASE / MILLI_TO_BASE;
constexpr int NANO_TO_MILLI = NANO_TO_BASE / MILLI_TO_BASE;
}
REGISTER_SYSTEM_ABILITY_BY_ID(TimeService, TIME_SERVICE_ID, true);
const std::int32_t INIT_INTERVAL = 10000L;
std::mutex TimeService::instanceLock_;
sptr<TimeService> TimeService::instance_;
std::shared_ptr<AppExecFwk::EventHandler> TimeService::serviceHandler_ = nullptr;
@@ -65,19 +67,19 @@ std::shared_ptr<MiscServices::TimeServiceNotify> TimeService::timeServiceNotify_
std::shared_ptr<TimerManager> TimeService::timerManagerHandler_ = nullptr;
TimeService::TimeService(int32_t systemAbilityId, bool runOnCreate)
: SystemAbility(systemAbilityId, runOnCreate), state_(ServiceRunningState::STATE_NOT_START), rtc_id(get_wall_clock_rtc_id())
: SystemAbility(systemAbilityId, runOnCreate),
state_(ServiceRunningState::STATE_NOT_START),
rtc_id(get_wall_clock_rtc_id())
{
TIME_HILOGI(TIME_MODULE_SERVICE," TimeService Start.");
TIME_HILOGI(TIME_MODULE_SERVICE, " TimeService Start.");
}
TimeService::TimeService() : state_(ServiceRunningState::STATE_NOT_START), rtc_id(get_wall_clock_rtc_id())
TimeService::TimeService()
: state_(ServiceRunningState::STATE_NOT_START), rtc_id(get_wall_clock_rtc_id())
{
//TODO : Read time zone information from the global and set to kernel;
}
TimeService::~TimeService()
{
}
TimeService::~TimeService() {};
sptr<TimeService> TimeService::GetInstance()
{
@@ -92,23 +94,25 @@ sptr<TimeService> TimeService::GetInstance()
void TimeService::OnStart()
{
TIME_HILOGI(TIME_MODULE_SERVICE," TimeService OnStart.");
TIME_HILOGI(TIME_MODULE_SERVICE, " TimeService OnStart.");
if (state_ == ServiceRunningState::STATE_RUNNING) {
TIME_HILOGE(TIME_MODULE_SERVICE," TimeService is already running.");
TIME_HILOGE(TIME_MODULE_SERVICE, " TimeService is already running.");
return;
}
InitServiceHandler();
InitTimerHandler();
InitNotifyHandler();
// init timezone
DelayedSingleton<TimeZoneInfo>::GetInstance()->Init();
if (Init() != ERR_OK) {
auto callback = [=]() { Init(); };
serviceHandler_->PostTask(callback, INIT_INTERVAL);
TIME_HILOGE(TIME_MODULE_SERVICE,"Init failed. Try again 10s later.");
TIME_HILOGE(TIME_MODULE_SERVICE, "Init failed. Try again 10s later.");
return;
}
TIME_HILOGI(TIME_MODULE_SERVICE,"Start TimeService success.");
TIME_HILOGI(TIME_MODULE_SERVICE, "Start TimeService success.");
return;
}
@@ -116,56 +120,31 @@ int32_t TimeService::Init()
{
bool ret = Publish(TimeService::GetInstance());
if (!ret) {
TIME_HILOGE(TIME_MODULE_SERVICE,"Init Failed.");
TIME_HILOGE(TIME_MODULE_SERVICE, "Init Failed.");
return E_TIME_PUBLISH_FAIL;
}
TIME_HILOGI(TIME_MODULE_SERVICE,"Init Success.");
TIME_HILOGI(TIME_MODULE_SERVICE, "Init Success.");
state_ = ServiceRunningState::STATE_RUNNING;
return ERR_OK;
}
void TimeService::OnStop()
{
TIME_HILOGI(TIME_MODULE_SERVICE,"OnStop Started.");
TIME_HILOGI(TIME_MODULE_SERVICE, "OnStop Started.");
if (state_ != ServiceRunningState::STATE_RUNNING) {
return;
}
serviceHandler_ = nullptr;
timeServiceNotify_ = nullptr;
state_ = ServiceRunningState::STATE_NOT_START;
TIME_HILOGI(TIME_MODULE_SERVICE,"OnStop End.");
TIME_HILOGI(TIME_MODULE_SERVICE, "OnStop End.");
}
void TimeService::InitTimeZone(){
TIME_HILOGD(TIME_MODULE_SERVICE,"start");
std::string timeZoneId;
auto hasTimeZone = GetTimeZoneId(timeZoneId);
if (!hasTimeZone){
TIME_HILOGE(TIME_MODULE_SERVICE,"Time Zone Not Found.");
return;
}
int gmtOffset;
struct timezone tz;
TIME_HILOGD(TIME_MODULE_SERVICE,"timezone id: %{public}s.", timeZoneId.c_str());
auto ret = TimeZoneInfo::GetInstance()->GetOffset(timeZoneId, gmtOffset);
TIME_HILOGE(TIME_MODULE_SERVICE,"get timezone offset: %{public}d.", gmtOffset);
if (ret != ERR_OK){
TIME_HILOGE(TIME_MODULE_SERVICE,"get timezone info fail: %{public}d.", ret);
}
tz.tz_minuteswest = gmtOffset * 60;
tz.tz_dsttime = 0;
int result = settimeofday(NULL, &tz);
if (result < 0) {
TIME_HILOGE(TIME_MODULE_SERVICE,"settimeofday fail: %{public}d.",result);
}
}
void TimeService::InitNotifyHandler(){
TIME_HILOGI(TIME_MODULE_SERVICE,"InitNotify started.");
void TimeService::InitNotifyHandler()
{
TIME_HILOGI(TIME_MODULE_SERVICE, "InitNotify started.");
if (timeServiceNotify_ != nullptr) {
TIME_HILOGE(TIME_MODULE_SERVICE," Already init.");
TIME_HILOGE(TIME_MODULE_SERVICE, " Already init.");
return;
}
timeServiceNotify_ = std::make_shared<MiscServices::TimeServiceNotify>();
@@ -174,136 +153,140 @@ void TimeService::InitNotifyHandler(){
void TimeService::InitServiceHandler()
{
TIME_HILOGI(TIME_MODULE_SERVICE,"InitServiceHandler started.");
TIME_HILOGI(TIME_MODULE_SERVICE, "InitServiceHandler started.");
if (serviceHandler_ != nullptr) {
TIME_HILOGE(TIME_MODULE_SERVICE," Already init.");
TIME_HILOGE(TIME_MODULE_SERVICE, " Already init.");
return;
}
std::shared_ptr<AppExecFwk::EventRunner> runner = AppExecFwk::EventRunner::Create(TIME_SERVICE_NAME);
serviceHandler_ = std::make_shared<AppExecFwk::EventHandler>(runner);
TIME_HILOGI(TIME_MODULE_SERVICE,"InitServiceHandler Succeeded.");
TIME_HILOGI(TIME_MODULE_SERVICE, "InitServiceHandler Succeeded.");
}
void TimeService::InitTimerHandler(){
TIME_HILOGI(TIME_MODULE_SERVICE,"Init Timer started.");
void TimeService::InitTimerHandler()
{
TIME_HILOGI(TIME_MODULE_SERVICE, "Init Timer started.");
if (timerManagerHandler_ != nullptr) {
TIME_HILOGE(TIME_MODULE_SERVICE," Already init.");
TIME_HILOGE(TIME_MODULE_SERVICE, " Already init.");
return;
}
timerManagerHandler_ = TimerManager::Create();
}
void TimeService::PaserTimerPara(int32_t type, bool repeat, uint64_t interval, TimerPara &paras)
{
bool isRealtime = false;
bool isWakeup = false;
paras.flag = 0;
if ((type & TIMER_TYPE_REALTIME_MASK) > 0 ) {
isRealtime = true;
}
if ((type & TIMER_TYPE_REALTIME_WAKEUP_MASK) > 0 ) {
isWakeup = true;
}
if ((type & TIMER_TYPE_EXACT_MASK) > 0) {
paras.windowLength = 0;
}else{
paras.windowLength = -1;
}
if (isRealtime && isWakeup) {
paras.timerType = ITimerManager::TimerType::ELAPSED_REALTIME_WAKEUP;
}else if (isRealtime) {
paras.timerType = ITimerManager::TimerType::ELAPSED_REALTIME;
}else if (isWakeup) {
paras.timerType = ITimerManager::TimerType::RTC_WAKEUP;
}else{
paras.timerType = ITimerManager::TimerType::RTC;
}
if (repeat) {
paras.interval = (interval < FIVE_THOUSANDS) ? FIVE_THOUSANDS : interval;
}else{
paras.interval = 0;
}
return;
}
uint64_t TimeService::CreateTimer(int32_t type, bool repeat, uint64_t interval,
sptr<IRemoteObject> &obj)
{
if (obj == nullptr){
TIME_HILOGE(TIME_MODULE_SERVICE,"Input nullptr.");
if (obj == nullptr) {
TIME_HILOGE(TIME_MODULE_SERVICE, "Input nullptr.");
return 0;
}
auto isRealtime = false;
auto isWakeup = false;
int timerType;
int64_t windowLength;
uint64_t intervalOut;
int flag = 0;
if ((type & TIMER_TYPE_REALTIME_MASK) > 0 ){
isRealtime = true;
}
if ((type & TIMER_TYPE_REALTIME_WAKEUP_MASK) > 0 ){
isWakeup = true;
}
if ((type & TIMER_TYPE_EXACT_MASK) > 0){
windowLength = 0;
}else{
windowLength = -1;
}
if (isRealtime && isWakeup){
timerType = 2; // ELAPSED_REALTIME_WAKEUP = 2
}else if (isRealtime){
timerType = 3; // ELAPSED_REALTIME = 3
}else if (isWakeup){
timerType = 0; // RTC_WAKEUP = 0
}else{
timerType = 1; // RTC = 1
}
if (repeat){
intervalOut = (interval < 5000) ? 5000 : interval;
}else{
intervalOut = 0;
}
struct TimerPara paras {};
PaserTimerPara(type, repeat, interval, paras);
sptr<ITimerCallback> timerCallback = iface_cast<ITimerCallback>(obj);
if (timerCallback == nullptr){
TIME_HILOGE(TIME_MODULE_SERVICE,"ITimerCallback nullptr.");
if (timerCallback == nullptr) {
TIME_HILOGE(TIME_MODULE_SERVICE, "ITimerCallback nullptr.");
return 0;
}
TIME_HILOGI(TIME_MODULE_SERVICE,"Start create timer.");
auto callbackFunc = [timerCallback](uint64_t id){
TIME_HILOGI(TIME_MODULE_SERVICE, "Start create timer.");
auto callbackFunc = [timerCallback](uint64_t id) {
timerCallback->NotifyTimer(id);
};
if (timerManagerHandler_ == nullptr){
TIME_HILOGE(TIME_MODULE_SERVICE,"Timer manager nullptr.");
if (timerManagerHandler_ == nullptr) {
TIME_HILOGE(TIME_MODULE_SERVICE, "Timer manager nullptr.");
timerManagerHandler_ = TimerManager::Create();
if (timerManagerHandler_ == nullptr){
TIME_HILOGE(TIME_MODULE_SERVICE,"Redo Timer manager Init Failed.");
if (timerManagerHandler_ == nullptr) {
TIME_HILOGE(TIME_MODULE_SERVICE, "Redo Timer manager Init Failed.");
return 0;
}
}
return timerManagerHandler_->CreateTimer(timerType, windowLength, intervalOut, flag, callbackFunc, 0);
return timerManagerHandler_->CreateTimer(paras.timerType,
paras.windowLength, paras.interval, paras.flag, callbackFunc, 0);
}
bool TimeService::StartTimer(uint64_t timerId, uint64_t triggerTimes)
{
uint64_t triggerTimesIn;
uint64_t triggerTimesIn = 5000;
triggerTimesIn = (triggerTimes < 5000) ? 5000 : triggerTimes;
if (timerManagerHandler_ == nullptr){
TIME_HILOGE(TIME_MODULE_SERVICE,"Timer manager nullptr.");
if (timerManagerHandler_ == nullptr) {
TIME_HILOGE(TIME_MODULE_SERVICE, "Timer manager nullptr.");
timerManagerHandler_ = TimerManager::Create();
if (timerManagerHandler_ == nullptr){
TIME_HILOGE(TIME_MODULE_SERVICE,"Redo Timer manager Init Failed.");
if (timerManagerHandler_ == nullptr) {
TIME_HILOGE(TIME_MODULE_SERVICE, "Redo Timer manager Init Failed.");
return 0;
}
}
auto ret = timerManagerHandler_->StartTimer(timerId, triggerTimesIn);
if (!ret){
TIME_HILOGE(TIME_MODULE_SERVICE,"TimerId Not found.");
if (!ret) {
TIME_HILOGE(TIME_MODULE_SERVICE, "TimerId Not found.");
}
return ret;
}
bool TimeService::StopTimer(uint64_t timerId)
{
if (timerManagerHandler_ == nullptr){
TIME_HILOGE(TIME_MODULE_SERVICE,"Timer manager nullptr.");
if (timerManagerHandler_ == nullptr) {
TIME_HILOGE(TIME_MODULE_SERVICE, "Timer manager nullptr.");
timerManagerHandler_ = TimerManager::Create();
if (timerManagerHandler_ == nullptr){
TIME_HILOGE(TIME_MODULE_SERVICE,"Redo Timer manager Init Failed.");
if (timerManagerHandler_ == nullptr) {
TIME_HILOGE(TIME_MODULE_SERVICE, "Redo Timer manager Init Failed.");
return 0;
}
}
auto ret = timerManagerHandler_->StopTimer(timerId);
if (!ret){
TIME_HILOGE(TIME_MODULE_SERVICE,"TimerId Not found.");
if (!ret) {
TIME_HILOGE(TIME_MODULE_SERVICE, "TimerId Not found.");
}
return ret;
}
bool TimeService::DestroyTimer(uint64_t timerId)
{
if (timerManagerHandler_ == nullptr){
TIME_HILOGE(TIME_MODULE_SERVICE,"Timer manager nullptr.");
if (timerManagerHandler_ == nullptr) {
TIME_HILOGE(TIME_MODULE_SERVICE, "Timer manager nullptr.");
timerManagerHandler_ = TimerManager::Create();
if (timerManagerHandler_ == nullptr){
TIME_HILOGE(TIME_MODULE_SERVICE,"Redo Timer manager Init Failed.");
if (timerManagerHandler_ == nullptr) {
TIME_HILOGE(TIME_MODULE_SERVICE, "Redo Timer manager Init Failed.");
return 0;
}
}
auto ret = timerManagerHandler_->DestroyTimer(timerId);
if (!ret){
TIME_HILOGE(TIME_MODULE_SERVICE,"TimerId Not found.");
if (!ret) {
TIME_HILOGE(TIME_MODULE_SERVICE, "TimerId Not found.");
}
return ret;
}
@@ -311,13 +294,13 @@ bool TimeService::DestroyTimer(uint64_t timerId)
int32_t TimeService::SetTime(const int64_t time)
{
pid_t uid = IPCSkeleton::GetCallingUid();
auto hasPerm = TimePermission::GetInstance()->CheckCallingPermission(uid, setTimePermName_);
if (!hasPerm){
auto hasPerm = DelayedSingleton<TimePermission>::GetInstance()->CheckCallingPermission(uid, setTimePermName_);
if (!hasPerm) {
TIME_HILOGE(TIME_MODULE_SERVICE, "Permission check failed, uid : %{public}d", uid);
return E_TIME_NO_PERMISSION;
}
TIME_HILOGI(TIME_MODULE_SERVICE,"Setting time of day to milliseconds: %{public}" PRId64 "", time);
if (time < 0) {
TIME_HILOGI(TIME_MODULE_SERVICE, "Setting time of day to milliseconds: %{public}" PRId64 "", time);
if (time < 0 || time / 1000LL >= LONG_MAX) {
TIME_HILOGE(TIME_MODULE_SERVICE, "input param error");
return E_TIME_PARAMETERS_INVALID;
}
@@ -327,42 +310,41 @@ int32_t TimeService::SetTime(const int64_t time)
int result = settimeofday(&tv, NULL);
if (result < 0) {
TIME_HILOGE(TIME_MODULE_SERVICE,"settimeofday fail: %{public}d.",result);
TIME_HILOGE(TIME_MODULE_SERVICE, "settimeofday fail: %{public}d.",result);
return E_TIME_DEAL_FAILED;
}
auto ret = set_rtc_time(tv.tv_sec);
if (ret < 0){
TIME_HILOGE(TIME_MODULE_SERVICE,"set rtc fail: %{public}d.", ret);
if (ret < 0) {
TIME_HILOGE(TIME_MODULE_SERVICE, "set rtc fail: %{public}d.", ret);
return E_TIME_SET_RTC_FAILED;
}
int64_t currentTime = 0;
GetWallTimeMs(currentTime);
if (timeServiceNotify_ != nullptr){
if (timeServiceNotify_ != nullptr) {
timeServiceNotify_->PublishTimeChanageEvents(currentTime);
}
return ERR_OK;
}
int TimeService::set_rtc_time(time_t sec){
struct rtc_time rtc{};
struct tm tm{};
int TimeService::set_rtc_time(time_t sec) {
struct rtc_time rtc {};
struct tm tm {};
struct tm *gmtime_res = nullptr;
int fd = 0;
int res;
if (rtc_id < 0) {
TIME_HILOGE(TIME_MODULE_SERVICE,"invalid rtc id: %{public}s:", strerror(ENODEV));
TIME_HILOGE(TIME_MODULE_SERVICE, "invalid rtc id: %{public}s:", strerror(ENODEV));
return -1;
}
std::stringstream strs;
strs << "/dev/rtc" << rtc_id;
auto rtc_dev = strs.str();
TIME_HILOGI(TIME_MODULE_SERVICE,"rtc_dev : %{public}s:", rtc_dev.data());
TIME_HILOGI(TIME_MODULE_SERVICE, "rtc_dev : %{public}s:", rtc_dev.data());
fd = open(rtc_dev.data(), O_RDWR);
if (fd < 0) {
TIME_HILOGE(TIME_MODULE_SERVICE,"open failed %{public}s: %{public}s", rtc_dev.data(), strerror(errno));
TIME_HILOGE(TIME_MODULE_SERVICE, "open failed %{public}s: %{public}s", rtc_dev.data(), strerror(errno));
return -1;
}
@@ -378,11 +360,11 @@ int TimeService::set_rtc_time(time_t sec){
rtc.tm_yday = tm.tm_yday;
rtc.tm_isdst = tm.tm_isdst;
res = ioctl(fd, RTC_SET_TIME, &rtc);
if (res < 0){
TIME_HILOGE(TIME_MODULE_SERVICE,"ioctl RTC_SET_TIME failed: %{public}s", strerror(errno));
if (res < 0) {
TIME_HILOGE(TIME_MODULE_SERVICE, "ioctl RTC_SET_TIME failed: %{public}s", strerror(errno));
}
}else{
TIME_HILOGE(TIME_MODULE_SERVICE,"convert rtc time failed: %{public}s", strerror(errno));
TIME_HILOGE(TIME_MODULE_SERVICE, "convert rtc time failed: %{public}s", strerror(errno));
res = -1;
}
close(fd);
@@ -400,7 +382,7 @@ bool TimeService::check_rtc(std::string rtc_path, uint32_t rtc_id_t)
if (file.is_open()) {
file >> hctosys;
} else {
TIME_HILOGE(TIME_MODULE_SERVICE,"failed to open %{public}s", hctosys_path.data());
TIME_HILOGE(TIME_MODULE_SERVICE, "failed to open %{public}s", hctosys_path.data());
return false;
}
return true;
@@ -412,29 +394,30 @@ int TimeService::get_wall_clock_rtc_id()
std::unique_ptr<DIR, int(*)(DIR*)> dir(opendir(rtc_path.c_str()), closedir);
if (!dir.get()) {
TIME_HILOGE(TIME_MODULE_SERVICE,"failed to open %{public}s: %{public}s", rtc_path.c_str(), strerror(errno));
TIME_HILOGE(TIME_MODULE_SERVICE, "failed to open %{public}s: %{public}s", rtc_path.c_str(), strerror(errno));
return -1;
}
struct dirent *dirent;
while (errno = 0, dirent = readdir(dir.get())) {
while (errno = 0,
dirent = readdir(dir.get())) {
unsigned int rtc_id_t;
int matched = sscanf_s(dirent->d_name, "rtc%u", &rtc_id_t, sizeof(int));
if (matched < 0) {
break;
} else if (matched != 1) {
continue;
continue;
}
if (check_rtc(rtc_path, rtc_id_t)) {
TIME_HILOGD(TIME_MODULE_SERVICE,"found wall clock rtc %{public}u", rtc_id_t);
TIME_HILOGD(TIME_MODULE_SERVICE, "found wall clock rtc %{public}u", rtc_id_t);
return rtc_id_t;
}
}
if (errno == 0){
TIME_HILOGE(TIME_MODULE_SERVICE,"no wall clock rtc found");
if (errno == 0) {
TIME_HILOGE(TIME_MODULE_SERVICE, "no wall clock rtc found");
}else{
TIME_HILOGE(TIME_MODULE_SERVICE,"failed to check rtc: %{public}s", strerror(errno));
TIME_HILOGE(TIME_MODULE_SERVICE, "failed to check rtc: %{public}s", strerror(errno));
}
return -1;
}
@@ -442,55 +425,38 @@ int TimeService::get_wall_clock_rtc_id()
int32_t TimeService::SetTimeZone(const std::string timeZoneId)
{
pid_t uid = IPCSkeleton::GetCallingUid();
auto hasPerm = TimePermission::GetInstance()->CheckCallingPermission(uid, setTimezonePermName_);
if (!hasPerm){
auto hasPerm = DelayedSingleton<TimePermission>::GetInstance()->CheckCallingPermission(uid, setTimezonePermName_);
if (!hasPerm) {
TIME_HILOGE(TIME_MODULE_SERVICE, "Permission check failed, uid : %{public}d", uid);
return E_TIME_NO_PERMISSION;
}
int gmtOffset;
struct timezone tz;
TIME_HILOGE(TIME_MODULE_SERVICE,"timezone id: %{public}s.", timeZoneId.c_str());
auto ret = TimeZoneInfo::GetInstance()->GetOffset(timeZoneId, gmtOffset);
TIME_HILOGE(TIME_MODULE_SERVICE,"get timezone offset: %{public}d.", gmtOffset);
if (ret != ERR_OK){
TIME_HILOGE(TIME_MODULE_SERVICE,"get timezone info fail: %{public}d.", ret);
return ret;
}
tz.tz_minuteswest = gmtOffset * 60;
tz.tz_dsttime = 0;
int result = settimeofday(NULL, &tz);
if (result < 0) {
TIME_HILOGE(TIME_MODULE_SERVICE,"settimeofday fail: %{public}d.",result);
if (!DelayedSingleton<TimeZoneInfo>::GetInstance()->SetTimezone(timeZoneId)) {
TIME_HILOGE(TIME_MODULE_SERVICE, "Set timezone failed :%{public}s", timeZoneId.c_str());
return E_TIME_DEAL_FAILED;
}
int64_t currentTime = 0;
GetWallTimeMs(currentTime);
if (timeServiceNotify_ != nullptr){
if (timeServiceNotify_ != nullptr) {
timeServiceNotify_->PublishTimeZoneChangeEvents(currentTime);
}
return ERR_OK;
}
int32_t TimeService::GetTimeZone(std::string &timeZoneId)
{
std::string curTimezone;
auto ret = TimeZoneInfo::GetInstance()->GetTimezoneId(curTimezone);
TIME_HILOGI(TIME_MODULE_SERVICE,"get timezone : %{public}s.", curTimezone.c_str());
if (ret == ERR_OK){
timeZoneId = curTimezone;
return ERR_OK;
if (!DelayedSingleton<TimeZoneInfo>::GetInstance()->GetTimezone(timeZoneId)) {
TIME_HILOGE(TIME_MODULE_SERVICE, "get timezone failed.");
return E_TIME_DEAL_FAILED;
}
TIME_HILOGE(TIME_MODULE_SERVICE,"get timezone info fail: %{public}d.", ret);
return ret;
TIME_HILOGD(TIME_MODULE_SERVICE, "Current timezone : %{public}s", timeZoneId.c_str());
return ERR_OK;
}
int32_t TimeService::GetWallTimeMs(int64_t &times)
{
struct timespec tv{};
if(GetTimeByClockid(CLOCK_REALTIME, &tv)){
if (GetTimeByClockid(CLOCK_REALTIME, &tv)) {
times = tv.tv_sec * MILLI_TO_BASE + tv.tv_nsec / NANO_TO_MILLI;
return ERR_OK;
}
@@ -502,7 +468,7 @@ int32_t TimeService::GetWallTimeNs(int64_t &times)
{
struct timespec tv{};
if(GetTimeByClockid(CLOCK_REALTIME, &tv)){
if (GetTimeByClockid(CLOCK_REALTIME, &tv)) {
times = tv.tv_sec * NANO_TO_BASE + tv.tv_nsec;
return ERR_OK;
}
@@ -514,7 +480,7 @@ int32_t TimeService::GetBootTimeMs(int64_t &times)
{
struct timespec tv{};
if(GetTimeByClockid(CLOCK_BOOTTIME, &tv)){
if (GetTimeByClockid(CLOCK_BOOTTIME, &tv)) {
times = tv.tv_sec * MILLI_TO_BASE + tv.tv_nsec / NANO_TO_MILLI;
return ERR_OK;
}
@@ -526,7 +492,7 @@ int32_t TimeService::GetBootTimeNs(int64_t &times)
{
struct timespec tv{};
if(GetTimeByClockid(CLOCK_BOOTTIME, &tv)){
if (GetTimeByClockid(CLOCK_BOOTTIME, &tv)) {
times = tv.tv_sec * NANO_TO_BASE + tv.tv_nsec;
return ERR_OK;
}
@@ -538,7 +504,7 @@ int32_t TimeService::GetMonotonicTimeMs(int64_t &times)
{
struct timespec tv{};
if(GetTimeByClockid(CLOCK_MONOTONIC, &tv)){
if (GetTimeByClockid(CLOCK_MONOTONIC, &tv)) {
times = tv.tv_sec * MILLI_TO_BASE + tv.tv_nsec / NANO_TO_MILLI;
return ERR_OK;
}
@@ -550,7 +516,7 @@ int32_t TimeService::GetMonotonicTimeNs(int64_t &times)
{
struct timespec tv{};
if(GetTimeByClockid(CLOCK_MONOTONIC, &tv)){
if (GetTimeByClockid(CLOCK_MONOTONIC, &tv)) {
times = tv.tv_sec * NANO_TO_BASE + tv.tv_nsec;
return ERR_OK;
}
@@ -565,11 +531,11 @@ int32_t TimeService::GetThreadTimeMs(int64_t &times)
int ret;
clockid_t cid;
ret = pthread_getcpuclockid(pthread_self(), &cid);
if (ret != 0){
if (ret != 0) {
return E_TIME_PARAMETERS_INVALID;
}
if(GetTimeByClockid(cid, &tv)){
if (GetTimeByClockid(cid, &tv)) {
times = tv.tv_sec * MILLI_TO_BASE + tv.tv_nsec / NANO_TO_MILLI;
return ERR_OK;
}
@@ -583,11 +549,11 @@ int32_t TimeService::GetThreadTimeNs(int64_t &times)
int ret;
clockid_t cid;
ret = pthread_getcpuclockid(pthread_self(), &cid);
if (ret != 0){
if (ret != 0) {
return E_TIME_PARAMETERS_INVALID;
}
if(GetTimeByClockid(cid, &tv)){
if (GetTimeByClockid(cid, &tv)) {
times = tv.tv_sec * NANO_TO_BASE + tv.tv_nsec;
return ERR_OK;
}
@@ -596,10 +562,10 @@ int32_t TimeService::GetThreadTimeNs(int64_t &times)
}
bool TimeService::GetTimeByClockid(clockid_t clk_id, struct timespec* tv){
if (clock_gettime(clk_id, tv) < 0){
TIME_HILOGE(TIME_MODULE_SERVICE,"Failed clock_gettime.");
bool TimeService::GetTimeByClockid(clockid_t clk_id, struct timespec *tv)
{
if (clock_gettime(clk_id, tv) < 0) {
TIME_HILOGE(TIME_MODULE_SERVICE, "Failed clock_gettime.");
return false;
}
return true;
@@ -22,7 +22,6 @@
namespace OHOS {
namespace MiscServices {
std::mutex TimeServiceClient::instanceLock_;
sptr<TimeServiceClient> TimeServiceClient::instance_;
sptr<ITimeService> TimeServiceClient::timeServiceProxy_;
@@ -34,6 +33,12 @@ TimeServiceClient::TimeServiceClient()
TimeServiceClient::~TimeServiceClient()
{
if (timeServiceProxy_ != nullptr) {
auto remoteObject = timeServiceProxy_->AsObject();
if (remoteObject != nullptr) {
remoteObject->RemoveDeathRecipient(deathRecipient_);
}
}
}
sptr<TimeServiceClient> TimeServiceClient::GetInstance()
@@ -63,14 +68,14 @@ sptr<ITimeService> TimeServiceClient::ConnectService()
}
deathRecipient_ = new TimeSaDeathRecipient();
systemAbility->AddDeathRecipient(deathRecipient_);
sptr<ITimeService> timeServiceProxy = iface_cast<ITimeService>(systemAbility);
if (timeServiceProxy == nullptr) {
sptr<ITimeService> timeServiceProxy_ = iface_cast<ITimeService>(systemAbility);
if (timeServiceProxy_ == nullptr) {
TIME_HILOGE(TIME_MODULE_CLIENT, "Get TimeServiceProxy from SA failed.");
return nullptr;
}
TIME_HILOGD(TIME_MODULE_CLIENT, "Getting TimeServiceProxy succeeded.");
return timeServiceProxy;
return timeServiceProxy_;
}
bool TimeServiceClient::TimeServiceClient::SetTime(const int64_t time)
@@ -85,7 +90,7 @@ bool TimeServiceClient::TimeServiceClient::SetTime(const int64_t time)
return false;
}
if(timeServiceProxy_->SetTime(time) != ERR_OK){
if (timeServiceProxy_->SetTime(time) != ERR_OK) {
return false;
}
return true;
@@ -103,16 +108,15 @@ bool TimeServiceClient::SetTimeZone(const std::string timezoneId)
return false;
}
if(timeServiceProxy_->SetTimeZone(timezoneId) != ERR_OK){
if (timeServiceProxy_->SetTimeZone(timezoneId) != ERR_OK) {
return false;
}
return true;
}
uint64_t TimeServiceClient::CreateTimer(std::shared_ptr<ITimerInfo> TimerOptions)
{
if (TimerOptions == nullptr){
if (TimerOptions == nullptr) {
TIME_HILOGW(TIME_MODULE_CLIENT, "Input nullptr");
return 0;
}
@@ -132,16 +136,19 @@ uint64_t TimeServiceClient::CreateTimer(std::shared_ptr<ITimerInfo> TimerOptions
return 0;
}
auto timerId = timeServiceProxy_->CreateTimer(TimerOptions->type, TimerOptions->repeat, TimerOptions->interval, timerCallbackInfoObject);
auto timerId = timeServiceProxy_->CreateTimer(TimerOptions->type,
TimerOptions->repeat,
TimerOptions->interval,
timerCallbackInfoObject);
if (timerId == 0){
if (timerId == 0) {
TIME_HILOGE(TIME_MODULE_CLIENT, "Create timer failed");
return 0;
}
TIME_HILOGI(TIME_MODULE_SERVICE,"CreateTimer id: %{public}" PRId64 "", timerId);
TIME_HILOGI(TIME_MODULE_SERVICE, "CreateTimer id: %{public}" PRId64 "", timerId);
auto ret = TimerCallback::GetInstance()->InsertTimerCallbackInfo(timerId, TimerOptions);
if(!ret){
if (!ret) {
return 0;
}
return timerId;
@@ -188,7 +195,7 @@ bool TimeServiceClient::DestroyTimer(uint64_t timerId)
TIME_HILOGE(TIME_MODULE_CLIENT, "DestroyTimer quit because redoing ConnectService failed.");
return false;
}
if (timeServiceProxy_->DestroyTimer(timerId)){
if (timeServiceProxy_->DestroyTimer(timerId)) {
TimerCallback::GetInstance()->RemoveTimerCallbackInfo(timerId);
return true;
}
@@ -208,7 +215,7 @@ std::string TimeServiceClient::GetTimeZone()
return std::string("");
}
if(timeServiceProxy_->GetTimeZone(timeZoneId) != ERR_OK){
if (timeServiceProxy_->GetTimeZone(timeZoneId) != ERR_OK) {
TIME_HILOGE(TIME_MODULE_CLIENT, "get failed.");
return std::string("");
}
@@ -227,11 +234,11 @@ int64_t TimeServiceClient::GetWallTimeMs()
TIME_HILOGE(TIME_MODULE_CLIENT, "GetWallTimeMs quit because redoing ConnectService failed.");
return -1;
}
if(timeServiceProxy_->GetWallTimeMs(times) != ERR_OK){
if (timeServiceProxy_->GetWallTimeMs(times) != ERR_OK) {
TIME_HILOGE(TIME_MODULE_CLIENT, "get failed.");
return -1;
}
TIME_HILOGI(TIME_MODULE_SERVICE,"Result: %{public}" PRId64 "", times);
TIME_HILOGI(TIME_MODULE_SERVICE, "Result: %{public}" PRId64 "", times);
return times;
}
@@ -248,11 +255,11 @@ int64_t TimeServiceClient::GetWallTimeNs()
return -1;
}
if(timeServiceProxy_->GetWallTimeNs(times) != ERR_OK){
if (timeServiceProxy_->GetWallTimeNs(times) != ERR_OK) {
TIME_HILOGE(TIME_MODULE_CLIENT, "get failed.");
return -1;
}
TIME_HILOGI(TIME_MODULE_SERVICE,"Result: %{public}" PRId64 "", times);
TIME_HILOGI(TIME_MODULE_SERVICE, "Result: %{public}" PRId64 "", times);
return times;
}
@@ -269,11 +276,11 @@ int64_t TimeServiceClient::GetBootTimeMs()
return -1;
}
if(timeServiceProxy_->GetBootTimeMs(times) != ERR_OK){
if (timeServiceProxy_->GetBootTimeMs(times) != ERR_OK) {
TIME_HILOGE(TIME_MODULE_CLIENT, "get failed.");
return -1;
}
TIME_HILOGI(TIME_MODULE_SERVICE,"Result: %{public}" PRId64 "", times);
TIME_HILOGI(TIME_MODULE_SERVICE, "Result: %{public}" PRId64 "", times);
return times;
}
@@ -290,11 +297,11 @@ int64_t TimeServiceClient::GetBootTimeNs()
return -1;
}
if(timeServiceProxy_->GetBootTimeNs(times) != ERR_OK){
if (timeServiceProxy_->GetBootTimeNs(times) != ERR_OK) {
TIME_HILOGE(TIME_MODULE_CLIENT, "get failed.");
return -1;
}
TIME_HILOGI(TIME_MODULE_SERVICE,"Result: %{public}" PRId64 "", times);
TIME_HILOGI(TIME_MODULE_SERVICE, "Result: %{public}" PRId64 "", times);
return times;
}
@@ -311,11 +318,11 @@ int64_t TimeServiceClient::GetMonotonicTimeMs()
return -1;
}
if(timeServiceProxy_->GetMonotonicTimeMs(times) != ERR_OK){
if (timeServiceProxy_->GetMonotonicTimeMs(times) != ERR_OK) {
TIME_HILOGE(TIME_MODULE_CLIENT, "get failed.");
return -1;
}
TIME_HILOGI(TIME_MODULE_SERVICE,"Result: %{public}" PRId64 "", times);
TIME_HILOGI(TIME_MODULE_SERVICE, "Result: %{public}" PRId64 "", times);
return times;
}
@@ -332,11 +339,11 @@ int64_t TimeServiceClient::GetMonotonicTimeNs()
return -1;
}
if(timeServiceProxy_->GetMonotonicTimeNs(times) != ERR_OK){
if (timeServiceProxy_->GetMonotonicTimeNs(times) != ERR_OK) {
TIME_HILOGE(TIME_MODULE_CLIENT, "get failed.");
return -1;
}
TIME_HILOGI(TIME_MODULE_SERVICE,"Result: %{public}" PRId64 "", times);
TIME_HILOGI(TIME_MODULE_SERVICE, "Result: %{public}" PRId64 "", times);
return times;
}
@@ -353,11 +360,11 @@ int64_t TimeServiceClient::GetThreadTimeMs()
return -1;
}
if(timeServiceProxy_->GetThreadTimeMs(times) != ERR_OK){
if (timeServiceProxy_->GetThreadTimeMs(times) != ERR_OK) {
TIME_HILOGE(TIME_MODULE_CLIENT, "get failed.");
return -1;
}
TIME_HILOGI(TIME_MODULE_SERVICE,"Result: %{public}" PRId64 "", times);
TIME_HILOGI(TIME_MODULE_SERVICE, "Result: %{public}" PRId64 "", times);
return times;
}
@@ -373,11 +380,11 @@ int64_t TimeServiceClient::GetThreadTimeNs()
TIME_HILOGE(TIME_MODULE_CLIENT, "GetThreadTimeNs quit because redoing ConnectService failed.");
return -1;
}
if(timeServiceProxy_->GetThreadTimeNs(times) != ERR_OK){
if (timeServiceProxy_->GetThreadTimeNs(times) != ERR_OK) {
TIME_HILOGE(TIME_MODULE_CLIENT, "get failed.");
return -1;
}
TIME_HILOGI(TIME_MODULE_SERVICE,"Result: %{public}" PRId64 "", times);
TIME_HILOGI(TIME_MODULE_SERVICE, "Result: %{public}" PRId64 "", times);
return times;
}
@@ -396,6 +403,5 @@ void TimeSaDeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &object)
TIME_HILOGE(TIME_MODULE_CLIENT, "TimeSaDeathRecipient on remote systemAbility died.");
TimeServiceClient::GetInstance()->OnRemoteSaDied(object);
}
} // namespace MiscServices
} // namespace OHOS
@@ -25,7 +25,6 @@ using namespace OHOS::EventFwk;
namespace OHOS{
namespace MiscServices{
void TimeServiceNotify::RegisterPublishEvents()
{
if (publishInfo_ != nullptr) {
@@ -41,7 +41,7 @@ int32_t TimeServiceProxy::SetTime(const int64_t time)
return E_TIME_WRITE_PARCEL_ERROR;
}
int32_t result = Remote()->SendRequest(SET_TIME, data, reply, option);
if (result != ERR_NONE){
if (result != ERR_NONE) {
TIME_HILOGE(TIME_MODULE_CLIENT, "SetTime failed, error code is: %{public}d",result);
return result;
}
@@ -78,7 +78,7 @@ uint64_t TimeServiceProxy::CreateTimer(int32_t type, bool repeat, uint64_t inter
return 0;
}
int32_t result = Remote()->SendRequest(CREATE_TIMER, data, reply, option);
if (result != ERR_NONE){
if (result != ERR_NONE) {
TIME_HILOGE(TIME_MODULE_CLIENT, "CreateTimer failed, error code is: %{public}d",result);
return 0;
}
@@ -107,7 +107,7 @@ bool TimeServiceProxy::StartTimer(uint64_t timerId, uint64_t triggerTimes)
return E_TIME_WRITE_PARCEL_ERROR;
}
int32_t result = Remote()->SendRequest(START_TIMER, data, reply, option);
if (result != ERR_NONE){
if (result != ERR_NONE) {
TIME_HILOGE(TIME_MODULE_CLIENT, "Start failed, error code is: %{public}d",result);
return false;
}
@@ -129,7 +129,7 @@ bool TimeServiceProxy::StopTimer(uint64_t timerId)
return E_TIME_WRITE_PARCEL_ERROR;
}
int32_t result = Remote()->SendRequest(STOP_TIMER, data, reply, option);
if (result != ERR_NONE){
if (result != ERR_NONE) {
TIME_HILOGE(TIME_MODULE_CLIENT, "Stop failed, error code is: %{public}d",result);
return false;
}
@@ -151,7 +151,7 @@ bool TimeServiceProxy::DestroyTimer(uint64_t timerId)
return E_TIME_WRITE_PARCEL_ERROR;
}
int32_t result = Remote()->SendRequest(DESTORY_TIMER, data, reply, option);
if (result != ERR_NONE){
if (result != ERR_NONE) {
TIME_HILOGE(TIME_MODULE_CLIENT, "failed, error code is: %{public}d",result);
return false;
}
@@ -159,7 +159,7 @@ bool TimeServiceProxy::DestroyTimer(uint64_t timerId)
return true;
}
int32_t TimeServiceProxy::SetTimeZone(std::string timezoneId)
int32_t TimeServiceProxy::SetTimeZone(const std::string timezoneId)
{
MessageParcel data, reply;
MessageOption option;
@@ -175,7 +175,7 @@ int32_t TimeServiceProxy::SetTimeZone(std::string timezoneId)
}
int32_t result = Remote()->SendRequest(SET_TIME_ZONE, data, reply, option);
if (result != ERR_NONE){
if (result != ERR_NONE) {
TIME_HILOGE(TIME_MODULE_CLIENT, "SetTimeZone failed, error code is: %{public}d",result);
return result;
}
@@ -193,7 +193,7 @@ int32_t TimeServiceProxy::GetTimeZone(std::string &timezoneId)
}
int32_t result = Remote()->SendRequest(GET_TIME_ZONE, data, reply, option);
if (result != ERR_NONE){
if (result != ERR_NONE) {
TIME_HILOGE(TIME_MODULE_CLIENT, "GetTimeZone failed, error code is: %{public}d",result);
return result;
}
@@ -212,7 +212,7 @@ int32_t TimeServiceProxy::GetWallTimeMs(int64_t &times)
}
int32_t result = Remote()->SendRequest(GET_WALL_TIME_MILLI, data, reply, option);
if (result != ERR_NONE){
if (result != ERR_NONE) {
TIME_HILOGE(TIME_MODULE_CLIENT, "GetWallTimeMs failed, error code is: %{public}d",result);
return result;
}
@@ -231,7 +231,7 @@ int32_t TimeServiceProxy::GetWallTimeNs(int64_t &times)
}
int32_t result = Remote()->SendRequest(GET_WALL_TIME_NANO, data, reply, option);
if (result != ERR_NONE){
if (result != ERR_NONE) {
TIME_HILOGE(TIME_MODULE_CLIENT, "GetWallTimeNs failed, error code is: %{public}d",result);
return result;
}
@@ -250,7 +250,7 @@ int32_t TimeServiceProxy::GetBootTimeMs(int64_t &times)
}
int32_t result = Remote()->SendRequest(GET_BOOT_TIME_MILLI, data, reply, option);
if (result != ERR_NONE){
if (result != ERR_NONE) {
TIME_HILOGE(TIME_MODULE_CLIENT, "GetBootTimeMs failed, error code is: %{public}d",result);
return result;
}
@@ -269,7 +269,7 @@ int32_t TimeServiceProxy::GetBootTimeNs(int64_t &times)
}
int32_t result = Remote()->SendRequest(GET_BOOT_TIME_MILLI, data, reply, option);
if (result != ERR_NONE){
if (result != ERR_NONE) {
TIME_HILOGE(TIME_MODULE_CLIENT, "GetBootTimeNs failed, error code is: %{public}d",result);
return result;
}
@@ -288,7 +288,7 @@ int32_t TimeServiceProxy::GetMonotonicTimeMs(int64_t &times)
}
int32_t result = Remote()->SendRequest(GET_MONO_TIME_MILLI, data, reply, option);
if (result != ERR_NONE){
if (result != ERR_NONE) {
TIME_HILOGE(TIME_MODULE_CLIENT, "GetMonotonicTimeMs failed, error code is: %{public}d",result);
return result;
}
@@ -307,7 +307,7 @@ int32_t TimeServiceProxy::GetMonotonicTimeNs(int64_t &times)
}
int32_t result = Remote()->SendRequest(GET_MONO_TIME_NANO, data, reply, option);
if (result != ERR_NONE){
if (result != ERR_NONE) {
TIME_HILOGE(TIME_MODULE_CLIENT, "GetMonotonicTimeNs failed, error code is: %{public}d",result);
return result;
}
@@ -326,7 +326,7 @@ int32_t TimeServiceProxy::GetThreadTimeMs(int64_t &times)
}
int32_t result = Remote()->SendRequest(GET_THREAD_TIME_MILLI, data, reply, option);
if (result != ERR_NONE){
if (result != ERR_NONE) {
TIME_HILOGE(TIME_MODULE_CLIENT, "GetThreadTimeMs failed, error code is: %{public}d",result);
return result;
}
@@ -345,7 +345,7 @@ int32_t TimeServiceProxy::GetThreadTimeNs(int64_t &times)
}
int32_t result = Remote()->SendRequest(GET_THREAD_TIME_NANO, data, reply, option);
if (result != ERR_NONE){
if (result != ERR_NONE) {
TIME_HILOGE(TIME_MODULE_CLIENT, "GetThreadTimeNs failed, error code is: %{public}d",result);
return result;
}
+65 -67
View File
@@ -22,7 +22,8 @@ namespace OHOS {
namespace MiscServices {
using namespace OHOS::HiviewDFX;
TimeServiceStub::TimeServiceStub(){
TimeServiceStub::TimeServiceStub()
{
memberFuncMap_[SET_TIME] = &TimeServiceStub::OnSetTime;
memberFuncMap_[SET_TIME_ZONE] = &TimeServiceStub::OnSetTimeZone;
memberFuncMap_[GET_TIME_ZONE] = &TimeServiceStub::OnGetTimeZone;
@@ -40,23 +41,25 @@ TimeServiceStub::TimeServiceStub(){
memberFuncMap_[STOP_TIMER] = &TimeServiceStub::OnStopTimer;
memberFuncMap_[DESTORY_TIMER] = &TimeServiceStub::OnDestoryTimer;
}
TimeServiceStub::~TimeServiceStub(){
TimeServiceStub::~TimeServiceStub()
{
memberFuncMap_.clear();
}
int32_t TimeServiceStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply,
MessageOption &option)
{
TIME_HILOGI(TIME_MODULE_SERVICE," start##code = %{public}u", code);
TIME_HILOGI(TIME_MODULE_SERVICE, " start##code = %{public}u", code);
std::u16string myDescripter = TimeServiceStub::GetDescriptor();
std::u16string remoteDescripter = data.ReadInterfaceToken();
if (myDescripter != remoteDescripter) {
TIME_HILOGE(TIME_MODULE_SERVICE," end##descriptor checked fail");
TIME_HILOGE(TIME_MODULE_SERVICE, " end##descriptor checked fail");
return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
}
pid_t p = IPCSkeleton::GetCallingPid();
pid_t p1 = IPCSkeleton::GetCallingUid();
TIME_HILOGI(TIME_MODULE_SERVICE,"CallingPid = %{public}d, CallingUid = %{public}d, code = %{public}u", p, p1, code);
TIME_HILOGI(TIME_MODULE_SERVICE, "CallingPid = %{public}d, CallingUid = %{public}d, code = %{public}u", p, p1, code);
auto itFunc = memberFuncMap_.find(code);
if (itFunc != memberFuncMap_.end()) {
auto memberFunc = itFunc->second;
@@ -65,230 +68,225 @@ int32_t TimeServiceStub::OnRemoteRequest(uint32_t code, MessageParcel &data, Mes
}
}
int ret = IPCObjectStub::OnRemoteRequest(code, data, reply, option);
TIME_HILOGI(TIME_MODULE_SERVICE," end##ret = %{public}d", ret);
TIME_HILOGI(TIME_MODULE_SERVICE, " end##ret = %{public}d", ret);
return ret;
}
int32_t TimeServiceStub::OnSetTime(MessageParcel& data, MessageParcel& reply)
{
TIME_HILOGI(TIME_MODULE_SERVICE," start.");
TIME_HILOGI(TIME_MODULE_SERVICE, " start.");
int64_t time = data.ReadInt64();
int32_t ret = SetTime(time);
TIME_HILOGI(TIME_MODULE_SERVICE," end##ret = %{public}d", ret);
TIME_HILOGI(TIME_MODULE_SERVICE, " end##ret = %{public}d", ret);
return ret;
}
int32_t TimeServiceStub::OnSetTimeZone(MessageParcel &data, MessageParcel &reply)
{
TIME_HILOGI(TIME_MODULE_SERVICE," start.");
TIME_HILOGI(TIME_MODULE_SERVICE, " start.");
std::string timeZoneId = data.ReadString();
int32_t ret = SetTimeZone(timeZoneId);
TIME_HILOGI(TIME_MODULE_SERVICE," end##ret = %{public}d", ret);
TIME_HILOGI(TIME_MODULE_SERVICE, " end##ret = %{public}d", ret);
return ret;
}
int32_t TimeServiceStub::OnGetTimeZone(MessageParcel &data, MessageParcel &reply)
{
TIME_HILOGI(TIME_MODULE_SERVICE," start.");
TIME_HILOGI(TIME_MODULE_SERVICE, " start.");
std::string timeZoneId;
int32_t ret = GetTimeZone(timeZoneId);
if (ret != ERR_OK){
TIME_HILOGE(TIME_MODULE_SERVICE," end##ret = %{public}d", ret);
if (ret != ERR_OK) {
TIME_HILOGE(TIME_MODULE_SERVICE, " end##ret = %{public}d", ret);
return ret;
}
reply.WriteString(timeZoneId);
TIME_HILOGI(TIME_MODULE_SERVICE," end.");
TIME_HILOGI(TIME_MODULE_SERVICE, " end.");
return ret;
}
int32_t TimeServiceStub::OnGetWallTimeMs(MessageParcel &data, MessageParcel &reply)
{
TIME_HILOGI(TIME_MODULE_SERVICE," start.");
TIME_HILOGI(TIME_MODULE_SERVICE, " start.");
int64_t times;
int32_t ret = GetWallTimeMs(times);
if (ret != ERR_OK){
TIME_HILOGE(TIME_MODULE_SERVICE," end##ret = %{public}d", ret);
if (ret != ERR_OK) {
TIME_HILOGE(TIME_MODULE_SERVICE, " end##ret = %{public}d", ret);
return ret;
}
reply.WriteInt64(times);
TIME_HILOGI(TIME_MODULE_SERVICE," end.");
TIME_HILOGI(TIME_MODULE_SERVICE, " end.");
return ret;
}
int32_t TimeServiceStub::OnGetWallTimeNs(MessageParcel &data, MessageParcel &reply)
{
TIME_HILOGI(TIME_MODULE_SERVICE," start.");
TIME_HILOGI(TIME_MODULE_SERVICE, " start.");
int64_t times;
int32_t ret = GetWallTimeNs(times);
if (ret != ERR_OK){
TIME_HILOGE(TIME_MODULE_SERVICE," end##ret = %{public}d", ret);
if (ret != ERR_OK) {
TIME_HILOGE(TIME_MODULE_SERVICE, " end##ret = %{public}d", ret);
return ret;
}
reply.WriteInt64(times);
TIME_HILOGI(TIME_MODULE_SERVICE," end.");
TIME_HILOGI(TIME_MODULE_SERVICE, " end.");
return ret;
}
int32_t TimeServiceStub::OnGetBootTimeMs(MessageParcel &data, MessageParcel &reply)
{
TIME_HILOGI(TIME_MODULE_SERVICE," start.");
TIME_HILOGI(TIME_MODULE_SERVICE, " start.");
int64_t times;
int32_t ret = GetBootTimeMs(times);
if (ret != ERR_OK){
TIME_HILOGE(TIME_MODULE_SERVICE," end##ret = %{public}d", ret);
if (ret != ERR_OK) {
TIME_HILOGE(TIME_MODULE_SERVICE, " end##ret = %{public}d", ret);
return ret;
}
reply.WriteInt64(times);
TIME_HILOGI(TIME_MODULE_SERVICE," end.");
TIME_HILOGI(TIME_MODULE_SERVICE, " end.");
return ret;
}
int32_t TimeServiceStub::OnGetBootTimeNs(MessageParcel &data, MessageParcel &reply)
{
TIME_HILOGI(TIME_MODULE_SERVICE," start.");
TIME_HILOGI(TIME_MODULE_SERVICE, " start.");
int64_t times;
int32_t ret = GetBootTimeNs(times);
if (ret != ERR_OK){
TIME_HILOGE(TIME_MODULE_SERVICE," end##ret = %{public}d", ret);
if (ret != ERR_OK) {
TIME_HILOGE(TIME_MODULE_SERVICE, " end##ret = %{public}d", ret);
return ret;
}
reply.WriteInt64(times);
TIME_HILOGI(TIME_MODULE_SERVICE," end.");
TIME_HILOGI(TIME_MODULE_SERVICE, " end.");
return ret;
}
int32_t TimeServiceStub::OnGetMonotonicTimeMs(MessageParcel &data, MessageParcel &reply)
{
TIME_HILOGI(TIME_MODULE_SERVICE," start.");
TIME_HILOGI(TIME_MODULE_SERVICE, " start.");
int64_t times;
int32_t ret = GetMonotonicTimeMs(times);
if (ret != ERR_OK){
TIME_HILOGE(TIME_MODULE_SERVICE," end##ret = %{public}d", ret);
if (ret != ERR_OK) {
TIME_HILOGE(TIME_MODULE_SERVICE, " end##ret = %{public}d", ret);
return ret;
}
reply.WriteInt64(times);
TIME_HILOGI(TIME_MODULE_SERVICE," end.");
TIME_HILOGI(TIME_MODULE_SERVICE, " end.");
return ret;
}
int32_t TimeServiceStub::OnGetMonotonicTimeNs(MessageParcel &data, MessageParcel &reply)
{
TIME_HILOGI(TIME_MODULE_SERVICE," start.");
TIME_HILOGI(TIME_MODULE_SERVICE, " start.");
int64_t times;
int32_t ret = GetMonotonicTimeNs(times);
if (ret != ERR_OK){
TIME_HILOGE(TIME_MODULE_SERVICE," end##ret = %{public}d", ret);
if (ret != ERR_OK) {
TIME_HILOGE(TIME_MODULE_SERVICE, " end##ret = %{public}d", ret);
return ret;
}
reply.WriteInt64(times);
TIME_HILOGI(TIME_MODULE_SERVICE," end.");
TIME_HILOGI(TIME_MODULE_SERVICE, " end.");
return ret;
}
int32_t TimeServiceStub::OnGetThreadTimeMs(MessageParcel &data, MessageParcel &reply)
{
TIME_HILOGI(TIME_MODULE_SERVICE," start.");
TIME_HILOGI(TIME_MODULE_SERVICE, " start.");
int64_t times;
int32_t ret = GetThreadTimeMs(times);
if (ret != ERR_OK){
TIME_HILOGE(TIME_MODULE_SERVICE," end##ret = %{public}d", ret);
if (ret != ERR_OK) {
TIME_HILOGE(TIME_MODULE_SERVICE, " end##ret = %{public}d", ret);
return ret;
}
reply.WriteInt64(times);
TIME_HILOGI(TIME_MODULE_SERVICE," end.");
TIME_HILOGI(TIME_MODULE_SERVICE, " end.");
return ret;
}
int32_t TimeServiceStub::OnGetThreadTimeNs(MessageParcel &data, MessageParcel &reply)
{
TIME_HILOGI(TIME_MODULE_SERVICE," start.");
TIME_HILOGI(TIME_MODULE_SERVICE, " start.");
int64_t times;
int32_t ret = GetThreadTimeNs(times);
if (ret != ERR_OK){
TIME_HILOGE(TIME_MODULE_SERVICE," end##ret = %{public}d", ret);
if (ret != ERR_OK) {
TIME_HILOGE(TIME_MODULE_SERVICE, " end##ret = %{public}d", ret);
return ret;
}
reply.WriteInt64(times);
TIME_HILOGI(TIME_MODULE_SERVICE," end.");
TIME_HILOGI(TIME_MODULE_SERVICE, " end.");
return ret;
}
int32_t TimeServiceStub::OnCreateTimer(MessageParcel &data, MessageParcel &reply)
{
TIME_HILOGI(TIME_MODULE_SERVICE,"start.");
TIME_HILOGI(TIME_MODULE_SERVICE, "start.");
auto type = data.ReadInt32();
auto repeat = data.ReadBool();
auto interval = data.ReadUint64();
sptr<IRemoteObject> obj = data.ReadRemoteObject();
if(obj == nullptr){
if (obj == nullptr) {
TIME_HILOGE(TIME_MODULE_SERVICE, "Input nullptr");
return E_TIME_PARAMETERS_INVALID;
}
auto timerId = CreateTimer(type, repeat, interval, obj);
if (timerId == 0 ){
if (timerId == 0 ) {
TIME_HILOGE(TIME_MODULE_SERVICE, "Create timer failed");
return E_TIME_DEAL_FAILED;
}
if (!reply.WriteUint64(timerId)){
if (!reply.WriteUint64(timerId)) {
TIME_HILOGE(TIME_MODULE_SERVICE, "Failed to write parcelable");
return E_TIME_WRITE_PARCEL_ERROR;
}
TIME_HILOGI(TIME_MODULE_SERVICE,"end.");
TIME_HILOGI(TIME_MODULE_SERVICE, "end.");
return ERR_OK;
}
int32_t TimeServiceStub::OnStartTimer(MessageParcel &data, MessageParcel &reply)
{
TIME_HILOGI(TIME_MODULE_SERVICE,"start.");
TIME_HILOGI(TIME_MODULE_SERVICE, "start.");
auto timerId = data.ReadUint64();
auto triggerTime = data.ReadUint64();
if (!StartTimer(timerId, triggerTime)){
if (!StartTimer(timerId, triggerTime)) {
TIME_HILOGE(TIME_MODULE_SERVICE, "Failed to start timer");
return E_TIME_DEAL_FAILED;
}
TIME_HILOGI(TIME_MODULE_SERVICE,"end.");
TIME_HILOGI(TIME_MODULE_SERVICE, "end.");
return ERR_OK;
}
int32_t TimeServiceStub::OnStopTimer(MessageParcel &data, MessageParcel &reply)
{
TIME_HILOGI(TIME_MODULE_SERVICE,"start.");
TIME_HILOGI(TIME_MODULE_SERVICE, "start.");
auto timerId = data.ReadUint64();
if (!StopTimer(timerId)){
if (!StopTimer(timerId)) {
TIME_HILOGE(TIME_MODULE_SERVICE, "Failed to stop timer");
return E_TIME_DEAL_FAILED;
}
TIME_HILOGI(TIME_MODULE_SERVICE,"end.");
TIME_HILOGI(TIME_MODULE_SERVICE, "end.");
return ERR_OK;
}
int32_t TimeServiceStub::OnDestoryTimer(MessageParcel &data, MessageParcel &reply)
{
TIME_HILOGI(TIME_MODULE_SERVICE,"start.");
TIME_HILOGI(TIME_MODULE_SERVICE, "start.");
auto timerId = data.ReadUint64();
if (!DestroyTimer(timerId)){
if (!DestroyTimer(timerId)) {
TIME_HILOGE(TIME_MODULE_SERVICE, "Failed to destory timer");
return E_TIME_DEAL_FAILED;
}
TIME_HILOGI(TIME_MODULE_SERVICE,"end.");
TIME_HILOGI(TIME_MODULE_SERVICE, "end.");
return ERR_OK;
}
} // namespace MiscServices
+132 -53
View File
@@ -14,84 +14,163 @@
*/
#include "time_zone_info.h"
#include "time_common.h"
#include <vector>
namespace OHOS{
namespace MiscServices{
std::mutex TimeZoneInfo::instanceLock_;
sptr<TimeZoneInfo> TimeZoneInfo::instance_;
namespace {
static const int HOURS_TO_MINUTES = 60;
}
TimeZoneInfo::TimeZoneInfo()
{
std::vector<struct zoneInfoEntry> timezoneList = {
{"Anadyr, Russia", "ANA", 12, "Anadyr Time"},
{"Honiara, SolomonIslands", "SBT", 11, "Solomon Islands Time"},
{"Melbourne, Australia", "AEST", 10, "Australian Eastern Standard Time"},
{"Tokyo, Japan", "JST", 9, "Japan Standard Time"},
{"Beijing, China", "CST", 8, "China Standard Time"},
{"Jakarta, Indonesia", "WIB", 7, "Western Indonesian Time"},
{"Dhaka, Bangladesh", "BST", 6, "Bangladesh Standard Time"},
{"Tashkent, Uzbekistan", "UZT", 5, "Uzbekistan Time"},
{"Dubai, U.A.E.", "GST", 4, "Gulf Standard Time"},
{"Moscow, Russia", "MSK", 3, "Moscow Standard Time"},
{"Brussels, Belgium", "CEST", 2, "Central European Summer Time"},
{"London, England", "BST", 1, "British Summer Time"},
{"Accra, Ghana", "GMT", 0, "Greenwich Mean Time"},
{"Accra, Ghana", "UTC", 0, "Universal Time Coordinated"},
{"Praia, CaboVerde", "CVT", -1, "Cabo Verde Time"},
{"Nuuk, Greenland", "WGS", -2, "Western Greenland Summer Time"},
{"Buenos Aires, Argentina", "ART", -3, "Argentina Time"},
{"New York, U.S.A.", "EDT", -4, "Eastern Daylight Time"},
{"Mexico City, Mexico", "CDT", -5, "Central Daylight Time"},
{"Guatemala City, Guatemala", "CST", -6, "Central Standard Time"},
{"Los Angeles, U.S.A.", "PDT", -7, "Pacific Daylight Time"},
{"Anchorage, U.S.A.", "AKD", -8, "Alaska Daylight Time"},
{"Adak, U.S.A.", "HDT", -9, "Hawaii-Aleutian Daylight Time"},
{"Honolulu, U.S.A.", "HST", -10, "Hawaii Standard Time"},
{"Alofi, Niue", "NUT", -11, "Niue Time"},
{"Baker Island, U.S.A.", "AoE", -12, "Anywhere on Earth"},
{"Antarctica/McMurdo", "AQ", 12},
{"America/Argentina/Buenos_Aires", "AR", -3},
{"Australia/Sydney", "AU", 10},
{"America/Noronha", "BR", -2},
{"America/St_Johns", "CA", -2.5},
{"Africa/Kinshasa", "CD", 1},
{"America/Santiago", "CL", -3},
{"Asia/Shanghai", "CN", 8},
{"Asia/Nicosia", "CY", 3},
{"Europe/Berlin", "DE", 2},
{"America/Guayaquil", "CEST", -5},
{"Europe/Madrid", "ES", 2},
{"Pacific/Pohnpei", "FM", 11},
{"America/Godthab", "GL", -2},
{"Asia/Jakarta", "ID", 7},
{"Pacific/Tarawa", "KI", 12},
{"Asia/Almaty", "KZ", 6},
{"Pacific/Majuro", "MH", 12},
{"Asia/Ulaanbaatar", "MN", 8},
{"America/Mexico_City", "MX", -5},
{"Asia/Kuala_Lumpur", "MY", 8},
{"Pacific/Auckland", "NZ", 12},
{"Pacific/Tahiti", "PF", -10},
{"Pacific/Port_Moresby", "PG", 10},
{"Asia/Gaza", "PS", 3},
{"Europe/Lisbon", "PT", 1},
{"Europe/Moscow", "RU", 3},
{"Europe/Kiev", "UA", 3},
{"Pacific/Wake", "UM", 12},
{"America/New_York", "US", -4},
{"Asia/Tashkent", "UZ", 5}
};
for (auto tz : timezoneList) {
timezoneInfoMap_[tz.ID] = tz;
}
}
TimeZoneInfo::~TimeZoneInfo(){
TimeZoneInfo::~TimeZoneInfo()
{
timezoneInfoMap_.clear();
}
int32_t TimeZoneInfo::GetOffset(const std::string timezoneId, int &offset){
void TimeZoneInfo::Init()
{
TIME_HILOGD(TIME_MODULE_SERVICE, "start.");
std::string timezoneId;
float gmtOffset;
if (!GetTimezoneFromFile(timezoneId)) {
TIME_HILOGE(TIME_MODULE_SERVICE, "end, init timezone failed.");
return;
}
if (!GetOffsetById(timezoneId, gmtOffset)) {
TIME_HILOGE(TIME_MODULE_SERVICE, "end, init timezone failed.");
return;
}
if (!SetOffsetToKernel(gmtOffset)) {
TIME_HILOGE(TIME_MODULE_SERVICE, "end, init timezone failed.");
return;
}
TIME_HILOGD(TIME_MODULE_SERVICE, "end.");
}
bool TimeZoneInfo::SetTimezone(std::string timezoneId)
{
float gmtOffset;
if (!GetOffsetById(timezoneId, gmtOffset)) {
TIME_HILOGE(TIME_MODULE_SERVICE, "Timezone unsupport %{public}s.", timezoneId.c_str());
return false;
}
TIME_HILOGD(TIME_MODULE_SERVICE, "timezone :%{public}s , GMT Offset :%{public}f", timezoneId.c_str(), gmtOffset);
if (!SetOffsetToKernel(gmtOffset)) {
TIME_HILOGE(TIME_MODULE_SERVICE, "Set kernel failed.");
return false;
}
if (!SaveTimezoneToFile(timezoneId)) {
TIME_HILOGE(TIME_MODULE_SERVICE, "Save file failed.");
return false;
}
curTimezoneId_ = timezoneId;
return true;
}
bool TimeZoneInfo::GetTimezone(std::string &timezoneId) {
timezoneId = curTimezoneId_;
return true;
}
bool TimeZoneInfo::SetOffsetToKernel(float offsetHour)
{
struct timezone tz{};
tz.tz_minuteswest = static_cast<int>(offsetHour * HOURS_TO_MINUTES);
tz.tz_dsttime = 0;
TIME_HILOGD(TIME_MODULE_SERVICE, "settimeofday, Offset hours :%{public}f , Offset minutes :%{public}d", offsetHour, tz.tz_minuteswest);
int result = settimeofday(NULL, &tz);
if (result < 0) {
TIME_HILOGE(TIME_MODULE_SERVICE, "settimeofday fail: %{public}d.",result);
return false;
}
return true;
}
bool TimeZoneInfo::GetTimezoneFromFile(std::string &timezoneId)
{
Json::Value root;
std::ifstream ifs;
ifs.open(TIMEZONE_FILE_PATH);
Json::CharReaderBuilder builder;
builder["collectComments"] = true;
JSONCPP_STRING errs;
if (!parseFromStream(builder, ifs, &root, &errs)) {
ifs.close();
TIME_HILOGE(TIME_MODULE_SERVICE, "Read file failed %{public}s.", errs.c_str());
return false;
}
timezoneId = root["TimezoneId"].asString();
TIME_HILOGE(TIME_MODULE_SERVICE, "Read file %{public}s.", timezoneId.c_str());
ifs.close();
return true;
}
bool TimeZoneInfo::SaveTimezoneToFile(std::string timezoneId)
{
std::ofstream ofs;
ofs.open(TIMEZONE_FILE_PATH);
Json::Value root;
root["TimezoneId"] = timezoneId;
Json::StreamWriterBuilder builder;
const std::string json_file = Json::writeString(builder, root);
ofs << json_file;
ofs.close();
TIME_HILOGD(TIME_MODULE_SERVICE, "Write file %{public}s.", timezoneId.c_str());
return true;
}
bool TimeZoneInfo::GetOffsetById(const std::string timezoneId, float &offset)
{
auto itEntry = timezoneInfoMap_.find(timezoneId);
if (itEntry != timezoneInfoMap_.end()) {
auto zoneInfo = itEntry->second;
offset = zoneInfo.utcOffsetHours;
curTimezoneId_ = timezoneId;
return ERR_OK;
return true;
}
TIME_HILOGE(TIME_MODULE_SERVICE, "TimezoneId not found.");
return E_TIME_NOT_FOUND;
return false;
}
int32_t TimeZoneInfo::GetTimezoneId( std::string &timezoneId ){
timezoneId = curTimezoneId_;
return ERR_OK;
}
sptr<TimeZoneInfo> TimeZoneInfo::GetInstance()
{
if (instance_ == nullptr) {
std::lock_guard<std::mutex> autoLock(instanceLock_);
if (instance_ == nullptr) {
instance_ = new TimeZoneInfo;
}
}
return instance_;
}
}
}
@@ -17,7 +17,6 @@
namespace OHOS {
namespace MiscServices {
std::mutex TimerCallback::instanceLock_;
sptr<TimerCallback> TimerCallback::instance_;
@@ -45,10 +44,10 @@ sptr<TimerCallback> TimerCallback::GetInstance()
}
bool TimerCallback::InsertTimerCallbackInfo(const uint64_t timerId,
const std::shared_ptr<ITimerInfo> &timerInfo)
const std::shared_ptr<ITimerInfo> &timerInfo)
{
TIME_HILOGD(TIME_MODULE_SERVICE, "start.");
if (timerInfo == nullptr){
if (timerInfo == nullptr) {
return false;
}
@@ -87,17 +86,18 @@ void TimerCallback::NotifyTimer(const uint64_t timerId)
TIME_HILOGD(TIME_MODULE_SERVICE, "ontrigger.");
it->second->OnTrigger();
if (it->second->wantAgent != nullptr){
if (it->second->wantAgent != nullptr) {
TIME_HILOGD(TIME_MODULE_SERVICE, "trigger wantagent.");
std::shared_ptr<AppExecFwk::Context> context = std::make_shared<OHOS::AppExecFwk::AbilityContext>();
std::shared_ptr<AAFwk::Want> want = Notification::WantAgent::WantAgentHelper::GetWant(it->second->wantAgent);
std::shared_ptr<AAFwk::Want> want =
Notification::WantAgent::WantAgentHelper::GetWant(it->second->wantAgent);
OHOS::Notification::WantAgent::TriggerInfo paramsInfo("", nullptr, want, 11);
Notification::WantAgent::WantAgentHelper::TriggerWantAgent(context, it->second->wantAgent, nullptr, paramsInfo);
Notification::WantAgent::WantAgentHelper::TriggerWantAgent(context,
it->second->wantAgent, nullptr, paramsInfo);
}
}
TIME_HILOGD(TIME_MODULE_SERVICE, "end.");
}
} // namespace MiscServices
} // namespace OHOS
@@ -18,7 +18,6 @@
namespace OHOS {
namespace MiscServices {
TimerCallbackProxy::TimerCallbackProxy(const sptr<IRemoteObject> &object) : IRemoteProxy<ITimerCallback>(object)
{
}
@@ -29,11 +28,11 @@ TimerCallbackProxy::~TimerCallbackProxy()
TIME_HILOGD(TIME_MODULE_CLIENT, "TimerCallbackProxy instance destoryed");
}
void TimerCallbackProxy::NotifyTimer(uint64_t timerId)
void TimerCallbackProxy::NotifyTimer(const uint64_t timerId)
{
TIME_HILOGD(TIME_MODULE_CLIENT, "start id: %{public}" PRId64 "", timerId);
sptr<IRemoteObject> remote = Remote();
if (remote == nullptr){
if (remote == nullptr) {
return;
}
@@ -17,7 +17,6 @@
namespace OHOS {
namespace MiscServices {
int TimerCallbackStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply,
MessageOption &option)
{
+3
View File
@@ -0,0 +1,3 @@
{
"TimezoneId" : "Asia/Shanghai"
}
@@ -12,6 +12,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_GLOBAL_TIME_SERVICE_TEST_H
#define OHOS_GLOBAL_TIME_SERVICE_TEST_H
#include "napi/native_api.h"
#include "napi/native_node_api.h"
#include <functional>
@@ -26,8 +29,8 @@
#include <string>
#include <inttypes.h>
namespace OHOS{
namespace MiscServices{
namespace OHOS {
namespace MiscServices {
class TimerInfoTest : public ITimerInfo {
public:
TimerInfoTest();
@@ -54,7 +57,7 @@ TimerInfoTest::~TimerInfoTest()
void TimerInfoTest::OnTrigger()
{
TIME_HILOGD(TIME_MODULE_SERVICE, "start.");
if (callBack_ != nullptr){
if (callBack_ != nullptr) {
TIME_HILOGD(TIME_MODULE_SERVICE, "call back.");
callBack_();
}
@@ -83,6 +86,6 @@ void TimerInfoTest::SetWantAgent(std::shared_ptr<OHOS::Notification::WantAgent::
{
wantAgent = _wantAgent;
}
}
}
#endif
@@ -12,7 +12,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "timer_test.h"
#include "time_service_test.h"
using namespace testing::ext;
using namespace OHOS;
@@ -53,7 +54,8 @@ HWTEST_F(TimeServiceTest, SetTime001, TestSize.Level0)
struct timeval getTime;
gettimeofday(&getTime, NULL);
int64_t time = (getTime.tv_sec + 1000) * 1000 + getTime.tv_usec / 1000;
if (time < 0){
if (time < 0) {
TIME_HILOGE(TIME_MODULE_CLIENT, "Time now invalid : %{public}" PRId64 "",time);
time = 1627307312000;
}
TIME_HILOGI(TIME_MODULE_CLIENT, "Time now : %{public}" PRId64 "",time);
@@ -67,11 +69,16 @@ HWTEST_F(TimeServiceTest, SetTime001, TestSize.Level0)
* @tc.type: FUNC
*/
HWTEST_F(TimeServiceTest, SetTimeZone001, TestSize.Level0)
{
std::string timeZoneSet("Beijing, China");
{
struct timezone tz = {};
gettimeofday(NULL, &tz);
TIME_HILOGD(TIME_MODULE_CLIENT, "Before set timezone, GMT offset in kernel : %{public}d", tz.tz_minuteswest);
std::string timeZoneSet("Asia/Shanghai");
bool result = TimeServiceClient::GetInstance()->SetTimeZone(timeZoneSet);
EXPECT_TRUE(result);
auto ret = gettimeofday(NULL, &tz);
TIME_HILOGD(TIME_MODULE_CLIENT, "gettimeofday result : %{public}d", ret);
TIME_HILOGD(TIME_MODULE_CLIENT, "After set timezone, GMT offset minutes in kernel : %{public}d", tz.tz_minuteswest);
auto timeZoneRes = TimeServiceClient::GetInstance()->GetTimeZone();
EXPECT_EQ(timeZoneRes, timeZoneSet);
}
@@ -83,10 +90,16 @@ HWTEST_F(TimeServiceTest, SetTimeZone001, TestSize.Level0)
*/
HWTEST_F(TimeServiceTest, SetTimeZone002, TestSize.Level0)
{
std::string timeZoneSet("Beijing, China");
struct timezone tz = {};
gettimeofday(NULL, &tz);
TIME_HILOGD(TIME_MODULE_CLIENT, "Before set timezone, GMT offset in kernel : %{public}d", tz.tz_minuteswest);
std::string timeZoneSet("Asia/Ulaanbaatar");
bool result = TimeServiceClient::GetInstance()->SetTimeZone(timeZoneSet);
EXPECT_TRUE(result);
auto ret = gettimeofday(NULL, &tz);
TIME_HILOGD(TIME_MODULE_CLIENT, "gettimeofday result : %{public}d", ret);
TIME_HILOGD(TIME_MODULE_CLIENT, "After set timezone, GMT offset minutes in kernel : %{public}d", tz.tz_minuteswest);
auto timeZoneRes = TimeServiceClient::GetInstance()->GetTimeZone();
EXPECT_EQ(timeZoneRes, timeZoneSet);
}
@@ -349,7 +362,7 @@ HWTEST_F(TimeServiceTest, CreateTimer06, TestSize.Level0)
struct timeval getTime;
gettimeofday(&getTime, NULL);
int64_t current_time = (getTime.tv_sec + 100) * 1000 + getTime.tv_usec / 1000;
if (current_time < 0){
if (current_time < 0) {
current_time = 0;
}
auto timerId1 = TimeServiceClient::GetInstance()->CreateTimer(timerInfo);
+2 -6
View File
@@ -24,21 +24,18 @@
#include "time_common.h"
namespace OHOS {
namespace MiscServices {
class Batch {
public:
Batch ();
explicit Batch (const TimerInfo &seed);
virtual ~Batch() = default;
std::chrono::steady_clock::time_point GetStart () const;
std::chrono::steady_clock::time_point GetEnd () const;
uint32_t GetFlags () const;
size_t Size () const;
std::shared_ptr<TimerInfo> Get (size_t index) const;
bool CanHold (std::chrono::steady_clock::time_point whenElapsed,
std::chrono::steady_clock::time_point maxWhen) const;
std::chrono::steady_clock::time_point maxWhen) const;
bool Add (const std::shared_ptr<TimerInfo> &alarm);
bool Remove (const TimerInfo &alarm);
bool Remove (std::function<bool (const TimerInfo &)> predicate);
@@ -51,7 +48,6 @@ private:
uint32_t flags_;
std::vector<std::shared_ptr<TimerInfo>> alarms_;
};
}
}
#endif
+3 -14
View File
@@ -13,8 +13,6 @@
* limitations under the License.
*/
#ifndef TIMER_HANDLER_H
#define TIMER_HANDLER_H
@@ -26,32 +24,23 @@
#include <chrono>
#include <memory>
namespace OHOS {
namespace MiscServices {
static const size_t ALARM_TYPE_COUNT = 5;
static const size_t N_TIMER_FDS = ALARM_TYPE_COUNT + 1;
typedef std::array<int, N_TIMER_FDS> TimerFds;
class TimerHandler {
public:
static std::shared_ptr<TimerHandler> Create ();
int Set (uint32_t type, std::chrono::nanoseconds when);
int WaitForAlarm ();
uint32_t WaitForAlarm ();
~TimerHandler ();
private:
TimerHandler (const TimerFds &fds, int epollfd);
const TimerFds fds_;
const int epollFd_;
};
}// MiscService
}// OHOS
} // MiscService
} // OHOS
#endif
+12 -16
View File
@@ -25,9 +25,7 @@
namespace OHOS {
namespace MiscServices {
class TimerInfo {
public:
const uint64_t id;
const int type;
@@ -37,7 +35,7 @@ public:
const uint32_t flags;
const uint64_t uid;
uint64_t count{};
uint64_t count {};
std::chrono::milliseconds when;
std::chrono::milliseconds windowLength;
std::chrono::steady_clock::time_point whenElapsed;
@@ -47,20 +45,18 @@ public:
std::chrono::milliseconds repeatInterval;
TimerInfo (uint64_t id, int type,
std::chrono::milliseconds when,
std::chrono::steady_clock::time_point whenElapsed,
std::chrono::milliseconds windowLength,
std::chrono::steady_clock::time_point maxWhen,
std::chrono::milliseconds interval,
std::function<void (const uint64_t)> callback,
uint32_t flags,
uint64_t uid);
std::chrono::milliseconds when,
std::chrono::steady_clock::time_point whenElapsed,
std::chrono::milliseconds windowLength,
std::chrono::steady_clock::time_point maxWhen,
std::chrono::milliseconds interval,
std::function<void (const uint64_t)> callback,
uint32_t flags,
uint64_t uid);
virtual ~TimerInfo() = default;
bool operator== (const TimerInfo &other) const;
bool Matches (const std::string &packageName) const;
};
}// MiscService
}// OHOSw
} // MiscService
} // OHOS
#endif
+2 -3
View File
@@ -27,9 +27,8 @@
#include "batch.h"
#include <inttypes.h>
namespace OHOS{
namespace MiscServices{
namespace OHOS {
namespace MiscServices {
class TimerManager : public ITimerManager {
public:
static std::shared_ptr<TimerManager> Create();
@@ -21,7 +21,6 @@
namespace OHOS {
namespace MiscServices {
struct TimerEntry {
uint64_t id;
int type;
@@ -57,8 +56,8 @@ public:
virtual bool StopTimer (uint64_t timerNumber) = 0;
virtual bool DestroyTimer (uint64_t timerNumber) = 0;
virtual ~ITimerManager () = default;
};// ITimerManager
}// MiscService
}// OHOS
}; // ITimerManager
} // MiscService
} // OHOS
#endif
+21 -21
View File
@@ -18,7 +18,6 @@
namespace OHOS {
namespace MiscServices {
const auto TYPE_NONWAKEUP_MASK = 0x1;
Batch::Batch ()
@@ -43,11 +42,11 @@ size_t Batch::Size () const
std::shared_ptr<TimerInfo> Batch::Get (size_t index) const
{
return index >= alarms_.size () ? nullptr : alarms_.at (index);
return (index >= alarms_.size()) ? nullptr : alarms_.at(index);
}
bool Batch::CanHold (std::chrono::steady_clock::time_point whenElapsed,
std::chrono::steady_clock::time_point maxWhen) const
std::chrono::steady_clock::time_point maxWhen) const
{
return (end_ > whenElapsed) && (start_ <= maxWhen);
}
@@ -55,12 +54,13 @@ bool Batch::CanHold (std::chrono::steady_clock::time_point whenElapsed,
bool Batch::Add (const std::shared_ptr<TimerInfo> &alarm)
{
bool new_start = false;
auto it = std::upper_bound (alarms_.begin (), alarms_.end (), alarm,
[] (const std::shared_ptr<TimerInfo> &first, const std::shared_ptr<TimerInfo> &second)
{
return first->whenElapsed < second->whenElapsed;
});
alarms_.insert (it, alarm); //根据Alarm.when_elapsed从小到大排列
auto it = std::upper_bound(alarms_.begin(),
alarms_.end(),
alarm,
[] (const std::shared_ptr<TimerInfo> &first, const std::shared_ptr<TimerInfo> &second) {
return first->whenElapsed < second->whenElapsed;
});
alarms_.insert (it, alarm); // 根据Alarm.when_elapsed从小到大排列
if (alarm->whenElapsed > start_) {
start_ = alarm->whenElapsed;
@@ -68,7 +68,7 @@ bool Batch::Add (const std::shared_ptr<TimerInfo> &alarm)
}
if (alarm->maxWhenElapsed < end_) {
end_ = alarm->maxWhenElapsed;
end_ = alarm->maxWhenElapsed;
}
flags_ |= alarm->flags;
@@ -77,7 +77,7 @@ bool Batch::Add (const std::shared_ptr<TimerInfo> &alarm)
bool Batch::Remove (const TimerInfo &alarm)
{
return Remove ([alarm] (const TimerInfo &a){ return a == alarm; });
return Remove ([alarm] (const TimerInfo &a) { return a == alarm; });
}
bool Batch::Remove (std::function<bool (const TimerInfo &)> predicate)
@@ -89,7 +89,7 @@ bool Batch::Remove (std::function<bool (const TimerInfo &)> predicate)
uint32_t newFlags = 0;
for (auto it = alarms_.begin (); it != alarms_.end ();) {
auto alarm = *it;
TIME_HILOGD(TIME_MODULE_SERVICE, "looper");
TIME_HILOGD(TIME_MODULE_SERVICE, "looper");
if (predicate (*alarm)) {
TIME_HILOGD(TIME_MODULE_SERVICE, "erase");
it = alarms_.erase(it);
@@ -111,23 +111,24 @@ bool Batch::Remove (std::function<bool (const TimerInfo &)> predicate)
end_ = newEnd;
flags_ = newFlags;
}
return didRemove;
return didRemove;
}
bool Batch::HasPackage (const std::string &package_name)
{
return std::find_if (alarms_.begin (), alarms_.end (),
[package_name] (const std::shared_ptr<TimerInfo> &alarm)
{ return alarm->Matches (package_name); }) != alarms_.end ();
return std::find_if (alarms_.begin(),
alarms_.end(),
[package_name] (const std::shared_ptr<TimerInfo> &alarm) {
return alarm->Matches (package_name);
}) != alarms_.end();
}
bool Batch::HasWakeups () const
{
return std::any_of (alarms_.begin (), alarms_.begin (),
[] (const std::shared_ptr<TimerInfo> &item)
{
return (static_cast<uint32_t>(item->type) & TYPE_NONWAKEUP_MASK) == 0;
});
[] (const std::shared_ptr<TimerInfo> &item) {
return (static_cast<uint32_t>(item->type) & TYPE_NONWAKEUP_MASK) == 0;
});
}
std::chrono::steady_clock::time_point Batch::GetStart () const
@@ -144,6 +145,5 @@ uint32_t Batch::GetFlags () const
{
return flags_;
}
} // MiscServices
} // OHOS
+44 -44
View File
@@ -29,56 +29,57 @@
namespace OHOS {
namespace MiscServices {
static constexpr int ALARM_TIME_CHANGE_MASK = 1 << 16;
namespace {
static const uint32_t ALARM_TIME_CHANGE_MASK = 1 << 16;
static const clockid_t alarm_to_clock_id[N_TIMER_FDS] = {
CLOCK_REALTIME_ALARM,
CLOCK_REALTIME,
CLOCK_BOOTTIME_ALARM,
CLOCK_BOOTTIME,
CLOCK_MONOTONIC,
CLOCK_REALTIME,
CLOCK_REALTIME_ALARM,
CLOCK_REALTIME,
CLOCK_BOOTTIME_ALARM,
CLOCK_BOOTTIME,
CLOCK_MONOTONIC,
CLOCK_REALTIME,
};
}
std::shared_ptr<TimerHandler> TimerHandler::Create()
{
int epollfd;
TimerFds fds;
epollfd = epoll_create (fds.size ());
epollfd = epoll_create(fds.size());
if (epollfd < 0) {
TIME_HILOGE(TIME_MODULE_SERVICE, "epoll_create %{public}d failed: %{public}s", static_cast<int>(fds.size()), strerror (errno));
return nullptr;
TIME_HILOGE(TIME_MODULE_SERVICE, "epoll_create %{public}d failed: %{public}s",
static_cast<int>(fds.size()), strerror(errno));
return nullptr;
}
for (size_t i = 0; i < fds.size (); i++) {
fds[i] = timerfd_create (alarm_to_clock_id[i], 0);
for(size_t i = 0; i < fds.size(); i++) {
fds[i] = timerfd_create(alarm_to_clock_id[i], 0);
if (fds[i] < 0) {
TIME_HILOGE(TIME_MODULE_SERVICE, "timerfd_create %{public}d failed: %{public}s", static_cast<int>(i), strerror (errno));
close (epollfd);
for (size_t j = 0; j < i; j++) {
close (fds[j]);
TIME_HILOGE(TIME_MODULE_SERVICE, "timerfd_create %{public}d failed: %{public}s",
static_cast<int>(i), strerror(errno));
close(epollfd);
for(size_t j = 0; j < i; j++) {
close(fds[j]);
}
return nullptr;
}
}
auto handler = std::shared_ptr<TimerHandler> (new TimerHandler (fds, epollfd));
for (size_t i = 0; i < fds.size (); i++) {
epoll_event event{};
std::shared_ptr<TimerHandler> handler = std::shared_ptr<TimerHandler>(new TimerHandler(fds, epollfd));
for(size_t i = 0; i < fds.size(); i++) {
epoll_event event {};
event.events = EPOLLIN | EPOLLWAKEUP;
event.data.u32 = i;
int err = epoll_ctl (epollfd, EPOLL_CTL_ADD, fds[i], &event);
int err = epoll_ctl(epollfd, EPOLL_CTL_ADD, fds[i], &event);
if (err < 0) {
TIME_HILOGE(TIME_MODULE_SERVICE, "epoll_ctl(EPOLL_CTL_ADD) failed: %{public}s", strerror (errno));
TIME_HILOGE(TIME_MODULE_SERVICE, "epoll_ctl(EPOLL_CTL_ADD) failed: %{public}s", strerror(errno));
return nullptr;
}
}
itimerspec spec{};
itimerspec spec {};
int err = timerfd_settime (fds[ALARM_TYPE_COUNT], TFD_TIMER_ABSTIME | TFD_TIMER_CANCEL_ON_SET, &spec, nullptr);
int err = timerfd_settime(fds[ALARM_TYPE_COUNT], TFD_TIMER_ABSTIME | TFD_TIMER_CANCEL_ON_SET, &spec, nullptr);
if (err < 0) {
TIME_HILOGE(TIME_MODULE_SERVICE, "timerfd_settime() failed: %{public}s", strerror(errno));
return nullptr;
@@ -87,21 +88,21 @@ std::shared_ptr<TimerHandler> TimerHandler::Create()
return handler;
}
TimerHandler::TimerHandler (const TimerFds &fds, int epollfd)
: fds_{fds}, epollFd_{epollfd}
TimerHandler::TimerHandler(const TimerFds &fds, int epollfd)
: fds_ {fds}, epollFd_ {epollfd}
{
}
TimerHandler::~TimerHandler()
{
for (auto fd : fds_) {
epoll_ctl (epollFd_, EPOLL_CTL_DEL, fd, nullptr);
close (fd);
for(auto fd : fds_) {
epoll_ctl(epollFd_, EPOLL_CTL_DEL, fd, nullptr);
close(fd);
}
close (epollFd_);
close(epollFd_);
}
int TimerHandler::Set (uint32_t type, std::chrono::nanoseconds when)
int TimerHandler::Set(uint32_t type, std::chrono::nanoseconds when)
{
TIME_HILOGI(TIME_MODULE_SERVICE, "type= %{public}d, when= %{public}lld", type, when.count());
if (static_cast<size_t>(type) > ALARM_TYPE_COUNT) {
@@ -109,26 +110,26 @@ int TimerHandler::Set (uint32_t type, std::chrono::nanoseconds when)
return -1;
}
auto second = std::chrono::duration_cast<std::chrono::seconds> (when);
timespec ts { second.count (), (when - second).count()};
itimerspec spec{timespec{}, ts};
return timerfd_settime (fds_[type], TFD_TIMER_ABSTIME, &spec, nullptr);
auto second = std::chrono::duration_cast<std::chrono::seconds>(when);
timespec ts { second.count(),(when - second).count()};
itimerspec spec {timespec {}, ts};
return timerfd_settime(fds_[type], TFD_TIMER_ABSTIME, &spec, nullptr);
}
int TimerHandler::WaitForAlarm()
uint32_t TimerHandler::WaitForAlarm()
{
epoll_event events[N_TIMER_FDS];
int nevents = epoll_wait (epollFd_, events, N_TIMER_FDS, -1);
if (nevents < 0){
int nevents = epoll_wait(epollFd_, events, N_TIMER_FDS, -1);
if (nevents < 0) {
return nevents;
}
int result = 0;
for (int i = 0; i < nevents; i++) {
uint32_t result = 0;
for(int i = 0; i < nevents; i++) {
uint32_t alarm_idx = events[i].data.u32;
uint64_t unused;
ssize_t err = read (fds_[alarm_idx], &unused, sizeof (unused));
ssize_t err = read(fds_[alarm_idx], &unused, sizeof(unused));
if (err < 0) {
if (alarm_idx == ALARM_TYPE_COUNT && errno == ECANCELED) {
result |= ALARM_TIME_CHANGE_MASK;
@@ -141,6 +142,5 @@ int TimerHandler::WaitForAlarm()
}
return result;
}
} // MiscServices
} // OHOS
+26 -26
View File
@@ -17,40 +17,40 @@
namespace OHOS {
namespace MiscServices {
bool TimerInfo::operator== (const TimerInfo &other) const{
bool TimerInfo::operator== (const TimerInfo &other) const
{
return this->id == other.id;
}
bool TimerInfo::Matches (const std::string &packageName) const{
bool TimerInfo::Matches (const std::string &packageName) const
{
return false;
}
TimerInfo::TimerInfo (uint64_t _id, int _type,
std::chrono::milliseconds _when,
std::chrono::steady_clock::time_point _whenElapsed,
std::chrono::milliseconds _windowLength,
std::chrono::steady_clock::time_point _maxWhen,
std::chrono::milliseconds _interval,
std::function<void (const uint64_t)> _callback,
uint32_t _flags,
uint64_t _uid)
: id{_id},
type{_type},
origWhen{_when},
wakeup{_type == ITimerManager::ELAPSED_REALTIME_WAKEUP || _type == ITimerManager::RTC_WAKEUP},
callback{std::move (_callback)},
flags{_flags},
uid{_uid},
when{_when},
windowLength{_windowLength},
whenElapsed{_whenElapsed},
maxWhenElapsed{_maxWhen},
expectedWhenElapsed{_whenElapsed},
expectedMaxWhenElapsed{_maxWhen},
repeatInterval{_interval}
std::chrono::milliseconds _when,
std::chrono::steady_clock::time_point _whenElapsed,
std::chrono::milliseconds _windowLength,
std::chrono::steady_clock::time_point _maxWhen,
std::chrono::milliseconds _interval,
std::function<void (const uint64_t)> _callback,
uint32_t _flags,
uint64_t _uid)
: id {_id},
type {_type},
origWhen {_when},
wakeup {_type == ITimerManager::ELAPSED_REALTIME_WAKEUP || _type == ITimerManager::RTC_WAKEUP},
callback {std::move (_callback)},
flags {_flags},
uid {_uid},
when {_when},
windowLength {_windowLength},
whenElapsed {_whenElapsed},
maxWhenElapsed {_maxWhen},
expectedWhenElapsed {_whenElapsed},
expectedMaxWhenElapsed {_maxWhen},
repeatInterval {_interval}
{
}
} // MiscServices
} // OHOS
+130 -88
View File
@@ -17,14 +17,16 @@
#include <utility>
#include <vector>
#include <algorithm>
#include <time.h>
#include <ctime>
#include <iostream>
namespace OHOS{
namespace MiscServices{
namespace OHOS {
namespace MiscServices {
using namespace std::chrono;
static int TIME_CHANGED_MASK = 1 << 16;
static int TIME_CHANGED_BITS = 16;
static uint32_t TIME_CHANGED_MASK = 1 << TIME_CHANGED_BITS;
static int ONE_THOUSAND = 1000;
const auto MIN_FUTURITY = seconds(5);
const auto MIN_INTERVAL = seconds(5);
const auto MAX_INTERVAL = hours(24 * 365);
@@ -34,40 +36,55 @@ const auto MIN_FUZZABLE_INTERVAL = milliseconds(10000);
extern bool AddBatchLocked(std::vector<std::shared_ptr<Batch>> &list, const std::shared_ptr<Batch> &batch);
extern steady_clock::time_point MaxTriggerTime(steady_clock::time_point now,
steady_clock::time_point triggerAtTime,
milliseconds interval);
steady_clock::time_point triggerAtTime,
milliseconds interval);
std::shared_ptr<TimerManager> TimerManager::Create()
{
auto impl = TimerHandler::Create();
if (impl == nullptr){
TIME_HILOGE(TIME_MODULE_SERVICE,"Create Timer handle failed.");
if (impl == nullptr) {
TIME_HILOGE(TIME_MODULE_SERVICE, "Create Timer handle failed.");
return nullptr;
}
return std::shared_ptr<TimerManager>(new TimerManager(impl));
}
TimerManager::TimerManager(std::shared_ptr<TimerHandler> impl)
: random_{static_cast<uint64_t>(time(nullptr))},
runFlag_{false},
handler_{std::move(impl)},
lastTimeChangeClockTime_{system_clock::time_point::min()},
lastTimeChangeRealtime_{steady_clock::time_point::min()}
: random_ {static_cast<uint64_t>(time(nullptr))},
runFlag_ {false},
handler_ {std::move(impl)},
lastTimeChangeClockTime_ {system_clock::time_point::min()},
lastTimeChangeRealtime_ {steady_clock::time_point::min()}
{
runFlag_ = true;
alarmThread_.reset(new std::thread(&TimerManager::TimerLooper, this));
}
uint64_t TimerManager::CreateTimer(int type, uint64_t windowLength, uint64_t interval, int flag,
std::function<void (const uint64_t)> callback, uint64_t uid)
uint64_t TimerManager::CreateTimer(int type,
uint64_t windowLength,
uint64_t interval,
int flag,
std::function<void (const uint64_t)> callback,
uint64_t uid)
{
TIME_HILOGI(TIME_MODULE_SERVICE,"Create timer: %{public}d windowLength:%{public}" PRId64 "interval:%{public}" PRId64 "flag:%{public}d", type, windowLength, interval, flag);
TIME_HILOGI(TIME_MODULE_SERVICE,
"Create timer: %{public}d windowLength:%{public}" PRId64 "interval:%{public}" PRId64 "flag:%{public}d",
type,
windowLength,
interval,
flag);
uint64_t timerNumber = 0;
while (timerNumber == 0){
while (timerNumber == 0) {
timerNumber = random_();
}
auto timerInfo = std::make_shared<TimerEntry>(TimerEntry{timerNumber, type,windowLength,
interval, flag, std::move(callback), uid});
auto timerInfo = std::make_shared<TimerEntry>(TimerEntry {
timerNumber,
type,
windowLength,
interval,
flag,
std::move(callback),
uid});
std::lock_guard<std::mutex> lock(entryMapMutex_);
timerEntryMap_.insert(std::make_pair(timerNumber, timerInfo));
return timerNumber;
@@ -77,21 +94,21 @@ bool TimerManager::StartTimer(uint64_t timerNumber, uint64_t triggerTime)
{
std::lock_guard<std::mutex> lock(entryMapMutex_);
auto it = timerEntryMap_.find(timerNumber);
if (it == timerEntryMap_.end()){
TIME_HILOGE(TIME_MODULE_SERVICE,"Timer id not found: %{public}" PRId64 "", timerNumber);
if (it == timerEntryMap_.end()) {
TIME_HILOGE(TIME_MODULE_SERVICE, "Timer id not found: %{public}" PRId64 "", timerNumber);
return false;
}
TIME_HILOGI(TIME_MODULE_SERVICE,"Start timer : %{public}" PRId64 "", timerNumber);
TIME_HILOGI(TIME_MODULE_SERVICE,"TriggerTime : %{public}" PRId64 "", triggerTime);
TIME_HILOGI(TIME_MODULE_SERVICE, "Start timer : %{public}" PRId64 "", timerNumber);
TIME_HILOGI(TIME_MODULE_SERVICE, "TriggerTime : %{public}" PRId64 "", triggerTime);
auto timerInfo = it->second;
SetHandler(timerInfo->id,
timerInfo->type,
triggerTime,
timerInfo->windowLength,
timerInfo->interval,
timerInfo->flag,
timerInfo->callback,
timerInfo->uid);
timerInfo->type,
triggerTime,
timerInfo->windowLength,
timerInfo->interval,
timerInfo->flag,
timerInfo->callback,
timerInfo->uid);
return true;
}
@@ -100,7 +117,7 @@ bool TimerManager::StopTimer(uint64_t timerNumber)
TIME_HILOGD(TIME_MODULE_SERVICE, "start.");
std::lock_guard<std::mutex> lock(entryMapMutex_);
auto it = timerEntryMap_.find(timerNumber);
if (it == timerEntryMap_.end()){
if (it == timerEntryMap_.end()) {
TIME_HILOGD(TIME_MODULE_SERVICE, "end.");
return false;
}
@@ -114,7 +131,7 @@ bool TimerManager::DestroyTimer(uint64_t timerNumber)
TIME_HILOGD(TIME_MODULE_SERVICE, "start id: %{public}" PRId64 "", timerNumber);
std::lock_guard<std::mutex> lock(entryMapMutex_);
auto it = timerEntryMap_.find(timerNumber);
if (it == timerEntryMap_.end()){
if (it == timerEntryMap_.end()) {
TIME_HILOGD(TIME_MODULE_SERVICE, "end.");
return false;
}
@@ -124,35 +141,42 @@ bool TimerManager::DestroyTimer(uint64_t timerNumber)
return true;
}
void TimerManager::SetHandler(uint64_t id, int type, uint64_t triggerAtTime, uint64_t windowLength, uint64_t interval, int flag,
std::function<void (const uint64_t)> callback, uint64_t uid)
void TimerManager::SetHandler(uint64_t id,
int type,
uint64_t triggerAtTime,
uint64_t windowLength,
uint64_t interval,
int flag,
std::function<void (const uint64_t)> callback,
uint64_t uid)
{
TIME_HILOGI(TIME_MODULE_SERVICE, "start id: %{public}" PRId64 "",id);
TIME_HILOGI(TIME_MODULE_SERVICE, "start type : %{public}d windowLength:%{public}" PRId64 "interval:%{public}" PRId64 "flag:%{public}d", type, windowLength, interval, flag);
TIME_HILOGI(TIME_MODULE_SERVICE,
"start type : %{public}d windowLength:%{public}" PRId64 "interval:%{public}" PRId64 "flag:%{public}d",
type, windowLength, interval, flag);
auto windowLengthDuration = milliseconds(windowLength);
if (windowLengthDuration > INTERVAL_HALF_DAY){
if (windowLengthDuration > INTERVAL_HALF_DAY) {
windowLengthDuration = INTERVAL_HOUR;
}
}
auto intervalDuration = milliseconds(interval);
if (intervalDuration > milliseconds::zero() && intervalDuration < MIN_INTERVAL){
if (intervalDuration > milliseconds::zero() && intervalDuration < MIN_INTERVAL) {
intervalDuration = MIN_INTERVAL;
}else if (intervalDuration > MAX_INTERVAL){
}else if (intervalDuration > MAX_INTERVAL) {
intervalDuration = MAX_INTERVAL;
}
if (triggerAtTime < 0){
if (triggerAtTime < 0) {
triggerAtTime = 0;
}
auto nowElapsed = steady_clock::now();
auto nominalTrigger = ConvertToElapsed(milliseconds(triggerAtTime), type);
auto minTrigger = nowElapsed + MIN_FUTURITY;
auto triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
steady_clock::time_point maxElapsed;
if (windowLengthDuration == milliseconds::zero()){
if (windowLengthDuration == milliseconds::zero()) {
maxElapsed = triggerElapsed;
} else if (windowLengthDuration < milliseconds::zero()){
} else if (windowLengthDuration < milliseconds::zero()) {
maxElapsed = MaxTriggerTime(nominalTrigger, triggerElapsed, intervalDuration);
windowLengthDuration = duration_cast<milliseconds>(maxElapsed - triggerElapsed);
} else {
@@ -161,8 +185,17 @@ void TimerManager::SetHandler(uint64_t id, int type, uint64_t triggerAtTime, uin
TIME_HILOGI(TIME_MODULE_SERVICE, "Try get lock");
std::lock_guard<std::mutex> lockGuard(mutex_);
TIME_HILOGI(TIME_MODULE_SERVICE, "Lock guard");
SetHandlerLocked(id,type, milliseconds(triggerAtTime),triggerElapsed, windowLengthDuration, maxElapsed,
intervalDuration, std::move(callback), static_cast<uint32_t>(flag), true, uid);
SetHandlerLocked(id,
type,
milliseconds(triggerAtTime),
triggerElapsed,
windowLengthDuration,
maxElapsed,
intervalDuration,
std::move(callback),
static_cast<uint32_t>(flag),
true,
uid);
}
void TimerManager::SetHandlerLocked(uint64_t id, int type,
@@ -201,7 +234,7 @@ void TimerManager::RemoveLocked(uint64_t id)
bool didRemove = false;
for (auto it = alarmBatches_.begin(); it != alarmBatches_.end();) {
auto batch = *it;
didRemove |= batch->Remove(whichAlarms);
didRemove = batch->Remove(whichAlarms);
if (batch->Size() == 0) {
TIME_HILOGD(TIME_MODULE_SERVICE, "erase");
it = alarmBatches_.erase(it);
@@ -234,22 +267,26 @@ void TimerManager::ReBatchAllTimers()
TIME_HILOGI(TIME_MODULE_SERVICE, "end");
}
void TimerManager::ReBatchAllTimersLocked(bool doValidate){
void TimerManager::ReBatchAllTimersLocked(bool doValidate)
{
TIME_HILOGI(TIME_MODULE_SERVICE, "start");
auto oldSet = alarmBatches_;
alarmBatches_.clear();
auto nowElapsed = steady_clock::now();
for (const auto &batch : oldSet){
for (const auto &batch : oldSet) {
auto n = batch->Size();
for (unsigned int i = 0; i < n; i++){
ReAddTimerLocked(batch->Get(i), nowElapsed, doValidate);
for (unsigned int i = 0; i < n; i++) {
ReAddTimerLocked(batch->Get(i), nowElapsed, doValidate);
}
}
RescheduleKernelTimerLocked();
TIME_HILOGI(TIME_MODULE_SERVICE, "end");
}
void TimerManager::ReAddTimerLocked(std::shared_ptr<TimerInfo> timer, std::chrono::steady_clock::time_point nowElapsed, bool doValidate){
void TimerManager::ReAddTimerLocked(std::shared_ptr<TimerInfo> timer,
std::chrono::steady_clock::time_point nowElapsed,
bool doValidate)
{
TIME_HILOGI(TIME_MODULE_SERVICE, "start");
timer->when = timer->origWhen;
auto whenElapsed = ConvertToElapsed(timer->when, timer->type);
@@ -257,8 +294,8 @@ void TimerManager::ReAddTimerLocked(std::shared_ptr<TimerInfo> timer, std::chron
if (timer->windowLength == milliseconds::zero()) {
maxElapsed = whenElapsed;
} else {
maxElapsed = (timer->windowLength > milliseconds::zero()) ? whenElapsed + timer->windowLength
: MaxTriggerTime(nowElapsed, whenElapsed, timer->repeatInterval);
maxElapsed = (timer->windowLength > milliseconds::zero()) ? (whenElapsed + timer->windowLength)
: MaxTriggerTime(nowElapsed, whenElapsed, timer->repeatInterval);
}
timer->whenElapsed = whenElapsed;
timer->maxWhenElapsed = maxElapsed;
@@ -269,7 +306,7 @@ void TimerManager::ReAddTimerLocked(std::shared_ptr<TimerInfo> timer, std::chron
std::chrono::steady_clock::time_point TimerManager::ConvertToElapsed(std::chrono::milliseconds when, int type)
{
TIME_HILOGI(TIME_MODULE_SERVICE, "start");
if (type == RTC || type == RTC_WAKEUP){
if (type == RTC || type == RTC_WAKEUP) {
auto offset = when - system_clock::now().time_since_epoch();
return steady_clock::now() + offset;
}
@@ -280,12 +317,12 @@ std::chrono::steady_clock::time_point TimerManager::ConvertToElapsed(std::chrono
void TimerManager::TimerLooper()
{
TIME_HILOGI(TIME_MODULE_SERVICE,"Start timer wait loop");
TIME_HILOGI(TIME_MODULE_SERVICE, "Start timer wait loop");
std::vector<std::shared_ptr<TimerInfo>> triggerList;
while (runFlag_) {
int result = 0;
uint32_t result = 0;
do {
result = handler_->WaitForAlarm();
result = handler_->WaitForAlarm();
} while (result < 0 && errno == EINTR);
TIME_HILOGI(TIME_MODULE_SERVICE, "result= %{public}d", result);
@@ -305,8 +342,8 @@ void TimerManager::TimerLooper()
if (lastTimeChangeClockTime == system_clock::time_point::min()
|| nowRtc < (expectedClockTime - milliseconds(1000))
|| nowRtc > (expectedClockTime + milliseconds(1000))) {
|| nowRtc < (expectedClockTime - milliseconds(ONE_THOUSAND))
|| nowRtc > (expectedClockTime + milliseconds(ONE_THOUSAND))) {
TIME_HILOGI(TIME_MODULE_SERVICE, "Time changed notification from kernel; rebatching");
ReBatchAllTimers();
lastTimeChangeClockTime_ = nowRtc;
@@ -337,29 +374,33 @@ TimerManager::~TimerManager()
}
bool TimerManager::TriggerTimersLocked(std::vector<std::shared_ptr<TimerInfo>> &triggerList,
std::chrono::steady_clock::time_point nowElapsed)
std::chrono::steady_clock::time_point nowElapsed)
{
TIME_HILOGI(TIME_MODULE_SERVICE, "alarmBatches_.size= %{public}d", static_cast<int>(alarmBatches_.size()));
bool hasWakeup = false;
while (!alarmBatches_.empty()) {
auto batch = alarmBatches_.at(0);
TIME_HILOGI(TIME_MODULE_SERVICE, "batch->GetStart()= %{public}lld", time_point_cast<nanoseconds>(batch->GetStart()).time_since_epoch().count());
TIME_HILOGI(TIME_MODULE_SERVICE, "nowElapsed= %{public}lld", time_point_cast<nanoseconds>(nowElapsed).time_since_epoch().count());
TIME_HILOGI(TIME_MODULE_SERVICE, "batch->GetStart()= %{public}lld",
time_point_cast<nanoseconds>(batch->GetStart()).time_since_epoch().count());
TIME_HILOGI(TIME_MODULE_SERVICE, "nowElapsed= %{public}lld",
time_point_cast<nanoseconds>(nowElapsed).time_since_epoch().count());
if (batch->GetStart() > nowElapsed) {
TIME_HILOGI(TIME_MODULE_SERVICE, "break alarmBatches_.size= %{public}d", static_cast<int>(alarmBatches_.size()));
TIME_HILOGI(TIME_MODULE_SERVICE, "break alarmBatches_.size= %{public}d",
static_cast<int>(alarmBatches_.size()));
break;
}
alarmBatches_.erase(alarmBatches_.begin());
TIME_HILOGI(TIME_MODULE_SERVICE, "after erase alarmBatches_.size= %{public}d", static_cast<int>(alarmBatches_.size()));
TIME_HILOGI(TIME_MODULE_SERVICE, "after erase alarmBatches_.size= %{public}d",
static_cast<int>(alarmBatches_.size()));
const auto n = batch->Size();
for (unsigned int i = 0; i < n; ++i) {
auto alarm = batch->Get(i);
alarm->count = 1;
triggerList.push_back(alarm);
if (alarm->repeatInterval > milliseconds::zero()) {
alarm->count += duration_cast<milliseconds>(nowElapsed - alarm->expectedWhenElapsed) / alarm->repeatInterval;
alarm->count += duration_cast<milliseconds>(nowElapsed -
alarm->expectedWhenElapsed) / alarm->repeatInterval;
auto delta = alarm->count * alarm->repeatInterval;
auto nextElapsed = alarm->whenElapsed + delta;
SetHandlerLocked(alarm->id, alarm->type, alarm->when + delta, nextElapsed, alarm->windowLength,
@@ -371,9 +412,11 @@ bool TimerManager::TriggerTimersLocked(std::vector<std::shared_ptr<TimerInfo>> &
}
}
}
std::sort(triggerList.begin(), triggerList.end(),
[](const std::shared_ptr<TimerInfo> &l,
const std::shared_ptr<TimerInfo> &r){return l->whenElapsed < r->whenElapsed;});
std::sort(triggerList.begin(),
triggerList.end(),
[] (const std::shared_ptr<TimerInfo> &l, const std::shared_ptr<TimerInfo> &r) {
return l->whenElapsed < r->whenElapsed;
});
return hasWakeup;
}
@@ -387,10 +430,10 @@ void TimerManager::RescheduleKernelTimerLocked()
auto firstWakeup = FindFirstWakeupBatchLocked();
auto firstBatch = alarmBatches_.front();
if (firstWakeup != nullptr) {
SetLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup->GetStart().time_since_epoch());
SetLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup->GetStart().time_since_epoch());
}
if (firstBatch != firstWakeup) {
nextNonWakeup = firstBatch->GetStart();
nextNonWakeup = firstBatch->GetStart();
}
}
@@ -402,12 +445,11 @@ void TimerManager::RescheduleKernelTimerLocked()
std::shared_ptr<Batch> TimerManager::FindFirstWakeupBatchLocked()
{
auto it = std::find_if(alarmBatches_.begin(),alarmBatches_.end(),
[](const std::shared_ptr<Batch> &batch)
{
return batch->HasWakeups();
});
return it != alarmBatches_.end() ? *it : nullptr;
auto it = std::find_if (alarmBatches_.begin(),alarmBatches_.end(),
[](const std::shared_ptr<Batch> &batch) {
return batch->HasWakeups();
});
return (it != alarmBatches_.end()) ? *it : nullptr;
}
void TimerManager::SetLocked(int type, std::chrono::nanoseconds when)
@@ -437,7 +479,7 @@ void TimerManager::InsertAndBatchTimerLocked(std::shared_ptr<TimerInfo> alarm)
}
int64_t TimerManager::AttemptCoalesceLocked(std::chrono::steady_clock::time_point whenElapsed,
std::chrono::steady_clock::time_point maxWhen)
std::chrono::steady_clock::time_point maxWhen)
{
TIME_HILOGI(TIME_MODULE_SERVICE, "start");
int64_t i = 0;
@@ -445,13 +487,13 @@ int64_t TimerManager::AttemptCoalesceLocked(std::chrono::steady_clock::time_poin
if ((item->GetFlags() & static_cast<uint32_t>(STANDALONE)) == 0 && item->CanHold(whenElapsed, maxWhen)) {
return i;
}
// ++i;
}
return -1;
}
void TimerManager::DeliverTimersLocked(const std::vector<std::shared_ptr<TimerInfo>> &triggerList,
std::chrono::steady_clock::time_point nowElapsed){
std::chrono::steady_clock::time_point nowElapsed)
{
TIME_HILOGI(TIME_MODULE_SERVICE, "start");
for (const auto &alarm : triggerList) {
if (alarm->callback) {
@@ -466,22 +508,22 @@ bool AddBatchLocked(std::vector<std::shared_ptr<Batch>> &list, const std::shared
{
TIME_HILOGI(TIME_MODULE_SERVICE, "start");
auto it = std::upper_bound(list.begin(), list.end(), newBatch,
[](const std::shared_ptr<Batch> &first, const std::shared_ptr<Batch> &second)
{
return first->GetStart() < second->GetStart();
});
[](const std::shared_ptr<Batch> &first, const std::shared_ptr<Batch> &second) {
return first->GetStart() < second->GetStart();
});
list.insert(it, newBatch);
TIME_HILOGI(TIME_MODULE_SERVICE, "end");
return it == list.begin();
}
steady_clock::time_point MaxTriggerTime(steady_clock::time_point now, steady_clock::time_point triggerAtTime, milliseconds interval){
milliseconds futurity = (interval == milliseconds::zero()) ? duration_cast<milliseconds>(triggerAtTime - now) : interval;
steady_clock::time_point MaxTriggerTime(steady_clock::time_point now, steady_clock::time_point triggerAtTime, milliseconds interval)
{
milliseconds futurity = (interval == milliseconds::zero()) ?
(duration_cast<milliseconds>(triggerAtTime - now)) : interval;
if (futurity < MIN_FUZZABLE_INTERVAL) {
futurity = milliseconds::zero();
}
return triggerAtTime + milliseconds(static_cast<long>(0.75 * futurity.count()));
return triggerAtTime + milliseconds(static_cast<long>(0.75 * futurity.count()));
}
} // MiscServices
} // OHOS
+4 -6
View File
@@ -19,12 +19,10 @@
#define MOCK_PERMISSION_H
namespace OHOS {
namespace MiscServices {
namespace MockPermission{
namespace MockPermission {
bool VerifyPermission(const std::string& bundleName, const std::string& permissionName, int userId);
}
}
}
} // MockPermission
} // MiscServices
} // OHOS
#endif // MOCK_PERMISSION_H
+1 -3
View File
@@ -17,13 +17,11 @@
namespace OHOS {
namespace MiscServices {
namespace MockPermission{
namespace MockPermission {
bool VerifyPermission(const std::string &bundleName, const std::string &permissionName, int userId)
{
return true;
}
} // OHOS
} // MiscServices
} // MockPermission
-6
View File
@@ -19,21 +19,16 @@
#include "errors.h"
#include "time_hilog_wreapper.h"
namespace OHOS {
namespace MiscServices {
#define TIME_SERVICE_NAME "TimeService"
enum TimeModule {
TIME_MODULE_SERVICE_ID = 0x04,
};
// time error offset, used only in this file.
constexpr ErrCode TIME_ERR_OFFSET = ErrCodeOffset(SUBSYS_SMALLSERVICES, TIME_MODULE_SERVICE_ID);
enum TimeError {
E_TIME_OK = TIME_ERR_OFFSET,
E_TIME_SA_DIED,
@@ -47,7 +42,6 @@ enum TimeError {
E_TIME_NOT_FOUND,
E_TIME_NO_PERMISSION,
};
} // namespace MiscServices
} // namespace OHOS
#endif // SERVICES_INCLUDE_TIME_COMMON_H
@@ -20,7 +20,6 @@
namespace OHOS {
namespace MiscServices {
// param of log interface, such as TIME_HILOGF.
enum TimeSubModule {
TIME_MODULE_INNERKIT = 0,
@@ -57,7 +56,6 @@ static constexpr OHOS::HiviewDFX::HiLogLabel TIME_MODULE_LABEL[TIME_MODULE_BUTT]
{LOG_CORE, TIME_JS_NAPI, "TimeJSNAPI"},
};
#define __FILENAME__ (__builtin_strrchr(__FILE__, '/') ? __builtin_strrchr(__FILE__, '/') + 1 : __FILE__)
#define __FORMATED(fmt, ...) "[%{public}s] %{public}s# " fmt, __FILENAME__, __FUNCTION__, ##__VA_ARGS__
@@ -68,9 +66,6 @@ static constexpr OHOS::HiviewDFX::HiLogLabel TIME_MODULE_LABEL[TIME_MODULE_BUTT]
#define TIME_HILOGW(module, ...) (void)OHOS::HiviewDFX::HiLog::Warn(TIME_MODULE_LABEL[module], __FORMATED(__VA_ARGS__))
#define TIME_HILOGI(module, ...) (void)OHOS::HiviewDFX::HiLog::Info(TIME_MODULE_LABEL[module], __FORMATED(__VA_ARGS__))
#define TIME_HILOGD(module, ...) (void)OHOS::HiviewDFX::HiLog::Debug(TIME_MODULE_LABEL[module], __FORMATED(__VA_ARGS__))
} // namespace MiscServices
} // namespace OHOS
#endif // TIME_HILOG_WRAPPER_H
+3 -7
View File
@@ -22,25 +22,21 @@
#include "mock_permission.h"
#include "system_ability_definition.h"
#include "iservice_registry.h"
#include "refbase.h"
#include <singleton.h>
#include <mutex>
#include <string>
namespace OHOS {
namespace MiscServices {
class TimePermission : public RefBase{
class TimePermission {
DECLARE_DELAYED_SINGLETON(TimePermission)
public:
static sptr<TimePermission> GetInstance();
bool CheckSelfPermission(const std::string permName);
bool CheckCallingPermission(const int32_t uid, const std::string permName);
private:
TimePermission();
~TimePermission();
sptr<AppExecFwk::IBundleMgr> GetBundleManager();
static std::mutex instanceLock_;
static sptr<TimePermission> instance_;
static sptr<AppExecFwk::IBundleMgr> bundleMgrProxy_;
};
} // namespace MiscServices
-103
View File
@@ -1,103 +0,0 @@
/*
* Copyright (C) 2021 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 "rdb_errno.h"
#include "rdb_helper.h"
#include <mutex>
namespace OHOS {
namespace MiscServices {
using namespace OHOS::NativeRdb;
class TimeOpenCallback : public RdbOpenCallback {
public:
int OnCreate(RdbStore &rdbStore) override;
int OnUpgrade(RdbStore &rdbStore, int oldVersion, int newVersion) override;
static const std::string CREATE_TIMEZONE_DB;
};
std::string const TimeOpenCallback::CREATE_TIMEZONE_DB = std::string("CREATE TABLE IF NOT EXISTS timezone ")
+ std::string("(id INTEGER PRIMARY KEY AUTOINCREMENT, "
"timezoneId TEXT NOT NULL)");
int TimeOpenCallback::OnCreate(RdbStore &store)
{
return store.ExecuteSql(CREATE_TIMEZONE_DB);
}
int TimeOpenCallback::OnUpgrade(RdbStore &store, int oldVersion, int newVersion)
{
return E_OK;
}
bool InsertTimeZoneIdToRdb(const std::string timeZoneId){
const std::string dbPath_ = "/data/misc/zoneinfo/";
const std::string dbName_ = "systime.db";
RdbStoreConfig config(dbPath_+ dbName_);
TimeOpenCallback helper;
int errCode = E_OK;
auto store = RdbHelper::GetRdbStore(config, 1, helper, errCode);
if (store == nullptr){
return false;
}
int deletedRows;
store->Delete(deletedRows, "timezone", "id = 1");
int64_t id;
ValuesBucket values;
values.PutInt("id", 1);
values.PutString("timezoneId", timeZoneId);
auto ret = store->Insert(id, "timezone", values);
TIME_HILOGD(TIME_MODULE_SERVICE,"end.");
return ret == E_OK;
}
bool GetTimeZoneId(std::string &timeZoneId){
const std::string dbPath_ = "/data/misc/zoneinfo/";
const std::string dbName_ = "systime.db";
RdbStoreConfig config(dbPath_+ dbName_);
TimeOpenCallback helper;
int errCode = E_OK;
auto store = RdbHelper::GetRdbStore(config, 1, helper, errCode);
if (store == nullptr){
return false;
}
std::unique_ptr<ResultSet> resultSet = store->QuerySql("SELECT * FROM timezone");
if (resultSet == nullptr){
TIME_HILOGD(TIME_MODULE_SERVICE,"not found");
return false;
}
int columnIndex;
std::string strVal;
auto ret = resultSet->GoToFirstRow();
if (ret != E_OK){
return false;
}
ret = resultSet->GetColumnIndex("timezoneId", columnIndex);
if (ret != E_OK){
return false;
}
ret = resultSet->GetString(columnIndex, strVal);
if (ret != E_OK){
return false;
}
timeZoneId = strVal;
return E_OK;
}
}
}
+15 -31
View File
@@ -18,29 +18,13 @@
namespace OHOS {
namespace MiscServices {
std::mutex TimePermission::instanceLock_;
sptr<TimePermission> TimePermission::instance_;
namespace {
static const int UID_TO_USERID = 100000;
}
sptr<AppExecFwk::IBundleMgr> TimePermission::bundleMgrProxy_;
TimePermission::TimePermission()
{
}
TimePermission::~TimePermission()
{
}
sptr<TimePermission> TimePermission::GetInstance()
{
if (instance_ == nullptr){
std::lock_guard<std::mutex> autoLock(instanceLock_);
if (instance_ == nullptr) {
instance_ = new TimePermission;
}
}
return instance_;
}
TimePermission::TimePermission() {};
TimePermission::~TimePermission() {};
bool TimePermission::CheckSelfPermission(std::string permName)
{
@@ -49,24 +33,25 @@ bool TimePermission::CheckSelfPermission(std::string permName)
bool TimePermission::CheckCallingPermission(int32_t uid, std::string permName)
{
if (bundleMgrProxy_ == nullptr){
if (bundleMgrProxy_ == nullptr) {
bundleMgrProxy_ = GetBundleManager();
TIME_HILOGI(TIME_MODULE_COMMON,"get bundle mgr");
TIME_HILOGI(TIME_MODULE_COMMON, "get bundle mgr");
}
if (bundleMgrProxy_ == nullptr){
TIME_HILOGE(TIME_MODULE_COMMON,"redo get bundle mgr failed");
if (bundleMgrProxy_ == nullptr) {
TIME_HILOGE(TIME_MODULE_COMMON, "redo get bundle mgr failed");
return false;
}
std::string bundleName;
auto ret = bundleMgrProxy_->GetBundleNameForUid(uid, bundleName);
if (!ret){
TIME_HILOGE(TIME_MODULE_COMMON,"get bundle name failed");
if (!ret) {
TIME_HILOGE(TIME_MODULE_COMMON, "get bundle name failed");
// always true
return true;
}
auto userId = uid / 100000;
TIME_HILOGI(TIME_MODULE_COMMON,"VerifyPermission bundleName %{public}s, permission %{public}s", bundleName.c_str(), permName.c_str());
auto userId = uid / UID_TO_USERID;
TIME_HILOGI(TIME_MODULE_COMMON, "VerifyPermission bundleName %{public}s, permission %{public}s",
bundleName.c_str(), permName.c_str());
return MockPermission::VerifyPermission(bundleName, permName, userId);
}
@@ -78,11 +63,10 @@ sptr<AppExecFwk::IBundleMgr> TimePermission::GetBundleManager()
bundleMgrProxy_ =
iface_cast<AppExecFwk::IBundleMgr>(systemManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID));
} else {
TIME_HILOGE(TIME_MODULE_COMMON,"fail to get SAMGR");
TIME_HILOGE(TIME_MODULE_COMMON, "fail to get SAMGR");
}
}
return bundleMgrProxy_;
}
} // namespace MiscServices
} // namespace OHOS