diff --git a/BUILD.gn b/BUILD.gn index 06ad71c..d6e2f3f 100755 --- a/BUILD.gn +++ b/BUILD.gn @@ -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", ] } } diff --git a/README_zh.md b/README_zh.md index bdb45a9..22843b2 100755 --- a/README_zh.md +++ b/README_zh.md @@ -22,7 +22,7 @@ ├── etc # 组件包含的进程的配置文件 ├── figures # 构架图 ├── interfaces # 组件对外提供的接口代码 -├ └── innerkits # 服务间接口 +│ └── innerkits # 服务间接口 │ └── kits # 对应用提供的接口 ├── profile # 组件包含的系统服务的配置文件 └── services # 时间服务实现 diff --git a/etc/init/timeservice.cfg b/etc/init/timeservice.cfg index 3e6510e..befefef 100644 --- a/etc/init/timeservice.cfg +++ b/etc/init/timeservice.cfg @@ -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"] } ] } diff --git a/interfaces/innerkits/include/itimer_info.h b/interfaces/innerkits/include/itimer_info.h index 334a4e6..2c9372b 100644 --- a/interfaces/innerkits/include/itimer_info.h +++ b/interfaces/innerkits/include/itimer_info.h @@ -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 #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 wantAgent) = 0; - virtual void OnTrigger() = 0; + virtual void OnTrigger() = 0; }; } // MiscServices } // OHOS +#endif // I_TIMER_INFO_H \ No newline at end of file diff --git a/interfaces/innerkits/include/time_service_client.h b/interfaces/innerkits/include/time_service_client.h index c6fcb9b..e576ec2 100644 --- a/interfaces/innerkits/include/time_service_client.h +++ b/interfaces/innerkits/include/time_service_client.h @@ -20,29 +20,24 @@ #include "time_service_interface.h" #include "iremote_object.h" #include "timer_call_back.h" - #include 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 &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 GetInstance(); /** @@ -172,15 +167,12 @@ public: private: TimeServiceClient(); ~TimeServiceClient(); - - static sptr ConnectService(); static std::mutex instanceLock_; static sptr instance_; static sptr timeServiceProxy_; static sptr deathRecipient_; - }; } // MiscServices } // OHOS diff --git a/interfaces/kits/js/declaration/api/@ohos.systemTime.d.ts b/interfaces/kits/js/declaration/api/@ohos.systemTime.d.ts index 2daeebb..1d19a79 100644 --- a/interfaces/kits/js/declaration/api/@ohos.systemTime.d.ts +++ b/interfaces/kits/js/declaration/api/@ohos.systemTime.d.ts @@ -44,7 +44,6 @@ declare namespace systemTime { */ function setTimezone(timezone: string, callback: AsyncCallback): void; function setTimezone(timezone: string): Promise; - } export default systemTime; diff --git a/interfaces/kits/js/napi/system_time/include/js_systemtime.h b/interfaces/kits/js/napi/system_time/include/js_systemtime.h index ffae810..5160bd9 100644 --- a/interfaces/kits/js/napi/system_time/include/js_systemtime.h +++ b/interfaces/kits/js/napi/system_time/include/js_systemtime.h @@ -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 { diff --git a/interfaces/kits/js/napi/system_time/src/js_systemtime.cpp b/interfaces/kits/js/napi/system_time/src/js_systemtime.cpp index 92cd584..45b10b9 100644 --- a/interfaces/kits/js/napi/system_time/src/js_systemtime.cpp +++ b/interfaces/kits/js/napi/system_time/src/js_systemtime.cpp @@ -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 - 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; diff --git a/interfaces/kits/js/napi/system_timer/BUILD.gn b/interfaces/kits/js/napi/system_timer/BUILD.gn index b6c7431..adaa3d5 100644 --- a/interfaces/kits/js/napi/system_timer/BUILD.gn +++ b/interfaces/kits/js/napi/system_timer/BUILD.gn @@ -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", ] diff --git a/interfaces/kits/js/napi/system_timer/include/system_timer.h b/interfaces/kits/js/napi/system_timer/include/system_timer.h index e6ec446..ef4ec4a 100644 --- a/interfaces/kits/js/napi/system_timer/include/system_timer.h +++ b/interfaces/kits/js/napi/system_timer/include/system_timer.h @@ -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 \ No newline at end of file diff --git a/interfaces/kits/js/napi/system_timer/include/timer_init.h b/interfaces/kits/js/napi/system_timer/include/timer_init.h new file mode 100644 index 0000000..094ee20 --- /dev/null +++ b/interfaces/kits/js/napi/system_timer/include/timer_init.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 \ No newline at end of file diff --git a/interfaces/kits/js/napi/system_timer/include/timer_type.h b/interfaces/kits/js/napi/system_timer/include/timer_type.h index 5147d32..b4fbbda 100644 --- a/interfaces/kits/js/napi/system_timer/include/timer_type.h +++ b/interfaces/kits/js/napi/system_timer/include/timer_type.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 diff --git a/interfaces/kits/js/napi/system_timer/src/system_timer.cpp b/interfaces/kits/js/napi/system_timer/src/system_timer.cpp index d357ef0..03618c1 100644 --- a/interfaces/kits/js/napi/system_timer/src/system_timer.cpp +++ b/interfaces/kits/js/napi/system_timer/src/system_timer.cpp @@ -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 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 &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 sWantAgent = std::make_shared(*wantAgent); + std::shared_ptr sWantAgent = + std::make_shared(*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, 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 \ No newline at end of file diff --git a/interfaces/kits/js/napi/system_timer/src/init.cpp b/interfaces/kits/js/napi/system_timer/src/timer_init.cpp similarity index 93% rename from interfaces/kits/js/napi/system_timer/src/init.cpp rename to interfaces/kits/js/napi/system_timer/src/timer_init.cpp index 2bca0f2..75e075f 100644 --- a/interfaces/kits/js/napi/system_timer/src/init.cpp +++ b/interfaces/kits/js/napi/system_timer/src/timer_init.cpp @@ -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 diff --git a/interfaces/kits/js/napi/system_timer/src/timer_type.cpp b/interfaces/kits/js/napi/system_timer/src/timer_type.cpp index 283534a..1ac87ac 100644 --- a/interfaces/kits/js/napi/system_timer/src/timer_type.cpp +++ b/interfaces/kits/js/napi/system_timer/src/timer_type.cpp @@ -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 \ No newline at end of file diff --git a/services/BUILD.gn b/services/BUILD.gn index b551356..0c4ff29 100755 --- a/services/BUILD.gn +++ b/services/BUILD.gn @@ -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" } diff --git a/services/time_manager/include/itimer_call_back.h b/services/time_manager/include/itimer_call_back.h index da41b63..9a31456 100644 --- a/services/time_manager/include/itimer_call_back.h +++ b/services/time_manager/include/itimer_call_back.h @@ -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 diff --git a/services/time_manager/include/time_service.h b/services/time_manager/include/time_service.h index 0d48dc0..a7ab896 100644 --- a/services/time_manager/include/time_service.h +++ b/services/time_manager/include/time_service.h @@ -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 #include + 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 ¶s); bool GetTimeByClockid(clockid_t clockID, struct timespec* tv); int set_rtc_time(time_t sec); diff --git a/services/time_manager/include/time_service_interface.h b/services/time_manager/include/time_service_interface.h index be96b76..b43612a 100644 --- a/services/time_manager/include/time_service_interface.h +++ b/services/time_manager/include/time_service_interface.h @@ -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 \ No newline at end of file diff --git a/services/time_manager/include/time_service_notify.h b/services/time_manager/include/time_service_notify.h index c2ecc78..c3f00d3 100644 --- a/services/time_manager/include/time_service_notify.h +++ b/services/time_manager/include/time_service_notify.h @@ -23,9 +23,7 @@ namespace OHOS { namespace MiscServices { - class TimeServiceNotify { - public: TimeServiceNotify() = default; ~TimeServiceNotify() = default; @@ -42,7 +40,6 @@ private: sptr timeZoneChangeWant_; sptr publishInfo_; }; - } // namespace MiscServices } // namespace OHOS diff --git a/services/time_manager/include/time_zone_info.h b/services/time_manager/include/time_zone_info.h index 1865fab..c6cc9aa 100644 --- a/services/time_manager/include/time_zone_info.h +++ b/services/time_manager/include/time_zone_info.h @@ -15,37 +15,38 @@ #ifndef SERVICES_INCLUDE_TIME_ZONE_INFO_H #define SERVICES_INCLUDE_TIME_ZONE_INFO_H +#include #include #include #include "refbase.h" +#include "time.h" +#include +#include "time_common.h" +#include +#include "json/json.h" +#include -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 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 instance_; std::map timezoneInfoMap_; }; } // MiscServices diff --git a/services/time_manager/include/timer_call_back.h b/services/time_manager/include/timer_call_back.h index 520b2bd..4b205af 100644 --- a/services/time_manager/include/timer_call_back.h +++ b/services/time_manager/include/timer_call_back.h @@ -25,13 +25,10 @@ namespace OHOS { namespace MiscServices { - class TimerCallback : public TimerCallbackStub { public: DISALLOW_COPY_AND_MOVE(TimerCallback); - static sptr 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 &timerInfo); - bool RemoveTimerCallbackInfo(const uint64_t timerId); private: @@ -50,11 +46,9 @@ private: static std::mutex instanceLock_; static sptr instance_; - static std::map> TimerInfoMap_; static std::mutex timerInfoMutex_; }; - } // namespace MiscServices } // namespace OHOS diff --git a/services/time_manager/include/timer_call_back_proxy.h b/services/time_manager/include/timer_call_back_proxy.h index 26e9c56..f85136b 100644 --- a/services/time_manager/include/timer_call_back_proxy.h +++ b/services/time_manager/include/timer_call_back_proxy.h @@ -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 delegator_; }; - } // namespace PowerMgr } // namespace OHOS diff --git a/services/time_manager/include/timer_call_back_stub.h b/services/time_manager/include/timer_call_back_stub.h index 865ff24..ee88a2a 100644 --- a/services/time_manager/include/timer_call_back_stub.h +++ b/services/time_manager/include/timer_call_back_stub.h @@ -23,7 +23,6 @@ #include namespace OHOS { namespace MiscServices { - class TimerCallbackStub : public IRemoteStub { public: DISALLOW_COPY_AND_MOVE(TimerCallbackStub); diff --git a/services/time_manager/src/itimer_info.cpp b/services/time_manager/src/itimer_info.cpp index b284023..e076603 100644 --- a/services/time_manager/src/itimer_info.cpp +++ b/services/time_manager/src/itimer_info.cpp @@ -17,16 +17,14 @@ namespace OHOS { namespace MiscServices { - ITimerInfo::ITimerInfo() + : type {0}, repeat {false}, interval {0} { - } + ITimerInfo::~ITimerInfo() { } - - } // MiscServices } // OHOS diff --git a/services/time_manager/src/time_service.cpp b/services/time_manager/src/time_service.cpp index f46136b..fbcf0d9 100644 --- a/services/time_manager/src/time_service.cpp +++ b/services/time_manager/src/time_service.cpp @@ -22,8 +22,8 @@ #include "system_ability_definition.h" #include "iservice_registry.h" -#include -#include +#include +#include #include #include #include @@ -33,7 +33,7 @@ #include #include #include -#include +#include #include #include #include @@ -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::instance_; std::shared_ptr TimeService::serviceHandler_ = nullptr; @@ -65,19 +67,19 @@ std::shared_ptr TimeService::timeServiceNotify_ std::shared_ptr 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::GetInstance() { @@ -92,23 +94,25 @@ sptr 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::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(); @@ -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 runner = AppExecFwk::EventRunner::Create(TIME_SERVICE_NAME); serviceHandler_ = std::make_shared(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 ¶s) +{ + 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 &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 timerCallback = iface_cast(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::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(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::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::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::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 ×) { 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 ×) { 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 ×) { 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 ×) { 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 ×) { 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 ×) { 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 ×) 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 ×) 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 ×) } -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; diff --git a/services/time_manager/src/time_service_client.cpp b/services/time_manager/src/time_service_client.cpp index 17a8b59..d9c5078 100644 --- a/services/time_manager/src/time_service_client.cpp +++ b/services/time_manager/src/time_service_client.cpp @@ -22,7 +22,6 @@ namespace OHOS { namespace MiscServices { - std::mutex TimeServiceClient::instanceLock_; sptr TimeServiceClient::instance_; sptr 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::GetInstance() @@ -63,14 +68,14 @@ sptr TimeServiceClient::ConnectService() } deathRecipient_ = new TimeSaDeathRecipient(); systemAbility->AddDeathRecipient(deathRecipient_); - sptr timeServiceProxy = iface_cast(systemAbility); - if (timeServiceProxy == nullptr) { + sptr timeServiceProxy_ = iface_cast(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 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 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 &object) TIME_HILOGE(TIME_MODULE_CLIENT, "TimeSaDeathRecipient on remote systemAbility died."); TimeServiceClient::GetInstance()->OnRemoteSaDied(object); } - } // namespace MiscServices } // namespace OHOS diff --git a/services/time_manager/src/time_service_notify.cpp b/services/time_manager/src/time_service_notify.cpp index 641c789..3985977 100644 --- a/services/time_manager/src/time_service_notify.cpp +++ b/services/time_manager/src/time_service_notify.cpp @@ -25,7 +25,6 @@ using namespace OHOS::EventFwk; namespace OHOS{ namespace MiscServices{ - void TimeServiceNotify::RegisterPublishEvents() { if (publishInfo_ != nullptr) { diff --git a/services/time_manager/src/time_service_proxy.cpp b/services/time_manager/src/time_service_proxy.cpp index 14210e9..a185d68 100644 --- a/services/time_manager/src/time_service_proxy.cpp +++ b/services/time_manager/src/time_service_proxy.cpp @@ -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 ×) } 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 ×) } 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 ×) } 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 ×) } 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 ×) } 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 ×) } 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 ×) } 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 ×) } 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; } diff --git a/services/time_manager/src/time_service_stub.cpp b/services/time_manager/src/time_service_stub.cpp index 940cc3d..4ef5fbb 100644 --- a/services/time_manager/src/time_service_stub.cpp +++ b/services/time_manager/src/time_service_stub.cpp @@ -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 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 diff --git a/services/time_manager/src/time_zone_info.cpp b/services/time_manager/src/time_zone_info.cpp index e3f5cf1..38748e8 100644 --- a/services/time_manager/src/time_zone_info.cpp +++ b/services/time_manager/src/time_zone_info.cpp @@ -14,84 +14,163 @@ */ #include "time_zone_info.h" -#include "time_common.h" -#include namespace OHOS{ namespace MiscServices{ - -std::mutex TimeZoneInfo::instanceLock_; -sptr TimeZoneInfo::instance_; +namespace { +static const int HOURS_TO_MINUTES = 60; +} TimeZoneInfo::TimeZoneInfo() { std::vector 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(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::GetInstance() -{ - if (instance_ == nullptr) { - std::lock_guard autoLock(instanceLock_); - if (instance_ == nullptr) { - instance_ = new TimeZoneInfo; - } - } - return instance_; -} - } } \ No newline at end of file diff --git a/services/time_manager/src/timer_call_back.cpp b/services/time_manager/src/timer_call_back.cpp index 378daea..d6c8a09 100644 --- a/services/time_manager/src/timer_call_back.cpp +++ b/services/time_manager/src/timer_call_back.cpp @@ -17,7 +17,6 @@ namespace OHOS { namespace MiscServices { - std::mutex TimerCallback::instanceLock_; sptr TimerCallback::instance_; @@ -45,10 +44,10 @@ sptr TimerCallback::GetInstance() } bool TimerCallback::InsertTimerCallbackInfo(const uint64_t timerId, - const std::shared_ptr &timerInfo) + const std::shared_ptr &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 context = std::make_shared(); - std::shared_ptr want = Notification::WantAgent::WantAgentHelper::GetWant(it->second->wantAgent); + std::shared_ptr 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 \ No newline at end of file diff --git a/services/time_manager/src/timer_call_back_proxy.cpp b/services/time_manager/src/timer_call_back_proxy.cpp index 794b6d4..33d9f33 100644 --- a/services/time_manager/src/timer_call_back_proxy.cpp +++ b/services/time_manager/src/timer_call_back_proxy.cpp @@ -18,7 +18,6 @@ namespace OHOS { namespace MiscServices { - TimerCallbackProxy::TimerCallbackProxy(const sptr &object) : IRemoteProxy(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 remote = Remote(); - if (remote == nullptr){ + if (remote == nullptr) { return; } diff --git a/services/time_manager/src/timer_call_back_stub.cpp b/services/time_manager/src/timer_call_back_stub.cpp index 2840536..1a27607 100644 --- a/services/time_manager/src/timer_call_back_stub.cpp +++ b/services/time_manager/src/timer_call_back_stub.cpp @@ -17,7 +17,6 @@ namespace OHOS { namespace MiscServices { - int TimerCallbackStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { diff --git a/services/time_manager/src/timezone.json b/services/time_manager/src/timezone.json new file mode 100644 index 0000000..6340094 --- /dev/null +++ b/services/time_manager/src/timezone.json @@ -0,0 +1,3 @@ +{ + "TimezoneId" : "Asia/Shanghai" +} diff --git a/services/time_manager/test/unittest/include/timer_test.h b/services/time_manager/test/unittest/include/time_service_test.h similarity index 93% rename from services/time_manager/test/unittest/include/timer_test.h rename to services/time_manager/test/unittest/include/time_service_test.h index 92efe34..b659e28 100644 --- a/services/time_manager/test/unittest/include/timer_test.h +++ b/services/time_manager/test/unittest/include/time_service_test.h @@ -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 @@ -26,8 +29,8 @@ #include #include -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_ptrSetTimeZone(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); diff --git a/services/timer/include/batch.h b/services/timer/include/batch.h index 3c2dd28..a9a0f46 100644 --- a/services/timer/include/batch.h +++ b/services/timer/include/batch.h @@ -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 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 &alarm); bool Remove (const TimerInfo &alarm); bool Remove (std::function predicate); @@ -51,7 +48,6 @@ private: uint32_t flags_; std::vector> alarms_; }; - } } #endif \ No newline at end of file diff --git a/services/timer/include/timer_handler.h b/services/timer/include/timer_handler.h index df87ac3..8a40b01 100644 --- a/services/timer/include/timer_handler.h +++ b/services/timer/include/timer_handler.h @@ -13,8 +13,6 @@ * limitations under the License. */ - - #ifndef TIMER_HANDLER_H #define TIMER_HANDLER_H @@ -26,32 +24,23 @@ #include #include - 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 TimerFds; class TimerHandler { public: static std::shared_ptr 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 \ No newline at end of file diff --git a/services/timer/include/timer_info.h b/services/timer/include/timer_info.h index 5e5026f..0c20cc3 100644 --- a/services/timer/include/timer_info.h +++ b/services/timer/include/timer_info.h @@ -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 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 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 \ No newline at end of file diff --git a/services/timer/include/timer_manager.h b/services/timer/include/timer_manager.h index d2b3da2..177246c 100644 --- a/services/timer/include/timer_manager.h +++ b/services/timer/include/timer_manager.h @@ -27,9 +27,8 @@ #include "batch.h" #include -namespace OHOS{ -namespace MiscServices{ - +namespace OHOS { +namespace MiscServices { class TimerManager : public ITimerManager { public: static std::shared_ptr Create(); diff --git a/services/timer/include/timer_manager_interface.h b/services/timer/include/timer_manager_interface.h index 0dcc691..a3929bc 100644 --- a/services/timer/include/timer_manager_interface.h +++ b/services/timer/include/timer_manager_interface.h @@ -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 \ No newline at end of file diff --git a/services/timer/src/batch.cpp b/services/timer/src/batch.cpp index ef808df..1333489 100644 --- a/services/timer/src/batch.cpp +++ b/services/timer/src/batch.cpp @@ -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 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 &alarm) { bool new_start = false; - auto it = std::upper_bound (alarms_.begin (), alarms_.end (), alarm, - [] (const std::shared_ptr &first, const std::shared_ptr &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 &first, const std::shared_ptr &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 &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 &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 predicate) @@ -89,7 +89,7 @@ bool Batch::Remove (std::function 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 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 &alarm) - { return alarm->Matches (package_name); }) != alarms_.end (); + return std::find_if (alarms_.begin(), + alarms_.end(), + [package_name] (const std::shared_ptr &alarm) { + return alarm->Matches (package_name); + }) != alarms_.end(); } bool Batch::HasWakeups () const { return std::any_of (alarms_.begin (), alarms_.begin (), - [] (const std::shared_ptr &item) - { - return (static_cast(item->type) & TYPE_NONWAKEUP_MASK) == 0; - }); + [] (const std::shared_ptr &item) { + return (static_cast(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 \ No newline at end of file diff --git a/services/timer/src/timer_handler.cpp b/services/timer/src/timer_handler.cpp index 82c053a..a7e7c0e 100644 --- a/services/timer/src/timer_handler.cpp +++ b/services/timer/src/timer_handler.cpp @@ -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::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(fds.size()), strerror (errno)); - return nullptr; + TIME_HILOGE(TIME_MODULE_SERVICE, "epoll_create %{public}d failed: %{public}s", + static_cast(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(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(i), strerror(errno)); + close(epollfd); + for(size_t j = 0; j < i; j++) { + close(fds[j]); } return nullptr; } } - auto handler = std::shared_ptr (new TimerHandler (fds, epollfd)); - for (size_t i = 0; i < fds.size (); i++) { - epoll_event event{}; + std::shared_ptr handler = std::shared_ptr(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::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(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 (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(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 \ No newline at end of file diff --git a/services/timer/src/timer_info.cpp b/services/timer/src/timer_info.cpp index d320a00..086f476 100644 --- a/services/timer/src/timer_info.cpp +++ b/services/timer/src/timer_info.cpp @@ -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 _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 _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 \ No newline at end of file diff --git a/services/timer/src/timer_manager.cpp b/services/timer/src/timer_manager.cpp index 58829a6..bd449e5 100644 --- a/services/timer/src/timer_manager.cpp +++ b/services/timer/src/timer_manager.cpp @@ -17,14 +17,16 @@ #include #include #include -#include +#include #include -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> &list, const std::shared_ptr &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::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(new TimerManager(impl)); } TimerManager::TimerManager(std::shared_ptr impl) - : random_{static_cast(time(nullptr))}, - runFlag_{false}, - handler_{std::move(impl)}, - lastTimeChangeClockTime_{system_clock::time_point::min()}, - lastTimeChangeRealtime_{steady_clock::time_point::min()} + : random_ {static_cast(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 callback, uint64_t uid) +uint64_t TimerManager::CreateTimer(int type, + uint64_t windowLength, + uint64_t interval, + int flag, + std::function 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{timerNumber, type,windowLength, - interval, flag, std::move(callback), uid}); + auto timerInfo = std::make_shared(TimerEntry { + timerNumber, + type, + windowLength, + interval, + flag, + std::move(callback), + uid}); std::lock_guard 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 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 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 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 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 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(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 lockGuard(mutex_); TIME_HILOGI(TIME_MODULE_SERVICE, "Lock guard"); - SetHandlerLocked(id,type, milliseconds(triggerAtTime),triggerElapsed, windowLengthDuration, maxElapsed, - intervalDuration, std::move(callback), static_cast(flag), true, uid); + SetHandlerLocked(id, + type, + milliseconds(triggerAtTime), + triggerElapsed, + windowLengthDuration, + maxElapsed, + intervalDuration, + std::move(callback), + static_cast(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 timer, std::chrono::steady_clock::time_point nowElapsed, bool doValidate){ +void TimerManager::ReAddTimerLocked(std::shared_ptr 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 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 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> 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> &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(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(batch->GetStart()).time_since_epoch().count()); - TIME_HILOGI(TIME_MODULE_SERVICE, "nowElapsed= %{public}lld", time_point_cast(nowElapsed).time_since_epoch().count()); + TIME_HILOGI(TIME_MODULE_SERVICE, "batch->GetStart()= %{public}lld", + time_point_cast(batch->GetStart()).time_since_epoch().count()); + TIME_HILOGI(TIME_MODULE_SERVICE, "nowElapsed= %{public}lld", + time_point_cast(nowElapsed).time_since_epoch().count()); if (batch->GetStart() > nowElapsed) { - TIME_HILOGI(TIME_MODULE_SERVICE, "break alarmBatches_.size= %{public}d", static_cast(alarmBatches_.size())); + TIME_HILOGI(TIME_MODULE_SERVICE, "break alarmBatches_.size= %{public}d", + static_cast(alarmBatches_.size())); break; } alarmBatches_.erase(alarmBatches_.begin()); - TIME_HILOGI(TIME_MODULE_SERVICE, "after erase alarmBatches_.size= %{public}d", static_cast(alarmBatches_.size())); + TIME_HILOGI(TIME_MODULE_SERVICE, "after erase alarmBatches_.size= %{public}d", + static_cast(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(nowElapsed - alarm->expectedWhenElapsed) / alarm->repeatInterval; + alarm->count += duration_cast(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::sort(triggerList.begin(), triggerList.end(), - [](const std::shared_ptr &l, - const std::shared_ptr &r){return l->whenElapsed < r->whenElapsed;}); + std::sort(triggerList.begin(), + triggerList.end(), + [] (const std::shared_ptr &l, const std::shared_ptr &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 TimerManager::FindFirstWakeupBatchLocked() { - auto it = std::find_if(alarmBatches_.begin(),alarmBatches_.end(), - [](const std::shared_ptr &batch) - { - return batch->HasWakeups(); - }); - return it != alarmBatches_.end() ? *it : nullptr; + auto it = std::find_if (alarmBatches_.begin(),alarmBatches_.end(), + [](const std::shared_ptr &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 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(STANDALONE)) == 0 && item->CanHold(whenElapsed, maxWhen)) { return i; } - // ++i; } return -1; } void TimerManager::DeliverTimersLocked(const std::vector> &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> &list, const std::shared { TIME_HILOGI(TIME_MODULE_SERVICE, "start"); auto it = std::upper_bound(list.begin(), list.end(), newBatch, - [](const std::shared_ptr &first, const std::shared_ptr &second) - { - return first->GetStart() < second->GetStart(); - }); + [](const std::shared_ptr &first, const std::shared_ptr &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(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(triggerAtTime - now)) : interval; if (futurity < MIN_FUZZABLE_INTERVAL) { futurity = milliseconds::zero(); } - return triggerAtTime + milliseconds(static_cast(0.75 * futurity.count())); + return triggerAtTime + milliseconds(static_cast(0.75 * futurity.count())); } - } // MiscServices } // OHOS \ No newline at end of file diff --git a/utils/mock/include/mock_permission.h b/utils/mock/include/mock_permission.h index a86b676..4db2204 100644 --- a/utils/mock/include/mock_permission.h +++ b/utils/mock/include/mock_permission.h @@ -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 \ No newline at end of file diff --git a/utils/mock/src/mock_permission.cpp b/utils/mock/src/mock_permission.cpp index 373112f..d4528b4 100644 --- a/utils/mock/src/mock_permission.cpp +++ b/utils/mock/src/mock_permission.cpp @@ -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 \ No newline at end of file diff --git a/utils/native/include/time_common.h b/utils/native/include/time_common.h index b16a0f8..1b9b04f 100644 --- a/utils/native/include/time_common.h +++ b/utils/native/include/time_common.h @@ -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 \ No newline at end of file diff --git a/utils/native/include/time_hilog_wreapper.h b/utils/native/include/time_hilog_wreapper.h index deb0c94..c320e69 100644 --- a/utils/native/include/time_hilog_wreapper.h +++ b/utils/native/include/time_hilog_wreapper.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 diff --git a/utils/native/include/time_permission.h b/utils/native/include/time_permission.h index a37c0af..b06d3b6 100644 --- a/utils/native/include/time_permission.h +++ b/utils/native/include/time_permission.h @@ -22,25 +22,21 @@ #include "mock_permission.h" #include "system_ability_definition.h" #include "iservice_registry.h" -#include "refbase.h" +#include #include #include namespace OHOS { namespace MiscServices { -class TimePermission : public RefBase{ +class TimePermission { + DECLARE_DELAYED_SINGLETON(TimePermission) public: - static sptr GetInstance(); bool CheckSelfPermission(const std::string permName); bool CheckCallingPermission(const int32_t uid, const std::string permName); private: - TimePermission(); - ~TimePermission(); sptr GetBundleManager(); - static std::mutex instanceLock_; - static sptr instance_; static sptr bundleMgrProxy_; }; } // namespace MiscServices diff --git a/utils/native/include/time_rdb_handler.h b/utils/native/include/time_rdb_handler.h deleted file mode 100644 index b67bc08..0000000 --- a/utils/native/include/time_rdb_handler.h +++ /dev/null @@ -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 - -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 = 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; - } -} -} \ No newline at end of file diff --git a/utils/native/src/time_permission.cpp b/utils/native/src/time_permission.cpp index c36e408..a8009b2 100644 --- a/utils/native/src/time_permission.cpp +++ b/utils/native/src/time_permission.cpp @@ -18,29 +18,13 @@ namespace OHOS { namespace MiscServices { - -std::mutex TimePermission::instanceLock_; -sptr TimePermission::instance_; +namespace { +static const int UID_TO_USERID = 100000; +} sptr TimePermission::bundleMgrProxy_; -TimePermission::TimePermission() -{ -} - -TimePermission::~TimePermission() -{ -} - -sptr TimePermission::GetInstance() -{ - if (instance_ == nullptr){ - std::lock_guard 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 TimePermission::GetBundleManager() bundleMgrProxy_ = iface_cast(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