!23 修改门禁提交codecheck问题

Merge pull request !23 from guduhanyan/master
This commit is contained in:
openharmony_ci
2021-09-27 13:58:41 +00:00
committed by Gitee
33 changed files with 1002 additions and 445 deletions
-1
View File
@@ -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",
]
}
}
+172 -20
View File
@@ -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
<a name="table033515471012"></a>
<table><thead align="left"><tr id="row143351854201012"><th class="cellrowborder" valign="top" width="50%" id="mcps1.2.3.1.1"><p id="p103351154121010"><a name="p103351154121010"></a><a name="p103351154121010"></a>Function</p>
<table><thead align="left"><tr id="row143351854201012"><th class="cellrowborder" valign="top" width="50%" id="mcps1.2.3.1.1"><p id="p103351154121010"><a name="p103351154121010"></a><a name="p103351154121010"></a>Interface name</p>
</th>
<th class="cellrowborder" valign="top" width="50%" id="mcps1.2.3.1.2"><p id="p1033585416105"><a name="p1033585416105"></a><a name="p1033585416105"></a>Description</p>
<th class="cellrowborder" valign="top" width="50%" id="mcps1.2.3.1.2"><p id="p1033585416105"><a name="p1033585416105"></a><a name="p1033585416105"></a>describe</p>
</th>
</tr>
</thead>
<tbody><tr id="row204321219393"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p1893413268144"><a name="p1893413268144"></a><a name="p1893413268144"></a>function setTime(time : number) : Promise&lt;boolean&gt;</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p18761104812149"><a name="p18761104812149"></a><a name="p18761104812149"></a>Sets the system time and uses a Promise to return the execution result.</p>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p18761104812149"><a name="p18761104812149"></a><a name="p18761104812149"></a>Set the system time (1970-01-01 to the present in milliseconds), Promise method</p>
</td>
</tr>
<tr id="row13335054111018"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p12832214151418"><a name="p12832214151418"></a><a name="p12832214151418"></a>function setTime(time : number, callback : AsyncCallback&lt;boolean&gt;) : void</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p3335145451011"><a name="p3335145451011"></a><a name="p3335145451011"></a>Sets the system time and uses a callback to return the execution result.</p>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p3335145451011"><a name="p3335145451011"></a><a name="p3335145451011"></a>Set the system time (1970-01-01 to the present in milliseconds), callback mode</p>
</td>
</tr>
<tr id="row204321219393"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p1893413268144"><a name="p1893413268144"></a><a name="p1893413268144"></a>function setDate(date: Date, callback: AsyncCallback&lt;boolean&gt;): void;</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p18761104812149"><a name="p18761104812149"></a><a name="p18761104812149"></a>Set the system time (Date format), Promise method</p>
</td>
</tr>
<tr id="row204321219393"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p1893413268144"><a name="p1893413268144"></a><a name="p1893413268144"></a>function setDate(date: Date): Promise&lt;boolean&gt;</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p18761104812149"><a name="p18761104812149"></a><a name="p18761104812149"></a>Set system time (Date format), callback method</p>
</td>
</tr>
<tr id="row204321219393"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p1893413268144"><a name="p1893413268144"></a><a name="p1893413268144"></a>function setTimezone(timezone: string, callback: AsyncCallback&lt;boolean&gt;): void</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p18761104812149"><a name="p18761104812149"></a><a name="p18761104812149"></a>Set the system time zone, callback method</p>
</td>
</tr>
<tr id="row204321219393"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p1893413268144"><a name="p1893413268144"></a><a name="p1893413268144"></a>function setTimezone(timezone: string): Promise&lt;boolean&gt;</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p18761104812149"><a name="p18761104812149"></a><a name="p18761104812149"></a>Set the system time zone, Promise method</p>
</td>
</tr>
</tbody>
</table>
**表 2** Major functions of systemTimer
<a name="table033515471012"></a>
<table><thead align="left"><tr id="row143351854201012"><th class="cellrowborder" valign="top" width="50%" id="mcps1.2.3.1.1"><p id="p103351154121010"><a name="p103351154121010"></a><a name="p103351154121010"></a>Interface name</p>
</th>
<th class="cellrowborder" valign="top" width="50%" id="mcps1.2.3.1.2"><p id="p1033585416105"><a name="p1033585416105"></a><a name="p1033585416105"></a>describe</p>
</th>
</tr>
</thead>
<tbody><tr id="row204321219393"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p1893413268144"><a name="p1893413268144"></a><a name="p1893413268144"></a>function createTimer(options: TimerOptions, callback: AsyncCallback&lt;number&gt;): void</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p18761104812149"><a name="p18761104812149"></a><a name="p18761104812149"></a>Create timer, callback method</p>
</td>
</tr>
<tr id="row13335054111018"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p12832214151418"><a name="p12832214151418"></a><a name="p12832214151418"></a>function createTimer(options: TimerOptions): Promise&lt;number&gt;</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p3335145451011"><a name="p3335145451011"></a><a name="p3335145451011"></a>Create timer, promise method</p>
</td>
</tr>
<tr id="row204321219393"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p1893413268144"><a name="p1893413268144"></a><a name="p1893413268144"></a>function startTimer(timer: number, triggerTime: number, callback: AsyncCallback&lt;boolean&gt;): void</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p18761104812149"><a name="p18761104812149"></a><a name="p18761104812149"></a>Start the timer, callback mode</p>
</td>
</tr>
<tr id="row204321219393"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p1893413268144"><a name="p1893413268144"></a><a name="p1893413268144"></a>function startTimer(timer: number, triggerTime: number): Promise&lt;boolean&gt;</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p18761104812149"><a name="p18761104812149"></a><a name="p18761104812149"></a>Start the timer, promise mode</p>
</td>
</tr>
<tr id="row204321219393"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p1893413268144"><a name="p1893413268144"></a><a name="p1893413268144"></a>function stopTimer(timer: number, callback: AsyncCallback&lt;boolean&gt;): void</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p18761104812149"><a name="p18761104812149"></a><a name="p18761104812149"></a>Stop the timer, callback mode</p>
</td>
</tr>
<tr id="row204321219393"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p1893413268144"><a name="p1893413268144"></a><a name="p1893413268144"></a>function stopTimer(timer: number): Promise&lt;boolean&gt;</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p18761104812149"><a name="p18761104812149"></a><a name="p18761104812149"></a>Stop the timer, promise mode</p>
</td>
</tr>
<tr id="row204321219393"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p1893413268144"><a name="p1893413268144"></a><a name="p1893413268144"></a>function destroyTimer(timer: number, callback: AsyncCallback&lt;boolean&gt;): void</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p18761104812149"><a name="p18761104812149"></a><a name="p18761104812149"></a>Destroy the timer, callback method</p>
</td>
</tr>
<tr id="row204321219393"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p1893413268144"><a name="p1893413268144"></a><a name="p1893413268144"></a>function destroyTimer(timer: number): Promise&lt;boolean&gt;</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p18761104812149"><a name="p18761104812149"></a><a name="p18761104812149"></a>Destroy the timer, the promise method</p>
</td>
</tr>
</tbody>
</table>
**表 3** parameter TimerOptions description of systemTimer
<a name="table033515471012"></a>
<table><thead align="left"><tr id="row143351854201012"><th class="cellrowborder" valign="top" width="20%" id="mcps1.2.3.1.1"><p id="p103351154121010"><a name="p103351154121010"></a><a name="p103351154121010"></a>name</p>
</th>
<th class="cellrowborder" valign="top" width="10%" id="mcps1.2.3.1.2"><p id="p1033585416105"><a name="p1033585416105"></a><a name="p1033585416105"></a>type</p>
</th>
<th class="cellrowborder" valign="top" width="70%" id="mcps1.2.3.1.3"><p id="p1033585416105"><a name="p1033585416105"></a><a name="p1033585416105"></a>illustrate</p>
</th>
</tr>
</thead>
<tbody><tr id="row204321219393"><td class="cellrowborder" valign="top" width="20%" headers="mcps1.2.3.1.1 "><p id="p1893413268144"><a name="p1893413268144"></a><a name="p1893413268144"></a>type</p>
</td>
<td class="cellrowborder" valign="top" width="10%" headers="mcps1.2.3.1.2 "><p id="p18761104812149"><a name="p18761104812149"></a><a name="p18761104812149"></a>number</p>
</td>
<td class="cellrowborder" valign="top" width="70%" headers="mcps1.2.3.1.3 "><p id="p18761104812149"><a name="p18761104812149"></a><a name="p18761104812149"></a>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)
</p>
</td>
</tr>
<tr id="row204321219393"><td class="cellrowborder" valign="top" width="20%" headers="mcps1.2.3.1.1 "><p id="p1893413268144"><a name="p1893413268144"></a><a name="p1893413268144"></a>repeat</p>
</td>
<td class="cellrowborder" valign="top" width="10%" headers="mcps1.2.3.1.2 "><p id="p18761104812149"><a name="p18761104812149"></a><a name="p18761104812149"></a>boolean</p>
</td>
<td class="cellrowborder" valign="top" width="70%" headers="mcps1.2.3.1.3 "><p id="p18761104812149"><a name="p18761104812149"></a><a name="p18761104812149"></a>true Is a cyclic timer, false is a single timer</p>
</td>
</tr>
<tr id="row204321219393"><td class="cellrowborder" valign="top" width="20%" headers="mcps1.2.3.1.1 "><p id="p1893413268144"><a name="p1893413268144"></a><a name="p1893413268144"></a>interval</p>
</td>
<td class="cellrowborder" valign="top" width="10%" headers="mcps1.2.3.1.2 "><p id="p18761104812149"><a name="p18761104812149"></a><a name="p18761104812149"></a>number</p>
</td>
<td class="cellrowborder" valign="top" width="70%" headers="mcps1.2.3.1.3 "><p id="p18761104812149"><a name="p18761104812149"></a><a name="p18761104812149"></a>If it is a cyclic timer, the repeat value should be greater than 5000 milliseconds, and the non-repeated timer is set to 0</p>
</td>
</tr>
<tr id="row204321219393"><td class="cellrowborder" valign="top" width="20%" headers="mcps1.2.3.1.1 "><p id="p1893413268144"><a name="p1893413268144"></a><a name="p1893413268144"></a>wantAgent</p>
</td>
<td class="cellrowborder" valign="top" width="10%" headers="mcps1.2.3.1.2 "><p id="p18761104812149"><a name="p18761104812149"></a><a name="p18761104812149"></a>wantAgent</p>
</td>
<td class="cellrowborder" valign="top" width="70%" headers="mcps1.2.3.1.3 "><p id="p18761104812149"><a name="p18761104812149"></a><a name="p18761104812149"></a>Set the wantagent to notify, and notify when the timer expires</p>
</td>
</tr>
<tr id="row204321219393"><td class="cellrowborder" valign="top" width="20%" headers="mcps1.2.3.1.1 "><p id="p1893413268144"><a name="p1893413268144"></a><a name="p1893413268144"></a>callback</p>
</td>
<td class="cellrowborder" valign="top" width="10%" headers="mcps1.2.3.1.2 "><p id="p18761104812149"><a name="p18761104812149"></a><a name="p18761104812149"></a> => void</p>
</td>
<td class="cellrowborder" valign="top" width="70%" headers="mcps1.2.3.1.3 "><p id="p18761104812149"><a name="p18761104812149"></a><a name="p18761104812149"></a>Set the callback function, which will be triggered after the timer expires</p>
</td>
</tr>
</tbody>
@@ -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<a name="section1371113476307"></a>
+173 -18
View File
@@ -10,7 +10,7 @@
## 简介<a name="section11660541593"></a>
时间组件提供管理系统时间的能力。
时间组件提供管理系统时间时区和定时的能力。
**图 1** 子系统架构图<a name="fig143011012341"></a>
![](figures/subsystem_architecture_zh.png "子系统架构图")
@@ -43,17 +43,142 @@
</thead>
<tbody><tr id="row204321219393"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p1893413268144"><a name="p1893413268144"></a><a name="p1893413268144"></a>function setTime(time : number) : Promise&lt;boolean&gt;</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p18761104812149"><a name="p18761104812149"></a><a name="p18761104812149"></a>设置系统时间,Promise方式</p>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p18761104812149"><a name="p18761104812149"></a><a name="p18761104812149"></a>设置系统时间1970-01-01至今毫秒数)Promise方式</p>
</td>
</tr>
<tr id="row13335054111018"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p12832214151418"><a name="p12832214151418"></a><a name="p12832214151418"></a>function setTime(time : number, callback : AsyncCallback&lt;boolean&gt;) : void</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p3335145451011"><a name="p3335145451011"></a><a name="p3335145451011"></a>设置系统时间,callback方式</p>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p3335145451011"><a name="p3335145451011"></a><a name="p3335145451011"></a>设置系统时间1970-01-01至今毫秒数)callback方式</p>
</td>
</tr>
<tr id="row204321219393"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p1893413268144"><a name="p1893413268144"></a><a name="p1893413268144"></a>function setDate(date: Date, callback: AsyncCallback&lt;boolean&gt;): void;</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p18761104812149"><a name="p18761104812149"></a><a name="p18761104812149"></a>设置系统时间(Date格式),Promise方式</p>
</td>
</tr>
<tr id="row204321219393"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p1893413268144"><a name="p1893413268144"></a><a name="p1893413268144"></a>function setDate(date: Date): Promise&lt;boolean&gt;</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p18761104812149"><a name="p18761104812149"></a><a name="p18761104812149"></a>设置系统时间(Date格式),callback方式</p>
</td>
</tr>
<tr id="row204321219393"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p1893413268144"><a name="p1893413268144"></a><a name="p1893413268144"></a>function setTimezone(timezone: string, callback: AsyncCallback&lt;boolean&gt;): void</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p18761104812149"><a name="p18761104812149"></a><a name="p18761104812149"></a>设置系统时区,callback方式</p>
</td>
</tr>
<tr id="row204321219393"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p1893413268144"><a name="p1893413268144"></a><a name="p1893413268144"></a>function setTimezone(timezone: string): Promise&lt;boolean&gt;</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p18761104812149"><a name="p18761104812149"></a><a name="p18761104812149"></a>设置系统时区,Promise方式</p>
</td>
</tr>
</tbody>
</table>
**表 2** js组件systemTimer开放的主要方法
<a name="table033515471012"></a>
<table><thead align="left"><tr id="row143351854201012"><th class="cellrowborder" valign="top" width="50%" id="mcps1.2.3.1.1"><p id="p103351154121010"><a name="p103351154121010"></a><a name="p103351154121010"></a>接口名</p>
</th>
<th class="cellrowborder" valign="top" width="50%" id="mcps1.2.3.1.2"><p id="p1033585416105"><a name="p1033585416105"></a><a name="p1033585416105"></a>描述</p>
</th>
</tr>
</thead>
<tbody><tr id="row204321219393"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p1893413268144"><a name="p1893413268144"></a><a name="p1893413268144"></a>function createTimer(options: TimerOptions, callback: AsyncCallback&lt;number&gt;): void</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p18761104812149"><a name="p18761104812149"></a><a name="p18761104812149"></a>创建定时器,callback方式</p>
</td>
</tr>
<tr id="row13335054111018"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p12832214151418"><a name="p12832214151418"></a><a name="p12832214151418"></a>function createTimer(options: TimerOptions): Promise&lt;number&gt;</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p3335145451011"><a name="p3335145451011"></a><a name="p3335145451011"></a>创建定时器,promise方式</p>
</td>
</tr>
<tr id="row204321219393"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p1893413268144"><a name="p1893413268144"></a><a name="p1893413268144"></a>function startTimer(timer: number, triggerTime: number, callback: AsyncCallback&lt;boolean&gt;): void</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p18761104812149"><a name="p18761104812149"></a><a name="p18761104812149"></a>开启定时器,callback方式</p>
</td>
</tr>
<tr id="row204321219393"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p1893413268144"><a name="p1893413268144"></a><a name="p1893413268144"></a>function startTimer(timer: number, triggerTime: number): Promise&lt;boolean&gt;</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p18761104812149"><a name="p18761104812149"></a><a name="p18761104812149"></a>开启定时器,promise方式</p>
</td>
</tr>
<tr id="row204321219393"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p1893413268144"><a name="p1893413268144"></a><a name="p1893413268144"></a>function stopTimer(timer: number, callback: AsyncCallback&lt;boolean&gt;): void</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p18761104812149"><a name="p18761104812149"></a><a name="p18761104812149"></a>停止定时器,callback方式</p>
</td>
</tr>
<tr id="row204321219393"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p1893413268144"><a name="p1893413268144"></a><a name="p1893413268144"></a>function stopTimer(timer: number): Promise&lt;boolean&gt;</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p18761104812149"><a name="p18761104812149"></a><a name="p18761104812149"></a>停止定时器,promise方式</p>
</td>
</tr>
<tr id="row204321219393"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p1893413268144"><a name="p1893413268144"></a><a name="p1893413268144"></a>function destroyTimer(timer: number, callback: AsyncCallback&lt;boolean&gt;): void</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p18761104812149"><a name="p18761104812149"></a><a name="p18761104812149"></a>销毁定时器,callback方式</p>
</td>
</tr>
<tr id="row204321219393"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p1893413268144"><a name="p1893413268144"></a><a name="p1893413268144"></a>function destroyTimer(timer: number): Promise&lt;boolean&gt;</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p18761104812149"><a name="p18761104812149"></a><a name="p18761104812149"></a>摧毁定时器,promise方式</p>
</td>
</tr>
</tbody>
</table>
**表 3** systemTimer组件参数TimerOptions说明
<a name="table033515471012"></a>
<table><thead align="left"><tr id="row143351854201012"><th class="cellrowborder" valign="top" width="20%" id="mcps1.2.3.1.1"><p id="p103351154121010"><a name="p103351154121010"></a><a name="p103351154121010"></a>名称</p>
</th>
<th class="cellrowborder" valign="top" width="10%" id="mcps1.2.3.1.2"><p id="p1033585416105"><a name="p1033585416105"></a><a name="p1033585416105"></a>类型</p>
</th>
<th class="cellrowborder" valign="top" width="70%" id="mcps1.2.3.1.3"><p id="p1033585416105"><a name="p1033585416105"></a><a name="p1033585416105"></a>说明</p>
</th>
</tr>
</thead>
<tbody><tr id="row204321219393"><td class="cellrowborder" valign="top" width="20%" headers="mcps1.2.3.1.1 "><p id="p1893413268144"><a name="p1893413268144"></a><a name="p1893413268144"></a>type</p>
</td>
<td class="cellrowborder" valign="top" width="10%" headers="mcps1.2.3.1.2 "><p id="p18761104812149"><a name="p18761104812149"></a><a name="p18761104812149"></a>number</p>
</td>
<td class="cellrowborder" valign="top" width="70%" headers="mcps1.2.3.1.3 "><p id="p18761104812149"><a name="p18761104812149"></a><a name="p18761104812149"></a>TIMER_TYPE_REALTIME: 设置为系统启动时间定时器,否则为walltime定时器;
TIMER_TYPE_WAKEUP: 设置为唤醒定时器,否则为非唤醒;
const TIMER_TYPE_EXACT: 设置为精准定时器,否则为非精准定时器;
const TIMER_TYPE_IDLE: 设置为IDLE模式定时器,否则为非IDLE模式定时器(暂不支持)
</p>
</td>
</tr>
<tr id="row204321219393"><td class="cellrowborder" valign="top" width="20%" headers="mcps1.2.3.1.1 "><p id="p1893413268144"><a name="p1893413268144"></a><a name="p1893413268144"></a>repeat</p>
</td>
<td class="cellrowborder" valign="top" width="10%" headers="mcps1.2.3.1.2 "><p id="p18761104812149"><a name="p18761104812149"></a><a name="p18761104812149"></a>boolean</p>
</td>
<td class="cellrowborder" valign="top" width="70%" headers="mcps1.2.3.1.3 "><p id="p18761104812149"><a name="p18761104812149"></a><a name="p18761104812149"></a>true 为循环定时器,false为单次定时器</p>
</td>
</tr>
<tr id="row204321219393"><td class="cellrowborder" valign="top" width="20%" headers="mcps1.2.3.1.1 "><p id="p1893413268144"><a name="p1893413268144"></a><a name="p1893413268144"></a>interval</p>
</td>
<td class="cellrowborder" valign="top" width="10%" headers="mcps1.2.3.1.2 "><p id="p18761104812149"><a name="p18761104812149"></a><a name="p18761104812149"></a>number</p>
</td>
<td class="cellrowborder" valign="top" width="70%" headers="mcps1.2.3.1.3 "><p id="p18761104812149"><a name="p18761104812149"></a><a name="p18761104812149"></a>如果是循环定时器,repeat值应大于5000毫秒,非重复定时器置为0</p>
</td>
</tr>
<tr id="row204321219393"><td class="cellrowborder" valign="top" width="20%" headers="mcps1.2.3.1.1 "><p id="p1893413268144"><a name="p1893413268144"></a><a name="p1893413268144"></a>wantAgent</p>
</td>
<td class="cellrowborder" valign="top" width="10%" headers="mcps1.2.3.1.2 "><p id="p18761104812149"><a name="p18761104812149"></a><a name="p18761104812149"></a>wantAgent</p>
</td>
<td class="cellrowborder" valign="top" width="70%" headers="mcps1.2.3.1.3 "><p id="p18761104812149"><a name="p18761104812149"></a><a name="p18761104812149"></a>设置通知的wantagent,定时器到期后通知</p>
</td>
</tr>
<tr id="row204321219393"><td class="cellrowborder" valign="top" width="20%" headers="mcps1.2.3.1.1 "><p id="p1893413268144"><a name="p1893413268144"></a><a name="p1893413268144"></a>callback</p>
</td>
<td class="cellrowborder" valign="top" width="10%" headers="mcps1.2.3.1.2 "><p id="p18761104812149"><a name="p18761104812149"></a><a name="p18761104812149"></a> => void</p>
</td>
<td class="cellrowborder" valign="top" width="70%" headers="mcps1.2.3.1.3 "><p id="p18761104812149"><a name="p18761104812149"></a><a name="p18761104812149"></a>设置回调函数,定时器到期后触发</p>
</td>
</tr>
</tbody>
</table>
### js接口使用说明<a name="section9938411124317"></a>
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');
```
## 相关仓<a name="section1371113476307"></a>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 24 KiB

After

Width:  |  Height:  |  Size: 733 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

After

Width:  |  Height:  |  Size: 804 KiB

@@ -16,11 +16,12 @@
#ifndef SERVICES_INCLUDE_TIME_SERVICES_MANAGER_H
#define SERVICES_INCLUDE_TIME_SERVICES_MANAGER_H
#include <mutex>
#include "refbase.h"
#include "time_service_interface.h"
#include "iremote_object.h"
#include "timer_call_back.h"
#include <mutex>
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.
*/
+6 -6
View File
@@ -26,24 +26,24 @@ declare namespace systemTime {
* @permission ohos.permission.SET_TIME
* @since 6
*/
function setTime(time : number, callback : AsyncCallback<boolean>) : void;
function setTime(time : number) : Promise<boolean>;
function setTime(time : number, callback : AsyncCallback<void>) : void;
function setTime(time : number) : Promise<void>;
/**
* Sets the system time.
* @permission ohos.permission.SET_TIME
* @since 7
*/
function setDate(date: Date, callback: AsyncCallback<boolean>): void;
function setDate(date: Date): Promise<boolean>;
function setDate(date: Date, callback: AsyncCallback<void>): void;
function setDate(date: Date): Promise<void>;
/**
* Sets the system time zone.
* @permission ohos.permission.SET_TIME_ZONE
* @since 7
*/
function setTimezone(timezone: string, callback: AsyncCallback<boolean>): void;
function setTimezone(timezone: string): Promise<boolean>;
function setTimezone(timezone: string, callback: AsyncCallback<void>): void;
function setTimezone(timezone: string): Promise<void>;
}
export default systemTime;
+6 -6
View File
@@ -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<boolean>): void;
function startTimer(timer: number, triggerTime: number): Promise<boolean>;
function startTimer(timer: number, triggerTime: number, callback: AsyncCallback<void>): void;
function startTimer(timer: number, triggerTime: number): Promise<void>;
/**
* 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<boolean>): void;
function stopTimer(timer: number): Promise<boolean>;
function stopTimer(timer: number, callback: AsyncCallback<void>): void;
function stopTimer(timer: number): Promise<void>;
/**
* 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<boolean>): void;
function destroyTimer(timer: number): Promise<boolean>;
function destroyTimer(timer: number, callback: AsyncCallback<void>): void;
function destroyTimer(timer: number): Promise<void>;
interface TimerOptions {
/**
@@ -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
@@ -12,20 +12,59 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "js_systemtime.h"
#include <string>
#include <initializer_list>
#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 <initializer_list>
#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);
}
}
} // MiscServicesNapi
} // OHOS
@@ -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
@@ -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<OHOS::Notification::WantAgent::WantAgent> sWantAgent =
std::shared_ptr<OHOS::Notification::WantAgent::WantAgent> sWantAgent =
std::make_shared<OHOS::Notification::WantAgent::WantAgent>(*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> iTimerInfoInstance = std::make_shared<ITimerInfoInstance>();
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);
-7
View File
@@ -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"
}
+1 -1
View File
@@ -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_;
@@ -18,20 +18,21 @@
#include <singleton.h>
#include <map>
#include <mutex>
#include <sys/time.h>
#include <vector>
#include <fstream>
#include "refbase.h"
#include "time.h"
#include <sys/time.h>
#include "time_common.h"
#include <vector>
#include "json/json.h"
#include <fstream>
namespace OHOS {
namespace MiscServices {
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);
+57 -65
View File
@@ -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 <ctime>
#include <cstdio>
#include <string>
#include <unistd.h>
#include <sys/time.h>
#include <cerrno>
#include "pthread.h"
#include <mutex>
#include <sys/ioctl.h>
#include <linux/rtc.h>
#include <dirent.h>
#include <cstring>
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <fstream>
#include <sstream>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <linux/rtc.h>
#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<TimeZoneInfo>::GetInstance()->Init();
if (Init() != ERR_OK) {
auto callback = [=]() { Init(); };
serviceHandler_->PostTask(callback, INIT_INTERVAL);
TIME_HILOGE(TIME_MODULE_SERVICE, "Init failed. Try again 10s later.");
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)
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 &times)
{
@@ -472,7 +475,6 @@ int32_t TimeService::GetWallTimeNs(int64_t &times)
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)
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 &times)
{
@@ -496,9 +497,8 @@ int32_t TimeService::GetBootTimeNs(int64_t &times)
times = tv.tv_sec * NANO_TO_BASE + tv.tv_nsec;
return ERR_OK;
}
return E_TIME_DEAL_FAILED;
}
}
int32_t TimeService::GetMonotonicTimeMs(int64_t &times)
{
@@ -509,8 +509,7 @@ int32_t TimeService::GetMonotonicTimeMs(int64_t &times)
return ERR_OK;
}
return E_TIME_DEAL_FAILED;
}
}
int32_t TimeService::GetMonotonicTimeNs(int64_t &times)
{
@@ -520,10 +519,8 @@ int32_t TimeService::GetMonotonicTimeNs(int64_t &times)
times = tv.tv_sec * NANO_TO_BASE + tv.tv_nsec;
return ERR_OK;
}
return E_TIME_DEAL_FAILED;
}
}
int32_t TimeService::GetThreadTimeMs(int64_t &times)
{
@@ -534,14 +531,13 @@ int32_t TimeService::GetThreadTimeMs(int64_t &times)
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 &times)
{
@@ -552,15 +548,13 @@ int32_t TimeService::GetThreadTimeNs(int64_t &times)
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
@@ -136,9 +136,9 @@ uint64_t TimeServiceClient::CreateTimer(std::shared_ptr<ITimerInfo> 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) {
+46 -19
View File
@@ -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<int>(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.");
@@ -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<AppExecFwk::Context> context = std::make_shared<OHOS::AppExecFwk::AbilityContext>();
std::shared_ptr<AAFwk::Want> want =
std::shared_ptr<AAFwk::Want> want =
Notification::WantAgent::WantAgentHelper::GetWant(it->second->wantAgent);
OHOS::Notification::WantAgent::TriggerInfo paramsInfo("", nullptr, want, 11);
-3
View File
@@ -1,3 +0,0 @@
{
"TimezoneId" : "Asia/Shanghai"
}
@@ -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 <functional>
#include <gtest/gtest.h>
#include <cstdint>
#include <vector>
#include <sys/time.h>
#ifndef TIME_SERVICE_TEST_H
#define TIME_SERVICE_TEST_H
#include <atomic>
#include <thread>
#include "time_common.h"
#include "time_service_client.h"
#include <string>
#include <inttypes.h>
std::atomic<int> 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<OHOS::Notification::WantAgent::WantAgent> wantAgent) override;
void SetCallbackInfo(const std::function<void()> &callBack);
private:
std::function<void()> callBack_ = nullptr;
};
TimerInfoTest::TimerInfoTest()
void TimeOutCallback1(void)
{
g_data1 += 1;
}
TimerInfoTest::~TimerInfoTest()
std::atomic<int> 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<void()> &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<OHOS::Notification::WantAgent::WantAgent> _wantAgent)
{
wantAgent = _wantAgent;
}
}
}
#endif
#endif // TIME_SERVICE_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 <string>
#include <inttypes.h>
#include <functional>
#include <gtest/gtest.h>
#include <cstdint>
#include <vector>
#include <sys/time.h>
#include <thread>
#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<OHOS::Notification::WantAgent::WantAgent> wantAgent) override;
void SetCallbackInfo(const std::function<void()> &callBack);
private:
std::function<void()> 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<void()> &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<OHOS::Notification::WantAgent::WantAgent> _wantAgent)
{
wantAgent = _wantAgent;
}
}
}
#endif
@@ -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<int> g_data1(0);
void TimeOutCallback1()
{
g_data1 += 1;
}
std::atomic<int> 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<TimerInfoTest>();
@@ -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<TimerInfoTest>();
@@ -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<TimerInfoTest>();
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<TimerInfoTest>();
@@ -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<TimerInfoTest>();
@@ -378,4 +365,3 @@ HWTEST_F(TimeServiceTest, CreateTimer06, TestSize.Level0)
ret = TimeServiceClient::GetInstance()->StopTimer(timerId1);
EXPECT_FALSE(ret);
}
#endif
+7 -7
View File
@@ -16,14 +16,14 @@
#ifndef TIMER_HANDLER_H
#define TIMER_HANDLER_H
#include "time_common.h"
#include <array>
#include <cstdint>
#include <string>
#include <chrono>
#include <memory>
#include "time_common.h"
namespace OHOS {
namespace MiscServices {
static const size_t ALARM_TYPE_COUNT = 5;
@@ -32,12 +32,12 @@ typedef std::array<int, N_TIMER_FDS> TimerFds;
class TimerHandler {
public:
static std::shared_ptr<TimerHandler> Create ();
int Set (uint32_t type, std::chrono::nanoseconds when);
uint32_t WaitForAlarm ();
~TimerHandler ();
static std::shared_ptr<TimerHandler> 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_;
};
+8 -8
View File
@@ -54,10 +54,10 @@ bool Batch::CanHold (std::chrono::steady_clock::time_point whenElapsed,
bool Batch::Add (const std::shared_ptr<TimerInfo> &alarm)
{
bool new_start = false;
auto it = std::upper_bound(alarms_.begin(),
alarms_.end(),
auto it = std::upper_bound(alarms_.begin(),
alarms_.end(),
alarm,
[] (const std::shared_ptr<TimerInfo> &first, const std::shared_ptr<TimerInfo> &second) {
[](const std::shared_ptr<TimerInfo> &first, const std::shared_ptr<TimerInfo> &second) {
return first->whenElapsed < second->whenElapsed;
});
alarms_.insert (it, alarm); // 根据Alarm.when_elapsed从小到大排列
@@ -116,11 +116,11 @@ bool Batch::Remove (std::function<bool (const TimerInfo &)> predicate)
bool Batch::HasPackage (const std::string &package_name)
{
return std::find_if (alarms_.begin(),
alarms_.end(),
[package_name] (const std::shared_ptr<TimerInfo> &alarm) {
return alarm->Matches (package_name);
}) != alarms_.end();
return std::find_if(alarms_.begin(),
alarms_.end(),
[package_name](const std::shared_ptr<TimerInfo> &alarm) {
return alarm->Matches(package_name);
}) != alarms_.end();
}
bool Batch::HasWakeups () const
+3 -3
View File
@@ -66,7 +66,7 @@ std::shared_ptr<TimerHandler> TimerHandler::Create()
}
std::shared_ptr<TimerHandler> handler = std::shared_ptr<TimerHandler>(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));
+1 -1
View File
@@ -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;
}
+41 -42
View File
@@ -60,15 +60,15 @@ TimerManager::TimerManager(std::shared_ptr<TimerHandler> 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<void (const uint64_t)> callback,
std::function<void (const uint64_t)> callback,
uint64_t uid)
{
TIME_HILOGI(TIME_MODULE_SERVICE,
"Create timer: %{public}d windowLength:%{public}" PRId64 "interval:%{public}" PRId64 "flag:%{public}d",
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>(TimerEntry {
timerNumber,
timerNumber,
type,
windowLength,
interval,
flag,
std::move(callback),
windowLength,
interval,
flag,
std::move(callback),
uid});
std::lock_guard<std::mutex> 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<void (const uint64_t)> callback,
std::function<void (const uint64_t)> callback,
uint64_t uid)
{
TIME_HILOGI(TIME_MODULE_SERVICE, "start id: %{public}" PRId64 "",id);
TIME_HILOGI(TIME_MODULE_SERVICE,
"start type : %{public}d windowLength:%{public}" PRId64 "interval:%{public}" PRId64 "flag:%{public}d",
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<std::mutex> 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<uint32_t>(flag),
true,
intervalDuration,
std::move(callback),
static_cast<uint32_t>(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<TimerInfo> timer,
std::chrono::steady_clock::time_point nowElapsed,
void TimerManager::ReAddTimerLocked(std::shared_ptr<TimerInfo> 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<milliseconds>(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<std::shared_ptr<TimerInfo>> &
alarm->count = 1;
triggerList.push_back(alarm);
if (alarm->repeatInterval > milliseconds::zero()) {
alarm->count += duration_cast<milliseconds>(nowElapsed -
alarm->expectedWhenElapsed) / alarm->repeatInterval;
alarm->count += duration_cast<milliseconds>(nowElapsed - alarm->expectedWhenElapsed) / alarm->repeatInterval;
auto delta = alarm->count * alarm->repeatInterval;
auto nextElapsed = alarm->whenElapsed + delta;
SetHandlerLocked(alarm->id, alarm->type, alarm->when + delta, nextElapsed, alarm->windowLength,
@@ -412,11 +411,11 @@ bool TimerManager::TriggerTimersLocked(std::vector<std::shared_ptr<TimerInfo>> &
}
}
}
std::sort(triggerList.begin(),
triggerList.end(),
[] (const std::shared_ptr<TimerInfo> &l, const std::shared_ptr<TimerInfo> &r) {
return l->whenElapsed < r->whenElapsed;
});
std::sort(triggerList.begin(),
triggerList.end(),
[](const std::shared_ptr<TimerInfo> &l, const std::shared_ptr<TimerInfo> &r) {
return l->whenElapsed < r->whenElapsed;
});
return hasWakeup;
}
@@ -492,7 +491,7 @@ int64_t TimerManager::AttemptCoalesceLocked(std::chrono::steady_clock::time_poin
}
void TimerManager::DeliverTimersLocked(const std::vector<std::shared_ptr<TimerInfo>> &triggerList,
std::chrono::steady_clock::time_point nowElapsed)
std::chrono::steady_clock::time_point nowElapsed)
{
TIME_HILOGI(TIME_MODULE_SERVICE, "start");
for (const auto &alarm : triggerList) {
@@ -508,7 +507,7 @@ bool AddBatchLocked(std::vector<std::shared_ptr<Batch>> &list, const std::shared
{
TIME_HILOGI(TIME_MODULE_SERVICE, "start");
auto it = std::upper_bound(list.begin(), list.end(), newBatch,
[](const std::shared_ptr<Batch> &first, const std::shared_ptr<Batch> &second) {
[](const std::shared_ptr<Batch> &first, const std::shared_ptr<Batch> &second) {
return first->GetStart() < second->GetStart();
});
list.insert(it, newBatch);
@@ -518,7 +517,7 @@ bool AddBatchLocked(std::vector<std::shared_ptr<Batch>> &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<milliseconds>(triggerAtTime - now)) : interval;
if (futurity < MIN_FUZZABLE_INTERVAL) {
futurity = milliseconds::zero();
+7 -6
View File
@@ -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",
+43
View File
@@ -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 <cstdint>
#include <string>
#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
+4 -5
View File
@@ -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 <mutex>
#include <string>
#include <singleton.h>
#include "bundle_mgr_interface.h"
#include "time_common.h"
#include "mock_permission.h"
#include "system_ability_definition.h"
#include "iservice_registry.h"
#include <singleton.h>
#include <mutex>
#include <string>
namespace OHOS {
namespace MiscServices {
class TimePermission {
+171
View File
@@ -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 <dirent.h>
#include <fcntl.h>
#include <climits>
#include <sys/stat.h>
#include <unistd.h>
#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<int32_t>(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
+1 -1
View File
@@ -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);
}