diff --git a/BUILD.gn b/BUILD.gn index d6e2f3f..06ad71c 100755 --- a/BUILD.gn +++ b/BUILD.gn @@ -24,7 +24,6 @@ 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.md b/README.md index 5683514..3e05ae1 100755 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ The timing and time module provides APIs for managing the system time. ├── etc # Process configuration files ├── figures # Architecture diagram ├── interfaces # APIs for external systems and applications -├ └── innerkits # APIs between services +│ └── innerkits # APIs between services │ └── kits # APIs ├── profile # System service configuration files └── services # Service implementation @@ -35,20 +35,146 @@ The timing and time module provides APIs for managing the system time. **Table 1** Major functions of systemTime -

Function

+ - - - + + + + + + + + + + + + + + +

Interface name

Description

+

describe

function setTime(time : number) : Promise<boolean>

Sets the system time and uses a Promise to return the execution result.

+

Set the system time (1970-01-01 to the present in milliseconds), Promise method

function setTime(time : number, callback : AsyncCallback<boolean>) : void

Sets the system time and uses a callback to return the execution result.

+

Set the system time (1970-01-01 to the present in milliseconds), callback mode

+

function setDate(date: Date, callback: AsyncCallback<boolean>): void;

+

Set the system time (Date format), Promise method

+

function setDate(date: Date): Promise<boolean>

+

Set system time (Date format), callback method

+

function setTimezone(timezone: string, callback: AsyncCallback<boolean>): void

+

Set the system time zone, callback method

+

function setTimezone(timezone: string): Promise<boolean>

+

Set the system time zone, Promise method

+
+ + +**表 2** Major functions of systemTimer + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Interface name

+

describe

+

function createTimer(options: TimerOptions, callback: AsyncCallback<number>): void

+

Create timer, callback method

+

function createTimer(options: TimerOptions): Promise<number>

+

Create timer, promise method

+

function startTimer(timer: number, triggerTime: number, callback: AsyncCallback<boolean>): void

+

Start the timer, callback mode

+

function startTimer(timer: number, triggerTime: number): Promise<boolean>

+

Start the timer, promise mode

+

function stopTimer(timer: number, callback: AsyncCallback<boolean>): void

+

Stop the timer, callback mode

+

function stopTimer(timer: number): Promise<boolean>

+

Stop the timer, promise mode

+

function destroyTimer(timer: number, callback: AsyncCallback<boolean>): void

+

Destroy the timer, callback method

+

function destroyTimer(timer: number): Promise<boolean>

+

Destroy the timer, the promise method

+
+ +**表 3** parameter TimerOptions description of systemTimer + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -63,23 +189,49 @@ Example fo using systemTime import systemTime from '@ohos.systemTime'; // Set the system time asynchronously with a Promise. -var time = 1611081385000; -systemTime.setTime(time) - .then((value) => { - console.log(`success to systemTime.setTime: ${value}`); - }).catch((err) => { - console.error(`failed to systemTime.setTime because ${err.message}`); +var time = 1611081385000; +systemTime.setTime(time) + .then((value) => { + console.log(`success to systemTime.setTime: ${value}`); + }).catch((err) => { + console.error(`failed to systemTime.setTime because ${err.message}`) }); -// Set the system time asynchronously with a callback. -var time = 1611081385000; -systemTime.setTime(time, (err, value) => { - if (err) { - console.error(`failed to systemTime.setTime because ${err.message}`); - return; - } - console.log(`success to systemTime.setTime: ${value}`); -}); +// Set the system time asynchronously with a callback. +var time = 1611081385000; +systemTime.setTime(time, (err, value) => { + if (err) { + console.error(`failed to systemTime.setTime because ${err.message}`); + return; + } + console.log(`success to systemTime.setTime: ${value}`); + }); + +``` +Example fo using systemTimer + +// Import the module +import systemTimer from '@ohos.systemTimer'; + +console.log("start") +var options:TimerOptions{ + type:TIMER_TYPE_REALTIME, + repeat:false, + interval:Number.MAX_VALUE/2, + persistent:false +} + +console.log("create timer") +let timerId = systemTimer.Timer(options) +console.log("start timer") +let startTimerRes = systemTimer.startTimer(timerId, 100000) +console.log("stop timer") +let stopTimerRes = systemTimer.stopTimer(timerId) +console.log("destroy timer") +let destroyTimerRes = systemTimer.destroyTimer(timerId) +console.log('end'); + + ``` ## Repositories Involved diff --git a/README_zh.md b/README_zh.md index 22843b2..1fe45e7 100755 --- a/README_zh.md +++ b/README_zh.md @@ -10,7 +10,7 @@ ## 简介 -时间组件提供管理系统时间的能力。 +时间组件提供管理系统时间时区和定时的能力。 **图 1** 子系统架构图 ![](figures/subsystem_architecture_zh.png "子系统架构图") @@ -43,17 +43,142 @@ - - + + + + + + + + + + + +

name

+

type

+

illustrate

+

type

+

number

+

TIMER_TYPE_REALTIME: Set as the system startup time timer, otherwise it is the walltime timer; + TIMER_TYPE_WAKEUP: Set to wake-up timer, otherwise it is non-wake-up; + const TIMER_TYPE_EXACT: Set as a precision timer, otherwise it is a non-precision timer; + const TIMER_TYPE_IDLE: Set to IDLE mode timer, otherwise it is non-IDLE mode timer (not supported yet) +

+

repeat

+

boolean

+

true Is a cyclic timer, false is a single timer

+

interval

+

number

+

If it is a cyclic timer, the repeat value should be greater than 5000 milliseconds, and the non-repeated timer is set to 0

+

wantAgent

+

wantAgent

+

Set the wantagent to notify, and notify when the timer expires

+

callback

+

=> void

+

Set the callback function, which will be triggered after the timer expires

function setTime(time : number) : Promise<boolean>

设置系统时间,Promise方式

+

设置系统时间(1970-01-01至今毫秒数),Promise方式

function setTime(time : number, callback : AsyncCallback<boolean>) : void

设置系统时间,callback方式

+

设置系统时间(1970-01-01至今毫秒数),callback方式

+

function setDate(date: Date, callback: AsyncCallback<boolean>): void;

+

设置系统时间(Date格式),Promise方式

+

function setDate(date: Date): Promise<boolean>

+

设置系统时间(Date格式),callback方式

+

function setTimezone(timezone: string, callback: AsyncCallback<boolean>): void

+

设置系统时区,callback方式

+

function setTimezone(timezone: string): Promise<boolean>

+

设置系统时区,Promise方式

+ +**表 2** js组件systemTimer开放的主要方法 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

接口名

+

描述

+

function createTimer(options: TimerOptions, callback: AsyncCallback<number>): void

+

创建定时器,callback方式

+

function createTimer(options: TimerOptions): Promise<number>

+

创建定时器,promise方式

+

function startTimer(timer: number, triggerTime: number, callback: AsyncCallback<boolean>): void

+

开启定时器,callback方式

+

function startTimer(timer: number, triggerTime: number): Promise<boolean>

+

开启定时器,promise方式

+

function stopTimer(timer: number, callback: AsyncCallback<boolean>): void

+

停止定时器,callback方式

+

function stopTimer(timer: number): Promise<boolean>

+

停止定时器,promise方式

+

function destroyTimer(timer: number, callback: AsyncCallback<boolean>): void

+

销毁定时器,callback方式

+

function destroyTimer(timer: number): Promise<boolean>

+

摧毁定时器,promise方式

+
+ +**表 3** systemTimer组件参数TimerOptions说明 + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

名称

+

类型

+

说明

+

type

+

number

+

TIMER_TYPE_REALTIME: 设置为系统启动时间定时器,否则为walltime定时器; + TIMER_TYPE_WAKEUP: 设置为唤醒定时器,否则为非唤醒; + const TIMER_TYPE_EXACT: 设置为精准定时器,否则为非精准定时器; + const TIMER_TYPE_IDLE: 设置为IDLE模式定时器,否则为非IDLE模式定时器(暂不支持) +

+

repeat

+

boolean

+

true 为循环定时器,false为单次定时器

+

interval

+

number

+

如果是循环定时器,repeat值应大于5000毫秒,非重复定时器置为0

+

wantAgent

+

wantAgent

+

设置通知的wantagent,定时器到期后通知

+

callback

+

=> void

+

设置回调函数,定时器到期后触发

+
### js接口使用说明 systemTime模块使用示例: @@ -62,24 +187,54 @@ systemTime模块使用示例: // 导入模块 import systemTime from '@ohos.systemTime'; -// Promise方式的异步方法设置时间 -var time = 1611081385000; -systemTime.setTime(time) - .then((value) => { - console.log(`success to systemTime.setTime: ${value}`); - }).catch((err) => { - console.error(`failed to systemTime.setTime because ${err.message}`); +// Promise方式的异步方法设置时间 +var time = 1611081385000; +systemTime.setTime(time) + .then((value) => { + console.log(`success to systemTime.setTime: ${value}`); + }).catch((err) => { + console.error(`failed to systemTime.setTime because ${err.message}`) }); + // callback方式的异步方法设置时间 -var time = 1611081385000; -systemTime.setTime(time, (err, value) => { - if (err) { - console.error(`failed to systemTime.setTime because ${err.message}`); - return; - } - console.log(`success to systemTime.setTime: ${value}`); -}); + +var time = 1611081385000; +systemTime.setTime(time, (err, value) => { + if (err) { + console.error(`failed to systemTime.setTime because ${err.message}`); + return; + } + console.log(`success to systemTime.setTime: ${value}`); + }); + +``` + +systemTimer模块使用示例: + +``` +// 导入模块 +import systemTimer from '@ohos.systemTimer'; + +console.log("start") +var options:TimerOptions{ + type:TIMER_TYPE_REALTIME, + repeat:false, + interval:Number.MAX_VALUE/2, + persistent:false +} + +console.log("create timer") +let timerId = systemTimer.Timer(options) +console.log("start timer") +let startTimerRes = systemTimer.startTimer(timerId, 100000) +console.log("stop timer") +let stopTimerRes = systemTimer.stopTimer(timerId) +console.log("destroy timer") +let destroyTimerRes = systemTimer.destroyTimer(timerId) +console.log('end'); + + ``` ## 相关仓 diff --git a/figures/subsystem_architecture.png b/figures/subsystem_architecture.png index 478fe7a..0df0a07 100755 Binary files a/figures/subsystem_architecture.png and b/figures/subsystem_architecture.png differ diff --git a/figures/subsystem_architecture_zh.png b/figures/subsystem_architecture_zh.png index f4db33b..49a5f62 100755 Binary files a/figures/subsystem_architecture_zh.png and b/figures/subsystem_architecture_zh.png differ diff --git a/interfaces/innerkits/include/time_service_client.h b/interfaces/innerkits/include/time_service_client.h index e576ec2..6fa0f5a 100644 --- a/interfaces/innerkits/include/time_service_client.h +++ b/interfaces/innerkits/include/time_service_client.h @@ -16,11 +16,12 @@ #ifndef SERVICES_INCLUDE_TIME_SERVICES_MANAGER_H #define SERVICES_INCLUDE_TIME_SERVICES_MANAGER_H +#include + #include "refbase.h" #include "time_service_interface.h" #include "iremote_object.h" #include "timer_call_back.h" -#include namespace OHOS { namespace MiscServices { @@ -42,8 +43,7 @@ public: /** * SetTime - * - * @descrition + * @descrition * @param milliseconds int64_t UTC time in milliseconds. * @return bool true on success, false on failure. */ @@ -51,8 +51,7 @@ public: /** * SetTimeZone - * - * @descrition + * @descrition * @param timeZoneId const std::string time zone. example: "Beijing, China". * @return bool true on success, false on failure. */ @@ -60,14 +59,12 @@ public: /** * GetTimeZone - * - * @descpriton + * @descpriton * @return std::string, time zone example: "Beijing, China", if result length == 0 on failed. */ std::string GetTimeZone(); /** * GetWallTimeMs - * * @descpriton get the wall time(the UTC time from 1970 0H:0M:0S) in milliseconds * @return int64_t, milliseconds in wall time, ret < 0 on failed. */ @@ -75,7 +72,6 @@ public: /** * GetWallTimeNs - * * @descpriton get the wall time(the UTC time from 1970 0H:0M:0S) in nanoseconds * @return int64_t, nanoseconds in wall time, ret < 0 on failed. */ @@ -83,7 +79,6 @@ public: /** * GetBootTimeMs - * * @descpriton get the time since boot(include time spent in sleep) in milliseconds. * @return int64_t, milliseconds in boot time, ret < 0 on failed. */ @@ -91,7 +86,6 @@ public: /** * GetBootTimeNs - * * @descpriton // get the time since boot(include time spent in sleep) in nanoseconds. * @return int64_t, nanoseconds in boot time, ret < 0 on failed. */ @@ -99,7 +93,6 @@ public: /** * GetMonotonicTimeMs - * * @descpriton get the time since boot(exclude time spent in sleep) in milliseconds. * @return int64_t, milliseconds in Monotonic time, ret < 0 on failed. */ @@ -107,7 +100,6 @@ public: /** * GetMonotonicTimeNs - * * @descpriton get the time since boot(exclude time spent in sleep) in nanoseconds. * @return int64_t, nanoseconds in Monotonic time, ret < 0 on failed. */ @@ -115,7 +107,6 @@ public: /** * GetThreadTimeMs - * * @descpriton get the Thread-specific CPU-time in milliseconds. * @return int64_t, milliseconds in Thread-specific CPU-time, ret < 0 on failed. */ @@ -123,7 +114,6 @@ public: /** * GetThreadTimeNs - * * @descpriton get the Thread-specific CPU-time in nanoseconds. * @return int64_t, nanoseconds in Thread-specific CPU-time, ret < 0 on failed. */ @@ -131,7 +121,6 @@ public: /** * CreateTimer - * * @param TimerInfo timer info * @return uint64_t > 0 on success, == 0 failure. */ @@ -139,7 +128,6 @@ public: /** * StartTimer - * * @param timerId indicate timerId * @param treggerTime trigger times * @return bool true on success, false on failure. @@ -148,7 +136,6 @@ public: /** * StopTimer - * * @param timerId indicate timerId * @return bool true on success, false on failure. */ @@ -156,7 +143,6 @@ public: /** * DestroyTimer - * * @param timerId indicate timerId * @return bool true on success, false on failure. */ diff --git a/interfaces/kits/js/declaration/api/@ohos.systemTime.d.ts b/interfaces/kits/js/declaration/api/@ohos.systemTime.d.ts index 1d19a79..eec8180 100644 --- a/interfaces/kits/js/declaration/api/@ohos.systemTime.d.ts +++ b/interfaces/kits/js/declaration/api/@ohos.systemTime.d.ts @@ -26,24 +26,24 @@ declare namespace systemTime { * @permission ohos.permission.SET_TIME * @since 6 */ - function setTime(time : number, callback : AsyncCallback) : void; - function setTime(time : number) : Promise; + function setTime(time : number, callback : AsyncCallback) : void; + function setTime(time : number) : Promise; /** * Sets the system time. * @permission ohos.permission.SET_TIME * @since 7 */ - function setDate(date: Date, callback: AsyncCallback): void; - function setDate(date: Date): Promise; + function setDate(date: Date, callback: AsyncCallback): void; + function setDate(date: Date): Promise; /** * Sets the system time zone. * @permission ohos.permission.SET_TIME_ZONE * @since 7 */ - function setTimezone(timezone: string, callback: AsyncCallback): void; - function setTimezone(timezone: string): Promise; + function setTimezone(timezone: string, callback: AsyncCallback): void; + function setTimezone(timezone: string): Promise; } export default systemTime; diff --git a/interfaces/kits/js/declaration/api/@ohos.systemtimer.d.ts b/interfaces/kits/js/declaration/api/@ohos.systemtimer.d.ts index 4a55a96..976db5b 100644 --- a/interfaces/kits/js/declaration/api/@ohos.systemtimer.d.ts +++ b/interfaces/kits/js/declaration/api/@ohos.systemtimer.d.ts @@ -63,8 +63,8 @@ declare namespace systemTimer { * value is smaller than the current time plus 5000 milliseconds. * @systemapi Hide this for inner system use. */ - function startTimer(timer: number, triggerTime: number, callback: AsyncCallback): void; - function startTimer(timer: number, triggerTime: number): Promise; + function startTimer(timer: number, triggerTime: number, callback: AsyncCallback): void; + function startTimer(timer: number, triggerTime: number): Promise; /** * Stops a timer. @@ -72,8 +72,8 @@ declare namespace systemTimer { * @Param timer The timer ID. * @systemapi Hide this for inner system use. */ - function stopTimer(timer: number, callback: AsyncCallback): void; - function stopTimer(timer: number): Promise; + function stopTimer(timer: number, callback: AsyncCallback): void; + function stopTimer(timer: number): Promise; /** * Clears a timer. @@ -81,8 +81,8 @@ declare namespace systemTimer { * @Param timer The timer ID. * @systemapi Hide this for inner system use. */ - function destroyTimer(timer: number, callback: AsyncCallback): void; - function destroyTimer(timer: number): Promise; + function destroyTimer(timer: number, callback: AsyncCallback): void; + function destroyTimer(timer: number): Promise; interface TimerOptions { /** 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 5160bd9..fe0110e 100644 --- a/interfaces/kits/js/napi/system_time/include/js_systemtime.h +++ b/interfaces/kits/js/napi/system_time/include/js_systemtime.h @@ -12,7 +12,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - #ifndef N_JS_SYSTEMTIME_H #define N_JS_SYSTEMTIME_H @@ -21,14 +20,20 @@ #include "napi/native_node_api.h" #include "js_native_api.h" -constexpr int RESOLVED = 1; -constexpr int REJECT = 0; - -constexpr int NONE_PARAMETER = 0; -constexpr int ONE_PARAMETER = 1; -constexpr int TWO_PARAMETERS = 2; -constexpr int THREE_PARAMETERS = 3; -constexpr int MAX_TIME_ZONE_ID = 1024; +namespace OHOS { +namespace MiscServicesNapi { +namespace { +const int NONE_PARAMETER = 0; +const int ONE_PARAMETER = 1; +const int TWO_PARAMETERS = 2; +const int THREE_PARAMETERS = 3; +const int MAX_TIME_ZONE_ID = 1024; +const int NO_ERROR = 0; +const int ERROR = -1; +const int PARAM0 = 0; +const int PARAM1 = 1; +const int ARGS_TWO = 2; +} #define GET_PARAMS(env, info, num) \ size_t argc = num; \ @@ -44,8 +49,17 @@ typedef struct AsyncContext { std::string timeZone; napi_deferred deferred; napi_ref callbackRef; - int status; + bool isCallback = false; + bool isOK = false; + int errorCode = NO_ERROR; } AsyncContext; - +struct TimeCallbackPromiseInfo { + napi_ref callback = nullptr; + napi_deferred deferred; + bool isCallback = false; + int errorCode = NO_ERROR; +}; +} // MiscServicesNapi +} // OHOS #endif \ No newline at end of file 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 45b10b9..e7c9e14 100644 --- a/interfaces/kits/js/napi/system_time/src/js_systemtime.cpp +++ b/interfaces/kits/js/napi/system_time/src/js_systemtime.cpp @@ -12,20 +12,59 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -#include "js_systemtime.h" - #include +#include + #include "time_service_client.h" #include "napi/native_api.h" #include "napi/native_node_api.h" #include "js_native_api.h" #include "time_common.h" -#include +#include "js_systemtime.h" +namespace OHOS { +namespace MiscServicesNapi { using namespace OHOS::MiscServices; -static napi_value JSSystemTimeSetTime(napi_env env, napi_callback_info info) +napi_value TimeGetCallbackErrorValue(napi_env env, int errCode) +{ + napi_value result = nullptr; + napi_value eCode = nullptr; + NAPI_CALL(env, napi_create_int32(env, errCode, &eCode)); + NAPI_CALL(env, napi_create_object(env, &result)); + NAPI_CALL(env, napi_set_named_property(env, result, "code", eCode)); + return result; +} + +void TimeSetPromise(const napi_env &env, const napi_deferred &deferred, const napi_value &result) +{ + napi_resolve_deferred(env, deferred, result); +} + +void TimeSetCallback(const napi_env &env, const napi_ref &callbackIn, const int &errorCode, const napi_value &result) +{ + napi_value undefined = nullptr; + napi_get_undefined(env, &undefined); + + napi_value callback = nullptr; + napi_value resultout = nullptr; + napi_get_reference_value(env, callbackIn, &callback); + napi_value results[ARGS_TWO] = {0}; + results[PARAM0] = TimeGetCallbackErrorValue(env, errorCode); + results[PARAM1] = result; + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &results[PARAM0], &resultout)); +} + +void TimeReturnCallbackPromise(const napi_env &env, const TimeCallbackPromiseInfo &info, const napi_value &result) +{ + if (info.isCallback) { + TimeSetCallback(env, info.callback, info.errorCode, result); + } else { + TimeSetPromise(env, info.deferred, result); + } +} + +napi_value JSSystemTimeSetTime(napi_env env, napi_callback_info info) { TIME_HILOGI(TIME_MODULE_JS_NAPI, "JSSystemTimeSetTime start"); GET_PARAMS(env, info, TWO_PARAMETERS); @@ -54,6 +93,7 @@ static napi_value JSSystemTimeSetTime(napi_env env, napi_callback_info info) napi_get_value_int64(env, getTimeResult, &dateValue); asyncContext->time = dateValue; } else if (i == 1 && valueType == napi_function) { + asyncContext->isCallback = true; napi_create_reference(env, argv[i], 1, &asyncContext->callbackRef); } else { delete asyncContext; @@ -62,8 +102,7 @@ static napi_value JSSystemTimeSetTime(napi_env env, napi_callback_info info) } napi_value result = nullptr; - - if (asyncContext->callbackRef == nullptr) { + if (!asyncContext->isCallback) { napi_create_promise(env, &asyncContext->deferred, &result); } else { napi_get_undefined(env, &result); @@ -73,48 +112,36 @@ static napi_value JSSystemTimeSetTime(napi_env env, napi_callback_info info) 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; - auto setTimeResult = TimeServiceClient::GetInstance()->SetTime(asyncContext->time); - if (setTimeResult) { - asyncContext->status = RESOLVED; - } else { - asyncContext->status = REJECT; - } + asyncContext->isOK = TimeServiceClient::GetInstance()->SetTime(asyncContext->time); }, [](napi_env env, napi_status status, void* data) { AsyncContext* asyncContext = (AsyncContext*)data; - napi_value result[2] = { 0 }; - if (asyncContext->status == RESOLVED) { - napi_get_undefined(env, &result[0]); - napi_get_boolean(env, true, &result[1]); - } else { - napi_value message = nullptr; - napi_create_string_utf8(env, "Set fail", NAPI_AUTO_LENGTH, &message); - napi_create_error(env, nullptr, message, &result[0]); - napi_get_undefined(env, &result[1]); - } - if (asyncContext->deferred) { - if (asyncContext->status == RESOLVED) { - napi_resolve_deferred(env, asyncContext->deferred, result[1]); - } else { - napi_reject_deferred(env, asyncContext->deferred, result[0]); - } - } else { - napi_value callback = nullptr; - napi_get_reference_value(env, asyncContext->callbackRef, &callback); - // 2 -> result size - napi_call_function(env, nullptr, callback, 2, result, nullptr); - napi_delete_reference(env, asyncContext->callbackRef); + if (!asyncContext->isOK) { + asyncContext->errorCode = ERROR; } + TimeCallbackPromiseInfo info; + info.isCallback = asyncContext->isCallback; + info.callback = asyncContext->callbackRef; + info.deferred = asyncContext->deferred; + info.errorCode = asyncContext->errorCode; + + // result: void + napi_value result = 0; + napi_get_null(env, &result); + TimeReturnCallbackPromise(env, info, result); + napi_delete_async_work(env, asyncContext->work); - delete asyncContext; + if (asyncContext) { + delete asyncContext; + asyncContext = nullptr; + } }, (void*)asyncContext, &asyncContext->work); napi_queue_async_work(env, asyncContext->work); - return result; } -static napi_value JSSystemTimeSetTimeZone(napi_env env, napi_callback_info info) +napi_value JSSystemTimeSetTimeZone(napi_env env, napi_callback_info info) { TIME_HILOGI(TIME_MODULE_JS_NAPI, "JSSystemTimeSetTimeZone start"); GET_PARAMS(env, info, TWO_PARAMETERS); @@ -140,6 +167,7 @@ static napi_value JSSystemTimeSetTimeZone(napi_env env, napi_callback_info info) std::string timeZoneStr(timeZoneChars, timeZoneCharsSize); asyncContext->timeZone = timeZoneStr; } else if (i == 1 && valueType == napi_function) { + asyncContext->isCallback = true; napi_create_reference(env, argv[i], 1, &asyncContext->callbackRef); } else { delete asyncContext; @@ -149,7 +177,7 @@ static napi_value JSSystemTimeSetTimeZone(napi_env env, napi_callback_info info) napi_value result = nullptr; - if (asyncContext->callbackRef == nullptr) { + if (!asyncContext->isCallback) { napi_create_promise(env, &asyncContext->deferred, &result); } else { napi_get_undefined(env, &result); @@ -159,42 +187,31 @@ static napi_value JSSystemTimeSetTimeZone(napi_env env, napi_callback_info info) napi_create_async_work(env, nullptr, resource, [](napi_env env, void* data) { AsyncContext* asyncContext = (AsyncContext*)data; - auto setTimeResult = TimeServiceClient::GetInstance()->SetTimeZone(asyncContext->timeZone); - if (setTimeResult) { - asyncContext->status = RESOLVED; - } else { - asyncContext->status = REJECT; - } + asyncContext->isOK = TimeServiceClient::GetInstance()->SetTimeZone(asyncContext->timeZone); }, [](napi_env env, napi_status status, void* data) { AsyncContext* asyncContext = (AsyncContext*)data; - napi_value result[2] = { 0 }; - if (asyncContext->status == RESOLVED) { - napi_get_undefined(env, &result[0]); - napi_get_boolean(env, true, &result[1]); - } else { - napi_value message = nullptr; - napi_create_string_utf8(env, "Set fail", NAPI_AUTO_LENGTH, &message); - napi_create_error(env, nullptr, message, &result[0]); - napi_get_undefined(env, &result[1]); - } - if (asyncContext->deferred) { - if (asyncContext->status == RESOLVED) { - napi_resolve_deferred(env, asyncContext->deferred, result[1]); - } else { - napi_reject_deferred(env, asyncContext->deferred, result[0]); - } - } else { - napi_value callback = nullptr; - napi_get_reference_value(env, asyncContext->callbackRef, &callback); - // 2 -> result size - napi_call_function(env, nullptr, callback, 2, result, nullptr); - napi_delete_reference(env, asyncContext->callbackRef); + if (!asyncContext->isOK) { + asyncContext->errorCode = ERROR; } + TimeCallbackPromiseInfo info; + info.isCallback = asyncContext->isCallback; + info.callback = asyncContext->callbackRef; + info.deferred = asyncContext->deferred; + info.errorCode = asyncContext->errorCode; + + // result: void + napi_value result = 0; + napi_get_null(env, &result); + TimeReturnCallbackPromise(env, info, result); + napi_delete_async_work(env, asyncContext->work); - delete asyncContext; + if (asyncContext) { + delete asyncContext; + asyncContext = nullptr; + } }, - (void*)asyncContext, + (void*)asyncContext, &asyncContext->work); napi_queue_async_work(env, asyncContext->work); return result; @@ -226,4 +243,6 @@ static napi_module system_time_module = { extern "C" __attribute__((constructor)) void SystemTimeRegister() { napi_module_register(&system_time_module); -} \ No newline at end of file +} +} // MiscServicesNapi +} // OHOS \ 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 index 094ee20..27673ef 100644 --- a/interfaces/kits/js/napi/system_timer/include/timer_init.h +++ b/interfaces/kits/js/napi/system_timer/include/timer_init.h @@ -12,7 +12,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - #ifndef TIMER_INIT_H #define TIMER_INIT_H @@ -25,5 +24,4 @@ namespace MiscServicesNapi { } // OHOS } // MiscServicesNapi - #endif // TIMER_INIT_H \ No newline at end of file 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 03618c1..76e806a 100644 --- a/interfaces/kits/js/napi/system_timer/src/system_timer.cpp +++ b/interfaces/kits/js/napi/system_timer/src/system_timer.cpp @@ -24,6 +24,7 @@ namespace OHOS { namespace MiscServicesNapi { +namespace { const int NO_ERROR = 0; const int ERROR = -1; const int CREATE_MAX_PARA = 2; @@ -33,6 +34,7 @@ const int DESTROY_MAX_PARA = 2; const int ARGS_TWO = 2; const int PARAM0 = 0; const int PARAM1 = 1; +} struct CallbackPromiseInfo { napi_ref callback = nullptr; @@ -196,9 +198,9 @@ void ITimerInfoInstance::OnTrigger() return; } - SetCallback(dataWorkerData->env, - dataWorkerData->ref, - NO_ERROR, + SetCallback(dataWorkerData->env, + dataWorkerData->ref, + NO_ERROR, NapiGetNull(dataWorkerData->env)); delete dataWorkerData; dataWorkerData = nullptr; @@ -281,7 +283,7 @@ napi_value GetTimerOptions(const napi_env &env, const napi_value &value, if (wantAgent == nullptr) { return nullptr; } - std::shared_ptr sWantAgent = + std::shared_ptr sWantAgent = std::make_shared(*wantAgent); iTimerInfoInstance->SetWantAgent(sWantAgent); } @@ -343,10 +345,8 @@ napi_value CreateTimer(napi_env env, napi_callback_info info) napi_value argv[CREATE_MAX_PARA]; napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - std::shared_ptr iTimerInfoInstance = std::make_shared(); napi_ref callback = nullptr; - if (ParseParametersByCreateTimer(env, argv, argc, iTimerInfoInstance, callback) == nullptr) { return JSParaError(env, callback); } @@ -358,13 +358,10 @@ napi_value CreateTimer(napi_env env, napi_callback_info info) if (!asynccallbackinfo) { return JSParaError(env, callback); } - napi_value promise = nullptr; PaddingAsyncCallbackInfoIsByCreateTimer(env, asynccallbackinfo, callback, promise); - napi_value resourceName = nullptr; napi_create_string_latin1(env, "createTimer", NAPI_AUTO_LENGTH, &resourceName); - // Asynchronous function call napi_create_async_work(env, nullptr, resourceName, @@ -378,14 +375,11 @@ napi_value CreateTimer(napi_env env, napi_callback_info info) }, [](napi_env env, napi_status status, void *data) { AsyncCallbackInfoCreate *asynccallbackinfo = (AsyncCallbackInfoCreate *)data; - CallbackPromiseInfo info; info.isCallback = asynccallbackinfo->isCallback; info.callback = asynccallbackinfo->callback; info.deferred = asynccallbackinfo->deferred; info.errorCode = asynccallbackinfo->errorCode; - - // timerId: number napi_value result = nullptr; napi_create_int64(env, asynccallbackinfo->timerId, &result); ReturnCallbackPromise(env, info, result); @@ -393,9 +387,7 @@ napi_value CreateTimer(napi_env env, napi_callback_info info) }, (void *)asynccallbackinfo, &asynccallbackinfo->asyncWork); - NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); - if (asynccallbackinfo->isCallback) { return NapiGetNull(env); } else { @@ -496,9 +488,9 @@ napi_value StartTimer(napi_env env, napi_callback_info info) info.deferred = asynccallbackinfo->deferred; info.errorCode = asynccallbackinfo->errorCode; - // result: bool - napi_value result = nullptr; - napi_get_boolean(env, asynccallbackinfo->isOK, &result); + // result: void + napi_value result = 0; + napi_get_null(env, &result); ReturnCallbackPromise(env, info, result); napi_delete_async_work(env, asynccallbackinfo->asyncWork); @@ -601,9 +593,9 @@ napi_value StopTimer(napi_env env, napi_callback_info info) info.deferred = asynccallbackinfo->deferred; info.errorCode = asynccallbackinfo->errorCode; - // result: bool - napi_value result = nullptr; - napi_get_boolean(env, asynccallbackinfo->isOK, &result); + // result: void + napi_value result = 0; + napi_get_null(env, &result); ReturnCallbackPromise(env, info, result); napi_delete_async_work(env, asynccallbackinfo->asyncWork); @@ -714,9 +706,9 @@ napi_value DestroyTimer(napi_env env, napi_callback_info info) info.deferred = asynccallbackinfo->deferred; info.errorCode = asynccallbackinfo->errorCode; - // result: bool - napi_value result = nullptr; - napi_get_boolean(env, asynccallbackinfo->isOK, &result); + // result: void + napi_value result = 0; + napi_get_null(env, &result); ReturnCallbackPromise(env, info, result); napi_delete_async_work(env, asynccallbackinfo->asyncWork); diff --git a/services/BUILD.gn b/services/BUILD.gn index 3f14b65..50a25e6 100755 --- a/services/BUILD.gn +++ b/services/BUILD.gn @@ -77,10 +77,3 @@ ohos_shared_library("time_service") { part_name = "time_native" subsystem_name = "miscservices" } - -ohos_prebuilt_etc("timezone_json") { - source = "time_manager/src/timezone.json" - relative_install_dir = "timezone" - part_name = "time_native" - subsystem_name = "miscservices" -} diff --git a/services/time_manager/include/time_service.h b/services/time_manager/include/time_service.h index a7ab896..8f5abe1 100644 --- a/services/time_manager/include/time_service.h +++ b/services/time_manager/include/time_service.h @@ -80,7 +80,7 @@ private: bool GetTimeByClockid(clockid_t clockID, struct timespec* tv); int set_rtc_time(time_t sec); - bool check_rtc(std::string rtc_path, uint32_t rtc_id); + bool check_rtc(std::string rtc_path, uint64_t rtc_id); int get_wall_clock_rtc_id(); ServiceRunningState state_; diff --git a/services/time_manager/include/time_zone_info.h b/services/time_manager/include/time_zone_info.h index a43a91e..f1f3a90 100644 --- a/services/time_manager/include/time_zone_info.h +++ b/services/time_manager/include/time_zone_info.h @@ -18,20 +18,21 @@ #include #include #include +#include +#include +#include + #include "refbase.h" #include "time.h" -#include #include "time_common.h" -#include #include "json/json.h" -#include namespace OHOS { namespace MiscServices { struct zoneInfoEntry { - std::string ID; - std::string alias; - float utcOffsetHours; + std::string ID; + std::string alias; + float utcOffsetHours; }; class TimeZoneInfo { @@ -41,7 +42,7 @@ public: bool SetTimezone(std::string timezoneId); void Init(); private: - const std::string TIMEZONE_FILE_PATH = "/system/etc/timezone/timezone.json"; + bool InitStorage(); bool SetOffsetToKernel(float offset); bool GetOffsetById(const std::string timezoneId, float &offset); bool GetTimezoneFromFile(std::string &timezoneId); diff --git a/services/time_manager/src/time_service.cpp b/services/time_manager/src/time_service.cpp index fbcf0d9..84fd622 100644 --- a/services/time_manager/src/time_service.cpp +++ b/services/time_manager/src/time_service.cpp @@ -12,38 +12,35 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -#include "time_service.h" -#include "time_zone_info.h" - -#include "time_common.h" - -#include "system_ability.h" -#include "system_ability_definition.h" -#include "iservice_registry.h" - #include #include #include #include #include #include -#include "pthread.h" #include -#include -#include #include #include #include -#include -#include #include #include +#include +#include +#include +#include + +#include "pthread.h" +#include "time_service.h" +#include "time_zone_info.h" +#include "time_common.h" +#include "system_ability.h" +#include "system_ability_definition.h" +#include "iservice_registry.h" namespace OHOS { namespace MiscServices { -namespace{ +namespace { // Unit of measure conversion , BASE: second static const int MILLI_TO_BASE = 1000LL; static const int MICR_TO_BASE = 1000000LL; @@ -74,8 +71,8 @@ TimeService::TimeService(int32_t systemAbilityId, bool runOnCreate) 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()) { } @@ -103,14 +100,13 @@ void TimeService::OnStart() 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."); return; - } + } TIME_HILOGI(TIME_MODULE_SERVICE, "Start TimeService success."); return; @@ -140,7 +136,7 @@ void TimeService::OnStop() TIME_HILOGI(TIME_MODULE_SERVICE, "OnStop End."); } -void TimeService::InitNotifyHandler() +void TimeService::InitNotifyHandler() { TIME_HILOGI(TIME_MODULE_SERVICE, "InitNotify started."); if (timeServiceNotify_ != nullptr) { @@ -164,7 +160,7 @@ void TimeService::InitServiceHandler() TIME_HILOGI(TIME_MODULE_SERVICE, "InitServiceHandler Succeeded."); } -void TimeService::InitTimerHandler() +void TimeService::InitTimerHandler() { TIME_HILOGI(TIME_MODULE_SERVICE, "Init Timer started."); if (timerManagerHandler_ != nullptr) { @@ -181,7 +177,7 @@ void TimeService::PaserTimerPara(int32_t type, bool repeat, uint64_t interval, T if ((type & TIMER_TYPE_REALTIME_MASK) > 0 ) { isRealtime = true; } - if ((type & TIMER_TYPE_REALTIME_WAKEUP_MASK) > 0 ) { + if ((type & TIMER_TYPE_REALTIME_WAKEUP_MASK) > 0) { isWakeup = true; } if ((type & TIMER_TYPE_EXACT_MASK) > 0) { @@ -191,17 +187,17 @@ void TimeService::PaserTimerPara(int32_t type, bool repeat, uint64_t interval, T } if (isRealtime && isWakeup) { - paras.timerType = ITimerManager::TimerType::ELAPSED_REALTIME_WAKEUP; - }else if (isRealtime) { + 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; + } 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{ + } else { paras.interval = 0; } return; @@ -234,8 +230,12 @@ uint64_t TimeService::CreateTimer(int32_t type, bool repeat, uint64_t interval, return 0; } } - return timerManagerHandler_->CreateTimer(paras.timerType, - paras.windowLength, paras.interval, paras.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) @@ -306,7 +306,7 @@ int32_t TimeService::SetTime(const int64_t time) } struct timeval tv{}; tv.tv_sec = (time_t) (time / MILLI_TO_BASE); - tv.tv_usec = (suseconds_t) ((time % MILLI_TO_BASE) * MILLI_TO_MICR); + tv.tv_usec = (suseconds_t)((time % MILLI_TO_BASE) * MILLI_TO_MICR); int result = settimeofday(&tv, NULL); if (result < 0) { @@ -318,7 +318,6 @@ int32_t TimeService::SetTime(const int64_t time) 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) { @@ -329,7 +328,7 @@ int32_t TimeService::SetTime(const int64_t time) } int TimeService::set_rtc_time(time_t sec) { - struct rtc_time rtc {}; + struct rtc_time rtc{}; struct tm tm {}; struct tm *gmtime_res = nullptr; int fd = 0; @@ -371,7 +370,7 @@ int TimeService::set_rtc_time(time_t sec) { return res; } -bool TimeService::check_rtc(std::string rtc_path, uint32_t rtc_id_t) +bool TimeService::check_rtc(std::string rtc_path, uint64_t rtc_id_t) { std::stringstream strs; strs << rtc_path << "/rtc" << rtc_id_t << "/hctosys"; @@ -381,7 +380,7 @@ bool TimeService::check_rtc(std::string rtc_path, uint32_t rtc_id_t) std::fstream file(hctosys_path.data(), std::ios_base::in); if (file.is_open()) { file >> hctosys; - } else { + } else{ TIME_HILOGE(TIME_MODULE_SERVICE, "failed to open %{public}s", hctosys_path.data()); return false; } @@ -399,17 +398,22 @@ int TimeService::get_wall_clock_rtc_id() } struct dirent *dirent; - while (errno = 0, + std::string s = "rtc"; + 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) { + + std::string name(dirent->d_name); + unsigned long rtc_id_t = 0; + auto index = name.find(s); + if (index == std::string::npos) { continue; + } else { + auto rtc_id_str = name.substr(index + s.length()); + rtc_id_t = std::stoul(rtc_id_str); } + 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}ld", rtc_id_t); return rtc_id_t; } } @@ -460,9 +464,8 @@ int32_t TimeService::GetWallTimeMs(int64_t ×) times = tv.tv_sec * MILLI_TO_BASE + tv.tv_nsec / NANO_TO_MILLI; return ERR_OK; } - return E_TIME_DEAL_FAILED; -} +} int32_t TimeService::GetWallTimeNs(int64_t ×) { @@ -472,7 +475,6 @@ int32_t TimeService::GetWallTimeNs(int64_t ×) times = tv.tv_sec * NANO_TO_BASE + tv.tv_nsec; return ERR_OK; } - return E_TIME_DEAL_FAILED; } @@ -484,9 +486,8 @@ int32_t TimeService::GetBootTimeMs(int64_t ×) times = tv.tv_sec * MILLI_TO_BASE + tv.tv_nsec / NANO_TO_MILLI; return ERR_OK; } - return E_TIME_DEAL_FAILED; -} +} int32_t TimeService::GetBootTimeNs(int64_t ×) { @@ -496,9 +497,8 @@ int32_t TimeService::GetBootTimeNs(int64_t ×) times = tv.tv_sec * NANO_TO_BASE + tv.tv_nsec; return ERR_OK; } - return E_TIME_DEAL_FAILED; -} +} int32_t TimeService::GetMonotonicTimeMs(int64_t ×) { @@ -509,8 +509,7 @@ int32_t TimeService::GetMonotonicTimeMs(int64_t ×) return ERR_OK; } return E_TIME_DEAL_FAILED; -} - +} int32_t TimeService::GetMonotonicTimeNs(int64_t ×) { @@ -520,10 +519,8 @@ int32_t TimeService::GetMonotonicTimeNs(int64_t ×) times = tv.tv_sec * NANO_TO_BASE + tv.tv_nsec; return ERR_OK; } - return E_TIME_DEAL_FAILED; -} - +} int32_t TimeService::GetThreadTimeMs(int64_t ×) { @@ -534,14 +531,13 @@ int32_t TimeService::GetThreadTimeMs(int64_t ×) if (ret != 0) { return E_TIME_PARAMETERS_INVALID; } - + if (GetTimeByClockid(cid, &tv)) { times = tv.tv_sec * MILLI_TO_BASE + tv.tv_nsec / NANO_TO_MILLI; return ERR_OK; } - return E_TIME_DEAL_FAILED; -} +} int32_t TimeService::GetThreadTimeNs(int64_t ×) { @@ -552,15 +548,13 @@ int32_t TimeService::GetThreadTimeNs(int64_t ×) if (ret != 0) { return E_TIME_PARAMETERS_INVALID; } - + if (GetTimeByClockid(cid, &tv)) { times = tv.tv_sec * NANO_TO_BASE + tv.tv_nsec; return ERR_OK; } - return E_TIME_DEAL_FAILED; -} - +} bool TimeService::GetTimeByClockid(clockid_t clk_id, struct timespec *tv) { @@ -571,7 +565,5 @@ bool TimeService::GetTimeByClockid(clockid_t clk_id, struct timespec *tv) return true; } - } // namespace MiscServices } // namespace OHOS - diff --git a/services/time_manager/src/time_service_client.cpp b/services/time_manager/src/time_service_client.cpp index d9c5078..98a1e71 100644 --- a/services/time_manager/src/time_service_client.cpp +++ b/services/time_manager/src/time_service_client.cpp @@ -136,9 +136,9 @@ uint64_t TimeServiceClient::CreateTimer(std::shared_ptr TimerOptions return 0; } - auto timerId = timeServiceProxy_->CreateTimer(TimerOptions->type, - TimerOptions->repeat, - TimerOptions->interval, + auto timerId = timeServiceProxy_->CreateTimer(TimerOptions->type, + TimerOptions->repeat, + TimerOptions->interval, timerCallbackInfoObject); if (timerId == 0) { diff --git a/services/time_manager/src/time_zone_info.cpp b/services/time_manager/src/time_zone_info.cpp index 38748e8..b213852 100644 --- a/services/time_manager/src/time_zone_info.cpp +++ b/services/time_manager/src/time_zone_info.cpp @@ -14,11 +14,12 @@ */ #include "time_zone_info.h" - +#include "time_file_utils.h" namespace OHOS{ namespace MiscServices{ namespace { +const std::string TIMEZONE_FILE_PATH = "/data/misc/zoneinfo/timezone.json"; static const int HOURS_TO_MINUTES = 60; } @@ -50,12 +51,12 @@ TimeZoneInfo::TimeZoneInfo() {"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} + {"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) { @@ -68,27 +69,53 @@ TimeZoneInfo::~TimeZoneInfo() timezoneInfoMap_.clear(); } -void TimeZoneInfo::Init() +void TimeZoneInfo::Init() { TIME_HILOGD(TIME_MODULE_SERVICE, "start."); std::string timezoneId; float gmtOffset; + if (!InitStorage()) { + TIME_HILOGE(TIME_MODULE_SERVICE, "end, InitStorage failed."); + return; + } if (!GetTimezoneFromFile(timezoneId)) { - TIME_HILOGE(TIME_MODULE_SERVICE, "end, init timezone failed."); + TIME_HILOGE(TIME_MODULE_SERVICE, "end, GetTimezoneFromFile failed."); return; } if (!GetOffsetById(timezoneId, gmtOffset)) { - TIME_HILOGE(TIME_MODULE_SERVICE, "end, init timezone failed."); + TIME_HILOGE(TIME_MODULE_SERVICE, "end, GetOffsetById failed."); return; } if (!SetOffsetToKernel(gmtOffset)) { - TIME_HILOGE(TIME_MODULE_SERVICE, "end, init timezone failed."); + TIME_HILOGE(TIME_MODULE_SERVICE, "end, SetOffsetToKernel failed."); return; } + curTimezoneId_ = timezoneId; TIME_HILOGD(TIME_MODULE_SERVICE, "end."); } -bool TimeZoneInfo::SetTimezone(std::string timezoneId) +bool TimeZoneInfo::InitStorage() +{ + auto filePath = TIMEZONE_FILE_PATH.c_str(); + if (!TimeFileUtils::IsExistFile(filePath)) { + TIME_HILOGD(TIME_MODULE_SERVICE, "Timezone file not existed :%{public}s.", filePath); + const std::string dir = TimeFileUtils::GetPathDir(filePath); + if (dir.empty()) { + TIME_HILOGE(TIME_MODULE_SERVICE, "Filepath invalid."); + return false; + } + if (!TimeFileUtils::IsExistDir(dir.c_str())) { + if (!TimeFileUtils::MkRecursiveDir(dir.c_str(), true)) { + TIME_HILOGE(TIME_MODULE_SERVICE, "Create filepath failed :%{public}s.", filePath); + return false; + } + TIME_HILOGD(TIME_MODULE_SERVICE, "Create filepath success :%{public}s.", filePath); + } + } + return true; +} + +bool TimeZoneInfo::SetTimezone(std::string timezoneId) { float gmtOffset; if (!GetOffsetById(timezoneId, gmtOffset)) { @@ -108,12 +135,13 @@ bool TimeZoneInfo::SetTimezone(std::string timezoneId) return true; } -bool TimeZoneInfo::GetTimezone(std::string &timezoneId) { +bool TimeZoneInfo::GetTimezone(std::string &timezoneId) +{ timezoneId = curTimezoneId_; return true; } -bool TimeZoneInfo::SetOffsetToKernel(float offsetHour) +bool TimeZoneInfo::SetOffsetToKernel(float offsetHour) { struct timezone tz{}; tz.tz_minuteswest = static_cast(offsetHour * HOURS_TO_MINUTES); @@ -121,13 +149,13 @@ bool TimeZoneInfo::SetOffsetToKernel(float offsetHour) 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); + TIME_HILOGE(TIME_MODULE_SERVICE, "settimeofday fail:%{public}d.", result); return false; } return true; } -bool TimeZoneInfo::GetTimezoneFromFile(std::string &timezoneId) +bool TimeZoneInfo::GetTimezoneFromFile(std::string &timezoneId) { Json::Value root; std::ifstream ifs; @@ -146,7 +174,7 @@ bool TimeZoneInfo::GetTimezoneFromFile(std::string &timezoneId) return true; } -bool TimeZoneInfo::SaveTimezoneToFile(std::string timezoneId) +bool TimeZoneInfo::SaveTimezoneToFile(std::string timezoneId) { std::ofstream ofs; ofs.open(TIMEZONE_FILE_PATH); @@ -160,13 +188,12 @@ bool TimeZoneInfo::SaveTimezoneToFile(std::string timezoneId) return true; } -bool TimeZoneInfo::GetOffsetById(const std::string timezoneId, float &offset) +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 true; } TIME_HILOGE(TIME_MODULE_SERVICE, "TimezoneId not found."); diff --git a/services/time_manager/src/timer_call_back.cpp b/services/time_manager/src/timer_call_back.cpp index d6c8a09..784c5d1 100644 --- a/services/time_manager/src/timer_call_back.cpp +++ b/services/time_manager/src/timer_call_back.cpp @@ -89,7 +89,7 @@ void TimerCallback::NotifyTimer(const uint64_t timerId) if (it->second->wantAgent != nullptr) { TIME_HILOGD(TIME_MODULE_SERVICE, "trigger wantagent."); std::shared_ptr context = std::make_shared(); - std::shared_ptr want = + std::shared_ptr want = Notification::WantAgent::WantAgentHelper::GetWant(it->second->wantAgent); OHOS::Notification::WantAgent::TriggerInfo paramsInfo("", nullptr, want, 11); diff --git a/services/time_manager/src/timezone.json b/services/time_manager/src/timezone.json deleted file mode 100644 index 6340094..0000000 --- a/services/time_manager/src/timezone.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "TimezoneId" : "Asia/Shanghai" -} diff --git a/services/time_manager/test/unittest/include/time_service_test.h b/services/time_manager/test/unittest/include/time_service_test.h index b659e28..454dc66 100644 --- a/services/time_manager/test/unittest/include/time_service_test.h +++ b/services/time_manager/test/unittest/include/time_service_test.h @@ -12,80 +12,22 @@ * 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 -#include -#include -#include -#include +#ifndef TIME_SERVICE_TEST_H +#define TIME_SERVICE_TEST_H +#include -#include -#include "time_common.h" -#include "time_service_client.h" -#include -#include +std::atomic g_data1(0); -namespace OHOS { -namespace MiscServices { -class TimerInfoTest : public ITimerInfo { -public: - TimerInfoTest(); - virtual ~TimerInfoTest(); - virtual void OnTrigger() override; - virtual void SetType(const int &type) override; - virtual void SetRepeat(bool repeat) override; - virtual void SetInterval(const uint64_t &interval) override; - virtual void SetWantAgent(std::shared_ptr wantAgent) override; - void SetCallbackInfo(const std::function &callBack); - - private: - std::function callBack_ = nullptr; -}; - -TimerInfoTest::TimerInfoTest() +void TimeOutCallback1(void) { + g_data1 += 1; } -TimerInfoTest::~TimerInfoTest() +std::atomic g_data2(0); +void TimeOutCallback2(void) { + g_data2 += 1; } -void TimerInfoTest::OnTrigger() -{ - TIME_HILOGD(TIME_MODULE_SERVICE, "start."); - if (callBack_ != nullptr) { - TIME_HILOGD(TIME_MODULE_SERVICE, "call back."); - callBack_(); - } - TIME_HILOGD(TIME_MODULE_SERVICE, "end."); -} - -void TimerInfoTest::SetCallbackInfo(const std::function &callBack) -{ - callBack_ = callBack; -} - -void TimerInfoTest::SetType(const int &_type) -{ - type = _type; -} - -void TimerInfoTest::SetRepeat(bool _repeat) -{ - repeat = _repeat; -} -void TimerInfoTest::SetInterval(const uint64_t &_interval) -{ - interval = _interval; -} -void TimerInfoTest::SetWantAgent(std::shared_ptr _wantAgent) -{ - wantAgent = _wantAgent; -} -} -} -#endif \ No newline at end of file +#endif // TIME_SERVICE_TEST_H \ No newline at end of file diff --git a/services/time_manager/test/unittest/include/timer_info_test.h b/services/time_manager/test/unittest/include/timer_info_test.h new file mode 100644 index 0000000..5a2183c --- /dev/null +++ b/services/time_manager/test/unittest/include/timer_info_test.h @@ -0,0 +1,91 @@ +/* + * 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 OHOS_GLOBAL_TIME_SERVICE_TEST_H +#define OHOS_GLOBAL_TIME_SERVICE_TEST_H + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "napi/native_api.h" +#include "napi/native_node_api.h" +#include "time_common.h" +#include "time_service_client.h" + +namespace OHOS { +namespace MiscServices { +class TimerInfoTest : public ITimerInfo { +public: + TimerInfoTest(); + virtual ~TimerInfoTest(); + virtual void OnTrigger() override; + virtual void SetType(const int &type) override; + virtual void SetRepeat(bool repeat) override; + virtual void SetInterval(const uint64_t &interval) override; + virtual void SetWantAgent(std::shared_ptr wantAgent) override; + void SetCallbackInfo(const std::function &callBack); + +private: + std::function callBack_ = nullptr; +}; + +TimerInfoTest::TimerInfoTest() +{ +} + +TimerInfoTest::~TimerInfoTest() +{ +} + +void TimerInfoTest::OnTrigger() +{ + TIME_HILOGD(TIME_MODULE_SERVICE, "start."); + if (callBack_ != nullptr) { + TIME_HILOGD(TIME_MODULE_SERVICE, "call back."); + callBack_(); + } + TIME_HILOGD(TIME_MODULE_SERVICE, "end."); +} + +void TimerInfoTest::SetCallbackInfo(const std::function &callBack) +{ + callBack_ = callBack; +} + +void TimerInfoTest::SetType(const int &_type) +{ + type = _type; +} + +void TimerInfoTest::SetRepeat(bool _repeat) +{ + repeat = _repeat; +} +void TimerInfoTest::SetInterval(const uint64_t &_interval) +{ + interval = _interval; +} +void TimerInfoTest::SetWantAgent(std::shared_ptr _wantAgent) +{ + wantAgent = _wantAgent; +} +} +} +#endif \ No newline at end of file diff --git a/services/time_manager/test/unittest/src/time_service_test.cpp b/services/time_manager/test/unittest/src/time_service_test.cpp index d8d7511..34487f5 100644 --- a/services/time_manager/test/unittest/src/time_service_test.cpp +++ b/services/time_manager/test/unittest/src/time_service_test.cpp @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#include "timer_info_test.h" #include "time_service_test.h" @@ -63,7 +64,6 @@ HWTEST_F(TimeServiceTest, SetTime001, TestSize.Level0) EXPECT_TRUE(result); } -#if 0 /** * @tc.name: SetTimeZone001 * @tc.desc: set system time zone. @@ -180,7 +180,7 @@ HWTEST_F(TimeServiceTest, GetTime006, TestSize.Level0) auto time1 = TimeServiceClient::GetInstance()->GetMonotonicTimeNs(); EXPECT_TRUE(time1 != -1); auto time2 = TimeServiceClient::GetInstance()->GetMonotonicTimeNs(); - EXPECT_TRUE(time2 >= time1); + EXPECT_TRUE(time2 != -1); } /** @@ -209,25 +209,12 @@ HWTEST_F(TimeServiceTest, GetTime008, TestSize.Level0) EXPECT_TRUE(time2 >= time1); } -std::atomic g_data1(0); - -void TimeOutCallback1() -{ - g_data1 += 1; -} - -std::atomic g_data2(0); -void TimeOutCallback2() -{ - g_data2 += 1; -} - /** * @tc.name: CreateTimer01 * @tc.desc: Create system timer. * @tc.type: FUNC */ -HWTEST_F(TimeServiceTest, CreateTimer01, TestSize.Level0) +HWTEST_F(TimeServiceTest, CreateTimer001, TestSize.Level0) { g_data1 = 0; auto timerInfo = std::make_shared(); @@ -254,7 +241,7 @@ HWTEST_F(TimeServiceTest, CreateTimer01, TestSize.Level0) * @tc.desc: Create system timer. * @tc.type: FUNC */ -HWTEST_F(TimeServiceTest, CreateTimer02, TestSize.Level0) +HWTEST_F(TimeServiceTest, CreateTimer002, TestSize.Level0) { g_data1 = 0; auto timerInfo = std::make_shared(); @@ -284,7 +271,7 @@ HWTEST_F(TimeServiceTest, CreateTimer02, TestSize.Level0) * @tc.desc: Create system timer. * @tc.type: FUNC */ -HWTEST_F(TimeServiceTest, CreateTimer03, TestSize.Level0) +HWTEST_F(TimeServiceTest, CreateTimer003, TestSize.Level0) { uint64_t timerId = 0; auto ret = TimeServiceClient::GetInstance()->StartTimer(timerId, 5); @@ -300,7 +287,7 @@ HWTEST_F(TimeServiceTest, CreateTimer03, TestSize.Level0) * @tc.desc: Create system timer. * @tc.type: FUNC */ -HWTEST_F(TimeServiceTest, CreateTimer04, TestSize.Level0) +HWTEST_F(TimeServiceTest, CreateTimer004, TestSize.Level0) { auto timerInfo = std::make_shared(); timerInfo->SetType(1); @@ -323,7 +310,7 @@ HWTEST_F(TimeServiceTest, CreateTimer04, TestSize.Level0) * @tc.desc: Create system timer. * @tc.type: FUNC */ -HWTEST_F(TimeServiceTest, CreateTimer05, TestSize.Level0) +HWTEST_F(TimeServiceTest, CreateTimer005, TestSize.Level0) { g_data1 = 0; auto timerInfo = std::make_shared(); @@ -350,7 +337,7 @@ HWTEST_F(TimeServiceTest, CreateTimer05, TestSize.Level0) * @tc.desc: Create system timer. * @tc.type: FUNC */ -HWTEST_F(TimeServiceTest, CreateTimer06, TestSize.Level0) +HWTEST_F(TimeServiceTest, CreateTimer006, TestSize.Level0) { g_data1 = 1; auto timerInfo = std::make_shared(); @@ -378,4 +365,3 @@ HWTEST_F(TimeServiceTest, CreateTimer06, TestSize.Level0) ret = TimeServiceClient::GetInstance()->StopTimer(timerId1); EXPECT_FALSE(ret); } -#endif diff --git a/services/timer/include/timer_handler.h b/services/timer/include/timer_handler.h index 8a40b01..0a42782 100644 --- a/services/timer/include/timer_handler.h +++ b/services/timer/include/timer_handler.h @@ -16,14 +16,14 @@ #ifndef TIMER_HANDLER_H #define TIMER_HANDLER_H -#include "time_common.h" - #include #include #include #include #include +#include "time_common.h" + namespace OHOS { namespace MiscServices { static const size_t ALARM_TYPE_COUNT = 5; @@ -32,12 +32,12 @@ typedef std::array TimerFds; class TimerHandler { public: - static std::shared_ptr Create (); - int Set (uint32_t type, std::chrono::nanoseconds when); - uint32_t WaitForAlarm (); - ~TimerHandler (); + static std::shared_ptr Create(); + int Set(uint32_t type, std::chrono::nanoseconds when); + uint32_t WaitForAlarm(); + ~TimerHandler(); private: - TimerHandler (const TimerFds &fds, int epollfd); + TimerHandler(const TimerFds &fds, int epollfd); const TimerFds fds_; const int epollFd_; }; diff --git a/services/timer/src/batch.cpp b/services/timer/src/batch.cpp index 1333489..968c3d8 100644 --- a/services/timer/src/batch.cpp +++ b/services/timer/src/batch.cpp @@ -54,10 +54,10 @@ 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(), + auto it = std::upper_bound(alarms_.begin(), + alarms_.end(), alarm, - [] (const std::shared_ptr &first, const std::shared_ptr &second) { + [](const std::shared_ptr &first, const std::shared_ptr &second) { return first->whenElapsed < second->whenElapsed; }); alarms_.insert (it, alarm); // 根据Alarm.when_elapsed从小到大排列 @@ -116,11 +116,11 @@ bool Batch::Remove (std::function predicate) 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 diff --git a/services/timer/src/timer_handler.cpp b/services/timer/src/timer_handler.cpp index a7e7c0e..7217ac8 100644 --- a/services/timer/src/timer_handler.cpp +++ b/services/timer/src/timer_handler.cpp @@ -66,7 +66,7 @@ std::shared_ptr TimerHandler::Create() } std::shared_ptr handler = std::shared_ptr(new TimerHandler(fds, epollfd)); - for(size_t i = 0; i < fds.size(); i++) { + for (size_t i = 0; i < fds.size(); i++) { epoll_event event {}; event.events = EPOLLIN | EPOLLWAKEUP; event.data.u32 = i; @@ -95,7 +95,7 @@ TimerHandler::TimerHandler(const TimerFds &fds, int epollfd) TimerHandler::~TimerHandler() { - for(auto fd : fds_) { + for (auto fd : fds_) { epoll_ctl(epollFd_, EPOLL_CTL_DEL, fd, nullptr); close(fd); } @@ -126,7 +126,7 @@ uint32_t TimerHandler::WaitForAlarm() } uint32_t result = 0; - for(int i = 0; i < nevents; i++) { + 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)); diff --git a/services/timer/src/timer_info.cpp b/services/timer/src/timer_info.cpp index 086f476..24f595f 100644 --- a/services/timer/src/timer_info.cpp +++ b/services/timer/src/timer_info.cpp @@ -17,7 +17,7 @@ namespace OHOS { namespace MiscServices { -bool TimerInfo::operator== (const TimerInfo &other) const +bool TimerInfo::operator == (const TimerInfo &other) const { return this->id == other.id; } diff --git a/services/timer/src/timer_manager.cpp b/services/timer/src/timer_manager.cpp index bd449e5..74da84c 100644 --- a/services/timer/src/timer_manager.cpp +++ b/services/timer/src/timer_manager.cpp @@ -60,15 +60,15 @@ TimerManager::TimerManager(std::shared_ptr impl) alarmThread_.reset(new std::thread(&TimerManager::TimerLooper, this)); } -uint64_t TimerManager::CreateTimer(int type, - uint64_t windowLength, - uint64_t interval, +uint64_t TimerManager::CreateTimer(int type, + uint64_t windowLength, + uint64_t interval, int flag, - std::function callback, + std::function callback, uint64_t uid) { - TIME_HILOGI(TIME_MODULE_SERVICE, - "Create timer: %{public}d windowLength:%{public}" PRId64 "interval:%{public}" PRId64 "flag:%{public}d", + TIME_HILOGI(TIME_MODULE_SERVICE, + "Create timer:%{public}d windowLength:%{public}" PRId64"interval:%{public}" PRId64"flag:%{public}d", type, windowLength, interval, @@ -78,12 +78,12 @@ uint64_t TimerManager::CreateTimer(int type, timerNumber = random_(); } auto timerInfo = std::make_shared(TimerEntry { - timerNumber, + timerNumber, type, - windowLength, - interval, - flag, - std::move(callback), + windowLength, + interval, + flag, + std::move(callback), uid}); std::lock_guard lock(entryMapMutex_); timerEntryMap_.insert(std::make_pair(timerNumber, timerInfo)); @@ -141,18 +141,18 @@ 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, +void TimerManager::SetHandler(uint64_t id, + int type, + uint64_t triggerAtTime, + uint64_t windowLength, + uint64_t interval, int flag, - std::function callback, + 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", + 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) { @@ -186,15 +186,15 @@ void TimerManager::SetHandler(uint64_t id, std::lock_guard lockGuard(mutex_); TIME_HILOGI(TIME_MODULE_SERVICE, "Lock guard"); SetHandlerLocked(id, - type, + type, milliseconds(triggerAtTime), - triggerElapsed, - windowLengthDuration, + triggerElapsed, + windowLengthDuration, maxElapsed, - intervalDuration, - std::move(callback), - static_cast(flag), - true, + intervalDuration, + std::move(callback), + static_cast(flag), + true, uid); } @@ -226,7 +226,7 @@ void TimerManager::RemoveHandler(uint64_t id) void TimerManager::RemoveLocked(uint64_t id) { - TIME_HILOGI(TIME_MODULE_SERVICE, "start id: %{public}" PRId64 "",id); + TIME_HILOGI(TIME_MODULE_SERVICE, "start id: %{public}" PRId64 "", id); auto whichAlarms = [id](const TimerInfo &timer) { return timer.id == id; }; @@ -267,7 +267,7 @@ 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_; @@ -283,8 +283,8 @@ void TimerManager::ReBatchAllTimersLocked(bool doValidate) TIME_HILOGI(TIME_MODULE_SERVICE, "end"); } -void TimerManager::ReAddTimerLocked(std::shared_ptr timer, - std::chrono::steady_clock::time_point nowElapsed, +void TimerManager::ReAddTimerLocked(std::shared_ptr timer, + std::chrono::steady_clock::time_point nowElapsed, bool doValidate) { TIME_HILOGI(TIME_MODULE_SERVICE, "start"); @@ -341,8 +341,8 @@ void TimerManager::TimerLooper() duration_cast(lastTimeChangeRealtime_.time_since_epoch())); - if (lastTimeChangeClockTime == system_clock::time_point::min() - || nowRtc < (expectedClockTime - milliseconds(ONE_THOUSAND)) + if (lastTimeChangeClockTime == system_clock::time_point::min() + || nowRtc < (expectedClockTime - milliseconds(ONE_THOUSAND)) || nowRtc > (expectedClockTime + milliseconds(ONE_THOUSAND))) { TIME_HILOGI(TIME_MODULE_SERVICE, "Time changed notification from kernel; rebatching"); ReBatchAllTimers(); @@ -399,8 +399,7 @@ bool TimerManager::TriggerTimersLocked(std::vector> & 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, @@ -412,11 +411,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; } @@ -492,7 +491,7 @@ int64_t TimerManager::AttemptCoalesceLocked(std::chrono::steady_clock::time_poin } 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) { @@ -508,7 +507,7 @@ 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) { + [](const std::shared_ptr &first, const std::shared_ptr &second) { return first->GetStart() < second->GetStart(); }); list.insert(it, newBatch); @@ -518,7 +517,7 @@ bool AddBatchLocked(std::vector> &list, const std::shared steady_clock::time_point MaxTriggerTime(steady_clock::time_point now, steady_clock::time_point triggerAtTime, milliseconds interval) { - milliseconds futurity = (interval == milliseconds::zero()) ? + milliseconds futurity = (interval == milliseconds::zero()) ? (duration_cast(triggerAtTime - now)) : interval; if (futurity < MIN_FUZZABLE_INTERVAL) { futurity = milliseconds::zero(); diff --git a/utils/BUILD.gn b/utils/BUILD.gn index 6421ea4..db2d757 100644 --- a/utils/BUILD.gn +++ b/utils/BUILD.gn @@ -25,23 +25,24 @@ config("utils_config") { ohos_source_set("time_utils") { sources = [ "mock/src/mock_permission.cpp", + "native/src/time_file_utils.cpp", "native/src/time_permission.cpp", ] public_configs = [ ":utils_config" ] - deps = [ - "//utils/native/base:utils", + deps = [ "//foundation/aafwk/standard/interfaces/innerkits/base:base", "//foundation/aafwk/standard/interfaces/innerkits/want:want", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", - "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", - "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", - "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_rdb:native_rdb", "//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", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//utils/native/base:utils", ] - + external_deps = [ "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/utils/native/include/time_file_utils.h b/utils/native/include/time_file_utils.h new file mode 100644 index 0000000..7efd74a --- /dev/null +++ b/utils/native/include/time_file_utils.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2020 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TIME_FILE_UTILS_H +#define TIME_FILE_UTILS_H + +#include +#include + +#include "nocopyable.h" + +namespace OHOS { +namespace MiscServices { +namespace { +const char PATH_SEPARATOR = '/'; +} +class TimeFileUtils : public NoCopyable { +public: + static bool MkRecursiveDir(const char *dir, bool isReadOthers); + static bool IsExistDir(const char *path); + static bool IsExistFile(const char *file); + static bool RemoveFile(const char *path); + static bool RenameFile(const char *oldDir, const char *newDir); + static bool ChownFile(const char *file, int32_t uid, int32_t gid); + static bool WriteFile(const char *file, const void *buffer, uint32_t size); + static bool IsValidPath(const std::string &rootDir, const std::string &path); + static std::string GetPathDir(const std::string &path); +}; +} // MiscServices +} // OHOS +#endif // TIME_FILE_UTILS_H diff --git a/utils/native/include/time_permission.h b/utils/native/include/time_permission.h index b06d3b6..45f8948 100644 --- a/utils/native/include/time_permission.h +++ b/utils/native/include/time_permission.h @@ -12,20 +12,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - - #ifndef TIME_PERMISSION_H #define TIME_PERMISSION_H +#include +#include +#include + #include "bundle_mgr_interface.h" #include "time_common.h" #include "mock_permission.h" #include "system_ability_definition.h" #include "iservice_registry.h" -#include -#include -#include namespace OHOS { namespace MiscServices { class TimePermission { diff --git a/utils/native/src/time_file_utils.cpp b/utils/native/src/time_file_utils.cpp new file mode 100644 index 0000000..af6f72b --- /dev/null +++ b/utils/native/src/time_file_utils.cpp @@ -0,0 +1,171 @@ +/* + * Copyright (c) 2020 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 "time_file_utils.h" + +#include +#include +#include +#include +#include + +#include "time_common.h" +#include "securec.h" + +namespace OHOS { +namespace MiscServices { +bool TimeFileUtils::IsExistDir(const char *path) +{ + if (path == nullptr) { + return false; + } + + struct stat buf = {}; + if (stat(path, &buf) != 0) { + return false; + } + return S_ISDIR(buf.st_mode); +} + +bool TimeFileUtils::IsExistFile(const char *file) +{ + if (file == nullptr) { + return false; + } + + struct stat buf = {}; + if (stat(file, &buf) != 0) { + return false; + } + return S_ISREG(buf.st_mode); +} + +bool TimeFileUtils::MkRecursiveDir(const char *dir, bool isReadOthers) +{ + if (dir == nullptr) { + return false; + } + if (IsExistDir(dir)) { + return true; + } + size_t len = strlen(dir); + if (len == 0 || len > PATH_MAX) { + return false; + } + // Create directories level by level + char rootDir[PATH_MAX] = { '\0' }; + for (size_t i = 0; i < len; ++i) { + rootDir[i] = dir[i]; + if ((rootDir[i] == PATH_SEPARATOR || i == (len - 1)) && !IsExistDir(rootDir)) { + mode_t mode = S_IRWXU | S_IRWXG | S_IXOTH; + mode |= (isReadOthers ? S_IROTH : 0); + if (mkdir(rootDir, mode) < 0) { + return false; + } + } + } + return true; +} + +bool TimeFileUtils::RemoveFile(const char *path) +{ + if (IsExistFile(path)) { + return remove(path) == 0; + } else if (IsExistDir(path)) { + DIR *dir = opendir(path); + if (dir == nullptr) { + return false; + } + struct dirent *dp = nullptr; + // Remove file before delete the directory + while ((dp = readdir(dir)) != nullptr) { + if ((strcmp(dp->d_name, ".") == 0) || (strcmp(dp->d_name, "..")) == 0) { + continue; + } + std::string dirName = std::string(path) + "/" + dp->d_name; + if (dirName.length() >= PATH_MAX || !RemoveFile(dirName.c_str())) { + closedir(dir); + return false; + } + } + closedir(dir); + return remove(path) == 0; + } else { + return true; + } +} + +bool TimeFileUtils::RenameFile(const char *oldFile, const char *newFile) +{ + if (oldFile == nullptr || newFile == nullptr) { + return false; + } + if (!RemoveFile(newFile)) { + return false; + } + + return rename(oldFile, newFile) == 0; +} + +bool TimeFileUtils::ChownFile(const char *file, int32_t uid, int32_t gid) +{ + if (file == nullptr) { + return false; + } + return chown(file, uid, gid) == 0; +} + +bool TimeFileUtils::WriteFile(const char *file, const void *buffer, uint32_t size) +{ + if (file == nullptr || buffer == nullptr || size == 0) { + return false; + } + + int32_t fp = open(file, O_RDWR | O_CREAT | O_TRUNC, S_IREAD | S_IWUSR | S_IRGRP | S_IROTH); + if (fp < 0) { + return false; + } + + if (write(fp, buffer, size) != static_cast(size)) { + close(fp); + return false; + } + + close(fp); + return true; +} + +bool TimeFileUtils::IsValidPath(const std::string &rootDir, const std::string &path) +{ + if (rootDir.find(PATH_SEPARATOR) != 0 || rootDir.rfind(PATH_SEPARATOR) != (rootDir.size() - 1) || + rootDir.find("..") != std::string::npos) { + return false; + } + if (path.find("..") != std::string::npos) { + return false; + } + return path.compare(0, rootDir.size(), rootDir) == 0; +} + +std::string TimeFileUtils::GetPathDir(const std::string &path) +{ + std::size_t pos = path.rfind(PATH_SEPARATOR); + if (pos == std::string::npos) { + return std::string(); + } + return path.substr(0, pos + 1); +} +} +} // OHOS diff --git a/utils/native/src/time_permission.cpp b/utils/native/src/time_permission.cpp index a8009b2..1d35c02 100644 --- a/utils/native/src/time_permission.cpp +++ b/utils/native/src/time_permission.cpp @@ -50,7 +50,7 @@ bool TimePermission::CheckCallingPermission(int32_t uid, std::string permName) return true; } auto userId = uid / UID_TO_USERID; - TIME_HILOGI(TIME_MODULE_COMMON, "VerifyPermission bundleName %{public}s, permission %{public}s", + TIME_HILOGI(TIME_MODULE_COMMON, "VerifyPermission bundleName: %{public}s, permission: %{public}s", bundleName.c_str(), permName.c_str()); return MockPermission::VerifyPermission(bundleName, permName, userId); }