update OpenHarmony 2.0 Canary

This commit is contained in:
mamingshuai 2021-06-02 00:03:55 +08:00
parent d87e602805
commit 3558e2f089
96 changed files with 8441 additions and 61 deletions

15
.gitattributes vendored Normal file
View File

@ -0,0 +1,15 @@
*.tgz filter=lfs diff=lfs merge=lfs -text
*.trp filter=lfs diff=lfs merge=lfs -text
*.apk filter=lfs diff=lfs merge=lfs -text
*.jar filter=lfs diff=lfs merge=lfs -text
*.mp4 filter=lfs diff=lfs merge=lfs -text
*.zip filter=lfs diff=lfs merge=lfs -text
*.asm filter=lfs diff=lfs merge=lfs -text
*.8svn filter=lfs diff=lfs merge=lfs -text
*.9svn filter=lfs diff=lfs merge=lfs -text
*.dylib filter=lfs diff=lfs merge=lfs -text
*.exe filter=lfs diff=lfs merge=lfs -text
*.a filter=lfs diff=lfs merge=lfs -text
*.so filter=lfs diff=lfs merge=lfs -text
*.bin filter=lfs diff=lfs merge=lfs -text
*.dll filter=lfs diff=lfs merge=lfs -text

177
LICENSE Normal file
View File

@ -0,0 +1,177 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS

View File

@ -1,36 +0,0 @@
# powermgr_power_manager
#### Description
Power manager | 系统电源管理服务模块
#### Software Architecture
Software architecture description
#### Installation
1. xxxx
2. xxxx
3. xxxx
#### Instructions
1. xxxx
2. xxxx
3. xxxx
#### Contribution
1. Fork the repository
2. Create Feat_xxx branch
3. Commit your code
4. Create Pull Request
#### Gitee Feature
1. You can use Readme\_XXX.md to support different languages, such as Readme\_en.md, Readme\_zh.md
2. Gitee blog [blog.gitee.com](https://blog.gitee.com)
3. Explore open source project [https://gitee.com/explore](https://gitee.com/explore)
4. The most valuable open source project [GVP](https://gitee.com/gvp)
5. The manual of Gitee [https://gitee.com/help](https://gitee.com/help)
6. The most popular members [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/)

53
README.md Normal file → Executable file
View File

@ -1,37 +1,40 @@
# powermgr_power_manager
# power\_manager<a name="EN-US_TOPIC_0000001115047353"></a>
#### 介绍
Power manager | 系统电源管理服务模块
- [Introduction](#section11660541593)
- [Directory Structure](#section19472752217)
- [Repositories Involved](#section63151229062)
#### 软件架构
软件架构说明
## Introduction<a name="section11660541593"></a>
Power Manager provides the following functionalities:
#### 安装教程
1. Rebooting the device
2. Managing running locks
3. Obtaining the power status
1. xxxx
2. xxxx
3. xxxx
**Figure 1** Power management subsystem architecture<a name="fig106301571239"></a>
![](figures/power-management-subsystem-architecture.png "power-management-subsystem-architecture")
#### 使用说明
## Directory Structure<a name="section19472752217"></a>
1. xxxx
2. xxxx
3. xxxx
```
/base/powermgr/power_manager
├── interfaces # APIs
│ ├── innerkits # Internal APIs
│ └── kits # External APIs
├── sa_profile # SA profile
└── services # Services
│ ├── native # Native services
│ └── zidl # zidl APIs
└── utils # Utilities and common code
```
#### 参与贡献
## Repositories Involved<a name="section63151229062"></a>
1. Fork 本仓库
2. 新建 Feat_xxx 分支
3. 提交代码
4. 新建 Pull Request
Power management subsystem
powermgr_battery_manager
#### 特技
**powermgr_power_manager**
1. 使用 Readme\_XXX.md 来支持不同的语言,例如 Readme\_en.md, Readme\_zh.md
2. Gitee 官方博客 [blog.gitee.com](https://blog.gitee.com)
3. 你可以 [https://gitee.com/explore](https://gitee.com/explore) 这个地址来了解 Gitee 上的优秀开源项目
4. [GVP](https://gitee.com/gvp) 全称是 Gitee 最有价值开源项目,是综合评定出的优秀开源项目
5. Gitee 官方提供的使用手册 [https://gitee.com/help](https://gitee.com/help)
6. Gitee 封面人物是一档用来展示 Gitee 会员风采的栏目 [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/)
powermgr_display_manager

42
README_zh.md Executable file
View File

@ -0,0 +1,42 @@
# 电源管理服务组件<a name="ZH-CN_TOPIC_0000001115047353"></a>
- [简介](#section11660541593)
- [目录](#section19472752217)
- [相关仓](#section63151229062)
## 简介<a name="section11660541593"></a>
电源管理服务组件提供如下功能:
1. 重启系统。
2. 管理休眠运行锁。
3. 系统电源状态查询。
**图 1** 电源管理子系统架构图<a name="fig106301571239"></a>
![](figures/power-management-subsystem-architecture.png "电源管理子系统架构图")
## 目录<a name="section19472752217"></a>
```
/base/powermgr/power_manager
├── interfaces # 接口层
│ ├── innerkits # 内部接口
│ └── kits # 外部接口
├── sa_profile # SA配置文件
└── services # 服务层
│ ├── native # native层
│ └── zidl # zidl层
└── utils # 工具和通用层
```
## 相关仓<a name="section63151229062"></a>
电源管理子系统
powermgr_battery_manager
**powermgr_power_manager**
powermgr_display_manager

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

View File

@ -0,0 +1,58 @@
# 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.
import("//base/powermgr/power_manager/powermgr.gni")
config("powermgr_private_config") {
include_dirs = [
"${powermgr_service_path}/zidl/include",
"//utils/system/safwk/native/include",
]
}
config("powermgr_public_config") {
include_dirs = [ "native/include" ]
}
ohos_shared_library("powermgr_client") {
sources = [
"${powermgr_service_path}/zidl/src/power_mgr_proxy.cpp",
"${powermgr_service_path}/zidl/src/power_state_callback_proxy.cpp",
"native/src/power_mgr_client.cpp",
"native/src/running_lock.cpp",
"native/src/running_lock_info.cpp",
"native/src/running_lock_token_stub.cpp",
]
configs = [
"${powermgr_utils_path}:utils_config",
":powermgr_private_config",
]
public_configs = [ ":powermgr_public_config" ]
deps = [
"${powermgr_utils_path}:powermgr_utils",
"//utils/native/base:utils",
]
external_deps = [
"appexecfwk_standard:libeventhandler",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"safwk:system_ability_fwk",
"samgr_L2:samgr_proxy",
]
part_name = "${powermgr_native_part_name}"
}

View File

@ -0,0 +1,78 @@
/*
* 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 POWERMGR_IPOWER_MANAGER_H
#define POWERMGR_IPOWER_MANAGER_H
#include <string>
#include <iremote_broker.h>
#include <iremote_object.h>
#include "ipower_state_callback.h"
#include "ishutdown_callback.h"
#include "power_state_machine_info.h"
#include "running_lock_info.h"
namespace OHOS {
namespace PowerMgr {
class IPowerMgr : public IRemoteBroker {
public:
enum {
RUNNINGLOCK_LOCK = 0,
RUNNINGLOCK_UNLOCK,
RUNNINGLOCK_SET_WORK_TRIGGER_LIST,
RUNNINGLOCK_ISUSED,
PROXY_RUNNINGLOCK,
WAKEUP_DEVICE,
SUSPEND_DEVICE,
REFRESH_ACTIVITY,
IS_SCREEN_ON,
FORCE_DEVICE_SUSPEND,
REBOOT_DEVICE,
SHUTDOWN_DEVICE,
REG_POWER_STATE_CALLBACK,
UNREG_POWER_STATE_CALLBACK,
REG_SHUTDOWN_CALLBACK,
UNREG_SHUTDOWN_CALLBACK
};
virtual void Lock(const sptr<IRemoteObject>& token, const RunningLockInfo& runningLockInfo,
uint32_t timeOutMs) = 0;
virtual void UnLock(const sptr<IRemoteObject>& token) = 0;
virtual bool IsUsed(const sptr<IRemoteObject>& token) = 0;
virtual void SetWorkTriggerList(const sptr<IRemoteObject>& token, const WorkTriggerList& workTriggerList) = 0;
virtual void ProxyRunningLock(bool proxyLock, pid_t uid, pid_t pid) = 0;
// Used for power state machine.
virtual void RebootDevice(const std::string& reason) = 0;
virtual void ShutDownDevice(const std::string& reason) = 0;
virtual void SuspendDevice(int64_t callTimeMs, SuspendDeviceType reason, bool suspendImmed) = 0;
virtual void WakeupDevice(int64_t callTimeMs, WakeupDeviceType reason, const std::string& details) = 0;
virtual void RefreshActivity(int64_t callTimeMs, UserActivityType type, bool needChangeBacklight) = 0;
virtual bool IsScreenOn() = 0;
virtual bool ForceSuspendDevice(int64_t callTimeMs) = 0;
virtual void RegisterPowerStateCallback(const sptr<IPowerStateCallback>& callback) = 0;
virtual void UnRegisterPowerStateCallback(const sptr<IPowerStateCallback>& callback) = 0;
// Used for callback registration upon shutdown.
virtual void RegisterShutdownCallback(const sptr<IShutdownCallback>& callback) = 0;
virtual void UnRegisterShutdownCallback(const sptr<IShutdownCallback>& callback) = 0;
DECLARE_INTERFACE_DESCRIPTOR(u"ohos.powermgr.IPowerMgr");
};
} // namespace PowerMgr
} // namespace OHOS
#endif // POWERMGR_IPOWER_MANAGER_H

View File

@ -0,0 +1,37 @@
/*
* 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 POWERMGR_IPOWER_STATE_CALLBACK_H
#define POWERMGR_IPOWER_STATE_CALLBACK_H
#include <iremote_broker.h>
#include <iremote_object.h>
#include "power_state_machine_info.h"
namespace OHOS {
namespace PowerMgr {
class IPowerStateCallback : public IRemoteBroker {
public:
enum {
POWER_STATE_CHANGED = 0,
};
virtual void OnPowerStateChanged(PowerState state) = 0;
DECLARE_INTERFACE_DESCRIPTOR(u"ohos.powermgr.IPowerStateCallback");
};
} // namespace PowerMgr
} // namespace OHOS
#endif // POWERMGR_IPOWER_STATE_CALLBACK_H

View File

@ -0,0 +1,32 @@
/*
* 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 IPOWER_MGR_SHUTDOWN_CALLBACK_H
#define IPOWER_MGR_SHUTDOWN_CALLBACK_H
#include <iremote_broker.h>
#include <iremote_object.h>
namespace OHOS {
namespace PowerMgr {
class IShutdownCallback : public IRemoteBroker {
public:
virtual void ShutdownCallback() = 0;
DECLARE_INTERFACE_DESCRIPTOR(u"ohos.powermgr.IShutdownCallback");
};
} // namespace PowerMgr
} // namespace OHOS
#endif // IPOWER_MGR_SHUTDOWN_CALLBACK_H

View File

@ -0,0 +1,112 @@
/*
* 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 POWERMGR_POWER_MGR_CLIENT_H
#define POWERMGR_POWER_MGR_CLIENT_H
#include <string>
#include <singleton.h>
#include "power_state_machine_info.h"
#include "running_lock.h"
namespace OHOS {
namespace PowerMgr {
class PowerMgrClient final : public DelayedRefSingleton<PowerMgrClient> {
DECLARE_DELAYED_REF_SINGLETON(PowerMgrClient)
public:
DISALLOW_COPY_AND_MOVE(PowerMgrClient);
/**
* Reboot the device.
*
* @param reason The reason for rebooting the device.
*/
void RebootDevice(const std::string& reason);
/**
* Shut down the device.
*
* @param reason The reason for shutting down the device. e.g.recovery.
*
*/
void ShutDownDevice(const std::string& reason);
/**
* Suspend device and set screen off.
*
* @param reason The reason why will you suspend the device, such as timeout/powerkey/forcesuspend and so on.
* @param suspendImmed The flag indicating whether the system will go to sleep immediately.
*/
void SuspendDevice(SuspendDeviceType reason = SuspendDeviceType::SUSPEND_DEVICE_REASON_APPLICATION,
bool suspendImmed = true);
/**
* Wake up the device and set the screen on.
*
* @param reason The reason for waking up the device, such as powerkey/plugin/application.
* @param details Details of the wakeup reason.
*/
void WakeupDevice(WakeupDeviceType reason = WakeupDeviceType::WAKEUP_DEVICE_APPLICATION,
const std::string& details = "SoftWare Wakeup");
/**
* Refresh the screentimeout time, and keep the screen on. RefreshActivity works only when the screen is on.
*
* @param type The RefreshActivity type, such as touch/button/accessibility and so on.
* @param needChangeBacklight Whether to change the backlight state, for example, from DIM to BRIGHT.
* Set it to false if you don't want to change the backlight state.
*/
void RefreshActivity(UserActivityType type = UserActivityType::USER_ACTIVITY_TYPE_OTHER,
bool needChangeBacklight = true);
/**
* Check whether the device screen is on. The result may be true or false, depending on the system state.
*/
bool IsScreenOn();
/**
* Forcibly suspend the device into deepsleep, and return the suspend result.
*/
bool ForceSuspendDevice();
std::shared_ptr<RunningLock> CreateRunningLock(const std::string& name, RunningLockType type,
const int screenOnFlag = 0);
void ProxyRunningLock(bool proxyLock, pid_t uid, pid_t pid = INVALID_PID);
void RegisterPowerStateCallback(const sptr<IPowerStateCallback>& callback);
void UnRegisterPowerStateCallback(const sptr<IPowerStateCallback>& callback);
void RegisterShutdownCallback(const sptr<IShutdownCallback>& callback);
void UnRegisterShutdownCallback(const sptr<IShutdownCallback>& callback);
private:
class PowerMgrDeathRecipient : public IRemoteObject::DeathRecipient {
public:
PowerMgrDeathRecipient() = default;
~PowerMgrDeathRecipient() = default;
void OnRemoteDied(const wptr<IRemoteObject>& remote);
private:
DISALLOW_COPY_AND_MOVE(PowerMgrDeathRecipient);
};
ErrCode Connect();
sptr<IPowerMgr> proxy_ {nullptr};
sptr<IRemoteObject::DeathRecipient> deathRecipient_ {nullptr};
void ResetProxy(const wptr<IRemoteObject>& remote);
std::mutex mutex_;
};
} // namespace PowerMgr
} // namespace OHOS
#endif // POWERMGR_POWER_MGR_CLIENT_H

View File

@ -0,0 +1,107 @@
/*
* 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 POWERMGR_POWER_STATE_MACHINE_INFO_H
#define POWERMGR_POWER_STATE_MACHINE_INFO_H
#include <string>
#include <parcel.h>
namespace OHOS {
namespace PowerMgr {
/*
* If already dimmed, extend the dim timeout but do not brighten. This flag is useful for keeping
* the screen on little longer without causing a visible change such as when the power key is pressed.
*/
constexpr uint32_t REFRESH_ACTIVITY_NO_CHANGE_LIGHTS = 1 << 0;
constexpr uint32_t REFRESH_ACTIVITY_NEED_CHANGE_LIGHTS = 0;
/*
* Indicate whether device enter suspend immediately
*/
constexpr uint32_t SUSPEND_DEVICE_NEED_DOZE = 0;
constexpr uint32_t SUSPEND_DEVICE_IMMEDIATELY = 1 << 0;
// This is use for judge whether the time is valid.
constexpr int DEFAULT_SYSTEM_START_TIME = 0;
// Max datails string length
constexpr int MAX_STRING_LENGTH = 128;
// Throttling interval for user activity calls.
constexpr int64_t MIN_TIME_MS_BETWEEN_USERACTIVITIES = 100; // 100ms
/**
* PowerState of Device.
*/
enum class PowerState : uint32_t {
/**
* Power State: screen on and cpu on.
*/
AWAKE,
/**
* Power State: screen off and cpu on.
*/
INACTIVE,
/**
* Power State: screen off and cpu off.
*/
SLEEP,
};
// UserActivityType list, must sync with A_PMS
enum class UserActivityType : uint32_t {
USER_ACTIVITY_TYPE_OTHER = 0,
USER_ACTIVITY_TYPE_BUTTON = 1,
USER_ACTIVITY_TYPE_TOUCH = 2,
USER_ACTIVITY_TYPE_ACCESSIBILITY = 3,
USER_ACTIVITY_TYPE_ATTENTION = 4,
USER_ACTIVITY_TYPE_SOFTWARE = 5,
};
// WakeupReasonType list
enum class WakeupDeviceType : uint32_t {
WAKEUP_DEVICE_UNKNOWN = 0,
WAKEUP_DEVICE_POWER_BUTTON = 1,
WAKEUP_DEVICE_APPLICATION = 2,
WAKEUP_DEVICE_PLUGGED_IN = 3,
WAKEUP_DEVICE_GESTURE = 4,
WAKEUP_DEVICE_CAMERA_LAUNCH = 5,
WAKEUP_DEVICE_WAKE_KEY = 6,
WAKEUP_DEVICE_WAKE_MOTION = 7,
WAKEUP_DEVICE_HDMI = 8,
WAKEUP_DEVICE_LID = 9,
};
// SuspendDeviceType list
enum class SuspendDeviceType : uint32_t {
SUSPEND_DEVICE_REASON_MIN = 0,
SUSPEND_DEVICE_REASON_APPLICATION = SUSPEND_DEVICE_REASON_MIN,
SUSPEND_DEVICE_REASON_DEVICE_ADMIN = 1,
SUSPEND_DEVICE_REASON_TIMEOUT = 2,
SUSPEND_DEVICE_REASON_LID_SWITCH = 3,
SUSPEND_DEVICE_REASON_POWER_BUTTON = 4,
SUSPEND_DEVICE_REASON_HDMI = 5,
SUSPEND_DEVICE_REASON_SLEEP_BUTTON = 6,
SUSPEND_DEVICE_REASON_ACCESSIBILITY = 7,
SUSPEND_DEVICE_REASON_FORCE_SUSPEND = 8,
SUSPEND_DEVICE_REASON_MAX = SUSPEND_DEVICE_REASON_FORCE_SUSPEND,
};
} // namespace PowerMgr
} // namespace OHOS
#endif // POWERMGR_POWER_STATE_MACHINE_INFO_H

View File

@ -0,0 +1,80 @@
/*
* 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 POWERMGR_RUNNING_LOCK_H
#define POWERMGR_RUNNING_LOCK_H
#include <memory>
#include <mutex>
#include <iremote_object.h>
#include "ipower_mgr.h"
#include "running_lock_info.h"
namespace OHOS {
namespace PowerMgr {
class RunningLock {
public:
RunningLock(const wptr<IPowerMgr>& proxy, const std::string& name, RunningLockType type);
~RunningLock();
DISALLOW_COPY_AND_MOVE(RunningLock);
enum class RunningLockState {
UNUSED = 0,
USED,
UNKNOWN,
BUTT,
};
bool Init();
bool IsUsed();
/**
* Acquires a runninglock.
* The parameter of last called will replace that of the previous called, and the effective parameter will
* be that of the last called. Eg : If call Lock(n) first then Lock(), a lasting lock will be hold, and
* need UnLock() to be called to release it. If else call Lock() first and then Lock(n), the parameter 'n'
* takes effect and it will be released in n ms automatiocly.
* @param timeOutMs timeOutMs this runninglock will be released in timeOutMs milliseconds. If it is called without
* parameter or parameter is 0 a lasting runninglock will be hold.
*/
ErrCode Lock(uint32_t timeOutMs = 0);
/**
* Release the runninglock, no matter how many times Lock() was called.
* The release can be done by calling UnLock() only once.
*/
ErrCode UnLock();
/**
* Maintain the information about the application that attempts to acquire the runninglock.
*/
ErrCode SetWorkTriggerList(const WorkTriggerList& list);
const WorkTriggerList& GetWorkTriggerList() const;
static constexpr uint32_t MAX_NAME_LEN = 256;
static constexpr uint32_t CREATE_WITH_SCREEN_ON = 0x10000000;
private:
std::mutex mutex_;
RunningLockInfo runningLockInfo_;
RunningLockState usedState_ {RunningLockState::UNUSED};
sptr<IRemoteObject> token_;
wptr<IPowerMgr> proxy_;
bool CheckUsedNoLock();
};
} // namespace PowerMgr
} // namespace OHOS
#endif // POWERMGR_RUNNING_LOCK_H

View File

@ -0,0 +1,81 @@
/*
* 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 POWERMGR_RUNNING_LOCK_INFO_H
#define POWERMGR_RUNNING_LOCK_INFO_H
#include <list>
#include <string>
#include <parcel.h>
#include "work_trigger.h"
namespace OHOS {
namespace PowerMgr {
/**
* Runninglock acquisition type
*/
enum class RunningLockType : uint32_t {
/**
* RunningLock type: used to keep screen on.
*/
RUNNINGLOCK_SCREEN,
/**
* RunningLock type: used to keep cpu running.
*/
RUNNINGLOCK_BACKGROUND,
/**
* RunningLock type: used to keep the screen on/off when the proximity sensor is active.
*/
RUNNINGLOCK_PROXIMITY_SCREEN_CONTROL,
RUNNINGLOCK_BUTT
};
using WorkTriggerList = std::list<std::shared_ptr<WorkTrigger>>;
/**
* Maintain runninglock information.
*/
struct RunningLockInfo : public Parcelable {
/**
* RunningLock name: used to identify user of the runninglock.
* You are advised to set it to a combination of information,
* such as package name and class name and a unique name.
*/
std::string name;
/**
* RunningLock type: used to identify the type of RunningLock.
*/
RunningLockType type;
/**
* WorkTriggerList: generally used to manintain the information about the application,
* which attempts to acquire the RunningLock.
*/
WorkTriggerList workTriggerlist;
RunningLockInfo() = default;
RunningLockInfo(const std::string& namestr, RunningLockType locktype) : name(namestr), type(locktype) {}
bool ReadFromParcel(Parcel& parcel);
bool Marshalling(Parcel& parcel) const override;
static RunningLockInfo* Unmarshalling(Parcel& parcel);
static bool MarshallingWorkTriggerList(Parcel& parcel, const WorkTriggerList& list);
static bool ReadFromParcelWorkTriggerList(Parcel& parcel, WorkTriggerList& list);
};
} // namespace PowerMgr
} // namespace OHOS
#endif // POWERMGR_RUNNING_LOCK_INFO_H

View File

@ -0,0 +1,46 @@
/*
* 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 POWERMGR_RUNNING_LOCK_TOKEN_STUB_H
#define POWERMGR_RUNNING_LOCK_TOKEN_STUB_H
#include <iremote_broker.h>
#include <iremote_proxy.h>
#include <iremote_stub.h>
namespace OHOS {
namespace PowerMgr {
class IRunningLockToken : public OHOS::IRemoteBroker {
public:
DECLARE_INTERFACE_DESCRIPTOR(u"ohos.powermgr.IRunningLockToken");
};
class RunningLockTokenStub : public IRemoteStub<IRunningLockToken> {
public:
virtual ~RunningLockTokenStub() = default;
};
class RunningLockTokenProxy : public IRemoteProxy<IRunningLockToken> {
public:
explicit RunningLockTokenProxy(const sptr<IRemoteObject>& impl)
: IRemoteProxy<IRunningLockToken>(impl) {}
virtual ~RunningLockTokenProxy() = default;
private:
static inline BrokerDelegator<RunningLockTokenProxy> delegator_;
};
} // namespace PowerMgr
} // namespace OHOS
#endif // POWERMGR_RUNNING_LOCK_TOKEN_STUB_H

View File

@ -0,0 +1,84 @@
/*
* 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 POWERMGR_WORKTRIGGER_H
#define POWERMGR_WORKTRIGGER_H
#include <string>
#include <list>
#include <parcel.h>
namespace OHOS {
namespace PowerMgr {
constexpr int INVALID_PID = -1;
constexpr int INVALID_UID = -1;
class WorkTrigger : public Parcelable {
public:
WorkTrigger() = default;
WorkTrigger(uint32_t uid, const std::string& name = "", uint32_t pid = 0)
: uid_(uid), name_(name), pid_(pid) {}
~WorkTrigger() = default;
void SetAbilityId(int abilityId)
{
abilityId_ = abilityId;
}
void SetPid(int pid)
{
pid_ = pid;
}
int GetAbilityId() const
{
return abilityId_;
}
int GetPid() const
{
return pid_;
}
int GetUid() const
{
return uid_;
}
const std::string& GetName() const
{
return name_;
}
bool operator==(const WorkTrigger& other) const
{
return (uid_ == other.uid_) && (pid_ == other.pid_) && (abilityId_ == other.abilityId_) &&
(name_.compare(other.name_) == 0);
}
bool ReadFromParcel(Parcel& parcel);
bool Marshalling(Parcel& parcel) const override;
static WorkTrigger* Unmarshalling(Parcel& parcel);
private:
uint32_t uid_{INVALID_UID};
std::string name_;
uint32_t pid_{INVALID_PID};
uint32_t abilityId_ {0};
};
} // namespace PowerMgr
} // namespace OHOS
#endif // POWERMGR_WORKTRIGGER_H

View File

@ -0,0 +1,237 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "power_mgr_client.h"
#include <datetime_ex.h>
#include <if_system_ability_manager.h>
#include <ipc_skeleton.h>
#include <iservice_registry.h>
#include <string_ex.h>
#include <system_ability_definition.h>
#include "permission.h"
#include "power_common.h"
namespace OHOS {
namespace PowerMgr {
namespace {
constexpr int APP_FIRST_UID = 10000;
}
PowerMgrClient::PowerMgrClient() {}
PowerMgrClient::~PowerMgrClient()
{
if (proxy_ != nullptr) {
auto remoteObject = proxy_->AsObject();
if (remoteObject != nullptr) {
remoteObject->RemoveDeathRecipient(deathRecipient_);
}
}
}
ErrCode PowerMgrClient::Connect()
{
std::lock_guard<std::mutex> lock(mutex_);
if (proxy_ != nullptr) {
return ERR_OK;
}
sptr<ISystemAbilityManager> sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (sam == nullptr) {
POWER_HILOGE(MODULE_INNERKIT, "%{public}s:Failed to get Registry!", __func__);
return E_GET_SYSTEM_ABILITY_MANAGER_FAILED;
}
sptr<IRemoteObject> remoteObject_ = sam->CheckSystemAbility(POWER_MANAGER_SERVICE_ID);
if (remoteObject_ == nullptr) {
POWER_HILOGE(MODULE_INNERKIT, "GetSystemAbility failed!");
return E_GET_POWER_SERVICE_FAILED;
}
deathRecipient_ = sptr<IRemoteObject::DeathRecipient>(new PowerMgrDeathRecipient());
if (deathRecipient_ == nullptr) {
POWER_HILOGE(MODULE_INNERKIT, "%{public}s :Failed to create PowerMgrDeathRecipient!", __func__);
return ERR_NO_MEMORY;
}
if ((remoteObject_->IsProxyObject()) && (!remoteObject_->AddDeathRecipient(deathRecipient_))) {
POWER_HILOGE(MODULE_INNERKIT, "%{public}s :Add death recipient to PowerMgr service failed.", __func__);
return E_ADD_DEATH_RECIPIENT_FAILED;
}
proxy_ = iface_cast<IPowerMgr>(remoteObject_);
POWER_HILOGI(MODULE_INNERKIT, "%{public}s :Connecting PowerMgrService success.", __func__);
return ERR_OK;
}
void PowerMgrClient::ResetProxy(const wptr<IRemoteObject>& remote)
{
std::lock_guard<std::mutex> lock(mutex_);
RETURN_IF(proxy_ == nullptr);
auto serviceRemote = proxy_->AsObject();
if ((serviceRemote != nullptr) && (serviceRemote == remote.promote())) {
serviceRemote->RemoveDeathRecipient(deathRecipient_);
proxy_ = nullptr;
}
}
void PowerMgrClient::PowerMgrDeathRecipient::OnRemoteDied(const wptr<IRemoteObject>& remote)
{
if (remote == nullptr) {
POWER_HILOGE(MODULE_INNERKIT, "PowerMgrDeathRecipient::OnRemoteDied failed, remote is nullptr.");
return;
}
PowerMgrClient::GetInstance().ResetProxy(remote);
POWER_HILOGI(MODULE_INNERKIT, "PowerMgrDeathRecipient::Recv death notice.");
}
void PowerMgrClient::RebootDevice(const std::string& reason)
{
RETURN_IF(Connect() != ERR_OK);
POWER_HILOGE(MODULE_INNERKIT, "%{public}s called.", __func__);
proxy_->RebootDevice(reason);
}
void PowerMgrClient::ShutDownDevice(const std::string& reason)
{
RETURN_IF(Connect() != ERR_OK);
POWER_HILOGE(MODULE_INNERKIT, "%{public}s called.", __func__);
proxy_->ShutDownDevice(reason);
}
void PowerMgrClient::SuspendDevice(SuspendDeviceType reason, bool suspendImmed)
{
RETURN_IF(Connect() != ERR_OK);
proxy_->SuspendDevice(GetTickCount(), reason, suspendImmed);
POWER_HILOGI(MODULE_INNERKIT, " Calling SuspendDevice success.");
}
void PowerMgrClient::WakeupDevice(WakeupDeviceType reason, const std::string& details)
{
RETURN_IF(Connect() != ERR_OK);
// Param details's length must > 0
if (details.empty()) {
POWER_HILOGE(MODULE_INNERKIT, "%{public}s : detail length is 0, Wakeup failed!", __func__);
return;
}
std::string subDetails;
if (details.length() > MAX_STRING_LENGTH) {
POWER_HILOGI(MODULE_INNERKIT, "%{public}s : detail = %{public}s, length is larger than %{public}d, \
do substring!", __func__, details.c_str(), MAX_STRING_LENGTH);
subDetails = details.substr(0, MAX_STRING_LENGTH);
} else {
subDetails = details;
}
proxy_->WakeupDevice(GetTickCount(), reason, subDetails);
POWER_HILOGI(MODULE_INNERKIT, " Calling WakeupDevice success.");
}
void PowerMgrClient::RefreshActivity(UserActivityType type, bool needChangeBacklight)
{
RETURN_IF_WITH_LOG(type == UserActivityType::USER_ACTIVITY_TYPE_ATTENTION, " is not supported!");
RETURN_IF(Connect() != ERR_OK);
proxy_->RefreshActivity(GetTickCount(), type, needChangeBacklight);
POWER_HILOGI(MODULE_INNERKIT, " Calling RefreshActivity Success!");
}
bool PowerMgrClient::ForceSuspendDevice()
{
RETURN_IF_WITH_RET(Connect() != ERR_OK, false);
bool ret = proxy_->ForceSuspendDevice(GetTickCount());
POWER_HILOGI(MODULE_INNERKIT, " Calling ForceSuspendDevice Success!");
return ret;
}
bool PowerMgrClient::IsScreenOn()
{
RETURN_IF_WITH_RET(Connect() != ERR_OK, false);
bool ret = false;
ret = proxy_->IsScreenOn();
POWER_HILOGI(MODULE_INNERKIT, " Calling IsScreenOn Success!");
return ret;
}
std::shared_ptr<RunningLock> PowerMgrClient::CreateRunningLock(const std::string& name, RunningLockType type,
const int screenOnFlag)
{
auto uid = IPCSkeleton::GetCallingUid();
if (uid >= APP_FIRST_UID && !Permission::CheckSelfPermission("ohos.permission.RUNNING_LOCK")) {
POWER_HILOGE(MODULE_SERVICE, "%{public}s Request failed, %{public}d permission check failed", __func__, uid);
return nullptr;
}
RETURN_IF_WITH_RET(Connect() != ERR_OK, nullptr);
if (screenOnFlag == RunningLock::CREATE_WITH_SCREEN_ON) {
if (type != RunningLockType::RUNNINGLOCK_SCREEN) {
POWER_HILOGE(MODULE_INNERKIT, "%{public}s failed to create RunningLock due to screenOnFlag error",
__func__);
return nullptr;
} else {
WakeupDevice(WakeupDeviceType::WAKEUP_DEVICE_APPLICATION, "RunningLockWakeUpScreen");
}
}
int nameLen = (name.size() > RunningLock::MAX_NAME_LEN) ? RunningLock::MAX_NAME_LEN : name.size();
std::shared_ptr<RunningLock> runningLock = std::make_shared<RunningLock>(proxy_, name.substr(0, nameLen), type);
if (runningLock == nullptr) {
POWER_HILOGE(MODULE_INNERKIT, "%{public}s failed to create new RunningLock record", __func__);
return nullptr;
}
if (!runningLock->Init()) {
POWER_HILOGE(MODULE_INNERKIT, "%{public}s runningLock->Init failed.", __func__);
return nullptr;
}
POWER_HILOGI(MODULE_INNERKIT, "%{public}s :name %{public}s, type = %d", __func__, name.c_str(), type);
return runningLock;
}
void PowerMgrClient::ProxyRunningLock(bool proxyLock, pid_t uid, pid_t pid)
{
RETURN_IF(Connect() != ERR_OK);
POWER_HILOGI(MODULE_INNERKIT, "%{public}s :proxyLock = %d, uid = %d, pid = %d", __func__,
proxyLock, uid, pid);
proxy_->ProxyRunningLock(proxyLock, uid, pid);
}
void PowerMgrClient::RegisterPowerStateCallback(const sptr<IPowerStateCallback>& callback)
{
RETURN_IF((callback == nullptr) || (Connect() != ERR_OK));
POWER_HILOGI(MODULE_INNERKIT, "%{public}s.", __func__);
proxy_->RegisterPowerStateCallback(callback);
}
void PowerMgrClient::UnRegisterPowerStateCallback(const sptr<IPowerStateCallback>& callback)
{
RETURN_IF((callback == nullptr) || (Connect() != ERR_OK));
POWER_HILOGI(MODULE_INNERKIT, "%{public}s.", __func__);
proxy_->UnRegisterPowerStateCallback(callback);
}
void PowerMgrClient::RegisterShutdownCallback(const sptr<IShutdownCallback>& callback)
{
RETURN_IF((callback == nullptr) || (Connect() != ERR_OK));
proxy_->RegisterShutdownCallback(callback);
}
void PowerMgrClient::UnRegisterShutdownCallback(const sptr<IShutdownCallback>& callback)
{
RETURN_IF((callback == nullptr) || (Connect() != ERR_OK));
proxy_->UnRegisterShutdownCallback(callback);
}
} // namespace PowerMgr
} // namespace OHOS

View File

@ -0,0 +1,143 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "running_lock.h"
#include "power_common.h"
#include "running_lock_token_stub.h"
using std::lock_guard;
namespace OHOS {
namespace PowerMgr {
RunningLock::RunningLock(const wptr<IPowerMgr>& proxy, const std::string& name, RunningLockType type)
: proxy_(proxy)
{
runningLockInfo_.name = name;
runningLockInfo_.type = type;
}
RunningLock::~RunningLock()
{
UnLock();
}
bool RunningLock::Init()
{
lock_guard<std::mutex> lock(mutex_);
token_ = new (std::nothrow)RunningLockTokenStub();
if (token_ == nullptr) {
POWER_HILOGE(MODULE_INNERKIT, "RunningLock::%{public}s :creating RunningLockTokenStub error.", __func__);
return false;
}
return true;
}
ErrCode RunningLock::Lock(uint32_t timeOutMs)
{
lock_guard<std::mutex> lock(mutex_);
POWER_HILOGI(MODULE_INNERKIT, "RunningLock::%{public}s :timeOutMs = %u.", __func__, timeOutMs);
sptr<IPowerMgr> proxy = proxy_.promote();
if (proxy == nullptr) {
POWER_HILOGE(MODULE_INNERKIT, "RunningLock::%{public}s :proxy nullptr.", __func__);
return E_GET_POWER_SERVICE_FAILED;
}
POWER_HILOGI(MODULE_INNERKIT, "RunningLock::%{public}s :service lock is called", __func__);
proxy->Lock(token_, runningLockInfo_, timeOutMs);
if (timeOutMs != 0) {
usedState_ = RunningLockState::UNKNOWN;
} else {
usedState_ = RunningLockState::USED;
}
return ERR_OK;
}
ErrCode RunningLock::UnLock()
{
lock_guard<std::mutex> lock(mutex_);
POWER_HILOGI(MODULE_INNERKIT, "RunningLock::%{public}s.", __func__);
if (!CheckUsedNoLock()) {
return ERR_OK;
}
sptr<IPowerMgr> proxy = proxy_.promote();
if (proxy == nullptr) {
POWER_HILOGE(MODULE_INNERKIT, "RunningLock::%{public}s :proxy nullptr.", __func__);
return E_GET_POWER_SERVICE_FAILED;
}
POWER_HILOGI(MODULE_INNERKIT, "RunningLock::%{public}s :really called service UnLock.", __func__);
proxy->UnLock(token_);
usedState_ = RunningLockState::UNUSED;
return ERR_OK;
}
bool RunningLock::CheckUsedNoLock()
{
if (usedState_ <= RunningLockState::USED) {
return (usedState_ == RunningLockState::USED);
}
sptr<IPowerMgr> proxy = proxy_.promote();
if (proxy == nullptr) {
POWER_HILOGE(MODULE_INNERKIT, "RunningLock::%{public}s :proxy nullptr.", __func__);
return false;
}
bool ret = proxy->IsUsed(token_);
if (!ret) {
// only ret false can update the unknown state.
usedState_ = RunningLockState::UNUSED;
return false;
}
POWER_HILOGI(MODULE_INNERKIT, "RunningLock::%{public}s, usedState_ = %d.", __func__, usedState_);
return true;
}
bool RunningLock::IsUsed()
{
lock_guard<std::mutex> lock(mutex_);
POWER_HILOGI(MODULE_INNERKIT, "RunningLock::%{public}s.", __func__);
return CheckUsedNoLock();
}
ErrCode RunningLock::SetWorkTriggerList(const WorkTriggerList& workTriggerList)
{
lock_guard<std::mutex> lock(mutex_);
auto& list = runningLockInfo_.workTriggerlist;
list.clear();
for (auto& w : workTriggerList) {
if (w != nullptr) {
list.push_back(w);
}
}
if (!CheckUsedNoLock()) {
// no need to notify service when the lock is not used.
return ERR_OK;
}
sptr<IPowerMgr> proxy = proxy_.promote();
if (proxy == nullptr) {
POWER_HILOGE(MODULE_INNERKIT, "RunningLock::%{public}s :proxy nullptr.", __func__);
return E_GET_POWER_SERVICE_FAILED;
}
POWER_HILOGI(MODULE_INNERKIT, "RunningLock::%{public}s :service SetWorkTriggerList is called.", __func__);
proxy->SetWorkTriggerList(token_, runningLockInfo_.workTriggerlist);
return ERR_OK;
}
const WorkTriggerList& RunningLock::GetWorkTriggerList() const
{
return runningLockInfo_.workTriggerlist;
}
} // namespace PowerMgr
} // namespace OHOS

View File

@ -0,0 +1,132 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "running_lock_info.h"
#include <string_ex.h>
#include "power_common.h"
namespace OHOS {
namespace PowerMgr {
bool RunningLockInfo::ReadFromParcelWorkTriggerList(Parcel& parcel, WorkTriggerList& list)
{
uint32_t listSize = 0;
if (!parcel.ReadUint32(listSize)) {
return false;
}
POWER_HILOGD(MODULE_SERVICE, "RunningLockInfo::%{public}s listSize = %u", __func__, listSize);
while (listSize > 0) {
std::shared_ptr<WorkTrigger> workTrigger(parcel.ReadParcelable<WorkTrigger>());
if (workTrigger == nullptr) {
return false;
}
list.emplace_back(workTrigger);
listSize--;
}
return true;
}
bool RunningLockInfo::ReadFromParcel(Parcel& parcel)
{
uint32_t readType;
READ_PARCEL_WITH_RET(parcel, String, name, false);
READ_PARCEL_WITH_RET(parcel, Uint32, readType, false);
type = static_cast<RunningLockType>(readType);
return ReadFromParcelWorkTriggerList(parcel, workTriggerlist);
}
RunningLockInfo* RunningLockInfo::Unmarshalling(Parcel& parcel)
{
POWER_HILOGD(MODULE_SERVICE, "RunningLockInfo::%{public}s enter.", __func__);
RunningLockInfo* info = new RunningLockInfo();
if (info == nullptr) {
return nullptr;
}
if (!info->ReadFromParcel(parcel)) {
delete info;
return nullptr;
}
return info;
}
bool RunningLockInfo::MarshallingWorkTriggerList(Parcel& parcel, const WorkTriggerList& list)
{
uint32_t listSize = static_cast<uint32_t>(list.size());
if (!parcel.WriteUint32(listSize)) {
POWER_HILOGE(MODULE_INNERKIT, "RunningLockInfo::%{public}s listSize = %u.", __func__, listSize);
return false;
}
POWER_HILOGD(MODULE_INNERKIT, "RunningLockInfo::%{public}s listSize = %u.", __func__, listSize);
for (const auto& templateVal : list) {
if (templateVal == nullptr) {
continue;
}
if (!parcel.WriteParcelable(templateVal.get())) {
POWER_HILOGE(MODULE_INNERKIT, "RunningLockInfo::%{public}s templateVal->Marshalling failed.", __func__);
return false;
}
}
return true;
}
bool RunningLockInfo::Marshalling(Parcel& parcel) const
{
WRITE_PARCEL_WITH_RET(parcel, String, name, false);
WRITE_PARCEL_WITH_RET(parcel, Uint32, static_cast<uint32_t>(type), false);
return MarshallingWorkTriggerList(parcel, workTriggerlist);
}
bool WorkTrigger::ReadFromParcel(Parcel& parcel)
{
READ_PARCEL_WITH_RET(parcel, String, name_, false);
READ_PARCEL_WITH_RET(parcel, Uint32, uid_, false);
READ_PARCEL_WITH_RET(parcel, Uint32, pid_, false);
READ_PARCEL_WITH_RET(parcel, Uint32, abilityId_, false);
POWER_HILOGD(MODULE_SERVICE, "WorkTrigger::%{public}s name_ = %s, uid_ = %d, pid_ = %d, abilityId_ = %d.", __func__,
name_.c_str(), uid_, pid_, abilityId_);
return true;
}
WorkTrigger* WorkTrigger::Unmarshalling(Parcel& parcel)
{
POWER_HILOGD(MODULE_SERVICE, "WorkTrigger::%{public}s enter.", __func__);
WorkTrigger* workTrigger = new WorkTrigger();
if (workTrigger == nullptr) {
return nullptr;
}
if (!workTrigger->ReadFromParcel(parcel)) {
delete workTrigger;
return nullptr;
}
return workTrigger;
}
bool WorkTrigger::Marshalling(Parcel& parcel) const
{
WRITE_PARCEL_WITH_RET(parcel, String, name_, false);
WRITE_PARCEL_WITH_RET(parcel, Uint32, uid_, false);
WRITE_PARCEL_WITH_RET(parcel, Uint32, pid_, false);
WRITE_PARCEL_WITH_RET(parcel, Uint32, abilityId_, false);
POWER_HILOGD(MODULE_INNERKIT, "WorkTrigger::%{public}s name_ = %s, uid_ = %d, pid_ = %d, abilityId_ = %d.",
__func__, name_.c_str(), uid_, pid_, abilityId_);
return true;
}
} // namespace PowerMgr
} // namespace OHOS

View File

@ -0,0 +1,18 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "running_lock_token_stub.h"
#include "power_common.h"

57
interfaces/kits/js/@ohos.power.d.ts vendored Normal file
View File

@ -0,0 +1,57 @@
/*
* 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.
*/
import {AsyncCallback} from './basic';
/**
* Provides interfaces to manage power.
*
* @SysCap SystemCapability.PowerMgr.PowerManager
* @devices phone, tablet
* @since 6
*/
declare namespace power {
/**
* Shuts down the system.
*
* <p>This method requires the ohos.permission.SHUTDOWN permission.
*
* @param reason Indicates the shutdown reason.
* @since 6
*/
function shutownDevice(reason: string): void;
/**
* Restarts the system.
*
* <p>This method requires the ohos.permission.REBOOT permission.
*
* @param reason Indicates the restart reason. For example, "recovery" indicates entering the recovery mode
* after the restart. If the parameter is not specified, the system enters the normal mode after the restart.
* @since 6
*/
function rebootDevice(reason: string): void;
/**
* Checks whether the screen of a device is on or off.
*
* @return Returns true if the screen is on; returns false otherwise.
* @since 6
*/
function isScreenOn(callback: AsyncCallback<boolean>): void;
function isScreenOn(): Promise<boolean>;
}
export default power;

View File

@ -0,0 +1,108 @@
/*
* 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.
*/
import {AsyncCallback} from './basic.d.ts';
/**
* Provides a mechanism to prevent the system from hibernating so that the applications can run in the background or
* when the screen is off.
*
* <p>{@link createRunningLock} can be called to obtain a {@link RunningLock}.
* <p>{@link lock} can be called to set the lock duration, during which the system will not hibernate. After the
* lock duration times out, the lock is automatically released and the system hibernates if no other {@link
* RunningLock} is set.
*
* @SysCap SystemCapability.PowerMgr.PowerManager
* @devices phone, tablet
* @since 6
*/
declare namespace runningLock {
class RunningLock {
/**
* Prevents the system from hibernating and sets the lock duration.
*
* @param timeout Indicates the lock duration (ms). After the lock duration times out, the lock is automatically
* released and the system hibernates if no other {@link RunningLock} is set.
* @since 6
*/
function lock(timeout: number): void;
/**
* Checks whether a lock is held or in use.
*
* @return Returns true if the lock is held or in use; returns false if the lock has been released.
* @since 6
*/
function isUsed(): boolean;
/**
* Release the {@link RunningLock} that prevents the system from hibernating.
*
* @since 6
*/
function unlock(): void;
}
/**
* Enumerates the {@link RunningLock} types.
*
* <p>Two {@link RunningLock} types are available: {@link BACKGROUND}, and {@link PROXIMITY_SCREEN_CONTROL}.
* {@link BACKGROUND} ensures that applications can run in the background.
* {@link PROXIMITY_SCREEN_CONTROL} determines whether to turn on or off the screen based on the proximity sensor.
*
* @since 6
*/
export enum RunningLockType {
/**
* Indicates the lock that prevents the system from hibernating.
*/
BACKGROUND = 1,
/**
* Indicates the lock that determines whether to turn on or off the screen based on the proximity sensor.
* For example, during a call, if the proximity sensor detects that the device is moving close to
* the user's ear, the screen turns off; if the proximity sensor detects that the device is moving away
* from the user's ear, the screen turns on.
*/
PROXIMITY_SCREEN_CONTROL
}
/**
* Checks whether the specified {@link RunningLockType} is supported.
*
* @param type Indicates the specified {@link RunningLockType}.
* @return Returns true if the specified {@link RunningLockType} is supported;
* returns false otherwise.
* @since 6
*/
function isRunningLockTypeSupported(type: RunningLockType, callback: AsyncCallback<boolean>): void;
function isRunningLockTypeSupported(type: RunningLockType): Promise<boolean>;
/**
* Creates a {@link RunningLock} object.
*
* <p>This method requires the ohos.permission.RUNNING_LOCK permission.
*
* <p>The {@link RunningLock} object can be used to perform a lock operation to prevent the system from hibernating.
*
* @param name Indicates the {@link RunningLock} name. A recommended name consists of the package or class name and
* a suffix.
* @param type Indicates the {@link RunningLockType}.
* @return Returns the {@link RunningLock} object.
* @since 6
*/
function createRunningLock(name: string, type: RunningLockType, callback: AsyncCallback<RunningLock>): void;
function createRunningLock(name: string, type: RunningLockType): Promise<RunningLock>;
}
export default runningLock;

33
ohos.build Normal file
View File

@ -0,0 +1,33 @@
{
"subsystem": "powermgr",
"parts": {
"power_manager_native": {
"module_list": [
"//base/powermgr/power_manager/interfaces/innerkits:powermgr_client",
"//base/powermgr/power_manager/sa_profile:powermgr_sa_profile",
"//base/powermgr/power_manager/services:powermgrservice"
],
"inner_kits": [
{
"name": "//base/powermgr/power_manager/interfaces/innerkits:powermgr_client",
"header": {
"header_files": [
"ipower_mgr.h",
"ipower_state_callback.h",
"ishutdown_callback.h",
"power_mgr_client.h",
"power_state_machine_info.h",
"running_lock.h",
"running_lock_info.h",
"work_trigger.h"
],
"header_base": "//base/powermgr/power_manager/interfaces/innerkits/native/include"
}
}
],
"test_list": [
"//base/powermgr/power_manager/services/native/test:powermgr_test"
]
}
}
}

30
powermgr.gni Normal file
View File

@ -0,0 +1,30 @@
# 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.
import("//build/ohos.gni")
powermgr_native_part_name = "power_manager_native"
powermgr_root_path = "//base/powermgr/power_manager"
powermgr_service_path = "${powermgr_root_path}/services"
powermgr_interfaces_path = "${powermgr_root_path}/interfaces"
powermgr_native_innerkits_path = "${powermgr_interfaces_path}/innerkits"
powermgr_kits_path = "${powermgr_interfaces_path}/kits"
powermgr_utils_path = "${powermgr_root_path}/utils"
system_type = "default"

24
sa_profile/3301.xml Normal file
View File

@ -0,0 +1,24 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- 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.
-->
<info>
<process>foundation</process>
<systemability>
<name>3301</name>
<libpath>libpowermgrservice.z.so</libpath>
<run-on-create>true</run-on-create>
<distributed>false</distributed>
<dump-level>1</dump-level>
</systemability>
</info>

20
sa_profile/BUILD.gn Normal file
View File

@ -0,0 +1,20 @@
# 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.
import("//base/powermgr/power_manager/powermgr.gni")
import("//build/ohos/sa_profile/sa_profile.gni")
ohos_sa_profile("powermgr_sa_profile") {
sources = [ "3301.xml" ]
part_name = "${powermgr_native_part_name}"
}

71
services/BUILD.gn Normal file
View File

@ -0,0 +1,71 @@
# 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.
import("//base/powermgr/power_manager/powermgr.gni")
config("powermgr_private_config") {
include_dirs = [ "//utils/system/safwk/native/include" ]
}
config("powermgr_public_config") {
include_dirs = [
"native/include",
"zidl/include",
]
}
ohos_shared_library("powermgrservice") {
sources = [
"native/src/power_mgr_dumper.cpp",
"native/src/power_mgr_factory.cpp",
"native/src/power_mgr_monitor.cpp",
"native/src/power_mgr_notify.cpp",
"native/src/power_mgr_service.cpp",
"native/src/power_state_machine.cpp",
"native/src/powerms_event_handler.cpp",
"native/src/running_lock_inner.cpp",
"native/src/running_lock_mgr.cpp",
"native/src/shutdown_service.cpp",
"zidl/src/power_mgr_stub.cpp",
"zidl/src/power_state_callback_stub.cpp",
]
configs = [
"${powermgr_utils_path}:utils_config",
":powermgr_private_config",
]
public_configs = [ ":powermgr_public_config" ]
deps = [
"${powermgr_native_innerkits_path}:powermgr_client",
"${powermgr_utils_path}:powermgr_utils",
"native/src/actions:powermgr_actions",
"//utils/native/base:utils",
]
external_deps = [
"aafwk_standard:base",
"aafwk_standard:want",
"appexecfwk_standard:appexecfwk_base",
"appexecfwk_standard:libeventhandler",
"ces_standard:cesfwk_kits",
"hisysevent_native:libhisysevent",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"safwk:system_ability_fwk",
"samgr_L2:samgr_proxy",
]
part_name = "${powermgr_native_part_name}"
}

View File

@ -0,0 +1,33 @@
/*
* 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 POWERMGR_IDEVICE_POWER_ACTION_H
#define POWERMGR_IDEVICE_POWER_ACTION_H
#include <string>
namespace OHOS {
namespace PowerMgr {
class IDevicePowerAction {
public:
IDevicePowerAction() = default;
virtual ~IDevicePowerAction() = default;
virtual void Reboot(const std::string& reason) = 0;
virtual void Shutdown(const std::string& reason) = 0;
};
} // namespace PowerMgr
} // namespace OHOS
#endif // POWERMGR_IDEVICE_POWER_ACTION_H

View File

@ -0,0 +1,38 @@
/*
* 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 POWERMGR_IDEVICE_STATE_ACTION_H
#define POWERMGR_IDEVICE_STATE_ACTION_H
#include <string>
#include "power_state_machine_info.h"
namespace OHOS {
namespace PowerMgr {
class IDeviceStateAction {
public:
IDeviceStateAction() = default;
virtual ~IDeviceStateAction() = default;
virtual void Suspend(int64_t callTimeMs, SuspendDeviceType type, uint32_t flags) = 0;
virtual void ForceSuspend() = 0;
virtual void Wakeup(int64_t callTimeMs, WakeupDeviceType type, const std::string& details,
const std::string& pkgName) = 0;
virtual void RefreshActivity(int64_t callTimeMs, UserActivityType type, uint32_t flags) = 0;
};
} // namespace PowerMgr
} // namespace OHOS
#endif // POWERMGR_IDEVICE_STATE_ACTION_H

View File

@ -0,0 +1,81 @@
/*
* 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 POWERMGR_IRUNNING_LOCK_ACTION_H
#define POWERMGR_IRUNNING_LOCK_ACTION_H
#include <array>
#include <string>
#include "power_common.h"
#include "running_lock_info.h"
namespace OHOS {
namespace PowerMgr {
class IRunningLockAction {
public:
IRunningLockAction() = default;
virtual ~IRunningLockAction() = default;
static inline std::string GetLockTag(RunningLockType type)
{
return LOCK_TAGS[ToUnderlying(type)];
}
void Acquire(RunningLockType type);
void Release(RunningLockType type);
virtual void Lock(RunningLockType type, const std::string& tag) = 0;
virtual void Unlock(RunningLockType type, const std::string& tag) = 0;
private:
class RunningLockDesc {
public:
inline void IncRef()
{
refCnt++;
}
inline void DecRef()
{
refCnt--;
}
inline bool IsRefNone() const
{
return refCnt == 0;
}
inline uint32_t GetRefCnt() const
{
return refCnt;
}
private:
uint32_t refCnt{0};
};
static inline bool IsValidType(RunningLockType type)
{
return type < RunningLockType::RUNNINGLOCK_BUTT;
}
static const std::array<std::string, ToUnderlying(RunningLockType::RUNNINGLOCK_BUTT)> LOCK_TAGS;
std::array<RunningLockDesc, ToUnderlying(RunningLockType::RUNNINGLOCK_BUTT)> lockDescs_;
};
} // namespace PowerMgr
} // namespace OHOS
#endif // POWERMGR_IRUNNING_LOCK_ACTION_H

View File

@ -0,0 +1,37 @@
/*
* 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 POWERMGR_POWER_MGR_DUMPER_H
#define POWERMGR_POWER_MGR_DUMPER_H
#include <string>
#include <vector>
namespace OHOS {
namespace PowerMgr {
class PowerMgrDumper {
public:
PowerMgrDumper() = delete;
~PowerMgrDumper() = delete;
static bool Dump(const std::vector<std::string>& args, std::string& result);
private:
static void DumpRunningLockInfo(std::string& result);
static void ShowUsage(std::string& result);
};
} // namespace PowerMgr
} // namespace OHOS
#endif // POWERMGR_POWER_MGR_DUMPER_H

View File

@ -0,0 +1,72 @@
/*
* 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 POWERMGR_POWER_MGR_MONITOR_H
#define POWERMGR_POWER_MGR_MONITOR_H
#include <functional>
#include <map>
#include <memory>
#include <string>
#include <common_event_subscriber.h>
#include <ohos/aafwk/content/want.h>
using IntentWant = OHOS::AAFwk::Want;
using Ces = OHOS::EventFwk::CommonEventSubscriber;
using CesInfo = OHOS::EventFwk::CommonEventSubscribeInfo;
using EventHandle = std::function<void(const IntentWant&)>;
namespace OHOS {
namespace PowerMgr {
class PowerMgrMonitor {
public:
PowerMgrMonitor() = default;
~PowerMgrMonitor();
bool Start();
private:
typedef void (PowerMgrMonitor::*HandleEventFunc)(const IntentWant&) const;
class EventSubscriber : public Ces {
public:
EventSubscriber(const sptr<CesInfo>& info, const std::map<std::string, EventHandle>& handles)
: Ces(*info), eventHandles_(handles) {}
void OnReceiveEvent(const EventFwk::CommonEventData &data) override
{
HandleEvent(data.GetWant());
}
~EventSubscriber() override = default;
private:
void HandleEvent(const IntentWant& want);
const std::map<std::string, EventHandle>& eventHandles_;
};
void InitEventHandles();
sptr<CesInfo> GetSubscribeInfo() const;
bool RegisterSubscriber(const sptr<CesInfo>& info);
void HandleScreenStateChanged(const IntentWant& want) const;
void HandleStartUpCompleted(const IntentWant& want) const;
static const std::map<std::string, HandleEventFunc> EVENT_HANDLES;
std::shared_ptr<Ces> subscriber_;
std::map<std::string, EventHandle> eventHandles_;
};
} // namespace PowerMgr
} // namespace OHOS
#endif // POWERMGR_POWER_MGR_MONITOR_H

View File

@ -0,0 +1,45 @@
/*
* 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 POWERMGR_POWER_MGR_NOTIFY_H
#define POWERMGR_POWER_MGR_NOTIFY_H
#include <mutex>
#include <common_event_publish_info.h>
#include <ohos/aafwk/content/want.h>
#include "errors.h"
namespace OHOS {
namespace PowerMgr {
class PowerMgrNotify {
public:
void RegisterPublishEvents();
void PublishScreenOffEvents(int64_t eventTime);
void PublishScreenOnEvents(int64_t eventTime);
private:
using IntentWant = OHOS::AAFwk::Want;
void PublishEvents(int64_t eventTime, sptr<IntentWant> intent);
sptr<IntentWant> screenOffWant_;
sptr<IntentWant> screenOnWant_;
sptr<OHOS::EventFwk::CommonEventPublishInfo> publishInfo_;
};
} // namespace PowerMgr
} // namespace OHOS
#endif // POWERMGR_POWER_MGR_NOTIFY_H

View File

@ -0,0 +1,102 @@
/*
* 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 POWERMGR_POWER_MGR_SERVICE_H
#define POWERMGR_POWER_MGR_SERVICE_H
#include <iremote_object.h>
#include <system_ability.h>
#include "actions/idevice_power_action.h"
#include "ipower_mgr.h"
#include "powerms_event_handler.h"
#include "power_mgr_notify.h"
#include "power_mgr_stub.h"
#include "power_state_machine.h"
#include "running_lock_mgr.h"
#include "shutdown_service.h"
#include "sp_singleton.h"
namespace OHOS {
namespace PowerMgr {
class RunningLockMgr;
class PowerMgrService final : public SystemAbility, public PowerMgrStub {
DECLARE_SYSTEM_ABILITY(PowerMgrService)
DECLARE_DELAYED_SP_SINGLETON(PowerMgrService);
public:
virtual void OnStart() override;
virtual void OnStop() override;
int32_t Dump(int32_t fd, const std::vector<std::u16string>& args) override;
virtual void RebootDevice(const std::string& reason) override;
virtual void ShutDownDevice(const std::string& reason) override;
virtual void SuspendDevice(int64_t callTimeMs, SuspendDeviceType reason, bool suspendImmed) override;
virtual void WakeupDevice(int64_t callTimeMs, WakeupDeviceType reason, const std::string& details) override;
virtual void RefreshActivity(int64_t callTimeMs, UserActivityType type, bool needChangeBacklight) override;
virtual bool IsScreenOn() override;
virtual bool ForceSuspendDevice(int64_t callTimeMs) override;
void Lock(const sptr<IRemoteObject>& token, const RunningLockInfo& runningLockInfo, uint32_t timeOutMS) override;
void UnLock(const sptr<IRemoteObject>& token) override;
void ForceUnLock(const sptr<IRemoteObject>& token);
bool IsUsed(const sptr<IRemoteObject>& token) override;
void SetWorkTriggerList(const sptr<IRemoteObject>& token, const WorkTriggerList& workTriggerList) override;
void ProxyRunningLock(bool proxyLock, pid_t uid, pid_t pid) override;
void RegisterPowerStateCallback(const sptr<IPowerStateCallback>& callback) override;
void UnRegisterPowerStateCallback(const sptr<IPowerStateCallback>& callback) override;
void RegisterShutdownCallback(const sptr<IShutdownCallback>& callback) override;
void UnRegisterShutdownCallback(const sptr<IShutdownCallback>& callback) override;
std::shared_ptr<PowermsEventHandler> GetHandler() const
{
return handler_;
}
std::shared_ptr<RunningLockMgr> GetRunningLockMgr() const
{
return runningLockMgr_;
}
std::shared_ptr<PowerStateMachine> GetPowerStateMachine() const
{
return powerStateMachine_;
}
std::shared_ptr<PowerMgrNotify> GetPowerMgrNotify() const
{
return powerMgrNotify_;
}
bool IsServiceReady() const
{
return ready_;
}
private:
bool Init();
bool PowerStateMachineInit();
void NotifyRunningLockChanged(bool isUnLock);
void FillUserIPCInfo(UserIPCInfo &userIPCinfo);
bool ready_ {false};
std::mutex mutex_;
std::shared_ptr<RunningLockMgr> runningLockMgr_;
std::shared_ptr<AppExecFwk::EventRunner> eventRunner_;
std::shared_ptr<PowermsEventHandler> handler_;
std::shared_ptr<PowerStateMachine> powerStateMachine_;
std::shared_ptr<PowerMgrNotify> powerMgrNotify_;
ShutdownService shutdownService_;
};
} // namespace PowerMgr
} // namespace OHOS
#endif // POWERMGR_POWER_MGR_SERVICE_H

View File

@ -0,0 +1,121 @@
/*
* 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 POWERMGR_POWER_STATE_MACHINE_H
#define POWERMGR_POWER_STATE_MACHINE_H
#include <set>
#include <singleton.h>
#include "actions/idevice_state_action.h"
#include "ipower_state_callback.h"
#include "power_common.h"
#include "power_mgr_monitor.h"
#include "power_state_machine_info.h"
namespace OHOS {
namespace PowerMgr {
class RunningLockMgr;
class PowerMgrService;
enum class ScreenStateType {
SCREEN_OFF = 0,
SCREEN_ON = 1,
SCREEN_DIM = 2,
};
struct ScreenState {
ScreenStateType state;
int64_t lastUpdateTime;
};
struct DevicePowerState {
ScreenState screenState;
// record the last time when get wakeup event from A side
int64_t lastWakeupEventTime;
// record the last time when calling func RefreshActivityInner
int64_t lastRefreshActivityTime;
// record the last time when calling func WakeupDeviceInner
int64_t lastWakeupDeviceTime;
// record the last time when calling func SuspendDeviceInner
int64_t lastSuspendDeviceTime;
};
class PowerStateMachine {
public:
explicit PowerStateMachine(const wptr<PowerMgrService>& pms);
~PowerStateMachine();
bool Init();
void SuspendDeviceInner(pid_t pid, int64_t callTimeMs, SuspendDeviceType type, bool suspendImmed,
bool ignoreScreenState = false);
void WakeupDeviceInner(pid_t pid, int64_t callTimeMs, WakeupDeviceType type, const std::string& details,
const std::string& pkgName);
void RefreshActivityInner(pid_t pid, int64_t callTimeMs, UserActivityType type, bool needChangeBacklight);
void ReceiveScreenEvent(bool isScreenOn);
bool IsScreenOn();
bool ForceSuspendDeviceInner(pid_t pid, int64_t callTimeMs);
void RegisterPowerStateCallback(const sptr<IPowerStateCallback>& callback);
void UnRegisterPowerStateCallback(const sptr<IPowerStateCallback>& callback);
void SetDelayTimer(int64_t delayTime, int32_t event);
void CancelDelayTimer(int32_t event);
void HandleDelayTimer();
// only use for test
int64_t GetLastSuspendDeviceTime() const
{
return mDeviceState_.lastSuspendDeviceTime;
}
int64_t GetLastWakeupDeviceTime() const
{
return mDeviceState_.lastWakeupDeviceTime;
}
int64_t GetLastRefreshActivityTime() const
{
return mDeviceState_.lastRefreshActivityTime;
}
int64_t GetLastWakeupEventTime() const
{
return mDeviceState_.lastWakeupEventTime;
}
class PowerStateCallbackDeathRecipient : public IRemoteObject::DeathRecipient {
public:
PowerStateCallbackDeathRecipient() = default;
virtual void OnRemoteDied(const wptr<IRemoteObject>& remote);
virtual ~PowerStateCallbackDeathRecipient() = default;
};
private:
struct classcomp {
bool operator() (const sptr<IPowerStateCallback>& l, const sptr<IPowerStateCallback>& r) const
{
return l->AsObject() < r->AsObject();
}
};
void NotifyPowerStateChanged(PowerState state);
void SendEventToPowerMgrNotify(PowerState state, int64_t callTime);
const wptr<PowerMgrService> pms_;
PowerMgrMonitor powerMgrMonitor_;
std::mutex mutex_;
DevicePowerState mDeviceState_;
sptr<IRemoteObject::DeathRecipient> powerStateCBDeathRecipient_;
std::set<const sptr<IPowerStateCallback>, classcomp> powerStateListeners_;
std::unique_ptr<IDeviceStateAction> stateAction_;
};
} // namespace PowerMgr
} // namespace OHOS
#endif // POWERMGR_POWER_STATE_MACHINE_H

View File

@ -0,0 +1,43 @@
/*
* 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 POWERMGR_POWERMS_EVENT_HANDLER_H
#define POWERMGR_POWERMS_EVENT_HANDLER_H
#include <event_handler.h>
#include <refbase.h>
namespace OHOS {
namespace PowerMgr {
class PowerMgrService;
class PowermsEventHandler : public AppExecFwk::EventHandler {
public:
enum {
CHECK_RUNNINGLOCK_OVERTIME_MSG = 1,
CHECK_USER_ACTIVITY_TIMEOUT_MSG = 2,
};
PowermsEventHandler(const std::shared_ptr<AppExecFwk::EventRunner>& runner,
const wptr<PowerMgrService>& service);
~PowermsEventHandler() = default;
void ProcessEvent(const AppExecFwk::InnerEvent::Pointer& event) override;
private:
wptr<PowerMgrService> service_;
};
} // namespace PowerMgr
} // namespace OHOS
#endif // POWERMGR_POWERMS_EVENT_HANDLER_H

View File

@ -0,0 +1,105 @@
/*
* 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 POWERMGR_RUNNING_LOCK_INNER_H
#define POWERMGR_RUNNING_LOCK_INNER_H
#include <mutex>
#include "power_common.h"
#include "running_lock_info.h"
namespace OHOS {
namespace PowerMgr {
struct UserIPCInfo {
pid_t uid = INVALID_UID;
pid_t pid = INVALID_PID;
bool operator==(const UserIPCInfo& other) const
{
return (((uid == other.uid) && (pid == other.pid)) ||
((uid == other.uid) && (other.pid == INVALID_PID)) ||
((other.uid == INVALID_PID) && (pid == other.pid)) ||
((other.uid == INVALID_PID) && (other.pid == INVALID_PID)));
}
};
class RunningLockInner {
public:
RunningLockInner(const RunningLockInfo& runningLockInfo, const UserIPCInfo &userIPCinfo);
~RunningLockInner() = default;
static std::shared_ptr<RunningLockInner> CreateRunningLockInner(const RunningLockInfo& runningLockInfo,
const UserIPCInfo &userIPCinfo);
void SetWorkTriggerList(const WorkTriggerList& workTriggerList);
void DumpInfo(const std::string& description);
RunningLockType GetRunningLockType() const
{
return runningLockInfo_.type;
}
const std::string& GetRunningLockName() const
{
return runningLockInfo_.name;
}
const RunningLockInfo& GetRunningLockInfo() const
{
return runningLockInfo_;
}
const UserIPCInfo& GetUserIPCInfo() const
{
return userIPCinfo_;
}
void SetDisabled(bool disabled)
{
disabled_ = disabled;
}
bool GetDisabled() const
{
return disabled_;
}
void SetReallyLocked(bool reallyLocked)
{
reallyLocked_ = reallyLocked;
}
bool GetReallyLocked() const
{
return reallyLocked_;
}
void SetOverTimeFlag(bool overTimeFlag)
{
overTimeFlag_ = overTimeFlag;
}
bool GetOverTimeFlag() const
{
return overTimeFlag_;
}
int64_t GetLockTimeMs() const
{
return lockTimeMs_;
}
private:
std::mutex mutex_;
RunningLockInfo runningLockInfo_;
UserIPCInfo userIPCinfo_;
bool disabled_ {false};
bool reallyLocked_ {false};
bool overTimeFlag_ {false};
int64_t lockTimeMs_ {0};
};
} // namespace PowerMgr
} // namespace OHOS
#endif // POWERMGR_RUNNING_LOCK_INNER_H

View File

@ -0,0 +1,108 @@
/*
* 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 POWERMGR_RUNNING_LOCK_MGR_H
#define POWERMGR_RUNNING_LOCK_MGR_H
#include <array>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <iremote_object.h>
#include "actions/irunning_lock_action.h"
#include "running_lock_inner.h"
#include "running_lock_token_stub.h"
namespace OHOS {
namespace PowerMgr {
class PowerMgrService;
class PowermsEventHandler;
using RunningLockMap = std::map<const sptr<IRemoteObject>, std::shared_ptr<RunningLockInner>>;
class RunningLockMgr {
public:
using RunningLockProxyMap = std::unordered_map<pid_t, std::unordered_set<pid_t>>;
explicit RunningLockMgr(const wptr<PowerMgrService>& pms) : pms_(pms) {}
~RunningLockMgr();
void Lock(const sptr<IRemoteObject>& token, const RunningLockInfo& runningLockInfo,
const UserIPCInfo &userIPCinfo, uint32_t timeOutMS = 0);
void UnLock(const sptr<IRemoteObject> token);
uint32_t GetRunningLockNum(RunningLockType type = RunningLockType::RUNNINGLOCK_BUTT);
uint32_t GetValidRunningLockNum(RunningLockType type = RunningLockType::RUNNINGLOCK_BUTT);
void SetWorkTriggerList(const sptr<IRemoteObject>& token, const WorkTriggerList& workTriggerList);
bool Init();
bool ExistValidRunningLock();
std::shared_ptr<RunningLockInner> GetRunningLockInner(const sptr<IRemoteObject>& token);
const RunningLockMap& GetRunningLockMap() const
{
return runningLocks_;
}
const RunningLockProxyMap& GetRunningLockProxyMap() const
{
return proxyMap_;
}
void ProxyRunningLock(bool proxyLock, pid_t uid, pid_t pid);
bool IsUsed(const sptr<IRemoteObject>& token);
static constexpr uint32_t CHECK_TIMEOUT_INTERVAL_MS = 60 * 1000;
static constexpr uint32_t MAX_DUMP_NUM = 10;
void CheckOverTime();
void DumpInfo(std::string& result);
private:
class RunningLockDeathRecipient : public IRemoteObject::DeathRecipient {
public:
RunningLockDeathRecipient() = default;
virtual void OnRemoteDied(const wptr<IRemoteObject>& remote);
virtual ~RunningLockDeathRecipient() = default;
};
bool MatchProxyMap(const UserIPCInfo& userIPCinfo);
void SetRunningLockDisableFlag(std::shared_ptr<RunningLockInner>& lockInner, bool forceRefresh = false);
void LockReally(const sptr<IRemoteObject>& token, std::shared_ptr<RunningLockInner>& lockInner);
void UnLockReally(const sptr<IRemoteObject>& token, std::shared_ptr<RunningLockInner>& lockInner);
void ProxyRunningLockInner(bool proxyLock);
void RemoveAndPostUnlockTask(const sptr<IRemoteObject>& token, uint32_t timeOutMS = 0);
std::shared_ptr<RunningLockInner> CreateRunningLockInner(const sptr<IRemoteObject>& token,
const RunningLockInfo& runningLockInfo, const UserIPCInfo &userIPCinfo);
const wptr<PowerMgrService> pms_;
std::weak_ptr<PowermsEventHandler> handler_;
std::mutex mutex_;
RunningLockMap runningLocks_;
RunningLockProxyMap proxyMap_;
sptr<IRemoteObject::DeathRecipient> runningLockDeathRecipient_;
std::shared_ptr<IRunningLockAction> runningLockAction_;
enum RunningLockChangedType {
NOTIFY_RUNNINGLOCK_ADD,
NOTIFY_RUNNINGLOCK_REMOVE,
NOTIFY_RUNNINGLOCK_WORKTRIGGER_CHANGED,
NOTIFY_RUNNINGLOCK_OVERTIME,
RUNNINGLOCK_CHANGED_BUTT
};
const std::array<std::string, RUNNINGLOCK_CHANGED_BUTT> runninglockNotifyStr_ {
"DUBAI_TAG_RUNNINGLOCK_ADD", "DUBAI_TAG_RUNNINGLOCK_REMOVE",
"DUBAI_TAG_RUNNINGLOCK_WORKTRIGGER_CHANGED", "DUBAI_TAG_RUNNINGLOCK_OVERTIME"
};
void NotifyRunningLockChanged(const sptr<IRemoteObject>& token, std::shared_ptr<RunningLockInner>& lockInner,
RunningLockChangedType changeType);
void SendCheckOverTimeMsg(int64_t delayTime);
void NotifyHiViewRunningLockInfo(const std::string& tokenstr, const RunningLockInner& lockInner,
RunningLockChangedType changeType) const;
void NotifyHiView(RunningLockChangedType changeType, const std::string& msg) const;
};
} // namespace PowerMgr
} // namespace OHOS
#endif // POWERMGR_RUNNING_LOCK_MGR_H

View File

@ -0,0 +1,62 @@
/*
* 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 SHUTDOWN_REBOOT_THREAD_H
#define SHUTDOWN_REBOOT_THREAD_H
#include <mutex>
#include <set>
#include <string>
#include <ohos/aafwk/content/want.h>
#include "device_power_action.h"
#include "ishutdown_callback.h"
namespace OHOS {
namespace PowerMgr {
class ShutdownService {
public:
ShutdownService();
~ShutdownService() = default;
void Reboot(const std::string& reason);
void Shutdown(const std::string& reason);
void AddShutdownCallback(const sptr<IShutdownCallback>& callback);
void DelShutdownCallback(const sptr<IShutdownCallback>& callback);
private:
using IntentWant = OHOS::AAFwk::Want;
class CallbackManager : public IRemoteObject::DeathRecipient {
public:
void OnRemoteDied(const wptr<IRemoteObject>& remote) override;
void AddCallback(const sptr<IShutdownCallback>& callback);
void RemoveCallback(const sptr<IShutdownCallback>& callback);
void WaitingCallback();
private:
std::mutex mutex_;
std::set<sptr<IRemoteObject>> callbacks_;
};
void RebootOrShutdown(const std::string& reason, bool isReboot);
void Prepare();
void PublishShutdownEvent() const;
CallbackManager callbackMgr_;
std::atomic<bool> started_;
std::unique_ptr<IDevicePowerAction> devicePowerAction_;
};
} // namespace PowerMgr
} // namespace OHOS
#endif // SHUTDOWN_REBOOT_THREAD_H

View File

@ -0,0 +1,47 @@
# 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.
import("//base/powermgr/power_manager/powermgr.gni")
import("actions.gni")
config("powermgr_actions_common_public_config") {
include_dirs = [
"${powermgr_native_innerkits_path}/native/include",
"${powermgr_service_path}/native/include",
]
}
ohos_source_set("powermgr_actions_common") {
sources = [ "irunning_lock_action.cpp" ]
public_configs = [
":powermgr_actions_common_public_config",
"${powermgr_utils_path}:utils_config",
]
external_deps = [ "hiviewdfx_hilog_native:libhilog" ]
part_name = "${powermgr_native_part_name}"
}
actions_target = powermgr_actions_target
if (system_type == powermgr_actions_default) {
actions_target = powermgr_actions_default_target
}
group("powermgr_actions") {
public_deps = [
":powermgr_actions_common",
"${system_type}:${actions_target}",
]
}

View File

@ -0,0 +1,21 @@
# 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.
powermgr_actions_default = "default"
powermgr_actions_default_path =
get_path_info(powermgr_actions_default, "abspath")
powermgr_actions_default_target = "powermgr_actions_default_impl"
powermgr_actions_target = "powermgr_actions_impl"

View File

@ -0,0 +1,44 @@
# 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.
import("//base/powermgr/power_manager/powermgr.gni")
import("../actions.gni")
config("powermgr_actions_impl_public_config") {
include_dirs = [ "." ]
}
ohos_source_set("${powermgr_actions_default_target}") {
sources = [
"device_power_action.cpp",
"device_state_action.cpp",
"running_lock_action.cpp",
"suspend/running_lock_hub.cpp",
"suspend/suspend_controller.cpp",
"system_suspend_controller.cpp",
]
public_configs = [ ":powermgr_actions_impl_public_config" ]
deps = [
"../:powermgr_actions_common",
"//utils/native/base:utils",
]
external_deps = [
"display_manager_native:displaymgr",
"hiviewdfx_hilog_native:libhilog",
]
part_name = "${powermgr_native_part_name}"
}

View File

@ -0,0 +1,39 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "device_power_action.h"
#include <linux/reboot.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>
#include "hilog_wrapper.h"
namespace OHOS {
namespace PowerMgr {
void DevicePowerAction::Reboot(const std::string& reason)
{
POWER_HILOGI(MODULE_SERVICE, "Reboot executing.");
syscall(__NR_reboot, LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, LINUX_REBOOT_CMD_RESTART2, reason.c_str());
}
void DevicePowerAction::Shutdown(const std::string& reason)
{
POWER_HILOGI(MODULE_SERVICE, "Shutdown executing.");
syscall(__NR_reboot, LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, LINUX_REBOOT_CMD_POWER_OFF, reason.c_str());
}
} // namespace PowerMgr
} // namespace OHOS

View File

@ -0,0 +1,32 @@
/*
* 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 POWERMGR_DEVICE_POWER_ACTION_H
#define POWERMGR_DEVICE_POWER_ACTION_H
#include <string>
#include "actions/idevice_power_action.h"
namespace OHOS {
namespace PowerMgr {
class DevicePowerAction : public IDevicePowerAction {
public:
void Reboot(const std::string& reason) override;
void Shutdown(const std::string& reason) override;
};
} // namespace PowerMgr
} // namespace OHOS
#endif // POWERMGR_DEVICE_POWER_ACTION_H

View File

@ -0,0 +1,45 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "device_state_action.h"
#include "display_manager.h"
#include "system_suspend_controller.h"
using namespace OHOS::DisplayMgr;
using namespace std;
namespace OHOS {
namespace PowerMgr {
void DeviceStateAction::Suspend(int64_t callTimeMs, SuspendDeviceType type, uint32_t flags)
{
DisplayManager::SetScreenState(ScreenState::SCREEN_STATE_OFF);
SystemSuspendController::GetInstance().EnableSuspend();
}
void DeviceStateAction::ForceSuspend()
{
DisplayManager::SetScreenState(ScreenState::SCREEN_STATE_OFF);
SystemSuspendController::GetInstance().ForceSuspend();
}
void DeviceStateAction::Wakeup(int64_t callTimeMs, WakeupDeviceType type, const string& details,
const string& pkgName)
{
SystemSuspendController::GetInstance().DisableSuspend();
DisplayManager::SetScreenState(ScreenState::SCREEN_STATE_ON);
}
} // namespace PowerMgr
} // namespace OHOS

View File

@ -0,0 +1,34 @@
/*
* 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 POWERMGR_DEVICE_STATE_ACTION_H
#define POWERMGR_DEVICE_STATE_ACTION_H
#include "actions/idevice_state_action.h"
namespace OHOS {
namespace PowerMgr {
class DeviceStateAction : public IDeviceStateAction {
public:
void Suspend(int64_t callTimeMs, SuspendDeviceType type, uint32_t flags) override;
void ForceSuspend() override;
void Wakeup(int64_t callTimeMs, WakeupDeviceType type, const std::string& details,
const std::string& pkgName) override;
void RefreshActivity(int64_t callTimeMs __unused, UserActivityType type __unused,
uint32_t flags __unused) override {}
};
} // namespace PowerMgr
} // namespace OHOS
#endif // POWERMGR_DEVICE_STATE_ACTION_H

View File

@ -0,0 +1,35 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "running_lock_action.h"
#include "hilog_wrapper.h"
#include "system_suspend_controller.h"
using namespace std;
namespace OHOS {
namespace PowerMgr {
void RunningLockAction::Lock(RunningLockType type, const string& tag)
{
SystemSuspendController::GetInstance().AcquireRunningLock(tag);
}
void RunningLockAction::Unlock(RunningLockType type, const string& tag)
{
SystemSuspendController::GetInstance().ReleaseRunningLock(tag);
}
} // namespace PowerMgr
} // namespace OHOS

View File

@ -0,0 +1,30 @@
/*
* 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 POWERMGR_RUNNING_LOCK_ACTION_H
#define POWERMGR_RUNNING_LOCK_ACTION_H
#include "actions/irunning_lock_action.h"
namespace OHOS {
namespace PowerMgr {
class RunningLockAction : public IRunningLockAction {
public:
void Lock(RunningLockType type, const std::string& tag) override;
void Unlock(RunningLockType type, const std::string& tag) override;
};
} // namespace PowerMgr
} // namespace OHOS
#endif // POWERMGR_RUNNING_LOCK_ACTION_H

View File

@ -0,0 +1,35 @@
/*
* 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 POWERMGR_IRUNNING_LOCK_HUB_H
#define POWERMGR_IRUNNING_LOCK_HUB_H
#include <string>
namespace OHOS {
namespace PowerMgr {
namespace Suspend {
class IRunningLockHub {
public:
IRunningLockHub() = default;
virtual ~IRunningLockHub() = default;
virtual void Acquire(const std::string& name) = 0;
virtual void Release(const std::string& name) = 0;
};
} // namespace Suspend
} // namespace PowerMgr
} // namespace OHOS
#endif // POWERMGR_IRUNNING_LOCK_HUB_H

View File

@ -0,0 +1,35 @@
/*
* 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 POWERMGR_ISUSPEND_CONTROLLER_H
#define POWERMGR_ISUSPEND_CONTROLLER_H
namespace OHOS {
namespace PowerMgr {
namespace Suspend {
class ISuspendController {
public:
ISuspendController() = default;
virtual ~ISuspendController() = default;
virtual void EnableSuspend() = 0;
virtual void ForceSuspend() = 0;
virtual void IncSuspendBlockCounter() = 0;
virtual void DecSuspendBlockCounter() = 0;
};
} // namespace Suspend
} // namespace PowerMgr
} // namespace OHOS
#endif // POWERMGR_ISUSPEND_CONTROLLER_H

View File

@ -0,0 +1,95 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "suspend/running_lock_hub.h"
#include <file_ex.h>
#include <sys/capability.h>
#include <sys/eventfd.h>
#include "errors.h"
#include "pubdef.h"
#include "hilog_wrapper.h"
namespace OHOS {
namespace PowerMgr {
namespace Suspend {
void RunningLockHub::Acquire(const std::string& name)
{
{
std::lock_guard lock(mutex_);
if (!SaveLockFile(name, true)) {
POWER_HILOGE(MODULE_SERVICE, "Failed to write the lock state!");
}
runningLockMap_[name]++;
}
NotifySuspendCounter(true);
POWER_HILOGI(MODULE_SERVICE, "Acquire runningLock, id: %{public}s", name.c_str());
}
void RunningLockHub::Release(const std::string& name)
{
{
std::lock_guard lock(mutex_);
if (InitFd()) {
if (!SaveStringToFd(unlockFd_, name.c_str())) {
POWER_HILOGE(MODULE_SERVICE, "Failed to write the unlock state!");
}
}
if (runningLockMap_.find(name) == runningLockMap_.end()) {
return;
}
runningLockMap_[name]--;
if (runningLockMap_[name] == 0) {
runningLockMap_.erase(name);
}
}
NotifySuspendCounter(false);
POWER_HILOGI(MODULE_SERVICE, "Release runningLock, id: %{public}s", name.c_str());
}
bool RunningLockHub::InitFd()
{
static bool inited = false;
if (inited) {
return (lockFd_ >= 0 && lockFd_ >= 0);
}
lockFd_ = UniqueFd(TEMP_FAILURE_RETRY(open(LOCK_PATH, O_RDWR | O_CLOEXEC)));
unlockFd_ = UniqueFd(TEMP_FAILURE_RETRY(open(UNLOCK_PATH, O_RDWR | O_CLOEXEC)));
inited = true;
if (lockFd_ < 0 || unlockFd_ < 0) {
POWER_HILOGE(MODULE_SERVICE, "Running lock fd initialization failed!");
return false;
}
return inited;
}
bool RunningLockHub::SaveLockFile(const std::string& name, bool isAcquire)
{
if (InitFd()) {
int32_t fd = isAcquire ? lockFd_ : unlockFd_;
return SaveStringToFd(fd, name.c_str());
}
return false;
}
void RunningLockHub::NotifySuspendCounter(bool isAcquire)
{
isAcquire ? sc_->IncSuspendBlockCounter() : sc_->DecSuspendBlockCounter();
}
} // namespace Suspend
} // namespace PowerMgr
} // namespace OHOS

View File

@ -0,0 +1,57 @@
/*
* 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 POWERMGR_RUNNING_LOCK_HUB_H
#define POWERMGR_RUNNING_LOCK_HUB_H
#include <map>
#include <memory>
#include <mutex>
#include <string>
#include <unique_fd.h>
#include "suspend/irunning_lock_hub.h"
#include "suspend/isuspend_controller.h"
namespace OHOS {
namespace PowerMgr {
namespace Suspend {
class RunningLockHub : public IRunningLockHub {
public:
explicit RunningLockHub(const std::shared_ptr<ISuspendController>& sc) : sc_(sc) {};
~RunningLockHub() = default;
void Acquire(const std::string& name) override;
void Release(const std::string& name) override;
private:
bool InitFd();
bool SaveLockFile(const std::string& name, bool isAcquire);
void NotifySuspendCounter(bool isAcquire);
static constexpr const char * const LOCK_PATH = "/sys/power/wake_lock";
static constexpr const char * const UNLOCK_PATH = "/sys/power/wake_unlock";
UniqueFd lockFd_{-1};
UniqueFd unlockFd_{-1};
std::shared_ptr<ISuspendController> sc_;
std::mutex mutex_;
std::map<std::string, uint32_t> runningLockMap_;
};
} // namespace Suspend
} // namespace PowerMgr
} // namespace OHOS
#endif // POWERMGR_RUNNING_LOCK_HUB_H

View File

@ -0,0 +1,151 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "suspend/suspend_controller.h"
#include <file_ex.h>
#include <sys/eventfd.h>
#include "errors.h"
#include "pubdef.h"
#include "hilog_wrapper.h"
namespace OHOS {
namespace PowerMgr {
namespace Suspend {
SuspendController::SuspendController()
{
auto f = std::bind(&SuspendController::WaitingSuspendCondition, this);
suspend_ = std::make_unique<AutoSuspend>(f);
}
void SuspendController::AutoSuspend::AutoSuspendLoop()
{
while (true) {
std::this_thread::sleep_for(waitTime_);
const std::string wakeupCount = WaitWakeupCount();
if (wakeupCount.empty()) {
continue;
}
waitingFunc_();
if (!WriteWakeupCount(wakeupCount)) {
continue;
}
bool success = SuspendEnter();
if (!success) {
POWER_HILOGE(MODULE_SERVICE, "Start suspend failed!");
}
}
}
void SuspendController::AutoSuspend::Start()
{
static bool started = false;
if (started) {
return;
}
daemon_ = std::make_unique<std::thread>(&AutoSuspend::AutoSuspendLoop, this);
daemon_->detach();
started = true;
}
bool SuspendController::AutoSuspend::SuspendEnter()
{
static bool inited = false;
static UniqueFd suspendStateFd(TEMP_FAILURE_RETRY(open(SUSPEND_STATE_PATH, O_RDWR | O_CLOEXEC)));
if (!inited) {
if (suspendStateFd < 0) {
POWER_HILOGE(MODULE_SERVICE, "Failed to open the suspending state fd!");
return false;
}
inited = true;
}
bool ret = SaveStringToFd(suspendStateFd, SUSPEND_STATE);
if (!ret) {
POWER_HILOGE(MODULE_SERVICE, "Failed to write the suspending state!");
}
return ret;
}
std::string SuspendController::AutoSuspend::WaitWakeupCount()
{
if (wakeupCountFd < 0) {
wakeupCountFd = UniqueFd(TEMP_FAILURE_RETRY(open(WAKEUP_COUNT_PATH, O_RDWR | O_CLOEXEC)));
}
std::string wakeupCount;
bool ret = LoadStringFromFd(wakeupCountFd, wakeupCount);
if (!ret) {
POWER_HILOGW(MODULE_SERVICE, "Read wakeup count failed!");
return std::string();
}
return wakeupCount;
}
bool SuspendController::AutoSuspend::WriteWakeupCount(std::string wakeupCount)
{
if (wakeupCountFd < 0) {
return false;
}
bool ret = SaveStringToFd(wakeupCountFd, wakeupCount.c_str());
if (!ret) {
POWER_HILOGE(MODULE_SERVICE, "Failed to write the wakeup count!");
}
return ret;
}
void SuspendController::EnableSuspend()
{
suspend_->Start();
POWER_HILOGI(MODULE_SERVICE, "AutoSuspend enabled");
}
void SuspendController::ForceSuspend()
{
std::lock_guard lock(suspendMutex_);
bool success = suspend_->SuspendEnter();
POWER_HILOGI(MODULE_SERVICE, "Forced suspend %{public}s", success ? "succeeded." : "failed!");
}
void SuspendController::IncSuspendBlockCounter()
{
std::lock_guard lock(suspendMutex_);
suspendBlockCounter_++;
POWER_HILOGD(MODULE_SERVICE, "Running Lock Counter = %{public}d", suspendBlockCounter_);
}
void SuspendController::DecSuspendBlockCounter()
{
std::lock_guard lock(suspendMutex_);
suspendBlockCounter_--;
POWER_HILOGD(MODULE_SERVICE, "Running Lock Counter = %{public}d", suspendBlockCounter_);
if (SuspendConditionSatisfied()) {
suspendCv_.notify_one();
}
}
bool SuspendController::SuspendConditionSatisfied()
{
return suspendBlockCounter_ == 0;
}
void SuspendController::WaitingSuspendCondition()
{
auto suspendLock = std::unique_lock(suspendMutex_);
suspendCv_.wait(suspendLock, [this] { return this->SuspendConditionSatisfied(); });
}
} // namespace Suspend
} // namespace PowerMgr
} // namespace OHOS

View File

@ -0,0 +1,79 @@
/*
* 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 POWERMGR_SUSPEND_CONTROLLER_H
#define POWERMGR_SUSPEND_CONTROLLER_H
#include <chrono>
#include <condition_variable>
#include <functional>
#include <mutex>
#include <thread>
#include "suspend/isuspend_controller.h"
#include "unique_fd.h"
namespace OHOS {
namespace PowerMgr {
namespace Suspend {
using namespace std::chrono_literals;
class SuspendController : public ISuspendController {
public:
SuspendController();
~SuspendController() = default;
void EnableSuspend() override;
void ForceSuspend() override;
void IncSuspendBlockCounter() override;
void DecSuspendBlockCounter() override;
private:
using WaitingSuspendConditionFunc = std::function<void()>;
class AutoSuspend {
public:
explicit AutoSuspend(const WaitingSuspendConditionFunc& waitingFunc) : waitingFunc_(waitingFunc) {}
~AutoSuspend() = default;
void AutoSuspendLoop();
void Start();
bool SuspendEnter();
private:
std::string WaitWakeupCount();
bool WriteWakeupCount(std::string wakeupCount);
static constexpr const char * const SUSPEND_STATE = "mem";
static constexpr const char * const SUSPEND_STATE_PATH = "/sys/power/state";
static constexpr const char * const WAKEUP_COUNT_PATH = "/sys/power/wakeup_count";
UniqueFd wakeupCountFd {-1};
std::chrono::milliseconds waitTime_ {100ms};
std::unique_ptr<std::thread> daemon_;
WaitingSuspendConditionFunc waitingFunc_;
};
bool SuspendConditionSatisfied();
void WaitingSuspendCondition();
uint32_t suspendBlockCounter_ {0};
std::condition_variable suspendCv_;
std::unique_ptr<AutoSuspend> suspend_;
std::mutex suspendMutex_;
};
} // namespace Suspend
} // namespace PowerMgr
} // namespace OHOS
#endif // POWERMGR_SUSPEND_CONTROLLER_H

View File

@ -0,0 +1,66 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "system_suspend_controller.h"
#include "suspend/running_lock_hub.h"
#include "suspend/suspend_controller.h"
namespace OHOS {
namespace PowerMgr {
SystemSuspendController::SystemSuspendController()
{
sc_ = std::make_shared<Suspend::SuspendController>();
rlh_ = std::make_unique<Suspend::RunningLockHub>(sc_);
rlh_->Acquire(WAKEUP_HOLDER);
}
SystemSuspendController::~SystemSuspendController() = default;
void SystemSuspendController::EnableSuspend()
{
std::lock_guard lock(mutex_);
sc_->EnableSuspend();
if (!suspendEnabled_) {
rlh_->Release(WAKEUP_HOLDER);
suspendEnabled_ = true;
}
}
void SystemSuspendController::ForceSuspend()
{
sc_->ForceSuspend();
}
void SystemSuspendController::DisableSuspend()
{
std::lock_guard lock(mutex_);
if (suspendEnabled_) {
rlh_->Acquire(WAKEUP_HOLDER);
suspendEnabled_ = false;
}
}
void SystemSuspendController::AcquireRunningLock(const std::string& name)
{
rlh_->Acquire(name);
}
void SystemSuspendController::ReleaseRunningLock(const std::string& name)
{
rlh_->Release(name);
}
} // namespace PowerMgr
} // namespace OHOS

View File

@ -0,0 +1,48 @@
/*
* 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 POWERMGR_SYSTEM_SUSPEND_CONTROLLER_H
#define POWERMGR_SYSTEM_SUSPEND_CONTROLLER_H
#include <memory>
#include <mutex>
#include <singleton.h>
#include "suspend/irunning_lock_hub.h"
#include "suspend/isuspend_controller.h"
namespace OHOS {
namespace PowerMgr {
class SystemSuspendController : public DelayedRefSingleton<SystemSuspendController> {
public:
void EnableSuspend();
void ForceSuspend();
void DisableSuspend();
void AcquireRunningLock(const std::string& name);
void ReleaseRunningLock(const std::string& name);
private:
DECLARE_DELAYED_REF_SINGLETON(SystemSuspendController);
inline static const std::string WAKEUP_HOLDER = "OHOSPowerMgr.WakeupHolder";
bool suspendEnabled_ {false};
std::mutex mutex_;
std::unique_ptr<Suspend::IRunningLockHub> rlh_;
std::shared_ptr<Suspend::ISuspendController> sc_;
};
} // namespace PowerMgr
} // namespace OHOS
#endif // POWERMGR_SYSTEM_SUSPEND_CONTROLLER_H

View File

@ -0,0 +1,65 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "actions/irunning_lock_action.h"
#include "hilog_wrapper.h"
using namespace std;
namespace OHOS {
namespace PowerMgr {
const array<string, ToUnderlying(RunningLockType::RUNNINGLOCK_BUTT)> IRunningLockAction::LOCK_TAGS {
"OHOSPowerMgr.Screen", "OHOSPowerMgr.Background", "OHOSPowerMgr.Proximity",
};
void IRunningLockAction::Acquire(RunningLockType type)
{
if (!IsValidType(type)) {
POWER_HILOGE(MODULE_SERVICE, "Invalid runninglock type");
return;
}
auto t = ToUnderlying(type);
RunningLockDesc& desc = lockDescs_[t];
if (desc.IsRefNone()) {
Lock(type, GetLockTag(type));
}
desc.IncRef();
POWER_HILOGD(MODULE_SERVICE, "Acquire runninglock, type: %{public}u, refCnt: %{public}u", t, desc.GetRefCnt());
}
void IRunningLockAction::Release(RunningLockType type)
{
if (!IsValidType(type)) {
POWER_HILOGE(MODULE_SERVICE, "Invalid runninglock type");
return;
}
auto t = ToUnderlying(type);
RunningLockDesc& desc = lockDescs_[t];
if (desc.IsRefNone()) {
POWER_HILOGE(MODULE_SERVICE, "Invalid refCnt of wakelock: %{public}u", t);
return;
}
desc.DecRef();
POWER_HILOGD(MODULE_SERVICE, "Release runninglock, type: %{public}u, refCnt: %{public}u", t, desc.GetRefCnt());
if (desc.IsRefNone()) {
Unlock(type, GetLockTag(type));
}
}
} // namespace PowerMgr
} // namespace OHOS

View File

@ -0,0 +1,21 @@
# 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.
import("//base/powermgr/power_manager/powermgr.gni")
import("../actions.gni")
ohos_source_set("${powermgr_actions_target}") {
public_deps =
[ "${powermgr_actions_default_path}:${powermgr_actions_default_target}" ]
part_name = "${powermgr_native_part_name}"
}

View File

@ -0,0 +1,59 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "power_mgr_dumper.h"
#include "power_common.h"
#include "power_mgr_service.h"
namespace OHOS {
namespace PowerMgr {
namespace {
const std::string ARGS_HELP = "-h";
const std::string ARGS_RUNNINGLOCK = "-runninglock";
}
bool PowerMgrDumper::Dump(const std::vector<std::string>& args, std::string& result)
{
result.clear();
auto argc = args.size();
if ((argc == 0) || (args[0] == ARGS_HELP)) {
ShowUsage(result);
return true;
}
if (args[0] == ARGS_RUNNINGLOCK) {
auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
if (pms == nullptr) {
return true;
}
auto runningLockMgr = pms->GetRunningLockMgr();
if (runningLockMgr == nullptr) {
return true;
}
runningLockMgr->DumpInfo(result);
}
return true;
}
void PowerMgrDumper::ShowUsage(std::string& result)
{
result.append("Power manager dump options:\n")
.append(" [-h] [-runninglock]\n")
.append(" description of the cmd option:\n")
.append(" -h: show this help.\n")
.append(" -runninglock: show the all information of runninglock.\n");
}
} // namespace PowerMgr
} // namespace OHOS

View File

@ -0,0 +1,41 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "power_mgr_factory.h"
#include "device_power_action.h"
#include "device_state_action.h"
#include "running_lock_action.h"
using namespace std;
namespace OHOS {
namespace PowerMgr {
unique_ptr<IDevicePowerAction> PowerMgrFactory::GetDevicePowerAction()
{
return make_unique<DevicePowerAction>();
}
unique_ptr<IDeviceStateAction> PowerMgrFactory::GetDeviceStateAction()
{
return make_unique<DeviceStateAction>();
}
unique_ptr<IRunningLockAction> PowerMgrFactory::GetRunningLockAction()
{
return make_unique<RunningLockAction>();
}
} // namespace PowerMgr
} // namespace OHOS

View File

@ -0,0 +1,35 @@
/*
* 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 POWERMGR_POWER_MGR_FACTORY_H
#define POWERMGR_POWER_MGR_FACTORY_H
#include <memory>
#include "actions/idevice_power_action.h"
#include "actions/idevice_state_action.h"
#include "actions/irunning_lock_action.h"
namespace OHOS {
namespace PowerMgr {
class PowerMgrFactory {
public:
static std::unique_ptr<IDevicePowerAction> GetDevicePowerAction();
static std::unique_ptr<IDeviceStateAction> GetDeviceStateAction();
static std::unique_ptr<IRunningLockAction> GetRunningLockAction();
};
} // namespace PowerMgr
} // namespace OHOS
#endif // POWERMGR_POWER_MGR_FACTORY_H

View File

@ -0,0 +1,118 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "power_mgr_monitor.h"
#include <common_event_manager.h>
#include <common_event_support.h>
#include <unistd.h>
#include "power_common.h"
#include "power_mgr_service.h"
#include "power_state_machine.h"
using namespace OHOS::AAFwk;
using namespace OHOS::EventFwk;
using namespace std;
namespace OHOS {
namespace PowerMgr {
const map<string, PowerMgrMonitor::HandleEventFunc> PowerMgrMonitor::EVENT_HANDLES {
{CommonEventSupport::COMMON_EVENT_BOOT_COMPLETED, &PowerMgrMonitor::HandleStartUpCompleted},
};
PowerMgrMonitor::~PowerMgrMonitor()
{
if (subscriber_ != nullptr) {
CommonEventManager::UnSubscribeCommonEvent(subscriber_);
}
}
bool PowerMgrMonitor::Start()
{
InitEventHandles();
return RegisterSubscriber(GetSubscribeInfo());
}
void PowerMgrMonitor::InitEventHandles()
{
if (!eventHandles_.empty()) {
return;
}
for (auto &eh : EVENT_HANDLES) {
POWER_HILOGI(MODULE_SERVICE, "Add event: %{public}s", eh.first.c_str());
eventHandles_.emplace(eh.first, bind(eh.second, this, placeholders::_1));
}
}
sptr<CesInfo> PowerMgrMonitor::GetSubscribeInfo() const
{
MatchingSkills skill;
for (auto &eh : eventHandles_) {
skill.AddEvent(eh.first);
}
sptr<CesInfo> info = new CesInfo(skill);
return info;
}
bool PowerMgrMonitor::RegisterSubscriber(const sptr<CesInfo>& info)
{
static const int32_t MAX_RETRY_TIMES = 2;
auto succeed = false;
shared_ptr<Ces> s = make_shared<EventSubscriber>(info, eventHandles_);
// Retry to register subscriber due to timming issues between system abilities
for (int32_t tryTimes = 0; tryTimes < MAX_RETRY_TIMES; tryTimes++) {
succeed = CommonEventManager::SubscribeCommonEvent(s);
if (succeed) {
break;
}
POWER_HILOGE(MODULE_SERVICE, "Sleep for a while and retry to register subscriber");
usleep(50000); // sleep 50ms
}
if (!succeed) {
POWER_HILOGE(MODULE_SERVICE, "Failed to register subscriber");
return false;
}
subscriber_ = s;
POWER_HILOGI(MODULE_SERVICE, "Succeed to register subscriber");
return true;
}
void PowerMgrMonitor::HandleScreenStateChanged(const IntentWant& want) const
{
bool isScreenOn = want.GetAction() == CommonEventSupport::COMMON_EVENT_SCREEN_ON;
POWER_HILOGD(MODULE_SERVICE, "Screen is %{public}s", isScreenOn ? "on" : "off");
DelayedSpSingleton<PowerMgrService>::GetInstance()->GetPowerStateMachine()->ReceiveScreenEvent(isScreenOn);
}
void PowerMgrMonitor::HandleStartUpCompleted(const IntentWant& want __unused) const
{
POWER_HILOGD(MODULE_SERVICE, "Start up completed");
}
void PowerMgrMonitor::EventSubscriber::HandleEvent(const IntentWant& want)
{
auto action = want.GetAction();
auto it = eventHandles_.find(action);
if (it == eventHandles_.end()) {
POWER_HILOGI(MODULE_SERVICE, "Ignore event: %{public}s", action.c_str());
return;
}
POWER_HILOGI(MODULE_SERVICE, "Handle event: %{public}s", action.c_str());
it->second(want);
}
} // namespace PowerMgr
} // namespace OHOS

View File

@ -0,0 +1,67 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "power_mgr_notify.h"
#include <common_event_data.h>
#include <common_event_manager.h>
#include <common_event_support.h>
#include <unistd.h>
#include "power_common.h"
using namespace OHOS::AAFwk;
using namespace OHOS::EventFwk;
namespace OHOS {
namespace PowerMgr {
void PowerMgrNotify::RegisterPublishEvents()
{
if (publishInfo_ != nullptr) {
return;
}
publishInfo_ = new (std::nothrow)CommonEventPublishInfo();
publishInfo_->SetOrdered(false);
screenOffWant_ = new (std::nothrow)IntentWant();
screenOffWant_->SetAction(CommonEventSupport::COMMON_EVENT_SCREEN_OFF);
screenOnWant_ = new (std::nothrow)IntentWant();
screenOnWant_->SetAction(CommonEventSupport::COMMON_EVENT_SCREEN_ON);
}
void PowerMgrNotify::PublishEvents(int64_t eventTime, sptr<IntentWant> want)
{
if ((want == nullptr) || (publishInfo_ == nullptr)) {
POWER_HILOGE(MODULE_SERVICE, "Invalid parameter");
return;
}
POWER_HILOGI(MODULE_SERVICE, "Start to publish event %{public}s at %{public}lld",
want->GetAction().c_str(), static_cast<long long>(eventTime));
CommonEventData event(*want);
CommonEventManager::PublishCommonEvent(event, *publishInfo_, nullptr);
POWER_HILOGI(MODULE_SERVICE, "Publish event %{public}s done", want->GetAction().c_str());
}
void PowerMgrNotify::PublishScreenOffEvents(int64_t eventTime)
{
PublishEvents(eventTime, screenOffWant_);
}
void PowerMgrNotify::PublishScreenOnEvents(int64_t eventTime)
{
PublishEvents(eventTime, screenOnWant_);
}
} // namespace PowerMgr
} // namespace OHOS

View File

@ -0,0 +1,345 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "power_mgr_service.h"
#include <datetime_ex.h>
#include <file_ex.h>
#include <if_system_ability_manager.h>
#include <ipc_skeleton.h>
#include <iservice_registry.h>
#include <string_ex.h>
#include <system_ability_definition.h>
#include <unistd.h>
#include "permission.h"
#include "power_common.h"
#include "power_mgr_dumper.h"
namespace OHOS {
namespace PowerMgr {
namespace {
const std::string POWERMGR_SERVICE_NAME = "PowerMgrService";
const std::string TASK_RUNNINGLOCK_UNLOCK = "RunningLock_UnLock";
constexpr int APP_FIRST_UID = 10000;
auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
const bool G_REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(pms.GetRefPtr());
}
PowerMgrService::PowerMgrService() : SystemAbility(POWER_MANAGER_SERVICE_ID, true) {}
PowerMgrService::~PowerMgrService() {}
void PowerMgrService::OnStart()
{
POWER_HILOGI(MODULE_SERVICE, "OnStart enter.");
if (ready_) {
POWER_HILOGE(MODULE_SERVICE, "OnStart is ready, nothing to do.");
return;
}
if (!Init()) {
POWER_HILOGE(MODULE_SERVICE, "OnStart call init fail");
return;
}
if (!Publish(DelayedSpSingleton<PowerMgrService>::GetInstance())) {
POWER_HILOGE(MODULE_SERVICE, "OnStart register to system ability manager failed.");
return;
}
ready_ = true;
POWER_HILOGI(MODULE_SERVICE, "OnStart and add system ability success.");
}
bool PowerMgrService::Init()
{
POWER_HILOGI(MODULE_SERVICE, "Init start");
if (!eventRunner_) {
eventRunner_ = AppExecFwk::EventRunner::Create(POWERMGR_SERVICE_NAME);
if (eventRunner_ == nullptr) {
POWER_HILOGE(MODULE_SERVICE, "Init failed due to create EventRunner");
return false;
}
}
if (!handler_) {
handler_ = std::make_shared<PowermsEventHandler>(eventRunner_, pms);
}
if (!runningLockMgr_) {
runningLockMgr_ = std::make_shared<RunningLockMgr>(pms);
}
if (!runningLockMgr_->Init()) {
POWER_HILOGE(MODULE_SERVICE, "OnStart init fail");
return false;
}
if (!PowerStateMachineInit()) {
POWER_HILOGE(MODULE_SERVICE, "power state machine init fail!");
}
POWER_HILOGI(MODULE_SERVICE, "Init success");
return true;
}
bool PowerMgrService::PowerStateMachineInit()
{
if (powerStateMachine_ == nullptr) {
powerStateMachine_ = std::make_shared<PowerStateMachine>(pms);
if (!(powerStateMachine_->Init())) {
POWER_HILOGE(MODULE_SERVICE, "power state machine start fail!");
return false;
}
}
if (powerMgrNotify_ == nullptr) {
powerMgrNotify_ = std::make_shared<PowerMgrNotify>();
powerMgrNotify_->RegisterPublishEvents();
}
return true;
}
void PowerMgrService::OnStop()
{
POWER_HILOGI(MODULE_SERVICE, "stop service");
if (!ready_) {
return;
}
eventRunner_.reset();
handler_.reset();
ready_ = false;
}
int32_t PowerMgrService::Dump(int32_t fd, const std::vector<std::u16string>& args)
{
std::vector<std::string> argsInStr;
std::transform(args.begin(), args.end(), std::back_inserter(argsInStr), [](const std::u16string &arg) {
return Str16ToStr8(arg);
});
std::string result;
PowerMgrDumper::Dump(argsInStr, result);
if (!SaveStringToFd(fd, result)) {
POWER_HILOGE(MODULE_SERVICE, "PowerMgrService::Dump failed, save to fd failed.");
return ERR_OK;
}
return ERR_OK;
}
void PowerMgrService::RebootDevice(const std::string& reason)
{
pid_t pid = IPCSkeleton::GetCallingPid();
auto uid = IPCSkeleton::GetCallingUid();
if (reason.find("recovery") != std::string::npos) {
if (!Permission::CheckCallingPermission("ohos.permission.REBOOT_RECOVERY")) {
POWER_HILOGE(MODULE_SERVICE, "%{public}s Request failed, %{public}d permission check fail", __func__, pid);
return;
}
} else {
if ((uid >= APP_FIRST_UID) && !Permission::CheckCallingPermission("ohos.permission.REBOOT")) {
POWER_HILOGE(MODULE_SERVICE, "%{public}s Request failed, %{public}d permission check fail", __func__, pid);
return;
}
}
POWER_HILOGI(MODULE_SERVICE, "PID: %{public}d Call %{public}s !", pid, __func__);
shutdownService_.Reboot(reason);
}
void PowerMgrService::ShutDownDevice(const std::string& reason)
{
pid_t pid = IPCSkeleton::GetCallingPid();
auto uid = IPCSkeleton::GetCallingUid();
if ((uid >= APP_FIRST_UID) && !Permission::CheckCallingPermission("ohos.permission.REBOOT")) {
POWER_HILOGE(MODULE_SERVICE, "%{public}s Request failed, %{public}d permission check fail", __func__, pid);
return;
}
POWER_HILOGI(MODULE_SERVICE, "PID: %{public}d Call %{public}s !", pid, __func__);
shutdownService_.Shutdown(reason);
}
void PowerMgrService::SuspendDevice(int64_t callTimeMs, SuspendDeviceType reason, bool suspendImmed)
{
auto uid = IPCSkeleton::GetCallingUid();
if (uid >= APP_FIRST_UID) {
POWER_HILOGE(MODULE_SERVICE, "%{public}s Request failed, illegal calling uid %{public}d.", __func__, uid);
return;
}
pid_t pid = IPCSkeleton::GetCallingPid();
powerStateMachine_->SuspendDeviceInner(pid, callTimeMs, reason, suspendImmed);
}
void PowerMgrService::WakeupDevice(int64_t callTimeMs, WakeupDeviceType reason, const std::string& details)
{
auto uid = IPCSkeleton::GetCallingUid();
if (uid >= APP_FIRST_UID) {
POWER_HILOGE(MODULE_SERVICE, "%{public}s Request failed, illegal calling uid %{public}d.", __func__, uid);
return;
}
pid_t pid = IPCSkeleton::GetCallingPid();
powerStateMachine_->WakeupDeviceInner(pid, callTimeMs, reason, details, "OHOS");
}
void PowerMgrService::RefreshActivity(int64_t callTimeMs, UserActivityType type, bool needChangeBacklight)
{
auto uid = IPCSkeleton::GetCallingUid();
if ((uid >= APP_FIRST_UID) || !Permission::CheckCallingPermission("ohos.permission.REFRESH_USER_ACTION")) {
POWER_HILOGE(MODULE_SERVICE, "%{public}s Request failed, illegal calling uid %{public}d.", __func__, uid);
return;
}
pid_t pid = IPCSkeleton::GetCallingPid();
powerStateMachine_->RefreshActivityInner(pid, callTimeMs, type, needChangeBacklight);
}
bool PowerMgrService::IsScreenOn()
{
return powerStateMachine_->IsScreenOn();
}
bool PowerMgrService::ForceSuspendDevice(int64_t callTimeMs)
{
auto uid = IPCSkeleton::GetCallingUid();
if (uid >= APP_FIRST_UID) {
POWER_HILOGE(MODULE_SERVICE, "%{public}s Request failed, illegal calling uid %{public}d.", __func__, uid);
return false;
}
pid_t pid = IPCSkeleton::GetCallingPid();
return powerStateMachine_->ForceSuspendDeviceInner(pid, callTimeMs);
}
inline void PowerMgrService::FillUserIPCInfo(UserIPCInfo &userIPCinfo)
{
userIPCinfo.pid = IPCSkeleton::GetCallingPid();
userIPCinfo.uid = IPCSkeleton::GetCallingUid();
}
void PowerMgrService::Lock(const sptr<IRemoteObject>& token, const RunningLockInfo& runningLockInfo, uint32_t timeOutMS)
{
auto uid = IPCSkeleton::GetCallingUid();
if ((uid >= APP_FIRST_UID) && !Permission::CheckCallingPermission("ohos.permission.RUNNING_LOCK")) {
POWER_HILOGE(MODULE_SERVICE, "%{public}s Request failed, %{public}d permission check fail", __func__, uid);
return;
}
POWER_HILOGI(MODULE_SERVICE, "%{public}s :timeOutMS = %d, name = %s, type = %d", __func__,
timeOutMS, runningLockInfo.name.c_str(), runningLockInfo.type);
UserIPCInfo userIPCInfo;
FillUserIPCInfo(userIPCInfo);
runningLockMgr_->Lock(token, runningLockInfo, userIPCInfo, timeOutMS);
// notify runninglock is changed, true means unlock, false means lock
NotifyRunningLockChanged(false);
}
void PowerMgrService::UnLock(const sptr<IRemoteObject>& token)
{
auto uid = IPCSkeleton::GetCallingUid();
if ((uid >= APP_FIRST_UID) && !Permission::CheckCallingPermission("ohos.permission.RUNNING_LOCK")) {
POWER_HILOGE(MODULE_SERVICE, "%{public}s Request failed, %{public}d permission check fail", __func__, uid);
return;
}
POWER_HILOGI(MODULE_SERVICE, "%{public}s called.", __func__);
runningLockMgr_->UnLock(token);
// notify runninglock is changed, true means unlock, false means lock
NotifyRunningLockChanged(true);
}
void PowerMgrService::ForceUnLock(const sptr<IRemoteObject>& token)
{
POWER_HILOGI(MODULE_SERVICE, "%{public}s called.", __func__);
UnLock(token);
}
bool PowerMgrService::IsUsed(const sptr<IRemoteObject>& token)
{
POWER_HILOGI(MODULE_SERVICE, "%{public}s called.", __func__);
return runningLockMgr_->IsUsed(token);
}
void PowerMgrService::NotifyRunningLockChanged(bool isUnLock)
{
if (isUnLock) {
// When unlock we try to suspend
if (!runningLockMgr_->ExistValidRunningLock() && !powerStateMachine_->IsScreenOn()) {
// runninglock is empty and Screen is off, so we try to suspend device from Z side.
POWER_HILOGI(MODULE_SERVICE, "%{public}s :RunningLock is empty, try to suspend from Z Side!", __func__);
powerStateMachine_->SuspendDeviceInner(getpid(), GetTickCount(),
SuspendDeviceType::SUSPEND_DEVICE_REASON_MIN, true, true);
}
}
}
void PowerMgrService::SetWorkTriggerList(const sptr<IRemoteObject>& token, const WorkTriggerList& workTriggerList)
{
auto uid = IPCSkeleton::GetCallingUid();
if ((uid >= APP_FIRST_UID) && !Permission::CheckCallingPermission("ohos.permission.RUNNING_LOCK")) {
POWER_HILOGE(MODULE_SERVICE, "%{public}s Request failed, %{public}d permission check fail", __func__, uid);
return;
}
POWER_HILOGI(MODULE_SERVICE, "%{public}s called.", __func__);
runningLockMgr_->SetWorkTriggerList(token, workTriggerList);
}
void PowerMgrService::ProxyRunningLock(bool proxyLock, pid_t uid, pid_t pid)
{
auto calllingUid = IPCSkeleton::GetCallingUid();
if (calllingUid >= APP_FIRST_UID) {
POWER_HILOGE(MODULE_SERVICE, "%{public}s Request failed, illegal calling uid %{public}d.", __func__,
calllingUid);
return;
}
runningLockMgr_->ProxyRunningLock(proxyLock, uid, pid);
}
void PowerMgrService::RegisterPowerStateCallback(const sptr<IPowerStateCallback>& callback)
{
auto uid = IPCSkeleton::GetCallingUid();
if ((uid >= APP_FIRST_UID) && !Permission::CheckCallingPermission("ohos.permission.POWER_MANAGER")) {
POWER_HILOGE(MODULE_SERVICE, "%{public}s Request failed, %{public}d permission check fail", __func__, uid);
return;
}
powerStateMachine_->RegisterPowerStateCallback(callback);
}
void PowerMgrService::UnRegisterPowerStateCallback(const sptr<IPowerStateCallback>& callback)
{
auto uid = IPCSkeleton::GetCallingUid();
if ((uid >= APP_FIRST_UID) && !Permission::CheckCallingPermission("ohos.permission.POWER_MANAGER")) {
POWER_HILOGE(MODULE_SERVICE, "%{public}s Request failed, %{public}d permission check fail", __func__, uid);
return;
}
powerStateMachine_->UnRegisterPowerStateCallback(callback);
}
void PowerMgrService::RegisterShutdownCallback(const sptr<IShutdownCallback>& callback)
{
auto uid = IPCSkeleton::GetCallingUid();
if (uid >= APP_FIRST_UID) {
POWER_HILOGE(MODULE_SERVICE, "Register failed, %{public}d fail", uid);
return;
}
POWER_HILOGE(MODULE_SERVICE, "Register shutdown callback: %{public}d", uid);
shutdownService_.AddShutdownCallback(callback);
}
void PowerMgrService::UnRegisterShutdownCallback(const sptr<IShutdownCallback>& callback)
{
auto uid = IPCSkeleton::GetCallingUid();
if (uid >= APP_FIRST_UID) {
POWER_HILOGE(MODULE_SERVICE, "UnRegister failed, %{public}d fail", uid);
return;
}
POWER_HILOGE(MODULE_SERVICE, "UnRegister shutdown callback: %{public}d", uid);
shutdownService_.DelShutdownCallback(callback);
}
} // namespace PowerMgr
} // namespace OHOS

View File

@ -0,0 +1,268 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "power_state_machine.h"
#include <cinttypes>
#include <datetime_ex.h>
#include <file_ex.h>
#include <pubdef.h>
#include <sys/eventfd.h>
#include <unistd.h>
#include "powerms_event_handler.h"
#include "power_mgr_client.h"
#include "power_mgr_factory.h"
#include "power_mgr_service.h"
namespace OHOS {
namespace PowerMgr {
PowerStateMachine::PowerStateMachine(const wptr<PowerMgrService>& pms) : pms_(pms)
{
// NOTICE Need get screen state when device startup, rightnow we set screen is on as default
mDeviceState_.screenState.state = ScreenStateType::SCREEN_ON;
mDeviceState_.screenState.lastUpdateTime = GetTickCount();
mDeviceState_.lastWakeupEventTime = 0;
mDeviceState_.lastRefreshActivityTime = 0;
mDeviceState_.lastWakeupDeviceTime = 0;
mDeviceState_.lastSuspendDeviceTime = 0;
}
PowerStateMachine::~PowerStateMachine() {}
bool PowerStateMachine::Init()
{
POWER_HILOGI(MODULE_SERVICE, "PowerStateMachine:: Init start");
stateAction_ = PowerMgrFactory::GetDeviceStateAction();
if (powerStateCBDeathRecipient_ == nullptr) {
powerStateCBDeathRecipient_ = new PowerStateCallbackDeathRecipient();
}
if (!powerMgrMonitor_.Start()) {
POWER_HILOGE(MODULE_SERVICE, "Failed to start monitor");
return false;
}
POWER_HILOGI(MODULE_SERVICE, "PowerStateMachine:: Init success!");
return true;
}
void PowerStateMachine::SuspendDeviceInner(pid_t pid, int64_t callTimeMs, SuspendDeviceType type, bool suspendImmed,
bool ignoreScreenState)
{
POWER_HILOGI(MODULE_SERVICE, "PID: %{public}d Try to Suspend Device!!", pid);
// Check the screen state
if (!ignoreScreenState) {
if (stateAction_ != nullptr) {
stateAction_->Suspend(callTimeMs, type, suspendImmed ?
SUSPEND_DEVICE_IMMEDIATELY : SUSPEND_DEVICE_NEED_DOZE);
}
mDeviceState_.lastSuspendDeviceTime = callTimeMs;
POWER_HILOGD(MODULE_SERVICE, "Suspend Device Call Binder Success!!");
} else {
POWER_HILOGE(MODULE_SERVICE, "Suspend Device Failed, Screen State is ignored!");
}
}
void PowerStateMachine::WakeupDeviceInner(pid_t pid, int64_t callTimeMs, WakeupDeviceType type,
const std::string& details, const std::string& pkgName)
{
POWER_HILOGI(MODULE_SERVICE, "PID: %{public}d Try to Wakeup Device!!", pid);
// Check the screen state
if (stateAction_ != nullptr) {
stateAction_->Wakeup(callTimeMs, type, details, pkgName);
}
mDeviceState_.lastWakeupDeviceTime = callTimeMs;
POWER_HILOGD(MODULE_SERVICE, "Wakeup Device Call Binder Success!!");
}
void PowerStateMachine::RefreshActivityInner(pid_t pid, int64_t callTimeMs, UserActivityType type,
bool needChangeBacklight)
{
POWER_HILOGI(MODULE_SERVICE, "PID: %{public}d Start to RefreshActivity!!", pid);
// The minimum refreshactivity interval is 100ms!!
int64_t now = GetTickCount();
if ((mDeviceState_.lastRefreshActivityTime + MIN_TIME_MS_BETWEEN_USERACTIVITIES) > now) {
POWER_HILOGE(MODULE_SERVICE, "RefreshActivity Failed, refresh too fast!");
return;
}
mDeviceState_.lastRefreshActivityTime = now;
// Check the screen state
if (IsScreenOn()) {
if (stateAction_ != nullptr) {
stateAction_->RefreshActivity(callTimeMs, type, needChangeBacklight ?
REFRESH_ACTIVITY_NEED_CHANGE_LIGHTS : REFRESH_ACTIVITY_NO_CHANGE_LIGHTS);
}
POWER_HILOGD(MODULE_SERVICE, "Refresh Activity Call Binder Success!!");
} else {
POWER_HILOGE(MODULE_SERVICE, "RefreshActivity Failed, Screen is Off!");
}
}
bool PowerStateMachine::ForceSuspendDeviceInner(pid_t pid, int64_t callTimeMs)
{
if (stateAction_ != nullptr) {
stateAction_->ForceSuspend();
}
return true;
}
bool PowerStateMachine::IsScreenOn()
{
std::lock_guard lock(mutex_);
if (mDeviceState_.screenState.state == ScreenStateType::SCREEN_ON ||
mDeviceState_.screenState.state == ScreenStateType::SCREEN_DIM) {
POWER_HILOGI(MODULE_SERVICE, "Current Screen State: On!");
return true;
}
POWER_HILOGI(MODULE_SERVICE, "Current Screen State: Off!");
return false;
}
void PowerStateMachine::ReceiveScreenEvent(bool isScreenOn)
{
std::lock_guard lock(mutex_);
auto prestate = mDeviceState_.screenState.state;
mDeviceState_.screenState.lastUpdateTime = GetTickCount();
mDeviceState_.screenState.state = isScreenOn ? ScreenStateType::SCREEN_ON : ScreenStateType::SCREEN_OFF;
if (prestate != mDeviceState_.screenState.state) {
NotifyPowerStateChanged(isScreenOn ? PowerState::AWAKE : PowerState::INACTIVE);
}
POWER_HILOGI(MODULE_SERVICE, "receive new screen event, new state is %{public}d, at %{public}" PRId64 "",
mDeviceState_.screenState.state, mDeviceState_.screenState.lastUpdateTime);
}
void PowerStateMachine::RegisterPowerStateCallback(const sptr<IPowerStateCallback>& callback)
{
std::lock_guard lock(mutex_);
RETURN_IF(callback == nullptr);
auto object = callback->AsObject();
RETURN_IF(object == nullptr);
auto retIt = powerStateListeners_.insert(callback);
if (retIt.second) {
object->AddDeathRecipient(powerStateCBDeathRecipient_);
}
POWER_HILOGI(MODULE_SERVICE, "%{public}s, object = %p, callback = %p, listeners.size = %d,"
" insertOk = %d", __func__, object.GetRefPtr(), callback.GetRefPtr(),
static_cast<unsigned int>(powerStateListeners_.size()),
retIt.second);
}
void PowerStateMachine::UnRegisterPowerStateCallback(const sptr<IPowerStateCallback>& callback)
{
std::lock_guard lock(mutex_);
RETURN_IF(callback == nullptr);
auto object = callback->AsObject();
RETURN_IF(object == nullptr);
size_t eraseNum = powerStateListeners_.erase(callback);
if (eraseNum != 0) {
object->RemoveDeathRecipient(powerStateCBDeathRecipient_);
}
POWER_HILOGI(MODULE_SERVICE, "%{public}s, object = %p, callback = %p, listeners.size = %d,"
" eraseNum = %zu", __func__, object.GetRefPtr(), callback.GetRefPtr(),
static_cast<unsigned int>(powerStateListeners_.size()),
eraseNum);
}
void PowerStateMachine::NotifyPowerStateChanged(PowerState state)
{
POWER_HILOGI(MODULE_SERVICE, "%{public}s state = %u, listeners.size = %d", __func__,
static_cast<uint32_t>(state), static_cast<unsigned int>(powerStateListeners_.size()));
int64_t now = GetTickCount();
// Send Notification event
SendEventToPowerMgrNotify(state, now);
// Call back all native function
for (auto& listener : powerStateListeners_) {
listener->OnPowerStateChanged(state);
}
}
void PowerStateMachine::SendEventToPowerMgrNotify(PowerState state, int64_t callTime)
{
auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
if (pms == nullptr) {
POWER_HILOGE(MODULE_SERVICE, "SendEventToPowerMgrNotify pms is Null, Fail!!");
return;
}
auto notify = pms->GetPowerMgrNotify();
if (notify == nullptr) {
POWER_HILOGE(MODULE_SERVICE, "SendEventToPowerMgrNotify notify is Null, Fail!!");
return;
}
if (state == PowerState::AWAKE) {
notify->PublishScreenOnEvents(callTime);
} else {
notify->PublishScreenOffEvents(callTime);
}
}
const std::string TASK_UNREG_POWER_STATE_CALLBACK = "PowerState_UnRegPowerStateCB";
void PowerStateMachine::PowerStateCallbackDeathRecipient::OnRemoteDied(const wptr<IRemoteObject>& remote)
{
if (remote == nullptr || remote.promote() == nullptr) {
return;
}
POWER_HILOGI(MODULE_SERVICE, "PowerStateMachine::%{public}s remote = %p", __func__,
remote.promote().GetRefPtr());
auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
if (pms == nullptr) {
return;
}
auto handler = pms->GetHandler();
if (handler == nullptr) {
return;
}
sptr<IPowerStateCallback> callback = iface_cast<IPowerStateCallback>(remote.promote());
std::function<void()> unRegFunc = std::bind(&PowerMgrService::UnRegisterPowerStateCallback, pms, callback);
handler->PostTask(unRegFunc, TASK_UNREG_POWER_STATE_CALLBACK);
}
void PowerStateMachine::SetDelayTimer(int64_t delayTime, int32_t event)
{
auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
if (pms == nullptr) {
return;
}
auto handler = pms->GetHandler();
if (handler == nullptr) {
POWER_HILOGE(MODULE_SERVICE, "SetDelayTimer handler is null");
return;
}
handler->SendEvent(event, 0, delayTime);
}
void PowerStateMachine::CancelDelayTimer(int32_t event)
{
auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
if (pms == nullptr) {
return;
}
auto handler = pms->GetHandler();
if (handler == nullptr) {
POWER_HILOGE(MODULE_SERVICE, "CancelDelayTimer handler is null");
return;
}
handler->RemoveEvent(event);
POWER_HILOGI(MODULE_SERVICE, "remove event success");
}
void PowerStateMachine::HandleDelayTimer()
{
POWER_HILOGI(MODULE_SERVICE, "handle delay timer success");
}
} // namespace PowerMgr
} // namespace OHOS

View File

@ -0,0 +1,60 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "powerms_event_handler.h"
#include "power_common.h"
#include "power_mgr_service.h"
namespace OHOS {
namespace PowerMgr {
PowermsEventHandler::PowermsEventHandler(const std::shared_ptr<AppExecFwk::EventRunner>& runner,
const wptr<PowerMgrService>& service)
: AppExecFwk::EventHandler(runner), service_(service)
{
POWER_HILOGD(MODULE_SERVICE, "PowermsEventHandler::PowermsEventHandler instance created.");
}
void PowermsEventHandler::ProcessEvent([[maybe_unused]] const AppExecFwk::InnerEvent::Pointer& event)
{
auto pmsptr = service_.promote();
if (pmsptr == nullptr) {
return;
}
POWER_HILOGI(MODULE_SERVICE, "PowermsEventHandler::%{public}s ,eventid = %d", __func__,
event->GetInnerEventId());
switch (event->GetInnerEventId()) {
case CHECK_RUNNINGLOCK_OVERTIME_MSG: {
auto runningLockMgr = pmsptr->GetRunningLockMgr();
if (runningLockMgr == nullptr) {
return;
}
runningLockMgr->CheckOverTime();
break;
}
case CHECK_USER_ACTIVITY_TIMEOUT_MSG: {
auto powerStateMachine = pmsptr->GetPowerStateMachine();
if (powerStateMachine == nullptr) {
return;
}
powerStateMachine->HandleDelayTimer();
break;
}
default:
POWER_HILOGD(MODULE_SERVICE, "PowermsEventHandler::no event id matched.");
}
}
} // namespace PowerMgr
} // namespace OHOS

View File

@ -0,0 +1,68 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "running_lock_inner.h"
#include <datetime_ex.h>
#include "power_common.h"
namespace OHOS {
namespace PowerMgr {
RunningLockInner::RunningLockInner(const RunningLockInfo& runningLockInfo, const UserIPCInfo &userIPCinfo)
{
runningLockInfo_.name = runningLockInfo.name;
runningLockInfo_.type = runningLockInfo.type;
SetWorkTriggerList(runningLockInfo.workTriggerlist);
userIPCinfo_ = userIPCinfo;
lockTimeMs_ = GetTickCount();
}
std::shared_ptr<RunningLockInner> RunningLockInner::CreateRunningLockInner(const RunningLockInfo& runningLockInfo,
const UserIPCInfo &userIPCinfo)
{
std::shared_ptr<RunningLockInner> runningLockInner = std::make_shared<RunningLockInner>(runningLockInfo,
userIPCinfo);
if (runningLockInner == nullptr) {
POWER_HILOGE(MODULE_SERVICE, "failed to create new RunningLockInner record");
return nullptr;
}
POWER_HILOGI(MODULE_SERVICE, "RunningLockInner::%{public}s : name = %s, type = %d", __func__,
runningLockInfo.name.c_str(), runningLockInfo.type);
return runningLockInner;
}
void RunningLockInner::SetWorkTriggerList(const WorkTriggerList& workTriggerList)
{
DumpInfo("before");
runningLockInfo_.workTriggerlist = workTriggerList;
DumpInfo("after");
}
void RunningLockInner::DumpInfo(const std::string& description)
{
// this statement used to debug, can't find isDebugEnabled() interface. will be replaced later.
POWER_HILOGD(MODULE_SERVICE, "RunningLockInner::%{public}s :description = %s, name = %s, type = %d,", __func__,
description.c_str(), runningLockInfo_.name.c_str(), runningLockInfo_.type);
auto& list = runningLockInfo_.workTriggerlist;
for (auto& worker : list) {
POWER_HILOGD(MODULE_SERVICE, "usecount = %ld, name = %s, uid = %d,"
" pid = %d, abilityid = %d", worker.use_count(), worker->GetName().c_str(),
worker->GetUid(), worker->GetPid(), worker->GetAbilityId());
}
}
} // namespace PowerMgr
} // namespace OHOS

View File

@ -0,0 +1,577 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "running_lock_mgr.h"
#include <cinttypes>
#include <datetime_ex.h>
#include <hisysevent.h>
#include <string_ex.h>
#include "power_common.h"
#include "power_mgr_factory.h"
#include "power_mgr_service.h"
using namespace std;
namespace OHOS {
namespace PowerMgr {
namespace {
const string TASK_RUNNINGLOCK_FORCEUNLOCK = "RunningLock_ForceUnLock";
}
RunningLockMgr::~RunningLockMgr() {}
bool RunningLockMgr::Init()
{
POWER_HILOGI(MODULE_SERVICE, "RunningLockMgr::Init start");
if (runningLockDeathRecipient_ == nullptr) {
runningLockDeathRecipient_ = new RunningLockDeathRecipient();
}
if (runningLockAction_ == nullptr) {
runningLockAction_ = PowerMgrFactory::GetRunningLockAction();
if (!runningLockAction_) {
POWER_HILOGE(MODULE_SERVICE, "RunningLockMgr::Init create RunningLockMgr fail");
return false;
}
}
auto pmsptr = pms_.promote();
if (pmsptr == nullptr) {
return false;
}
handler_ = pmsptr->GetHandler();
POWER_HILOGI(MODULE_SERVICE, "RunningLockMgr::Init success");
return true;
}
std::shared_ptr<RunningLockInner> RunningLockMgr::GetRunningLockInner(const sptr<IRemoteObject>& token)
{
auto iterator = runningLocks_.find(token);
if (iterator != runningLocks_.end()) {
POWER_HILOGD(MODULE_SERVICE, "RunningLockMgr::%{public}s :find by token.", __func__);
return iterator->second;
}
return nullptr;
}
std::shared_ptr<RunningLockInner> RunningLockMgr::CreateRunningLockInner(const sptr<IRemoteObject>& token,
const RunningLockInfo& runningLockInfo, const UserIPCInfo& userIPCinfo)
{
auto lockInner = RunningLockInner::CreateRunningLockInner(runningLockInfo, userIPCinfo);
if (lockInner == nullptr) {
return nullptr;
}
POWER_HILOGD(MODULE_SERVICE, "RunningLockMgr::%{public}s : ok,name = %s,type = %d", __func__,
runningLockInfo.name.c_str(), runningLockInfo.type);
runningLocks_.emplace(token, lockInner);
token->AddDeathRecipient(runningLockDeathRecipient_);
SetRunningLockDisableFlag(lockInner);
return lockInner;
}
void RunningLockMgr::RemoveAndPostUnlockTask(const sptr<IRemoteObject>& token, uint32_t timeOutMS)
{
auto handler = handler_.lock();
if (handler == nullptr) {
return;
}
const string& tokenStr = to_string(reinterpret_cast<uintptr_t>(token.GetRefPtr()));
POWER_HILOGI(MODULE_SERVICE, "RunningLockMgr::%{public}s :token = %p,tokenStr = %s,timeOutMS = %d", __func__,
token.GetRefPtr(), tokenStr.c_str(), timeOutMS);
handler->RemoveTask(tokenStr);
if (timeOutMS != 0) {
std::function<void()> unLockFunc = std::bind(&RunningLockMgr::UnLock, this, token);
handler->PostTask(unLockFunc, tokenStr, timeOutMS);
}
}
void RunningLockMgr::Lock(const sptr<IRemoteObject>& token, const RunningLockInfo& runningLockInfo,
const UserIPCInfo& userIPCinfo, uint32_t timeOutMS)
{
std::lock_guard<std::mutex> lock(mutex_);
POWER_HILOGI(MODULE_SERVICE, "RunningLockMgr::%{public}s :token = %p,name = %s,type = %d", __func__,
token.GetRefPtr(), runningLockInfo.name.c_str(), runningLockInfo.type);
auto lockInner = GetRunningLockInner(token);
if (lockInner == nullptr) {
lockInner = CreateRunningLockInner(token, runningLockInfo, userIPCinfo);
if (lockInner == nullptr) {
POWER_HILOGE(MODULE_SERVICE, "RunningLockMgr::%{public}s :CreateRunningLockInner err,name = %s,type = %d",
__func__, runningLockInfo.name.c_str(), runningLockInfo.type);
return;
}
LockReally(token, lockInner);
POWER_HILOGD(MODULE_SERVICE, "RunningLockMgr::%{public}s :insert ok,name = %s,type = %d", __func__,
runningLockInfo.name.c_str(), runningLockInfo.type);
} else {
POWER_HILOGD(MODULE_SERVICE, "RunningLockMgr::%{public}s :GetRunningLockInner ok,name = %s,type = %d",
__func__, runningLockInfo.name.c_str(), runningLockInfo.type);
}
RemoveAndPostUnlockTask(token, timeOutMS);
}
void RunningLockMgr::UnLock(const sptr<IRemoteObject> token)
{
std::lock_guard<std::mutex> lock(mutex_);
POWER_HILOGI(MODULE_SERVICE, "RunningLockMgr::%{public}s :token = %p", __func__, token.GetRefPtr());
auto lockInner = GetRunningLockInner(token);
if (lockInner == nullptr) {
return;
}
RemoveAndPostUnlockTask(token);
runningLocks_.erase(token);
token->RemoveDeathRecipient(runningLockDeathRecipient_);
// Only disabled lock can really unlocked it.
lockInner->SetDisabled(true);
UnLockReally(token, lockInner);
POWER_HILOGD(MODULE_SERVICE, "RunningLockMgr::%{public}s :name = %s,type = %d,use_count = %ld,erase ok", __func__,
lockInner->GetRunningLockName().c_str(), lockInner->GetRunningLockType(),
lockInner.use_count());
}
bool RunningLockMgr::IsUsed(const sptr<IRemoteObject>& token)
{
std::lock_guard<std::mutex> lock(mutex_);
auto lockInner = GetRunningLockInner(token);
if (lockInner == nullptr) {
return false;
}
return true;
}
uint32_t RunningLockMgr::GetRunningLockNum(RunningLockType type)
{
std::lock_guard<std::mutex> lock(mutex_);
if (type == RunningLockType::RUNNINGLOCK_BUTT) {
return runningLocks_.size();
}
return std::count_if(runningLocks_.begin(), runningLocks_.end(),
[&type](const auto& pair) {
return pair.second->GetRunningLockType() == type;
});
}
uint32_t RunningLockMgr::GetValidRunningLockNum(RunningLockType type)
{
std::lock_guard<std::mutex> lock(mutex_);
return std::count_if(runningLocks_.begin(), runningLocks_.end(),
[&type](const auto& pair) {
auto& lockinner = pair.second;
return (((type == lockinner->GetRunningLockType()) || (type == RunningLockType::RUNNINGLOCK_BUTT)) &&
(lockinner->GetDisabled() == false));
});
}
bool RunningLockMgr::ExistValidRunningLock()
{
std::lock_guard<std::mutex> lock(mutex_);
for (auto it = runningLocks_.begin(); it != runningLocks_.end(); it++) {
auto& lockinner = it->second;
if (lockinner->GetDisabled() == false) {
return true;
}
}
return false;
}
void RunningLockMgr::SetWorkTriggerList(const sptr<IRemoteObject>& token, const WorkTriggerList& workTriggerList)
{
std::lock_guard<std::mutex> lock(mutex_);
POWER_HILOGI(MODULE_SERVICE, "RunningLockMgr::%{public}s :token = %p", __func__, token.GetRefPtr());
auto lockInner = GetRunningLockInner(token);
if (lockInner == nullptr) {
return;
}
lockInner->SetWorkTriggerList(workTriggerList);
NotifyRunningLockChanged(token, lockInner, NOTIFY_RUNNINGLOCK_WORKTRIGGER_CHANGED);
// After update triggerlist, maybe need disabled the lock or enable the lock.
SetRunningLockDisableFlag(lockInner);
// If enabled, we really lock here.
LockReally(token, lockInner);
// If disabled, we really unlock here.
UnLockReally(token, lockInner);
}
void RunningLockMgr::NotifyHiViewRunningLockInfo(const string& tokenStr, const RunningLockInner& lockInner,
RunningLockChangedType changeType) const
{
string lockName = lockInner.GetRunningLockName().empty() ? "NULL" : lockInner.GetRunningLockName();
string msg = "token=" + tokenStr + " lockName=" + lockName + " type=" +
to_string(ToUnderlying(lockInner.GetRunningLockType()));
auto MakeNotifyInfo = [](int uid, int pid, const string& tag) {
return (" uid=" + to_string(uid) + " pid=" + to_string(pid) + " tag=" + tag);
};
auto& list = lockInner.GetRunningLockInfo().workTriggerlist;
if (list.empty()) {
const UserIPCInfo& ipcInfo = lockInner.GetUserIPCInfo();
msg += MakeNotifyInfo(ipcInfo.uid, ipcInfo.pid, lockName);
} else {
for (auto& worker : list) {
string workName = worker->GetName().empty() ? "NULL" : worker->GetName();
msg += MakeNotifyInfo(worker->GetUid(), worker->GetPid(), workName);
}
}
NotifyHiView(changeType, msg);
}
void RunningLockMgr::CheckOverTime()
{
std::lock_guard<std::mutex> lock(mutex_);
auto handler = handler_.lock();
if (handler == nullptr) {
return;
}
handler->RemoveEvent(PowermsEventHandler::CHECK_RUNNINGLOCK_OVERTIME_MSG);
if (runningLocks_.empty()) {
return;
}
int64_t curTime = GetTickCount();
int64_t detectTime = curTime - CHECK_TIMEOUT_INTERVAL_MS;
POWER_HILOGI(MODULE_SERVICE, "RunningLockMgr::%{public}s :cur = %" PRId64 " detectTime=%" PRId64 "", __func__,
curTime, detectTime);
if (detectTime < 0) {
return;
}
int64_t nextDetectTime = INT_MAX;
for (auto& it : runningLocks_) {
auto lockInner = it.second;
if (!lockInner->GetDisabled() && (!lockInner->GetOverTimeFlag())) {
if (lockInner->GetLockTimeMs() < detectTime) {
lockInner->SetOverTimeFlag(true);
NotifyRunningLockChanged(it.first, lockInner, NOTIFY_RUNNINGLOCK_OVERTIME);
} else {
if (lockInner->GetLockTimeMs() < nextDetectTime) {
nextDetectTime = lockInner->GetLockTimeMs();
}
}
}
}
if (nextDetectTime != INT_MAX) {
detectTime = nextDetectTime - curTime + CHECK_TIMEOUT_INTERVAL_MS;
SendCheckOverTimeMsg(detectTime);
}
}
void RunningLockMgr::SendCheckOverTimeMsg(int64_t delayTime)
{
auto handler = handler_.lock();
if (handler == nullptr) {
return;
}
POWER_HILOGI(MODULE_SERVICE, "RunningLockMgr::%{public}s ,delay = %" PRId64 "", __func__,
delayTime);
handler->SendEvent(PowermsEventHandler::CHECK_RUNNINGLOCK_OVERTIME_MSG, 0, delayTime);
}
void RunningLockMgr::NotifyRunningLockChanged(const sptr<IRemoteObject>& token,
std::shared_ptr<RunningLockInner>& lockInner, RunningLockChangedType changeType)
{
if (changeType >= RUNNINGLOCK_CHANGED_BUTT) {
return;
}
const string& tokenStr = to_string(reinterpret_cast<uintptr_t>(token.GetRefPtr()));
switch (changeType) {
case NOTIFY_RUNNINGLOCK_ADD: {
NotifyHiViewRunningLockInfo(tokenStr, *lockInner, changeType);
SendCheckOverTimeMsg(CHECK_TIMEOUT_INTERVAL_MS);
break;
}
case NOTIFY_RUNNINGLOCK_REMOVE: {
string str = "token=" + tokenStr;
NotifyHiView(changeType, str);
break;
}
case NOTIFY_RUNNINGLOCK_WORKTRIGGER_CHANGED: {
NotifyHiViewRunningLockInfo(tokenStr, *lockInner, changeType);
break;
}
case NOTIFY_RUNNINGLOCK_OVERTIME: {
POWER_HILOGI(MODULE_SERVICE, "RunningLockMgr::%{public}s :%s token=%s", __func__,
runninglockNotifyStr_.at(changeType).c_str(), tokenStr.c_str());
break;
}
default: {
break;
}
}
}
bool RunningLockMgr::MatchProxyMap(const UserIPCInfo& userIPCinfo)
{
if (proxyMap_.empty()) {
POWER_HILOGD(MODULE_SERVICE, "%{public}s ret false by proxyMap_.empty(), useripcinfo uid = %d pid = %d.",
__func__, userIPCinfo.uid, userIPCinfo.pid);
return false;
}
auto it = proxyMap_.find(userIPCinfo.uid);
// 1. Find pidset by uid.
if (it == proxyMap_.end()) {
POWER_HILOGD(MODULE_SERVICE, "%{public}s not find uidmap, useripcinfo uid = %d pid = %d.",
__func__, userIPCinfo.uid, userIPCinfo.pid);
return false;
}
auto& pidset = it->second;
// 2. Count by owner pid.
if (pidset.count(userIPCinfo.pid) > 0) {
POWER_HILOGD(MODULE_SERVICE, "%{public}s find uidmap and count pid > 1, useripcinfo uid = %d pid = %d.",
__func__, userIPCinfo.uid, userIPCinfo.pid);
return true;
}
POWER_HILOGD(MODULE_SERVICE, "%{public}s find uidmap and count pid = 0,count(-1) = %d, useripcinfo uid = %d "
"pid = %d.", __func__,
static_cast<unsigned int>(pidset.count(INVALID_PID)),
userIPCinfo.uid, userIPCinfo.pid);
// 3. Count by INVALID_PID, return true when proxy (uid, -1).
return (pidset.count(INVALID_PID) > 0);
}
void RunningLockMgr::SetRunningLockDisableFlag(std::shared_ptr<RunningLockInner>& lockInner, bool forceRefresh)
{
if (proxyMap_.empty() && (!forceRefresh)) {
/**
* Generally when proxymap empty keep the default value false.
* When PGManager cancel proxy uid and pid, because we update the proxy map before, so we should refresh
* all of the runninglock disable flag always.
*/
POWER_HILOGD(MODULE_SERVICE, "%{public}s ret false by proxyMap_.empty() and forceRefresh = false", __func__);
lockInner->SetDisabled(false);
return;
}
const UserIPCInfo& userIPCinfo = lockInner->GetUserIPCInfo();
bool matched = MatchProxyMap(userIPCinfo);
if (matched) {
// Matched the lock owner useripcinfo, set disabled directly.
lockInner->SetDisabled(true);
POWER_HILOGD(MODULE_SERVICE, "%{public}s MatchProxyMap matched by useripcinfo uid = %d pid = %d.",
__func__, userIPCinfo.uid, userIPCinfo.pid);
return;
}
const RunningLockInfo& runningLockInfo = lockInner->GetRunningLockInfo();
const WorkTriggerList& list = runningLockInfo.workTriggerlist;
if (list.empty()) {
// Not matched, and no trigger list.
lockInner->SetDisabled(false);
POWER_HILOGD(MODULE_SERVICE, "%{public}s useripcinfo not matched and list is empty().", __func__);
return;
}
bool triggerMatched = true;
// Have trigger list, need to judge whether or not all of the list matched, otherwise we should hold the lock.
for (auto& workTrigger : list) {
UserIPCInfo triggerIPCInfo {workTrigger->GetUid(), workTrigger->GetPid()};
if (!MatchProxyMap(triggerIPCInfo)) {
triggerMatched = false;
POWER_HILOGD(MODULE_SERVICE, "%{public}s workTrigger not matched uid = %d, pid = %d.", __func__,
triggerIPCInfo.uid, triggerIPCInfo.pid);
break;
}
}
lockInner->SetDisabled(triggerMatched);
POWER_HILOGD(MODULE_SERVICE, "%{public}s useripcinfo uid = %d pid = %d, triggerMatched = %d.", __func__,
userIPCinfo.uid, userIPCinfo.pid, triggerMatched);
}
void RunningLockMgr::LockReally(const sptr<IRemoteObject>& token, std::shared_ptr<RunningLockInner>& lockInner)
{
if (lockInner->GetReallyLocked()) {
POWER_HILOGD(MODULE_SERVICE, "%{public}s :return by lockInner->GetReallyLocked() == true.", __func__);
return;
}
if (lockInner->GetDisabled()) {
POWER_HILOGD(MODULE_SERVICE, "%{public}s :return by lockInner->GetDisabled() == true.", __func__);
return;
}
runningLockAction_->Acquire(lockInner->GetRunningLockType());
lockInner->SetReallyLocked(true);
NotifyRunningLockChanged(token, lockInner, NOTIFY_RUNNINGLOCK_ADD);
POWER_HILOGD(MODULE_SERVICE, "%{public}s :called end.", __func__);
}
void RunningLockMgr::UnLockReally(const sptr<IRemoteObject>& token, std::shared_ptr<RunningLockInner>& lockInner)
{
/**
* Case 1: Firstly PGManager ProxyRunningLock by uid and pid, secondly application lock by the same uid and
* pid, when call Lock() we matched the proxymap, and no really locked to kernel. So we don't need to
* unlocked to kernel.
* Case 2: Firstly application create the runninglock and call Lock(), and then PGManager Proxyed it,
* At this time, lock should be unlocked to kernel because we have locked to kernel for it.
*/
if (!lockInner->GetReallyLocked()) {
POWER_HILOGD(MODULE_SERVICE, "%{public}s :return by lockInner->GetReallyLocked() == false.", __func__);
return;
}
// If disabled, unlock to the kernel.
if (!lockInner->GetDisabled()) {
POWER_HILOGD(MODULE_SERVICE, "%{public}s :return by lockInner->GetDisabled() == false.", __func__);
return;
}
runningLockAction_->Release(lockInner->GetRunningLockType());
lockInner->SetReallyLocked(false);
NotifyRunningLockChanged(token, lockInner, NOTIFY_RUNNINGLOCK_REMOVE);
POWER_HILOGD(MODULE_SERVICE, "%{public}s :called end.", __func__);
}
void RunningLockMgr::ProxyRunningLockInner(bool proxyLock)
{
if (proxyLock) {
for (auto& it : runningLocks_) {
SetRunningLockDisableFlag(it.second);
UnLockReally(it.first, it.second);
}
} else {
for (auto& it : runningLocks_) {
SetRunningLockDisableFlag(it.second, true);
LockReally(it.first, it.second);
}
}
}
void RunningLockMgr::ProxyRunningLock(bool proxyLock, pid_t uid, pid_t pid)
{
std::lock_guard<std::mutex> lock(mutex_);
POWER_HILOGD(MODULE_SERVICE, "%{public}s :proxyLock = %d, uid = %d, pid = %d", __func__,
proxyLock, uid, pid);
auto it = proxyMap_.find(uid);
if (proxyLock) {
// PGManager insert proxy info.
if (it == proxyMap_.end()) {
unordered_set<pid_t> pidset({pid});
proxyMap_.emplace(uid, pidset);
POWER_HILOGD(MODULE_SERVICE, "%{public}s :proxyLock = true first emplace {uid = %d, pid = %d}",
__func__, uid, pid);
} else {
if (pid == INVALID_PID) {
// Insert uid, pid = -1,remove other pid
proxyMap_.erase(uid);
unordered_set<pid_t> pidset({pid});
proxyMap_.emplace(uid, pidset);
} else {
auto& pidset = it->second;
pidset.insert(pid);
}
POWER_HILOGD(MODULE_SERVICE, "%{public}s :proxyLock = true uid = %d exist insert pid = %d",
__func__, uid, pid);
}
// 1. Set the matched runninglock inner disabled flag.
} else {
if (it == proxyMap_.end()) {
// No insert proxy info, nothing to erase.
POWER_HILOGD(MODULE_SERVICE, "%{public}s :proxyLock = false not find by uid = %d",
__func__, uid);
return;
}
// 1. Clear the runninglock inner disabled flag 2.removed from proxyMap_
if (pid == INVALID_PID) {
proxyMap_.erase(uid);
POWER_HILOGD(MODULE_SERVICE, "%{public}s :proxyLock = false pid = -1 rmv uid = %d map",
__func__, uid);
} else {
auto& pidset = it->second;
pidset.erase(pid);
POWER_HILOGD(MODULE_SERVICE, "%{public}s :proxyLock = false uid = %d erase single pid = %d",
__func__, uid, pid);
if (pidset.size() == 0) {
proxyMap_.erase(uid);
POWER_HILOGD(MODULE_SERVICE, "%{public}s :pidset.size()=0 erase uid keymap", __func__);
}
}
}
ProxyRunningLockInner(proxyLock);
}
void RunningLockMgr::NotifyHiView(RunningLockChangedType changeType, const std::string& msg) const
{
if (msg.empty()) {
return;
}
const int logLevel = 2;
const string &tag = runninglockNotifyStr_.at(changeType);
HiviewDFX::HiSysEvent::Write(HiviewDFX::HiSysEvent::Domain::POWERMGR, "Lock",
HiviewDFX::HiSysEvent::EventType::FAULT, "LOG_LEVEL", logLevel, "TAG", tag, "MESSAGE", msg);
POWER_HILOGI(MODULE_SERVICE, "RunningLockMgr::%{public}s: %s %s", __func__, tag.c_str(), msg.c_str());
}
void RunningLockMgr::DumpInfo(std::string& result)
{
auto validSize = GetValidRunningLockNum();
std::lock_guard<std::mutex> lock(mutex_);
result.append("POWER MANAGER DUMP (hidumper -runninglock):\n");
result.append(" totalSize=").append(ToString(runningLocks_.size()))
.append(" validSize=").append(ToString(validSize)).append("\n");
if (runningLocks_.empty()) {
return;
}
auto curTick = GetTickCount();
int index = 0;
for (auto& it : runningLocks_) {
if (index++ == MAX_DUMP_NUM) {
break;
}
auto lockInner = it.second;
if (lockInner == nullptr) {
return;
}
auto& lockinfo = lockInner->GetRunningLockInfo();
auto& ipcinfo = lockInner->GetUserIPCInfo();
result.append(" index=").append(ToString(index))
.append(" time=").append(ToString(curTick - lockInner->GetLockTimeMs()))
.append(" type=").append(ToString(static_cast<uint32_t>(lockinfo.type)))
.append(" name=").append(lockinfo.name)
.append(" uid=").append(ToString(ipcinfo.uid))
.append(" pid=").append(ToString(ipcinfo.pid))
.append(" disable=").append(ToString(lockInner->GetDisabled()))
.append(" reallyLocked=").append(ToString(lockInner->GetReallyLocked()))
.append(" overTimeFlag=").append(ToString(lockInner->GetOverTimeFlag())).append("\n");
auto& worklist = lockinfo.workTriggerlist;
result.append(" workTrigger: size=").append(ToString(worklist.size())).append("\n");
if (worklist.size() != 0) {
for (auto& work : worklist) {
result.append(" name=").append(work->GetName())
.append(" uid=").append(ToString(work->GetUid()))
.append(" pid=").append(ToString(work->GetPid()))
.append(" abilityid=").append(ToString(work->GetAbilityId())).append("\n");
}
}
result.append("\n");
}
}
void RunningLockMgr::RunningLockDeathRecipient::OnRemoteDied(const wptr<IRemoteObject>& remote)
{
if (remote.promote() == nullptr) {
return;
}
auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
if (pms == nullptr) {
return;
}
auto handler = pms->GetHandler();
if (handler == nullptr) {
return;
}
std::function<void()> forceUnLockFunc = std::bind(&PowerMgrService::ForceUnLock, pms,
remote.promote());
POWER_HILOGI(MODULE_SERVICE, "RunningLockDeathRecipient::%{public}s :remote.promote() = %p", __func__,
remote.promote().GetRefPtr());
handler->PostTask(forceUnLockFunc, TASK_RUNNINGLOCK_FORCEUNLOCK);
}
} // namespace PowerMgr
} // namespace OHOS

View File

@ -0,0 +1,165 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "shutdown_service.h"
#include <algorithm>
#include <atomic>
#include <future>
#include <thread>
#include <common_event_data.h>
#include <common_event_manager.h>
#include <common_event_publish_info.h>
#include <common_event_support.h>
#include "hilog_wrapper.h"
#include "power_mgr_factory.h"
using namespace OHOS::AAFwk;
using namespace OHOS::EventFwk;
using namespace std;
namespace OHOS {
namespace PowerMgr {
namespace {
const time_t MAX_TIMEOUT_SEC = 30;
}
ShutdownService::ShutdownService() : started_(false)
{
devicePowerAction_ = PowerMgrFactory::GetDevicePowerAction();
}
void ShutdownService::Reboot(const std::string& reason)
{
RebootOrShutdown(reason, true);
}
void ShutdownService::Shutdown(const std::string& reason)
{
RebootOrShutdown(reason, false);
}
void ShutdownService::AddShutdownCallback(const sptr<IShutdownCallback>& callback)
{
callbackMgr_.AddCallback(callback);
}
void ShutdownService::DelShutdownCallback(const sptr<IShutdownCallback>& callback)
{
callbackMgr_.RemoveCallback(callback);
}
void ShutdownService::RebootOrShutdown(const std::string& reason, bool isReboot)
{
if (started_) {
POWER_HILOGE(MODULE_SERVICE, "Shutdown is already running.");
return;
}
started_ = true;
make_unique<thread>([=] {
Prepare();
POWER_HILOGD(MODULE_SERVICE, "reason = %{public}s, reboot = %{public}d", reason.c_str(), isReboot);
if (devicePowerAction_ != nullptr) {
isReboot ? devicePowerAction_->Reboot(reason) : devicePowerAction_->Shutdown(reason);
}
started_ = false;
})->detach();
}
void ShutdownService::Prepare()
{
PublishShutdownEvent();
callbackMgr_.WaitingCallback();
}
void ShutdownService::PublishShutdownEvent() const
{
POWER_HILOGD(MODULE_SERVICE, "Start of publishing shutdown event");
CommonEventPublishInfo publishInfo;
publishInfo.SetOrdered(false);
IntentWant shutdownWant;
shutdownWant.SetAction(CommonEventSupport::COMMON_EVENT_SHUTDOWN);
CommonEventData event(shutdownWant);
if (!CommonEventManager::PublishCommonEvent(event, publishInfo, nullptr)) {
POWER_HILOGE(MODULE_SERVICE, "Failed to publish the shutdown event!");
return;
}
POWER_HILOGD(MODULE_SERVICE, "End of publishing shutdown event");
}
void ShutdownService::CallbackManager::AddCallback(const sptr<IShutdownCallback>& callback)
{
unique_lock<mutex> lock(mutex_);
RETURN_IF((callback == nullptr) || (callback->AsObject() == nullptr));
auto object = callback->AsObject();
auto retIt = callbacks_.insert(object);
if (retIt.second) {
object->AddDeathRecipient(this);
}
POWER_HILOGI(MODULE_SERVICE, "object = %{public}p, callback = %{public}p, callbacks.size = %{public}zu,"
" insertOk = %{public}d", object.GetRefPtr(),
callback.GetRefPtr(), callbacks_.size(), retIt.second);
}
void ShutdownService::CallbackManager::RemoveCallback(const sptr<IShutdownCallback>& callback)
{
unique_lock<mutex> lock(mutex_);
RETURN_IF((callback == nullptr) || (callback->AsObject() == nullptr));
auto object = callback->AsObject();
auto it = find(callbacks_.begin(), callbacks_.end(), object);
if (it != callbacks_.end()) {
callbacks_.erase(it);
object->RemoveDeathRecipient(this);
}
POWER_HILOGI(MODULE_SERVICE, "object = %{public}p, callback = %{public}p, callbacks.size = %{public}zu,",
object.GetRefPtr(), callback.GetRefPtr(), callbacks_.size());
}
void ShutdownService::CallbackManager::OnRemoteDied(const wptr<IRemoteObject>& remote)
{
RETURN_IF(remote.promote() == nullptr);
RemoveCallback(iface_cast<IShutdownCallback>(remote.promote()));
}
void ShutdownService::CallbackManager::WaitingCallback()
{
POWER_HILOGD(MODULE_SERVICE, "Shutdown callback started.");
auto callbackStart = [&]() {
unique_lock<mutex> lock(mutex_);
for (auto &obj : callbacks_) {
sptr<IShutdownCallback> callback = iface_cast<IShutdownCallback>(obj);
if (callback != nullptr) {
callback->ShutdownCallback();
}
}
};
packaged_task<void()> callbackTask(callbackStart);
future<void> fut = callbackTask.get_future();
make_unique<thread>(std::move(callbackTask))->detach();
time_t begin = time(nullptr);
POWER_HILOGI(MODULE_SERVICE, "Waiting for the callback execution is complete..."
" begin = %{public}ld, callback size: %{public}zu", begin, callbacks_.size());
future_status status = fut.wait_for(std::chrono::seconds(MAX_TIMEOUT_SEC));
if (status == future_status::timeout) {
POWER_HILOGW(MODULE_SERVICE, "Shutdown callback execution timedout!");
}
time_t end = time(nullptr);
POWER_HILOGI(MODULE_SERVICE, "The callback execution is complete. begin = %{public}ld, end = %{public}ld,"
" Execution Time(s): %{public}ld", begin, end, (end - begin));
}
} // namespace PowerMgr
} // namespace OHOS

View File

@ -0,0 +1,20 @@
# 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.
import("//base/powermgr/power_manager/powermgr.gni")
import("//build/test.gni")
group("powermgr_test") {
testonly = true
deps = [ "unittest:unittest" ]
}

View File

@ -0,0 +1,137 @@
# 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.
import("//base/powermgr/power_manager/powermgr.gni")
import("//build/test.gni")
module_output_path = "${powermgr_native_part_name}/powermgr_native"
###############################################################################
config("module_private_config") {
visibility = [ ":*" ]
include_dirs = [
"include",
"//utils/system/safwk/native/include",
]
}
deps_ex = [
"aafwk_standard:base",
"aafwk_standard:want",
"appexecfwk_standard:appexecfwk_base",
"appexecfwk_standard:libeventhandler",
"ipc:ipc_core",
"ces_standard:cesfwk_kits",
"hiviewdfx_hilog_native:libhilog",
"safwk:system_ability_fwk",
"samgr_L2:samgr_proxy",
]
##############################unittest##########################################
ohos_unittest("test_running_lock") {
module_out_path = module_output_path
sources = [ "src/running_lock_test.cpp" ]
configs = [
"${powermgr_utils_path}:utils_config",
":module_private_config",
]
deps = [
"${powermgr_native_innerkits_path}:powermgr_client",
"${powermgr_service_path}:powermgrservice",
"${powermgr_service_path}/native/src/actions:powermgr_actions",
"//third_party/googletest:gtest_main",
"//utils/native/base:utils",
]
external_deps = deps_ex
}
ohos_unittest("test_power_mgr_service") {
module_out_path = module_output_path
sources = [ "src/power_mgr_service_test.cpp" ]
configs = [
"${powermgr_utils_path}:utils_config",
":module_private_config",
]
deps = [
"${powermgr_native_innerkits_path}:powermgr_client",
"${powermgr_service_path}:powermgrservice",
"${powermgr_service_path}/native/src/actions:powermgr_actions",
"//third_party/googletest:gtest_main",
"//utils/native/base:utils",
]
external_deps = deps_ex
}
ohos_unittest("test_power_state_machine") {
module_out_path = module_output_path
sources = [ "src/power_state_machine_test.cpp" ]
configs = [
"${powermgr_utils_path}:utils_config",
":module_private_config",
]
deps = [
"${powermgr_native_innerkits_path}:powermgr_client",
"${powermgr_service_path}:powermgrservice",
"${powermgr_service_path}/native/src/actions:powermgr_actions",
"${powermgr_utils_path}:powermgr_utils",
"//third_party/googletest:gtest_main",
"//utils/native/base:utils",
]
external_deps = deps_ex
}
if (false) {
ohos_unittest("test_power_mgr_notify") {
module_out_path = module_output_path
sources = [ "src/power_mgr_notify_test.cpp" ]
configs = [
"${powermgr_utils_path}:utils_config",
":module_private_config",
]
deps = [
"${powermgr_native_innerkits_path}:powermgr_client",
"${powermgr_service_path}:powermgrservice",
"//third_party/googletest:gtest_main",
"//utils/native/base:utils",
]
external_deps = deps_ex
}
}
group("unittest") {
testonly = true
deps = [
":test_power_mgr_service",
":test_power_state_machine",
":test_running_lock",
#":test_power_mgr_notify",
]
}

View File

@ -0,0 +1,34 @@
/*
* 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 POWERMGR_NOTIFY_TEST_H
#define POWERMGR_NOTIFY_TEST_H
#include <gtest/gtest.h>
#include "power_mgr_service.h"
namespace OHOS {
namespace PowerMgr {
class PowerMgrNotifyTest : public testing::Test {
public:
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
};
} // namespace PowerMgr
} // namespace OHOS
#endif // POWERMGR_NOTIFY_TEST_H

View File

@ -0,0 +1,28 @@
/*
* 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 POWERMGR_POWERMGR_SERVICE_TEST_H
#define POWERMGR_POWERMGR_SERVICE_TEST_H
#include <gtest/gtest.h>
class PowerMgrServiceTest : public testing::Test {
public:
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
};
#endif // POWERMGR_POWERMGR_SERVICE_TEST_H

View File

@ -0,0 +1,52 @@
/*
* 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 POWERMGR_STATE_MACHINE_TEST_H
#define POWERMGR_STATE_MACHINE_TEST_H
#include <gtest/gtest.h>
#include "power_mgr_service.h"
#include "power_state_callback_stub.h"
namespace OHOS {
namespace PowerMgr {
constexpr int SLEEP_WAIT_TIME_S = 6;
constexpr int REFRESHACTIVITY_WAIT_TIME_S = 8;
constexpr int SCREEN_OFF_WAIT_TIME_S = 15;
class PowerStateMachineTest : public testing::Test {
public:
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
bool IsTestSupported();
class PowerStateTest1Callback : public PowerStateCallbackStub {
public:
PowerStateTest1Callback() {};
virtual ~PowerStateTest1Callback() {};
virtual void OnPowerStateChanged(PowerState state) override;
};
class PowerStateTest2Callback : public PowerStateCallbackStub {
public:
PowerStateTest2Callback() {};
virtual ~PowerStateTest2Callback() {};
virtual void OnPowerStateChanged(PowerState state) override;
};
};
} // namespace PowerMgr
} // namespace OHOS
#endif // POWERMGR_STATE_MACHINE_TEST_H

View File

@ -0,0 +1,65 @@
/*
* 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 POWERMGR_RUNNING_LOCK_TEST_H
#define POWERMGR_RUNNING_LOCK_TEST_H
#include <map>
#include <memory>
#include <stdlib.h>
#include <gtest/gtest.h>
#include "power_mgr_client.h"
#include "power_mgr_service.h"
namespace OHOS {
namespace PowerMgr {
class RunningLockTest : public testing::Test {
public:
static void SetUpTestCase(void);
static void TearDownTestCase(void) {}
void SetUp() {}
void TearDown() {}
void TestRunningLockInnerExisit(sptr<IRemoteObject>& token, RunningLockInfo& runningLockInfo)
{
auto lockMap = runningLockMgr_->GetRunningLockMap();
auto iterator = lockMap.find(token);
ASSERT_TRUE(iterator != lockMap.end());
auto runningLockInner = iterator->second;
ASSERT_TRUE(runningLockInner != nullptr);
ASSERT_TRUE(runningLockInner->GetRunningLockInfo().type == runningLockInfo.type);
ASSERT_TRUE((runningLockInfo.name).compare(runningLockInner->GetRunningLockName()) == 0);
}
void TestRunningLockInnerNoExisit(sptr<IRemoteObject>& token)
{
auto lockMap = runningLockMgr_->GetRunningLockMap();
auto iterator = lockMap.find(token);
ASSERT_TRUE(iterator == lockMap.end());
}
inline void DumpRunningLockInfo()
{
system("hidumper -s 3301 -a -runninglock");
}
static std::shared_ptr<RunningLockMgr> runningLockMgr_;
static sptr<PowerMgrService> pmsTest_;
};
} // namespace PowerMgr
} // namespace OHOS
#endif // POWERMGR_RUNNING_LOCK_TEST_H

View File

@ -0,0 +1,198 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "power_mgr_notify_test.h"
#include <iostream>
#include <common_event_data.h>
#include <common_event_manager.h>
#include <common_event_publish_info.h>
#include <common_event_subscriber.h>
#include <common_event_support.h>
#include <datetime_ex.h>
#include <gtest/gtest.h>
#include <if_system_ability_manager.h>
#include <ipc_skeleton.h>
#include <ohos/aafwk/content/intent.h>
#include <string_ex.h>
#include "power_common.h"
#include "power_mgr_client.h"
#include "power_mgr_service.h"
#include "power_state_machine.h"
using namespace testing::ext;
using namespace OHOS::PowerMgr;
using namespace OHOS;
using namespace std;
using namespace OHOS::AAFwk;
using namespace OHOS::Notification;
using NeedWaitFunc = std::function<bool()>;
using Clock = std::chrono::steady_clock;
using TimePoint = std::chrono::time_point<Clock>;
namespace {
constexpr int MAX_RETRY_TIME = 2;
constexpr int WAIT_EVENT_TIME_S = 1;
constexpr int RETRY_WAIT_TIME_US = 50000;
constexpr int SLEEP_WAIT_TIME_S = 3;
class TestCommonEventSubscriber : public CommonEventSubscriber {
public:
std::mutex onReceivedLock_;
bool received_ = false;
TimePoint receivedTime_;
std::string action_;
shared_ptr<OHOS::AppExecFwk::EventHandler> receiveHandler_ = nullptr;
bool receivedScreenOFF = false;
bool receivedScreenOn = false;
explicit TestCommonEventSubscriber(const sptr<CommonEventSubscribeInfo>& subscribeInfo)
: CommonEventSubscriber(subscribeInfo) {}
TestCommonEventSubscriber() {}
~TestCommonEventSubscriber() override {}
void OnReceive(const sptr<CommonEventData> &event) override
{
GTEST_LOG_(INFO) << "PowerMgrMonitor:: OnReceive!!";
receiveHandler_ = OHOS::AppExecFwk::EventHandler::Current();
receivedTime_ = Clock::now();
received_ = true;
action_ = event->GetIntent()->GetAction();
if (action_ == CommonEventSupport::COMMON_EVENT_SCREEN_OFF) {
receivedScreenOFF = true;
}
if (action_ == CommonEventSupport::COMMON_EVENT_SCREEN_ON) {
receivedScreenOn = true;
}
}
};
shared_ptr<TestCommonEventSubscriber> RegisterEvent()
{
GTEST_LOG_(INFO) << "PowerMgrNotifyTest:: Regist Subscriber Start!!";
sptr<AAFwk::Skills> skill = new AAFwk::Skills();
skill->AddAction(CommonEventSupport::COMMON_EVENT_SCREEN_OFF);
skill->AddAction(CommonEventSupport::COMMON_EVENT_SCREEN_ON);
sptr<CommonEventSubscribeInfo> subscriberInfo = new CommonEventSubscribeInfo();
subscriberInfo->SetSkills(skill);
int tryTimes = 0;
shared_ptr<TestCommonEventSubscriber> subscriber = make_shared<TestCommonEventSubscriber>(subscriberInfo);
// Notice, rightnow AddAbilityListener is not ok, we use this method to make sure register success
while (tryTimes < MAX_RETRY_TIME) {
const auto result = CommonEventManager::GetInstance().SubscribeCommonEvent(subscriber);
if (ERR_OK == result) {
break;
} else {
GTEST_LOG_(INFO) << "PowerMgrNotifyTest:: Fail to register Subscriber, Sleep 50ms and try again!!!";
usleep(RETRY_WAIT_TIME_US); // sleep 50ms
// Reset powerMgrMonitor_, otherwise we will register fail
subscriber = make_shared<TestCommonEventSubscriber>(subscriberInfo);
}
tryTimes++;
}
if (MAX_RETRY_TIME == tryTimes) {
GTEST_LOG_(INFO) << "PowerMgrNotifyTest:: Fail to register Subscriber!!!";
return nullptr;
}
GTEST_LOG_(INFO) << "PowerMgrNotifyTest:: register Subscriber Success!!";
return subscriber;
}
}
void PowerMgrNotifyTest::SetUpTestCase(void)
{
}
void PowerMgrNotifyTest::TearDownTestCase(void)
{
}
void PowerMgrNotifyTest::SetUp(void)
{
}
void PowerMgrNotifyTest::TearDown(void)
{
}
/**
* @tc.name: PowerMgrNotifyTest001
* @tc.desc: test powermgr notify for screen Off
* @tc.type: FUNC
*/
HWTEST_F (PowerMgrNotifyTest, PowerMgrNotifyTest001, TestSize.Level0)
{
// We need wait for 15s, to preivent the last test interfere(screen is in keyguard scene and screen is ON).
int waitForStatusOk = 15;
sleep(waitForStatusOk);
GTEST_LOG_(INFO) << "PowerMgrNotifyTest001: Test ScreenOFF Notification start.";
auto& powerMgrClient = PowerMgrClient::GetInstance();
// Wakeup Device before test
GTEST_LOG_(INFO) << "PowerMgrNotifyTest001: Wakeup Device before test.";
powerMgrClient.WakeupDevice();
sleep(SLEEP_WAIT_TIME_S); // wait for 3 second
EXPECT_EQ(powerMgrClient.IsScreenOn(), true) << "PowerMgrNotifyTest001: Prepare Fail, Screen is OFF.";
GTEST_LOG_(INFO) << "PowerMgrNotifyTest001: Screen is On, Begin to Suspend Device!";
shared_ptr<TestCommonEventSubscriber> subscriber = RegisterEvent();
EXPECT_FALSE(subscriber == nullptr);
powerMgrClient.SuspendDevice();
sleep(WAIT_EVENT_TIME_S);
auto err = CommonEventManager::GetInstance().UnsubscribeCommonEvent(subscriber);
EXPECT_EQ(ERR_OK, err);
GTEST_LOG_(INFO) << "PowerMgrNotifyTest001: Test ScreenOFF Notification end.";
}
/**
* @tc.name: PowerMgrNotifyTest002
* @tc.desc: test powermgr notify for screen On
* @tc.type: FUNC
*/
HWTEST_F (PowerMgrNotifyTest, PowerMgrNotifyTest002, TestSize.Level0)
{
sleep(SLEEP_WAIT_TIME_S);
GTEST_LOG_(INFO) << "PowerMgrNotifyTest002: Test ScreenOn Notification start.";
auto& powerMgrClient = PowerMgrClient::GetInstance();
// Wakeup Device before test
GTEST_LOG_(INFO) << "PowerMgrNotifyTest002: Suspend Device before test.";
powerMgrClient.SuspendDevice();
sleep(SLEEP_WAIT_TIME_S); // wait for 3 second
EXPECT_EQ(powerMgrClient.IsScreenOn(), false) << "PowerMgrNotifyTest002: Prepare Fail, Screen is On.";
GTEST_LOG_(INFO) << "PowerMgrNotifyTest002: Screen is Off, Begin to Wakeup Device!";
shared_ptr<TestCommonEventSubscriber> subscriber = RegisterEvent();
EXPECT_FALSE(subscriber == nullptr);
powerMgrClient.WakeupDevice();
sleep(WAIT_EVENT_TIME_S);
auto err = CommonEventManager::GetInstance().UnsubscribeCommonEvent(subscriber);
EXPECT_EQ(ERR_OK, err);
GTEST_LOG_(INFO) << "PowerMgrNotifyTest002: Test ScreenOn Notification end.";
}

View File

@ -0,0 +1,115 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "power_mgr_service_test.h"
#include <csignal>
#include <iostream>
#include <if_system_ability_manager.h>
#include <ipc_skeleton.h>
#include <iservice_registry.h>
#include <string_ex.h>
#include <system_ability_definition.h>
#include "power_common.h"
#include "power_mgr_client.h"
#include "power_mgr_service.h"
using namespace testing::ext;
using namespace OHOS::PowerMgr;
using namespace OHOS;
using namespace std;
void PowerMgrServiceTest::SetUpTestCase(void)
{
}
void PowerMgrServiceTest::TearDownTestCase(void)
{
}
void PowerMgrServiceTest::SetUp(void)
{
}
void PowerMgrServiceTest::TearDown(void)
{
}
/**
* @tc.name: PowerMgrService01
* @tc.desc: Test PowerMgrService service ready.
* @tc.type: FUNC
*/
HWTEST_F (PowerMgrServiceTest, PowerMgrService001, TestSize.Level0)
{
sptr<ISystemAbilityManager> sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
ASSERT_TRUE(sam != nullptr) << "PowerMgrService01 fail to get GetSystemAbilityManager";
sptr<IRemoteObject> remoteObject_ = sam->CheckSystemAbility(POWER_MANAGER_SERVICE_ID);
ASSERT_TRUE(remoteObject_ != nullptr) << "GetSystemAbility failed.";
}
/**
* @tc.name: PowerMgrService002
* @tc.desc: Test PowerMgrService Start and stop.
* @tc.type: FUNC
*/
HWTEST_F (PowerMgrServiceTest, PowerMgrService002, TestSize.Level0)
{
if (false) {
auto pmsTest_ = DelayedSpSingleton<PowerMgrService>::GetInstance();
ASSERT_TRUE(pmsTest_ != nullptr) << "PowerMgrService02 fail to get PowerMgrService";
ASSERT_TRUE(!pmsTest_->IsServiceReady()) << "SetUpTestCase pmsTest_ is ready";
pmsTest_->OnStart();
ASSERT_TRUE(pmsTest_->IsServiceReady()) << "SetUpTestCase pmsTest_ is not ready";
pmsTest_->OnStop();
ASSERT_TRUE(!pmsTest_->IsServiceReady()) << "SetUpTestCase pmsTest_ stop fail";
pmsTest_->OnStart();
ASSERT_TRUE(pmsTest_->IsServiceReady()) << "SetUpTestCase pmsTest_ is not ready";
pmsTest_->OnStop();
ASSERT_TRUE(!pmsTest_->IsServiceReady()) << "SetUpTestCase pmsTest_ stop fail";
}
}
/**
* @tc.name: PowerMgrService003
* @tc.desc: Test RunningLock Deconstructor unlock
* @tc.type: FUNC
*/
HWTEST_F (PowerMgrServiceTest, PowerMgrService003, TestSize.Level0)
{
auto& powerMgrClient = PowerMgrClient::GetInstance();
auto runningLock1 = powerMgrClient.CreateRunningLock("runninglock1", RunningLockType::RUNNINGLOCK_SCREEN);
ASSERT_TRUE(runningLock1 != nullptr);
runningLock1->Lock();
ASSERT_TRUE(runningLock1->IsUsed()) << "runningLock1->IsUsed() != true";
POWER_HILOGD(MODULE_SERVICE, "PowerMgrServiceTest::PowerMgrService003 end.");
}
/**
* @tc.name: PowerMgrService004
* @tc.desc: Test Reboot
* @tc.type: FUNC
*/
HWTEST_F (PowerMgrServiceTest, PowerMgrService004, TestSize.Level0)
{
if (false) {
auto& powerMgrClient = PowerMgrClient::GetInstance();
powerMgrClient.RebootDevice("test");
}
POWER_HILOGD(MODULE_SERVICE, "PowerMgrServiceTest::PowerMgrService004 end.");
}

View File

@ -0,0 +1,287 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "power_state_machine_test.h"
#include <iostream>
#include <datetime_ex.h>
#include <gtest/gtest.h>
#include <if_system_ability_manager.h>
#include <ipc_skeleton.h>
#include <string_ex.h>
#include "power_common.h"
#include "power_mgr_client.h"
#include "power_mgr_service.h"
#include "power_state_machine.h"
#include "sys_param.h"
using namespace testing::ext;
using namespace OHOS::PowerMgr;
using namespace OHOS;
using namespace std;
void PowerStateMachineTest::SetUpTestCase(void)
{
}
void PowerStateMachineTest::TearDownTestCase(void)
{
}
void PowerStateMachineTest::SetUp(void)
{
}
void PowerStateMachineTest::TearDown(void)
{
}
bool PowerStateMachineTest::IsTestSupported()
{
return !SysParam::IsDeviceType(DeviceType::DEVICE_CAR) && !SysParam::IsDeviceType(DeviceType::DEVICE_TV);
}
/**
* @tc.name: PowerStateMachine003
* @tc.desc: test Suspend Device in proxy
* @tc.type: FUNC
*/
HWTEST_F (PowerStateMachineTest, PowerStateMachine003, TestSize.Level0)
{
if (!PowerStateMachineTest::IsTestSupported()) {
POWER_HILOGI(MODULE_SERVICE, "PowerStateMachine003::test is not supported, do nothing!");
return;
}
sleep(SLEEP_WAIT_TIME_S);
GTEST_LOG_(INFO) << "PowerStateMachine003: Suspend Device start.";
auto& powerMgrClient = PowerMgrClient::GetInstance();
// Wakeup Device before test
GTEST_LOG_(INFO) << "PowerStateMachine003: Wakeup Device before test.";
powerMgrClient.WakeupDevice();
sleep(SLEEP_WAIT_TIME_S);
EXPECT_EQ(powerMgrClient.IsScreenOn(), true) << "PowerStateMachine003: Prepare Fail, Screen is OFF.";
GTEST_LOG_(INFO) << "PowerStateMachine003: Screen is On, Begin to Suspend Device!";
powerMgrClient.SuspendDevice();
sleep(REFRESHACTIVITY_WAIT_TIME_S);
EXPECT_EQ(powerMgrClient.IsScreenOn(), false) << "PowerStateMachine003: Suspend Device Fail, Screen is On";
GTEST_LOG_(INFO) << "PowerStateMachine003: Suspend Device end.";
}
/**
* @tc.name: PowerStateMachine004
* @tc.desc: test WakeupDevice(int64_t timeMs) in proxy
* @tc.type: FUNC
*/
HWTEST_F (PowerStateMachineTest, PowerStateMachine004, TestSize.Level0)
{
if (!PowerStateMachineTest::IsTestSupported()) {
POWER_HILOGI(MODULE_SERVICE, "PowerStateMachine004::test is not supported, do nothing!");
return;
}
sleep(SLEEP_WAIT_TIME_S);
GTEST_LOG_(INFO) << "PowerStateMachine004: Wakeup Device start.";
auto& powerMgrClient = PowerMgrClient::GetInstance();
// Suspend Device before test
GTEST_LOG_(INFO) << "PowerStateMachine004: Suspend Device before test.";
powerMgrClient.SuspendDevice();
sleep(SLEEP_WAIT_TIME_S);
EXPECT_EQ(powerMgrClient.IsScreenOn(), false) << "PowerStateMachine004: Prepare Fail, Screen is On.";
GTEST_LOG_(INFO) << "PowerStateMachine004: Screen is Off, Begin to Wakeup Device!";
powerMgrClient.WakeupDevice();
sleep(SLEEP_WAIT_TIME_S);
EXPECT_EQ(powerMgrClient.IsScreenOn(), true) << "PowerStateMachine004: Wakeup Device Fail, Screen is Off";
GTEST_LOG_(INFO) << "PowerStateMachine004: Wakeup Device end.";
}
/**
* @tc.name: PowerStateMachine005
* @tc.desc: test IsScreenOn in proxy
* @tc.type: FUNC
*/
HWTEST_F (PowerStateMachineTest, PowerStateMachine005, TestSize.Level0)
{
if (!PowerStateMachineTest::IsTestSupported()) {
POWER_HILOGI(MODULE_SERVICE, "PowerStateMachine005::test is not supported, do nothing!");
return;
}
sleep(SLEEP_WAIT_TIME_S);
GTEST_LOG_(INFO) << "PowerStateMachine005: IsScreenOn start.";
auto& powerMgrClient = PowerMgrClient::GetInstance();
for (int i = 0; i < 3; i++) {
if (powerMgrClient.IsScreenOn()) {
powerMgrClient.SuspendDevice();
sleep(SLEEP_WAIT_TIME_S);
EXPECT_EQ(powerMgrClient.IsScreenOn(), false) << "PowerStateMachine005_" << i
<< ": Suspend Device Fail, Screen is On";
} else {
powerMgrClient.WakeupDevice();
sleep(SLEEP_WAIT_TIME_S);
EXPECT_EQ(powerMgrClient.IsScreenOn(), true) << "PowerStateMachine005_" << i
<< ": Wakeup Device Fail, Screen is Off";
}
}
GTEST_LOG_(INFO) << "PowerStateMachine05: IsScreenOn end.";
}
/**
* @tc.name: PowerStateMachine006
* @tc.desc: test WakeupDevice(int64_t timeMs, const WakeupDeviceType reason, const std::string& details) in proxy
* @tc.type: FUNC
*/
HWTEST_F (PowerStateMachineTest, PowerStateMachine006, TestSize.Level0)
{
if (!PowerStateMachineTest::IsTestSupported()) {
POWER_HILOGI(MODULE_SERVICE, "PowerStateMachine006::test is not supported, do nothing!");
return;
}
sleep(SLEEP_WAIT_TIME_S);
GTEST_LOG_(INFO) << "PowerStateMachine006: Wakeup Device start.";
auto& powerMgrClient = PowerMgrClient::GetInstance();
// Suspend Device before test
GTEST_LOG_(INFO) << "PowerStateMachine006: Suspend Device before test.";
powerMgrClient.SuspendDevice();
sleep(SLEEP_WAIT_TIME_S);
EXPECT_EQ(powerMgrClient.IsScreenOn(), false) << "PowerStateMachine006: Prepare Fail, Screen is On.";
GTEST_LOG_(INFO) << "PowerStateMachine006: Screen is Off, Begin to Wakeup Device!";
// Check illegal para details
GTEST_LOG_(INFO) << "PowerStateMachine006: Check illegal para details Begin!";
powerMgrClient.WakeupDevice(WakeupDeviceType::WAKEUP_DEVICE_APPLICATION,
string("Software Wakeup test!Software Wakeup test! Software Wakeup test! Software Wakeup test! " \
"Software Wakeup test!Software Wakeup test! Software Wakeup test!"));
sleep(SLEEP_WAIT_TIME_S);
EXPECT_EQ(powerMgrClient.IsScreenOn(), true) << "PowerStateMachine006: Check details test Fail, Screen is Off.";
// Suspend Device before test
GTEST_LOG_(INFO) << "PowerStateMachine006: Suspend Device before real test.";
powerMgrClient.SuspendDevice();
sleep(SLEEP_WAIT_TIME_S);
EXPECT_EQ(powerMgrClient.IsScreenOn(), false) << "PowerStateMachine006: Real test tprepare Fail, Screen is On.";
GTEST_LOG_(INFO) << "PowerStateMachine006: Screen is Off, Begin to Real Wakeup Device!";
powerMgrClient.WakeupDevice(WakeupDeviceType::WAKEUP_DEVICE_APPLICATION, string("Software Wakeup"));
sleep(SLEEP_WAIT_TIME_S);
EXPECT_EQ(powerMgrClient.IsScreenOn(), true) << "PowerStateMachine006: Real Wakeup Device Fail, Screen is Off";
GTEST_LOG_(INFO) << "PowerStateMachine006: Wakeup Device end.";
}
/**
* @tc.name: PowerStateMachine007
* @tc.desc: test ForceSuspendDevice in proxy
* @tc.type: FUNC
*/
HWTEST_F (PowerStateMachineTest, PowerStateMachine007, TestSize.Level2)
{
sleep(SLEEP_WAIT_TIME_S);
GTEST_LOG_(INFO) << "PowerStateMachine007: ForceSuspendDevice start.";
auto& powerMgrClient = PowerMgrClient::GetInstance();
if (false) {
powerMgrClient.ForceSuspendDevice();
}
GTEST_LOG_(INFO) << "PowerStateMachine007: ForceSuspendDevice end.";
}
void PowerStateMachineTest::PowerStateTest1Callback::OnPowerStateChanged(PowerState state)
{
POWER_HILOGD(MODULE_SERVICE, "PowerStateTest1Callback::OnPowerStateChanged state = %u.",
static_cast<uint32_t>(state));
}
void PowerStateMachineTest::PowerStateTest2Callback::OnPowerStateChanged(PowerState state)
{
POWER_HILOGD(MODULE_SERVICE, "PowerStateTest2Callback::OnPowerStateChanged state = %u.",
static_cast<uint32_t>(state));
}
/**
* @tc.name: PowerStateCallback001
* @tc.desc: test PowerStateCallback
* @tc.type: FUNC
*/
HWTEST_F (PowerStateMachineTest, PowerStateCallback001, TestSize.Level0)
{
auto& powerMgrClient = PowerMgrClient::GetInstance();
sptr<IPowerStateCallback> cb1 = new PowerStateTest1Callback();
powerMgrClient.RegisterPowerStateCallback(cb1);
POWER_HILOGD(MODULE_SERVICE, "PowerStateCallback001 1.");
{
sptr<IPowerStateCallback> cb2 = new PowerStateTest2Callback();
powerMgrClient.UnRegisterPowerStateCallback(cb2);
POWER_HILOGD(MODULE_SERVICE, "PowerStateCallback001 2.");
powerMgrClient.RegisterPowerStateCallback(cb2);
POWER_HILOGD(MODULE_SERVICE, "PowerStateCallback001 3.");
powerMgrClient.RegisterPowerStateCallback(cb2);
POWER_HILOGD(MODULE_SERVICE, "PowerStateCallback001 4.");
}
powerMgrClient.UnRegisterPowerStateCallback(cb1);
POWER_HILOGD(MODULE_SERVICE, "PowerStateTestCallback::PowerStateCallback001 end.");
}
/**
* @tc.name: RebootDeviceTest001
* @tc.desc: test RebootDevice in proxy
* @tc.type: FUNC
*/
HWTEST_F (PowerStateMachineTest, RebootDeviceTest001, TestSize.Level2)
{
sleep(SLEEP_WAIT_TIME_S);
GTEST_LOG_(INFO) << "RebootDeviceTest001: RebootDevice start.";
auto& powerMgrClient = PowerMgrClient::GetInstance();
if (false) {
powerMgrClient.RebootDevice(string("RebootDeviceTest001"));
}
GTEST_LOG_(INFO) << "RebootDeviceTest001: RebootDevice end.";
}
/**
* @tc.name: ShutDownDeviceTest001
* @tc.desc: test ShutDownDevice in proxy
* @tc.type: FUNC
*/
HWTEST_F (PowerStateMachineTest, ShutDownDeviceTest001, TestSize.Level2)
{
sleep(SLEEP_WAIT_TIME_S);
GTEST_LOG_(INFO) << "ShutDownDeviceTest001: ShutDownDevice start.";
auto& powerMgrClient = PowerMgrClient::GetInstance();
if (false) {
powerMgrClient.ShutDownDevice(string("ShutDownDeviceTest001"));
}
GTEST_LOG_(INFO) << "ShutDownDeviceTest001: ShutDownDevice end.";
}

View File

@ -0,0 +1,548 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "running_lock_test.h"
#include <ipc_skeleton.h>
#include "actions/irunning_lock_action.h"
using namespace testing::ext;
using namespace OHOS::PowerMgr;
using namespace OHOS;
using namespace std;
sptr<PowerMgrService> RunningLockTest::pmsTest_ = nullptr;
std::shared_ptr<RunningLockMgr> RunningLockTest::runningLockMgr_ = nullptr;
void RunningLockTest::SetUpTestCase(void)
{
pmsTest_ = DelayedSpSingleton<PowerMgrService>::GetInstance();
runningLockMgr_ = std::make_shared<RunningLockMgr>(pmsTest_);
ASSERT_TRUE(runningLockMgr_ != nullptr);
ASSERT_TRUE(runningLockMgr_->Init());
}
/**
* @tc.name: RunningLockInnerKit000
* @tc.desc: Test RunningLockInnerKit function, connect PowerMgrService and call member function.
* @tc.type: FUNC
*/
HWTEST_F (RunningLockTest, RunningLockInnerKit000, TestSize.Level0)
{
auto& powerMgrClient = PowerMgrClient::GetInstance();
auto runningLock1 = powerMgrClient.CreateRunningLock("runninglock1", RunningLockType::RUNNINGLOCK_SCREEN);
ASSERT_TRUE(runningLock1 != nullptr);
ASSERT_TRUE(!runningLock1->IsUsed()) << "runningLock1->IsUsed() != false";
runningLock1->Lock();
ASSERT_TRUE(runningLock1->IsUsed()) << "runningLock1->IsUsed() != true";
runningLock1->UnLock();
ASSERT_TRUE(!runningLock1->IsUsed()) << "runningLock1->IsUsed() != false";
WorkTriggerList worklist;
worklist.push_back(nullptr);
worklist.push_back(nullptr);
worklist.push_back(nullptr);
runningLock1->SetWorkTriggerList(worklist);
auto& list1 = runningLock1->GetWorkTriggerList();
ASSERT_TRUE(list1.empty());
runningLock1->Lock();
runningLock1->SetWorkTriggerList(worklist);
auto& list2 = runningLock1->GetWorkTriggerList();
ASSERT_TRUE(list2.empty());
POWER_HILOGD(MODULE_SERVICE, "PowerMgrUnitTest::RunningLockInnerKit01 end.");
}
/**
* @tc.name: RunningLockInnerKit001
* @tc.desc: Test RunningLock proxy function.
* @tc.type: FUNC
*/
HWTEST_F (RunningLockTest, RunningLockInnerKit001, TestSize.Level0)
{
auto& powerMgrClient = PowerMgrClient::GetInstance();
auto runningLock = powerMgrClient.CreateRunningLock("runninglock", RunningLockType::RUNNINGLOCK_BACKGROUND);
ASSERT_TRUE(runningLock != nullptr);
std::shared_ptr<WorkTrigger> worker1 = std::make_shared<WorkTrigger>(1, "worker1");
std::shared_ptr<WorkTrigger> worker2 = std::make_shared<WorkTrigger>(2, "worker2", 20);
std::shared_ptr<WorkTrigger> worker3 = std::make_shared<WorkTrigger>(3, "worker3", 30);
std::shared_ptr<WorkTrigger> worker4 = std::make_shared<WorkTrigger>();
WorkTriggerList worklist;
POWER_HILOGD(MODULE_SERVICE, "PowerMgrUnitTest::RunningLockInnerKit02, 1 usecount = %ld", worker1.use_count());
runningLock->Lock();
worklist.push_back(worker1);
POWER_HILOGD(MODULE_SERVICE, "PowerMgrUnitTest::RunningLockInnerKit02, 2 usecount = %ld", worker1.use_count());
worklist.push_back(worker2);
worklist.push_back(worker3);
runningLock->SetWorkTriggerList(worklist);
{
auto& list = runningLock->GetWorkTriggerList();
for (auto& worker : list) {
POWER_HILOGD(MODULE_SERVICE, "PowerMgrUnitTest::RunningLockInnerKit02, 3 usecount = %ld, name = %s, "
"uid = %d, pid = %d, abilityid = %d", worker.use_count(), worker->GetName().c_str(),
worker->GetUid(), worker->GetPid(), worker->GetAbilityId());
}
}
worklist.remove(worker2);
worklist.remove(worker3);
runningLock->SetWorkTriggerList(worklist);
runningLock->UnLock();
{
auto& list2 = runningLock->GetWorkTriggerList();
for (auto& worker : list2) {
POWER_HILOGD(MODULE_SERVICE, "PowerMgrUnitTest::RunningLockInnerKit02, 4 usecount = %ld, name = %s, "
"uid = %d, pid = %d, abilityid = %d", worker.use_count(), worker->GetName().c_str(),
worker->GetUid(), worker->GetPid(), worker->GetAbilityId());
}
}
worklist.push_back(worker4);
runningLock->SetWorkTriggerList(worklist);
{
auto& list2 = runningLock->GetWorkTriggerList();
for (auto& worker : list2) {
POWER_HILOGD(MODULE_SERVICE, "PowerMgrUnitTest::RunningLockInnerKit02, 5 usecount = %ld, name = %s,"
"uid = %d, pid = %d, abilityid = %d", worker.use_count(), worker->GetName().c_str(),
worker->GetUid(), worker->GetPid(), worker->GetAbilityId());
}
}
runningLock->Lock();
POWER_HILOGD(MODULE_SERVICE, "PowerMgrUnitTest::RunningLockInnerKit002 end.");
}
/**
* @tc.name: RunningLockInnerKit002
* @tc.desc: Test RunningLockInnerKit function, timeout lock.
* @tc.type: FUNC
*/
HWTEST_F (RunningLockTest, RunningLockInnerKit002, TestSize.Level1)
{
auto& powerMgrClient = PowerMgrClient::GetInstance();
auto runningLock1 = powerMgrClient.CreateRunningLock("runninglock1", RunningLockType::RUNNINGLOCK_SCREEN);
ASSERT_TRUE(runningLock1 != nullptr);
ASSERT_TRUE(!runningLock1->IsUsed()) << "runningLock1->IsUsed() != false";
runningLock1->Lock();
ASSERT_TRUE(runningLock1->IsUsed()) << "runningLock1->IsUsed() != true";
runningLock1->UnLock();
ASSERT_TRUE(!runningLock1->IsUsed()) << "runningLock1->IsUsed() != false";
POWER_HILOGD(MODULE_SERVICE, "PowerMgrUnitTest::RunningLockInnerKit003 1.");
// lock 50ms
runningLock1->Lock(50);
usleep(4000);
POWER_HILOGD(MODULE_SERVICE, "PowerMgrUnitTest::RunningLockInnerKit003 2.");
ASSERT_TRUE(runningLock1->IsUsed()) << "runningLock1->IsUsed() != true";
usleep(1000);
POWER_HILOGD(MODULE_SERVICE, "PowerMgrUnitTest::RunningLockInnerKit003 3.");
ASSERT_TRUE(runningLock1->IsUsed()) << "runningLock1->IsUsed() != true";
// wait 60ms
usleep(60000);
ASSERT_TRUE(!runningLock1->IsUsed()) << "runningLock1->IsUsed() != false";
RunningLockInfo inInfo {"runninglockTest1", RunningLockType::RUNNINGLOCK_SCREEN};
std::shared_ptr<WorkTrigger> worker1 = std::make_shared<WorkTrigger>(1, "worker1");
std::shared_ptr<WorkTrigger> worker2 = std::make_shared<WorkTrigger>(2, "worker2", 20);
auto& worklist = inInfo.workTriggerlist;
worklist.push_back(worker1);
worklist.push_back(worker2);
Parcel data;
inInfo.Marshalling(data);
RunningLockInfo *outInfo = inInfo.Unmarshalling(data);
ASSERT_TRUE(outInfo != nullptr) << "outInfo != nullptr";
ASSERT_TRUE(outInfo->name == inInfo.name) << "outInfo->name == inInfo.name";
ASSERT_TRUE(outInfo->type == inInfo.type) << "outInfo->name == inInfo.name";
ASSERT_TRUE(outInfo->workTriggerlist.size() == inInfo.workTriggerlist.size()) <<
"outInfo->workTriggerlist.size() == inInfo.workTriggerlist.size()";
auto& list1 = inInfo.workTriggerlist;
auto& list2 = outInfo->workTriggerlist;
for (auto it1 = list1.begin(), it2 = list2.begin(); (it1 != list1.end()) && (it2 != list2.end());
it1++, it2++) {
ASSERT_TRUE((*it1)->GetUid() == (*it2)->GetUid()) << "it1->GetUid() == it2->GetUid()";
ASSERT_TRUE((*it1)->GetPid() == (*it2)->GetPid()) << "it1->GetPid() == it2->GetPid()";
ASSERT_TRUE((*it1)->GetAbilityId() == (*it2)->GetAbilityId()) << "it1->GetAbilityId() == it2->GetAbilityId()";
ASSERT_TRUE((*it1)->GetName() == (*it2)->GetName()) << "it1->GetName() == it2->GetName()";
}
POWER_HILOGD(MODULE_SERVICE, "PowerMgrUnitTest::RunningLockInnerKit003 end.");
}
/**
* @tc.name: RunningLockInnerKit003
* @tc.desc: Test RunningLockInnerKit function, timeout lock.
* @tc.type: FUNC
*/
HWTEST_F (RunningLockTest, RunningLockInnerKit003, TestSize.Level0)
{
auto& powerMgrClient = PowerMgrClient::GetInstance();
auto runningLock1 = powerMgrClient.CreateRunningLock("runninglock2", RunningLockType::RUNNINGLOCK_SCREEN);
ASSERT_TRUE(runningLock1 != nullptr);
ASSERT_TRUE(!runningLock1->IsUsed()) << "runningLock1->IsUsed() != false";
// after 8ms unlock
runningLock1->Lock(30);
runningLock1->Lock(80);
POWER_HILOGD(MODULE_SERVICE, "PowerMgrUnitTest::RunningLockInnerKit004 1.");
usleep(50000);
ASSERT_TRUE(runningLock1->IsUsed()) << "runningLock1->IsUsed() != true";
usleep(50000);
ASSERT_TRUE(!runningLock1->IsUsed()) << "runningLock1->IsUsed() != false";
// no unlock
POWER_HILOGD(MODULE_SERVICE, "PowerMgrUnitTest::RunningLockInnerKit004 2.");
runningLock1->Lock(2);
runningLock1->Lock(3);
runningLock1->Lock();
POWER_HILOGD(MODULE_SERVICE, "PowerMgrUnitTest::RunningLockInnerKit004 3.");
usleep(8000);
ASSERT_TRUE(runningLock1->IsUsed()) << "runningLock1->IsUsed() != true";
// after 3ms unlock
runningLock1->Lock(30);
POWER_HILOGD(MODULE_SERVICE, "PowerMgrUnitTest::RunningLockInnerKit004 4.");
usleep(50000);
ASSERT_TRUE(!runningLock1->IsUsed()) << "runningLock1->IsUsed() != false";
runningLock1->Lock(5);
runningLock1->UnLock();
ASSERT_TRUE(!runningLock1->IsUsed()) << "runningLock1->IsUsed() != false";
POWER_HILOGD(MODULE_SERVICE, "PowerMgrUnitTest::RunningLockInnerKit004 5.");
}
/**
* @tc.name: RunningLockInnerKit004
* @tc.desc: Test RunningLockInnerKit function, timeout lock.
* @tc.type: FUNC
*/
HWTEST_F (RunningLockTest, RunningLockInnerKit004, TestSize.Level1)
{
if (false) {
auto& powerMgrClient = PowerMgrClient::GetInstance();
auto runningLock1 = powerMgrClient.CreateRunningLock("runninglock005",
RunningLockType::RUNNINGLOCK_PROXIMITY_SCREEN_CONTROL);
ASSERT_TRUE(runningLock1 != nullptr);
ASSERT_TRUE(!runningLock1->IsUsed()) << "runningLock1->IsUsed() != false";
// after 8ms unlock
runningLock1->Lock(30);
runningLock1->Lock(80);
POWER_HILOGD(MODULE_SERVICE, "PowerMgrUnitTest::RunningLockInnerKit005 1.");
usleep(50000);
ASSERT_TRUE(runningLock1->IsUsed()) << "runningLock1->IsUsed() != true";
usleep(50000);
ASSERT_TRUE(!runningLock1->IsUsed()) << "runningLock1->IsUsed() != false";
// no unlock
POWER_HILOGD(MODULE_SERVICE, "PowerMgrUnitTest::RunningLockInnerKit005 2.");
runningLock1->Lock(2);
runningLock1->Lock(3);
runningLock1->Lock();
POWER_HILOGD(MODULE_SERVICE, "PowerMgrUnitTest::RunningLockInnerKit005 3.");
usleep(8000);
ASSERT_TRUE(runningLock1->IsUsed()) << "runningLock1->IsUsed() != true";
// after 3ms unlock
runningLock1->Lock(30);
POWER_HILOGD(MODULE_SERVICE, "PowerMgrUnitTest::RunningLockInnerKit005 4.");
usleep(50000);
ASSERT_TRUE(!runningLock1->IsUsed()) << "runningLock1->IsUsed() != false";
runningLock1->Lock(5);
runningLock1->UnLock();
ASSERT_TRUE(!runningLock1->IsUsed()) << "runningLock1->IsUsed() != false";
POWER_HILOGD(MODULE_SERVICE, "PowerMgrUnitTest::RunningLockInnerKit005 5.");
}
}
/**
* @tc.name: RunningLockInnerKit005
* @tc.desc: Test RunningLockInnerKit function, dfx.
* @tc.type: FUNC
*/
HWTEST_F (RunningLockTest, RunningLockInnerKit005, TestSize.Level2)
{
auto& powerMgrClient = PowerMgrClient::GetInstance();
auto runningLock1 = powerMgrClient.CreateRunningLock("runninglock1", RunningLockType::RUNNINGLOCK_SCREEN);
ASSERT_TRUE(runningLock1 != nullptr);
runningLock1->Lock();
DumpRunningLockInfo();
auto runningLock2 = powerMgrClient.CreateRunningLock("runninglock2", RunningLockType::RUNNINGLOCK_BACKGROUND);
ASSERT_TRUE(runningLock2 != nullptr);
runningLock2->Lock();
DumpRunningLockInfo();
powerMgrClient.ProxyRunningLock(true, getuid(), getpid());
DumpRunningLockInfo();
powerMgrClient.ProxyRunningLock(false, getuid(), getpid());
DumpRunningLockInfo();
runningLock1->UnLock();
DumpRunningLockInfo();
runningLock1->Lock();
std::shared_ptr<WorkTrigger> worker1 = std::make_shared<WorkTrigger>(1, "worker1");
std::shared_ptr<WorkTrigger> worker2 = std::make_shared<WorkTrigger>(2, "worker2", 20);
std::shared_ptr<WorkTrigger> worker3 = std::make_shared<WorkTrigger>(3, "worker3", 30);
std::shared_ptr<WorkTrigger> worker4 = std::make_shared<WorkTrigger>();
WorkTriggerList worklist;
worklist.push_back(worker1);
worklist.push_back(worker2);
worklist.push_back(worker3);
worklist.push_back(worker4);
runningLock1->SetWorkTriggerList(worklist);
DumpRunningLockInfo();
sleep(70);
DumpRunningLockInfo();
POWER_HILOGD(MODULE_SERVICE, "PowerMgrUnitTest::RunningLockInnerKit006.");
}
/**
* @tc.name: RunningLockMgr001
* @tc.desc: Test RunningLockMgr function, connect PowerMgrService and call member function.
* @tc.type: FUNC
*/
HWTEST_F (RunningLockTest, RunningLockMgr001, TestSize.Level0)
{
sptr<IRemoteObject> token = new RunningLockTokenStub();
ASSERT_TRUE(token != nullptr);
sptr<IRemoteObject> token2 = new RunningLockTokenStub();
ASSERT_TRUE(token2 != nullptr);
RunningLockInfo runningLockInfo1 {"runninglockTest1", RunningLockType::RUNNINGLOCK_SCREEN};
UserIPCInfo userIPCinfo {IPCSkeleton::GetCallingUid(), IPCSkeleton::GetCallingPid()};
{
runningLockMgr_->Lock(token, runningLockInfo1, userIPCinfo);
TestRunningLockInnerExisit(token, runningLockInfo1);
ASSERT_TRUE(1 == runningLockMgr_->GetRunningLockNum(RunningLockType::RUNNINGLOCK_SCREEN));
ASSERT_TRUE(0 == runningLockMgr_->GetRunningLockNum(RunningLockType::RUNNINGLOCK_BACKGROUND));
}
RunningLockInfo runningLockInfo2 {"runninglockTest2", RunningLockType::RUNNINGLOCK_BACKGROUND};
{
runningLockMgr_->Lock(token2, runningLockInfo2, userIPCinfo);
TestRunningLockInnerExisit(token2, runningLockInfo2);
ASSERT_TRUE(1 == runningLockMgr_->GetRunningLockNum(RunningLockType::RUNNINGLOCK_SCREEN));
ASSERT_TRUE(1 == runningLockMgr_->GetRunningLockNum(RunningLockType::RUNNINGLOCK_BACKGROUND));
}
{
runningLockMgr_->UnLock(token);
TestRunningLockInnerNoExisit(token);
ASSERT_TRUE(0 == runningLockMgr_->GetRunningLockNum(RunningLockType::RUNNINGLOCK_SCREEN));
ASSERT_TRUE(1 == runningLockMgr_->GetRunningLockNum(RunningLockType::RUNNINGLOCK_BACKGROUND));
}
{
runningLockMgr_->UnLock(token2);
TestRunningLockInnerNoExisit(token2);
ASSERT_TRUE(0 == runningLockMgr_->GetRunningLockNum(RunningLockType::RUNNINGLOCK_SCREEN));
ASSERT_TRUE(0 == runningLockMgr_->GetRunningLockNum(RunningLockType::RUNNINGLOCK_BACKGROUND));
}
POWER_HILOGD(MODULE_SERVICE, "RunningLockTest::RunningLockMgr001 end.");
}
/**
* @tc.name: RunningLockMgr002
* @tc.desc: Test RunningLockMgr SetWorkerList function.
* @tc.type: FUNC
*/
HWTEST_F (RunningLockTest, RunningLockMgr002, TestSize.Level0)
{
sptr<IRemoteObject> token = new RunningLockTokenStub();
ASSERT_TRUE(token != nullptr);
RunningLockInfo runningLockInfo1 {"runninglockTest1", RunningLockType::RUNNINGLOCK_SCREEN};
UserIPCInfo userIPCinfo {IPCSkeleton::GetCallingPid(), IPCSkeleton::GetCallingUid()};
{
runningLockMgr_->Lock(token, runningLockInfo1, userIPCinfo);
TestRunningLockInnerExisit(token, runningLockInfo1);
ASSERT_TRUE(1 == runningLockMgr_->GetRunningLockNum(RunningLockType::RUNNINGLOCK_SCREEN));
ASSERT_TRUE(0 == runningLockMgr_->GetRunningLockNum(RunningLockType::RUNNINGLOCK_BACKGROUND));
}
{
std::shared_ptr<WorkTrigger> worker1 = std::make_shared<WorkTrigger>(1, "worker1");
std::shared_ptr<WorkTrigger> worker2 = std::make_shared<WorkTrigger>(2, "worker2", 20);
std::shared_ptr<WorkTrigger> worker3 = std::make_shared<WorkTrigger>(3, "worker3", 30);
std::shared_ptr<WorkTrigger> worker4 = std::make_shared<WorkTrigger>();
RunningLockInfo runningLockInfo1;
auto& worklist = runningLockInfo1.workTriggerlist;
worklist.push_back(worker1);
worklist.push_back(worker2);
worklist.push_back(worker3);
runningLockMgr_->SetWorkTriggerList(token, worklist);
worklist.remove(worker3);
worklist.push_back(worker4);
runningLockMgr_->SetWorkTriggerList(token, worklist);
}
{
runningLockMgr_->UnLock(token);
TestRunningLockInnerNoExisit(token);
ASSERT_TRUE(0 == runningLockMgr_->GetRunningLockNum(RunningLockType::RUNNINGLOCK_SCREEN));
ASSERT_TRUE(0 == runningLockMgr_->GetRunningLockNum(RunningLockType::RUNNINGLOCK_BACKGROUND));
}
POWER_HILOGD(MODULE_SERVICE, "RunningLockTest::RunningLockMgr002 end.");
}
/**
* @tc.name: RunningLockMgr003
* @tc.desc: Test RunningLockMgr Proxy function.
* @tc.type: FUNC
*/
HWTEST_F (RunningLockTest, RunningLockMgr003, TestSize.Level0)
{
sptr<IRemoteObject> token1 = new RunningLockTokenStub();
sptr<IRemoteObject> token2 = new RunningLockTokenStub();
RunningLockInfo runningLockInfo1 {"runninglocktest1", RunningLockType::RUNNINGLOCK_SCREEN};
RunningLockInfo runningLockInfo2 {"runninglocktest2", RunningLockType::RUNNINGLOCK_SCREEN};
UserIPCInfo userIPCinfo1 {1, 1};
UserIPCInfo userIPCinfo2 {2, 2};
runningLockMgr_->Lock(token1, runningLockInfo1, userIPCinfo1);
runningLockMgr_->Lock(token2, runningLockInfo2, userIPCinfo2);
TestRunningLockInnerExisit(token1, runningLockInfo1);
TestRunningLockInnerExisit(token2, runningLockInfo2);
ASSERT_TRUE(2 == runningLockMgr_->GetRunningLockNum(RunningLockType::RUNNINGLOCK_SCREEN));
ASSERT_TRUE(2 == runningLockMgr_->GetValidRunningLockNum(RunningLockType::RUNNINGLOCK_SCREEN));
auto& proxymap = runningLockMgr_->GetRunningLockProxyMap();
ASSERT_TRUE(proxymap.empty());
{
// proxy by userIPCinfo1, lockinner1 disabled
runningLockMgr_->ProxyRunningLock(true, userIPCinfo1.uid, userIPCinfo1.pid);
auto lockInner1 = runningLockMgr_->GetRunningLockInner(token1);
ASSERT_TRUE(!lockInner1->GetReallyLocked());
ASSERT_TRUE(lockInner1->GetDisabled());
ASSERT_TRUE(!proxymap.empty() && (proxymap.count(userIPCinfo1.uid) > 0));
runningLockMgr_->ProxyRunningLock(true, userIPCinfo2.uid, userIPCinfo2.pid);
auto lockInner2 = runningLockMgr_->GetRunningLockInner(token2);
ASSERT_TRUE(!lockInner2->GetReallyLocked());
ASSERT_TRUE(lockInner2->GetDisabled());
ASSERT_TRUE(!proxymap.empty() && (proxymap.count(userIPCinfo2.uid) > 0));
ASSERT_TRUE(2 == runningLockMgr_->GetRunningLockNum(RunningLockType::RUNNINGLOCK_SCREEN));
ASSERT_TRUE(0 == runningLockMgr_->GetValidRunningLockNum(RunningLockType::RUNNINGLOCK_SCREEN));
runningLockMgr_->ProxyRunningLock(false, userIPCinfo1.uid, userIPCinfo1.pid);
ASSERT_TRUE(lockInner1->GetReallyLocked());
ASSERT_TRUE(!lockInner1->GetDisabled());
ASSERT_TRUE(!proxymap.empty() && (proxymap.count(userIPCinfo1.uid) == 0));
runningLockMgr_->ProxyRunningLock(false, userIPCinfo2.uid, userIPCinfo2.pid);
ASSERT_TRUE(lockInner2->GetReallyLocked());
ASSERT_TRUE(!lockInner2->GetDisabled());
ASSERT_TRUE(proxymap.empty());
ASSERT_TRUE(2 == runningLockMgr_->GetRunningLockNum(RunningLockType::RUNNINGLOCK_SCREEN));
ASSERT_TRUE(2 == runningLockMgr_->GetValidRunningLockNum(RunningLockType::RUNNINGLOCK_SCREEN));
}
runningLockMgr_->UnLock(token1);
runningLockMgr_->UnLock(token2);
POWER_HILOGD(MODULE_SERVICE, "RunningLockTest::RunningLockMgr003 end.");
}
/**
* @tc.name: RunningLockMgr004
* @tc.desc: Test RunningLockMgr Proxy function.
* @tc.type: FUNC
*/
HWTEST_F (RunningLockTest, RunningLockMgr004, TestSize.Level0)
{
sptr<IRemoteObject> token3 = new RunningLockTokenStub();
sptr<IRemoteObject> token4 = new RunningLockTokenStub();
RunningLockInfo runningLockInfo3 {"runninglocktest3", RunningLockType::RUNNINGLOCK_SCREEN};
RunningLockInfo runningLockInfo4 {"runninglocktest4", RunningLockType::RUNNINGLOCK_SCREEN};
UserIPCInfo userIPCinfo3 {3, 3};
UserIPCInfo userIPCinfo4 {3, 4};
runningLockMgr_->Lock(token3, runningLockInfo3, userIPCinfo3);
runningLockMgr_->Lock(token4, runningLockInfo4, userIPCinfo4);
TestRunningLockInnerExisit(token3, runningLockInfo3);
TestRunningLockInnerExisit(token4, runningLockInfo4);
ASSERT_TRUE(2 == runningLockMgr_->GetValidRunningLockNum(RunningLockType::RUNNINGLOCK_SCREEN));
auto& proxymap = runningLockMgr_->GetRunningLockProxyMap();
ASSERT_TRUE(proxymap.empty());
{
// lockinner3 and lockinner4 have same pid, save uid key, pid set {uid3,{pid3, pid4}}
runningLockMgr_->ProxyRunningLock(true, userIPCinfo3.uid, userIPCinfo3.pid);
runningLockMgr_->ProxyRunningLock(true, userIPCinfo4.uid, userIPCinfo4.pid);
auto lockInner3 = runningLockMgr_->GetRunningLockInner(token3);
ASSERT_TRUE(!lockInner3->GetReallyLocked());
ASSERT_TRUE(lockInner3->GetDisabled());
ASSERT_TRUE(!proxymap.empty() && (proxymap.count(userIPCinfo3.uid) > 0));
{
auto it = proxymap.find(userIPCinfo3.uid);
ASSERT_TRUE(it != proxymap.end());
auto& pidset = it->second;
ASSERT_TRUE(pidset.count(userIPCinfo3.pid) == 1);
}
auto lockInner4 = runningLockMgr_->GetRunningLockInner(token4);
ASSERT_TRUE(lockInner4 != nullptr);
ASSERT_TRUE(!lockInner4->GetReallyLocked());
ASSERT_TRUE(lockInner4->GetDisabled());
ASSERT_TRUE(!proxymap.empty() && (proxymap.count(userIPCinfo4.uid) > 0));
{
auto it = proxymap.find(userIPCinfo4.uid);
ASSERT_TRUE(it != proxymap.end());
auto& pidset = it->second;
ASSERT_TRUE(pidset.count(userIPCinfo4.pid) == 1);
}
ASSERT_TRUE(0 == runningLockMgr_->GetValidRunningLockNum(RunningLockType::RUNNINGLOCK_SCREEN));
runningLockMgr_->ProxyRunningLock(false, userIPCinfo3.uid, INVALID_PID);
ASSERT_TRUE(proxymap.empty());
ASSERT_TRUE(lockInner3->GetReallyLocked() && !lockInner3->GetDisabled());
ASSERT_TRUE(lockInner4->GetReallyLocked() && !lockInner4->GetDisabled());
ASSERT_TRUE(2 == runningLockMgr_->GetValidRunningLockNum(RunningLockType::RUNNINGLOCK_SCREEN));
}
runningLockMgr_->UnLock(token3);
runningLockMgr_->UnLock(token4);
POWER_HILOGD(MODULE_SERVICE, "RunningLockTest::RunningLockMgr004 end.");
}
/**
* @tc.name: RunningLockMgr005
* @tc.desc: Test RunningLockMgr Proxy function.
* @tc.type: FUNC
*/
HWTEST_F (RunningLockTest, RunningLockMgr005, TestSize.Level0)
{
sptr<IRemoteObject> token = new RunningLockTokenStub();
RunningLockInfo runningLockInfo1 {"runninglocktest1", RunningLockType::RUNNINGLOCK_SCREEN};
UserIPCInfo userIPCinfo1 {1, 1};
runningLockMgr_->Lock(token, runningLockInfo1, userIPCinfo1);
auto& proxymap = runningLockMgr_->GetRunningLockProxyMap();
ASSERT_TRUE(proxymap.empty());
{
auto lockInner1 = runningLockMgr_->GetRunningLockInner(token);
runningLockMgr_->ProxyRunningLock(true, userIPCinfo1.uid, userIPCinfo1.pid);
ASSERT_TRUE(!lockInner1->GetReallyLocked() && lockInner1->GetDisabled());
runningLockMgr_->ProxyRunningLock(false, userIPCinfo1.uid, userIPCinfo1.pid);
ASSERT_TRUE(lockInner1->GetReallyLocked() && !lockInner1->GetDisabled());
UserIPCInfo workeripc1 {10, 20};
UserIPCInfo workeripc2 {20, 20};
runningLockMgr_->ProxyRunningLock(true, workeripc1.uid, workeripc1.pid);
runningLockMgr_->ProxyRunningLock(true, workeripc2.uid, workeripc2.pid);
std::shared_ptr<WorkTrigger> worker1 = std::make_shared<WorkTrigger>(workeripc1.uid, "worker1", workeripc1.pid);
std::shared_ptr<WorkTrigger> worker2 = std::make_shared<WorkTrigger>(workeripc2.uid, "worker2", workeripc2.pid);
auto& worklist = runningLockInfo1.workTriggerlist;
worklist.push_back(worker1);
worklist.push_back(worker2);
runningLockMgr_->SetWorkTriggerList(token, worklist);
ASSERT_TRUE(!lockInner1->GetReallyLocked() && lockInner1->GetDisabled());
worklist.remove(worker2);
runningLockMgr_->SetWorkTriggerList(token, worklist);
ASSERT_TRUE(!lockInner1->GetReallyLocked() && lockInner1->GetDisabled());
runningLockMgr_->ProxyRunningLock(false, workeripc1.uid, workeripc1.pid);
runningLockMgr_->ProxyRunningLock(false, workeripc2.uid, workeripc2.pid);
ASSERT_TRUE(lockInner1->GetReallyLocked() && !lockInner1->GetDisabled());
UserIPCInfo workeripc3 {10, 30};
std::shared_ptr<WorkTrigger> worker3 = std::make_shared<WorkTrigger>(workeripc3.uid, "worker3", workeripc3.pid);
runningLockMgr_->ProxyRunningLock(true, workeripc1.uid, workeripc1.pid);
runningLockMgr_->ProxyRunningLock(true, workeripc3.uid, workeripc3.pid);
runningLockMgr_->SetWorkTriggerList(token, worklist);
ASSERT_TRUE(!lockInner1->GetReallyLocked() && lockInner1->GetDisabled());
runningLockMgr_->ProxyRunningLock(false, workeripc3.uid, INVALID_PID);
ASSERT_TRUE(lockInner1->GetReallyLocked() && !lockInner1->GetDisabled());
ASSERT_TRUE(proxymap.empty());
runningLockMgr_->ProxyRunningLock(true, workeripc1.uid, workeripc1.pid);
runningLockMgr_->ProxyRunningLock(true, workeripc3.uid, workeripc3.pid);
runningLockMgr_->ProxyRunningLock(true, workeripc1.uid, INVALID_PID);
auto it = proxymap.find(workeripc1.uid);
auto& pidset = it->second;
ASSERT_TRUE((pidset.size() == 1) && (pidset.count(INVALID_PID) == 1));
runningLockMgr_->ProxyRunningLock(false, workeripc1.uid, INVALID_PID);
ASSERT_TRUE(proxymap.empty());
}
runningLockMgr_->UnLock(token);
POWER_HILOGD(MODULE_SERVICE, "RunningLockTest::RunningLockMgr005 end.");
}

View File

@ -0,0 +1,57 @@
/*
* 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 POWERMGR_SERVICES_IPOWER_MANAGER_PROXY_H
#define POWERMGR_SERVICES_IPOWER_MANAGER_PROXY_H
#include <iremote_proxy.h>
#include <nocopyable.h>
#include "ipower_mgr.h"
#include "power_state_machine_info.h"
namespace OHOS {
namespace PowerMgr {
class PowerMgrProxy : public IRemoteProxy<IPowerMgr> {
public:
explicit PowerMgrProxy(const sptr<IRemoteObject>& impl)
: IRemoteProxy<IPowerMgr>(impl) {}
~PowerMgrProxy() = default;
DISALLOW_COPY_AND_MOVE(PowerMgrProxy);
virtual void Lock(const sptr<IRemoteObject>& token, const RunningLockInfo& runningLockInfo,
uint32_t timeOutMs) override;
virtual void UnLock(const sptr<IRemoteObject>& token) override;
virtual void SetWorkTriggerList(const sptr<IRemoteObject>& token, const WorkTriggerList& workTriggerList) override;
virtual void ProxyRunningLock(bool proxyLock, pid_t uid, pid_t pid) override;
virtual bool IsUsed(const sptr<IRemoteObject>& token) override;
// Use for PowerStateMachine
virtual void SuspendDevice(int64_t callTimeMs, SuspendDeviceType reason, bool suspendImmed) override;
virtual void WakeupDevice(int64_t callTimeMs, WakeupDeviceType reason, const std::string& details) override;
virtual void RefreshActivity(int64_t callTimeMs, UserActivityType type, bool needChangeBacklight) override;
virtual bool IsScreenOn() override;
virtual bool ForceSuspendDevice(int64_t callTimeMs) override;
virtual void RebootDevice(const std::string& reason) override;
virtual void ShutDownDevice(const std::string& reason) override;
virtual void RegisterPowerStateCallback(const sptr<IPowerStateCallback>& callback) override;
virtual void UnRegisterPowerStateCallback(const sptr<IPowerStateCallback>& callback) override;
virtual void RegisterShutdownCallback(const sptr<IShutdownCallback>& callback) override;
virtual void UnRegisterShutdownCallback(const sptr<IShutdownCallback>& callback) override;
private:
static inline BrokerDelegator<PowerMgrProxy> delegator_;
};
} // namespace PowerMgr
} // namespace OHOS
#endif // POWERMGR_SERVICES_IPOWER_MANAGER_PROXY_H

View File

@ -0,0 +1,53 @@
/*
* 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 POWERMGR_SERVICES_IPOWER_MANAGER_STUB_H
#define POWERMGR_SERVICES_IPOWER_MANAGER_STUB_H
#include <iremote_stub.h>
#include <nocopyable.h>
#include "ipower_mgr.h"
namespace OHOS {
namespace PowerMgr {
class PowerMgrStub : public IRemoteStub<IPowerMgr> {
public:
DISALLOW_COPY_AND_MOVE(PowerMgrStub);
PowerMgrStub() = default;
virtual ~PowerMgrStub() = default;
int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override;
private:
int32_t WakeupDeviceStub(MessageParcel& data);
int32_t SuspendDeviceStub(MessageParcel& data);
int32_t RefreshActivityStub(MessageParcel& data);
int32_t IsScreeOnStub(MessageParcel& reply);
int32_t ForceSuspendDeviceStub(MessageParcel& data, MessageParcel& reply);
int32_t ProxyRunningLockStub(MessageParcel& data);
int32_t LockStub(MessageParcel& data);
int32_t UnLockStub(MessageParcel& data);
int32_t SetWorkTriggerListStub(MessageParcel& data);
int32_t IsUsedStub(MessageParcel& data, MessageParcel& reply);
int32_t RebootDeviceStub(MessageParcel& data);
int32_t ShutDownDeviceStub(MessageParcel& data);
int32_t RegisterPowerStateCallbackStub(MessageParcel& data);
int32_t UnRegisterPowerStateCallbackStub(MessageParcel& data);
int32_t RegisterShutdownCallbackStub(MessageParcel& data);
int32_t UnRegisterShutdownCallbackStub(MessageParcel& data);
};
} // namespace PowerMgr
} // namespace OHOS
#endif // POWERMGR_SERVICES_IPOWER_MANAGER_STUB_H

View File

@ -0,0 +1,40 @@
/*
* 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 POWERMGR_SERVICES_IPOWER_STATE_CALLBACK_PROXY_H
#define POWERMGR_SERVICES_IPOWER_STATE_CALLBACK_PROXY_H
#include <iremote_proxy.h>
#include <nocopyable.h>
#include "ipower_state_callback.h"
#include "power_state_machine_info.h"
namespace OHOS {
namespace PowerMgr {
class PowerStateCallbackProxy : public IRemoteProxy<IPowerStateCallback> {
public:
explicit PowerStateCallbackProxy(const sptr<IRemoteObject>& impl)
: IRemoteProxy<IPowerStateCallback>(impl) {}
~PowerStateCallbackProxy() = default;
DISALLOW_COPY_AND_MOVE(PowerStateCallbackProxy);
virtual void OnPowerStateChanged(PowerState state) override;
private:
static inline BrokerDelegator<PowerStateCallbackProxy> delegator_;
};
} // namespace PowerMgr
} // namespace OHOS
#endif // POWERMGR_SERVICES_IPOWER_STATE_CALLBACK_PROXY_H

View File

@ -0,0 +1,39 @@
/*
* 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 POWERMGR_SERVICES_IPOWER_STATE_CALLBACK_STUB_H
#define POWERMGR_SERVICES_IPOWER_STATE_CALLBACK_STUB_H
#include <iremote_stub.h>
#include <nocopyable.h>
#include "ipower_state_callback.h"
namespace OHOS {
namespace PowerMgr {
class PowerStateCallbackStub : public IRemoteStub<IPowerStateCallback> {
public:
DISALLOW_COPY_AND_MOVE(PowerStateCallbackStub);
PowerStateCallbackStub() = default;
virtual ~PowerStateCallbackStub() = default;
int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override;
void OnPowerStateChanged(PowerState __attribute__((unused))state) override {}
private:
int32_t OnPowerStateChangedStub(MessageParcel& data);
};
} // namespace PowerMgr
} // namespace OHOS
#endif // POWERMGR_SERVICES_IPOWER_STATE_CALLBACK_STUB_H

View File

@ -0,0 +1,417 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "power_mgr_proxy.h"
#include <ipc_types.h>
#include <message_parcel.h>
#include <string_ex.h>
#include "power_common.h"
namespace OHOS {
namespace PowerMgr {
void PowerMgrProxy::Lock(const sptr<IRemoteObject>& token, const RunningLockInfo& runningLockInfo, uint32_t timeOutMs)
{
sptr<IRemoteObject> remote = Remote();
RETURN_IF(remote == nullptr);
MessageParcel data;
MessageParcel reply;
MessageOption option;
if (!data.WriteInterfaceToken(PowerMgrProxy::GetDescriptor())) {
POWER_HILOGE(MODULE_INNERKIT, "PowerMgrProxy::%{public}s write descriptor failed!", __func__);
return;
}
WRITE_PARCEL_NO_RET(data, RemoteObject, token.GetRefPtr());
WRITE_PARCEL_NO_RET(data, Parcelable, &runningLockInfo);
WRITE_PARCEL_NO_RET(data, Uint32, timeOutMs);
int ret = remote->SendRequest(static_cast<int>(IPowerMgr::RUNNINGLOCK_LOCK),
data, reply, option);
if (ret != ERR_OK) {
POWER_HILOGE(MODULE_INNERKIT, "PowerMgrProxy::%{public}s SendRequest is failed, error code: %d", __func__, ret);
return;
}
}
void PowerMgrProxy::UnLock(const sptr<IRemoteObject>& token)
{
sptr<IRemoteObject> remote = Remote();
RETURN_IF(remote == nullptr);
MessageParcel data;
MessageParcel reply;
MessageOption option;
if (!data.WriteInterfaceToken(PowerMgrProxy::GetDescriptor())) {
POWER_HILOGE(MODULE_INNERKIT, "PowerMgrProxy::%{public}s write descriptor failed!", __func__);
return;
}
WRITE_PARCEL_NO_RET(data, RemoteObject, token.GetRefPtr());
int ret = remote->SendRequest(static_cast<int>(IPowerMgr::RUNNINGLOCK_UNLOCK),
data, reply, option);
if (ret != ERR_OK) {
POWER_HILOGE(MODULE_INNERKIT, "PowerMgrProxy::%{public}s SendRequest is failed, error code: %d", __func__, ret);
return;
}
}
bool PowerMgrProxy::IsUsed(const sptr<IRemoteObject>& token)
{
sptr<IRemoteObject> remote = Remote();
RETURN_IF_WITH_RET(remote == nullptr, false);
MessageParcel data;
MessageParcel reply;
MessageOption option;
if (!data.WriteInterfaceToken(PowerMgrProxy::GetDescriptor())) {
POWER_HILOGE(MODULE_INNERKIT, "PowerMgrProxy::%{public}s write descriptor failed!", __func__);
return false;
}
WRITE_PARCEL_WITH_RET(data, RemoteObject, token.GetRefPtr(), false);
int ret = remote->SendRequest(static_cast<int>(IPowerMgr::RUNNINGLOCK_ISUSED),
data, reply, option);
if (ret != ERR_OK) {
POWER_HILOGE(MODULE_INNERKIT, "PowerMgrProxy::%{public}s SendRequest is failed, error code: %d", __func__, ret);
return false;
}
bool used = false;
READ_PARCEL_WITH_RET(reply, Bool, used, false);
return used;
}
void PowerMgrProxy::SetWorkTriggerList(const sptr<IRemoteObject>& token, const WorkTriggerList& workTriggerList)
{
sptr<IRemoteObject> remote = Remote();
RETURN_IF(remote == nullptr);
MessageParcel data;
MessageParcel reply;
MessageOption option;
if (!data.WriteInterfaceToken(PowerMgrProxy::GetDescriptor())) {
POWER_HILOGE(MODULE_INNERKIT, "PowerMgrProxy::%{public}s write descriptor failed!", __func__);
return;
}
WRITE_PARCEL_NO_RET(data, RemoteObject, token.GetRefPtr());
RETURN_IF(!RunningLockInfo::MarshallingWorkTriggerList(data, workTriggerList));
int ret = remote->SendRequest(static_cast<int>(IPowerMgr::RUNNINGLOCK_SET_WORK_TRIGGER_LIST),
data, reply, option);
if (ret != ERR_OK) {
POWER_HILOGE(MODULE_INNERKIT, "PowerMgrProxy::%{public}s SendRequest is failed, error code: %d", __func__, ret);
return;
}
}
void PowerMgrProxy::ProxyRunningLock(bool proxyLock, pid_t uid, pid_t pid)
{
sptr<IRemoteObject> remote = Remote();
RETURN_IF(remote == nullptr);
MessageParcel data;
MessageParcel reply;
MessageOption option;
if (!data.WriteInterfaceToken(PowerMgrProxy::GetDescriptor())) {
POWER_HILOGE(MODULE_INNERKIT, "PowerMgrProxy::%{public}s write descriptor failed!", __func__);
return;
}
WRITE_PARCEL_NO_RET(data, Bool, proxyLock);
WRITE_PARCEL_NO_RET(data, Int32, uid);
WRITE_PARCEL_NO_RET(data, Int32, pid);
int ret = remote->SendRequest(static_cast<int>(IPowerMgr::PROXY_RUNNINGLOCK),
data, reply, option);
if (ret != ERR_OK) {
POWER_HILOGE(MODULE_INNERKIT, "PowerMgrProxy::%{public}s SendRequest is failed, error code: %d", __func__, ret);
return;
}
}
void PowerMgrProxy::RebootDevice(const std::string& reason)
{
sptr<IRemoteObject> remote = Remote();
RETURN_IF(remote == nullptr);
MessageParcel data;
MessageParcel reply;
MessageOption option;
if (!data.WriteInterfaceToken(PowerMgrProxy::GetDescriptor())) {
POWER_HILOGE(MODULE_INNERKIT, "PowerMgrProxy::%{public}s write descriptor failed!", __func__);
return;
}
WRITE_PARCEL_NO_RET(data, String16, Str8ToStr16(reason));
int ret = remote->SendRequest(static_cast<int>(IPowerMgr::REBOOT_DEVICE), data, reply, option);
if (ret != ERR_OK) {
POWER_HILOGE(MODULE_INNERKIT, "PowerMgrProxy::%{public}s Transact is failed, error code: %d", __func__, ret);
}
}
void PowerMgrProxy::ShutDownDevice(const std::string& reason)
{
sptr<IRemoteObject> remote = Remote();
RETURN_IF(remote == nullptr);
MessageParcel data;
MessageParcel reply;
MessageOption option;
if (!data.WriteInterfaceToken(PowerMgrProxy::GetDescriptor())) {
POWER_HILOGE(MODULE_INNERKIT, "PowerMgrProxy::%{public}s write descriptor failed!", __func__);
return;
}
WRITE_PARCEL_NO_RET(data, String16, Str8ToStr16(reason));
int ret = remote->SendRequest(static_cast<int>(IPowerMgr::SHUTDOWN_DEVICE), data, reply, option);
if (ret != ERR_OK) {
POWER_HILOGE(MODULE_INNERKIT, "PowerMgrProxy::%{public}s Transact is failed, error code: %d", __func__, ret);
}
}
void PowerMgrProxy::SuspendDevice(int64_t callTimeMs, SuspendDeviceType reason, bool suspendImmed)
{
sptr<IRemoteObject> remote = Remote();
RETURN_IF(remote == nullptr);
MessageParcel data;
MessageParcel reply;
MessageOption option;
if (!data.WriteInterfaceToken(PowerMgrProxy::GetDescriptor())) {
POWER_HILOGE(MODULE_INNERKIT, "PowerMgrProxy::%{public}s write descriptor failed!", __func__);
return;
}
WRITE_PARCEL_NO_RET(data, Int64, callTimeMs);
WRITE_PARCEL_NO_RET(data, Uint32, static_cast<uint32_t>(reason));
WRITE_PARCEL_NO_RET(data, Bool, suspendImmed);
int ret = remote->SendRequest(static_cast<int>(IPowerMgr::SUSPEND_DEVICE), data, reply, option);
if (ret != ERR_OK) {
POWER_HILOGE(MODULE_INNERKIT, "PowerMgrProxy::%{public}s SendRequest is failed, error code: %d", __func__, ret);
}
}
void PowerMgrProxy::WakeupDevice(int64_t callTimeMs, WakeupDeviceType reason, const std::string& details)
{
sptr<IRemoteObject> remote = Remote();
RETURN_IF(remote == nullptr);
MessageParcel data;
MessageParcel reply;
MessageOption option;
if (!data.WriteInterfaceToken(PowerMgrProxy::GetDescriptor())) {
POWER_HILOGE(MODULE_INNERKIT, "PowerMgrProxy::%{public}s write descriptor failed!", __func__);
return;
}
WRITE_PARCEL_NO_RET(data, Int64, callTimeMs);
WRITE_PARCEL_NO_RET(data, Uint32, static_cast<uint32_t>(reason));
WRITE_PARCEL_NO_RET(data, String16, Str8ToStr16(details));
int ret = remote->SendRequest(static_cast<int>(IPowerMgr::WAKEUP_DEVICE), data, reply, option);
if (ret != ERR_OK) {
POWER_HILOGE(MODULE_INNERKIT, "PowerMgrProxy::%{public}s SendRequest is failed, error code: %d", __func__, ret);
return;
}
}
void PowerMgrProxy::RefreshActivity(int64_t callTimeMs, UserActivityType type, bool needChangeBacklight)
{
sptr<IRemoteObject> remote = Remote();
RETURN_IF(remote == nullptr);
MessageParcel data;
MessageParcel reply;
MessageOption option;
if (!data.WriteInterfaceToken(PowerMgrProxy::GetDescriptor())) {
POWER_HILOGE(MODULE_INNERKIT, "PowerMgrProxy::%{public}s write descriptor failed!", __func__);
return;
}
WRITE_PARCEL_NO_RET(data, Int64, callTimeMs);
WRITE_PARCEL_NO_RET(data, Uint32, static_cast<uint32_t>(type));
WRITE_PARCEL_NO_RET(data, Bool, needChangeBacklight);
int ret = remote->SendRequest(static_cast<int>(IPowerMgr::REFRESH_ACTIVITY), data, reply, option);
if (ret != ERR_OK) {
POWER_HILOGE(MODULE_INNERKIT, "PowerMgrProxy::%{public}s SendRequest is failed, error code: %d", __func__, ret);
return;
}
}
bool PowerMgrProxy::ForceSuspendDevice(int64_t callTimeMs)
{
sptr<IRemoteObject> remote = Remote();
RETURN_IF_WITH_RET(remote == nullptr, false);
bool result = false;
MessageParcel data;
MessageParcel reply;
MessageOption option;
if (!data.WriteInterfaceToken(PowerMgrProxy::GetDescriptor())) {
POWER_HILOGE(MODULE_INNERKIT, "PowerMgrProxy::%{public}s write descriptor failed!", __func__);
return result;
}
WRITE_PARCEL_WITH_RET(data, Int64, callTimeMs, false);
int ret = remote->SendRequest(static_cast<int>(IPowerMgr::FORCE_DEVICE_SUSPEND), data, reply, option);
if (ret != ERR_OK) {
POWER_HILOGE(MODULE_INNERKIT, "PowerMgrProxy::%{public}s SendRequest is failed, error code: %d", __func__, ret);
return result;
}
if (!reply.ReadBool(result)) {
POWER_HILOGE(MODULE_INNERKIT, "PowerMgrProxy::%{public}s Readback fail!", __func__);
}
return result;
}
bool PowerMgrProxy::IsScreenOn()
{
sptr<IRemoteObject> remote = Remote();
RETURN_IF_WITH_RET(remote == nullptr, false);
bool result = false;
MessageParcel data;
MessageParcel reply;
MessageOption option;
if (!data.WriteInterfaceToken(PowerMgrProxy::GetDescriptor())) {
POWER_HILOGE(MODULE_INNERKIT, "PowerMgrProxy::%{public}s write descriptor failed!", __func__);
return result;
}
int ret = remote->SendRequest(static_cast<int>(IPowerMgr::IS_SCREEN_ON), data, reply, option);
if (ret != ERR_OK) {
POWER_HILOGE(MODULE_INNERKIT, "PowerMgrProxy::%{public}s SendRequest is failed, error code: %d", __func__, ret);
return result;
}
if (!reply.ReadBool(result)) {
POWER_HILOGE(MODULE_INNERKIT, "PowerMgrProxy::%{public}s Readback fail!", __func__);
}
return result;
}
void PowerMgrProxy::RegisterPowerStateCallback(const sptr<IPowerStateCallback>& callback)
{
sptr<IRemoteObject> remote = Remote();
RETURN_IF((remote == nullptr) || (callback == nullptr));
MessageParcel data;
MessageParcel reply;
MessageOption option;
if (!data.WriteInterfaceToken(PowerMgrProxy::GetDescriptor())) {
POWER_HILOGE(MODULE_INNERKIT, "PowerMgrProxy::%{public}s write descriptor failed!", __func__);
return;
}
WRITE_PARCEL_NO_RET(data, RemoteObject, callback->AsObject());
int ret = remote->SendRequest(static_cast<int>(IPowerMgr::REG_POWER_STATE_CALLBACK), data, reply, option);
if (ret != ERR_OK) {
POWER_HILOGE(MODULE_INNERKIT, "PowerMgrProxy::%{public}s SendRequest is failed, error code: %d", __func__, ret);
return;
}
}
void PowerMgrProxy::UnRegisterPowerStateCallback(const sptr<IPowerStateCallback>& callback)
{
sptr<IRemoteObject> remote = Remote();
RETURN_IF((remote == nullptr) || (callback == nullptr));
MessageParcel data;
MessageParcel reply;
MessageOption option;
if (!data.WriteInterfaceToken(PowerMgrProxy::GetDescriptor())) {
POWER_HILOGE(MODULE_INNERKIT, "PowerMgrProxy::%{public}s write descriptor failed!", __func__);
return;
}
WRITE_PARCEL_NO_RET(data, RemoteObject, callback->AsObject());
int ret = remote->SendRequest(static_cast<int>(IPowerMgr::UNREG_POWER_STATE_CALLBACK), data, reply, option);
if (ret != ERR_OK) {
POWER_HILOGE(MODULE_INNERKIT, "PowerMgrProxy::%{public}s SendRequest is failed, error code: %d", __func__, ret);
return;
}
}
void PowerMgrProxy::RegisterShutdownCallback(const sptr<IShutdownCallback>& callback)
{
sptr<IRemoteObject> remote = Remote();
RETURN_IF((remote == nullptr) || (callback == nullptr));
MessageParcel data;
MessageParcel reply;
MessageOption option;
if (!data.WriteInterfaceToken(PowerMgrProxy::GetDescriptor())) {
POWER_HILOGE(MODULE_INNERKIT, "Write descriptor failed!");
return;
}
WRITE_PARCEL_NO_RET(data, RemoteObject, callback->AsObject());
int ret = remote->SendRequest(static_cast<int>(IPowerMgr::REG_SHUTDOWN_CALLBACK), data, reply, option);
if (ret != ERR_OK) {
POWER_HILOGE(MODULE_INNERKIT, "SendRequest is failed, error code: %{public}d", ret);
return;
}
}
void PowerMgrProxy::UnRegisterShutdownCallback(const sptr<IShutdownCallback>& callback)
{
sptr<IRemoteObject> remote = Remote();
RETURN_IF((remote == nullptr) || (callback == nullptr));
MessageParcel data;
MessageParcel reply;
MessageOption option;
if (!data.WriteInterfaceToken(PowerMgrProxy::GetDescriptor())) {
POWER_HILOGE(MODULE_INNERKIT, "Write descriptor failed!");
return;
}
WRITE_PARCEL_NO_RET(data, RemoteObject, callback->AsObject());
int ret = remote->SendRequest(static_cast<int>(IPowerMgr::UNREG_SHUTDOWN_CALLBACK), data, reply, option);
if (ret != ERR_OK) {
POWER_HILOGE(MODULE_INNERKIT, "SendRequest is failed, error code: %{public}d", ret);
return;
}
}
} // namespace PowerMgr
} // namespace OHOS

View File

@ -0,0 +1,266 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "power_mgr_stub.h"
#include <message_parcel.h>
#include <string_ex.h>
#include "power_common.h"
#include "power_mgr_proxy.h"
using namespace OHOS::HiviewDFX;
namespace OHOS {
namespace PowerMgr {
int PowerMgrStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option)
{
POWER_HILOGD(MODULE_SERVICE, "PowerMgrStub::OnRemoteRequest, cmd = %u, flags= %d", code, option.GetFlags());
std::u16string descripter = PowerMgrStub::GetDescriptor();
std::u16string remoteDescripter = data.ReadInterfaceToken();
if (descripter != remoteDescripter) {
POWER_HILOGE(MODULE_SERVICE, "PowerMgrStub::OnRemoteRequest failed, descriptor is not matched!");
return E_GET_POWER_SERVICE_FAILED;
}
switch (code) {
case static_cast<int>(IPowerMgr::WAKEUP_DEVICE): {
return WakeupDeviceStub(data);
}
case static_cast<int>(IPowerMgr::SUSPEND_DEVICE): {
return SuspendDeviceStub(data);
}
case static_cast<int>(IPowerMgr::REFRESH_ACTIVITY): {
return RefreshActivityStub(data);
}
case static_cast<int>(IPowerMgr::REBOOT_DEVICE): {
return RebootDeviceStub(data);
}
case static_cast<int>(IPowerMgr::SHUTDOWN_DEVICE): {
return ShutDownDeviceStub(data);
}
case static_cast<int>(IPowerMgr::IS_SCREEN_ON): {
return IsScreeOnStub(reply);
}
case static_cast<int>(IPowerMgr::FORCE_DEVICE_SUSPEND): {
return ForceSuspendDeviceStub(data, reply);
}
case static_cast<int>(IPowerMgr::RUNNINGLOCK_LOCK): {
return LockStub(data);
}
case static_cast<int>(IPowerMgr::RUNNINGLOCK_UNLOCK): {
return UnLockStub(data);
}
case static_cast<int>(IPowerMgr::RUNNINGLOCK_SET_WORK_TRIGGER_LIST): {
return SetWorkTriggerListStub(data);
}
case static_cast<int>(IPowerMgr::PROXY_RUNNINGLOCK): {
return ProxyRunningLockStub(data);
}
case static_cast<int>(IPowerMgr::RUNNINGLOCK_ISUSED): {
return IsUsedStub(data, reply);
}
case static_cast<int>(IPowerMgr::REG_POWER_STATE_CALLBACK): {
return RegisterPowerStateCallbackStub(data);
}
case static_cast<int>(IPowerMgr::UNREG_POWER_STATE_CALLBACK): {
return UnRegisterPowerStateCallbackStub(data);
}
case static_cast<int>(IPowerMgr::REG_SHUTDOWN_CALLBACK): {
return RegisterShutdownCallbackStub(data);
}
case static_cast<int>(IPowerMgr::UNREG_SHUTDOWN_CALLBACK): {
return UnRegisterShutdownCallbackStub(data);
}
default: {
return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
}
}
return ERR_OK;
}
int32_t PowerMgrStub::LockStub(MessageParcel& data)
{
sptr<IRemoteObject> token = data.ReadRemoteObject();
RETURN_IF_WITH_RET((token == nullptr), E_READ_PARCEL_ERROR);
std::unique_ptr<RunningLockInfo> runningLockInfo(data.ReadParcelable<RunningLockInfo>());
RETURN_IF_WITH_RET((runningLockInfo == nullptr), E_READ_PARCEL_ERROR);
uint32_t timeOutMs = 0;
READ_PARCEL_WITH_RET(data, Uint32, timeOutMs, E_READ_PARCEL_ERROR);
Lock(token, *runningLockInfo, timeOutMs);
return ERR_OK;
}
int32_t PowerMgrStub::UnLockStub(MessageParcel& data)
{
sptr<IRemoteObject> token = data.ReadRemoteObject();
RETURN_IF_WITH_RET((token == nullptr), E_READ_PARCEL_ERROR);
UnLock(token);
return ERR_OK;
}
int32_t PowerMgrStub::IsUsedStub(MessageParcel& data, MessageParcel& reply)
{
sptr<IRemoteObject> token = data.ReadRemoteObject();
RETURN_IF_WITH_RET((token == nullptr), E_READ_PARCEL_ERROR);
bool ret = IsUsed(token);
WRITE_PARCEL_WITH_RET(reply, Bool, ret, E_WRITE_PARCEL_ERROR);
return ERR_OK;
}
int32_t PowerMgrStub::SetWorkTriggerListStub(MessageParcel& data)
{
sptr<IRemoteObject> token = data.ReadRemoteObject();
RETURN_IF_WITH_RET((token == nullptr), E_READ_PARCEL_ERROR);
WorkTriggerList workTriggerList;
RunningLockInfo::ReadFromParcelWorkTriggerList(data, workTriggerList);
SetWorkTriggerList(token, workTriggerList);
return ERR_OK;
}
int32_t PowerMgrStub::ProxyRunningLockStub(MessageParcel& data)
{
bool proxyLock = false;
pid_t uid;
pid_t pid;
READ_PARCEL_WITH_RET(data, Bool, proxyLock, E_READ_PARCEL_ERROR);
READ_PARCEL_WITH_RET(data, Int32, uid, E_READ_PARCEL_ERROR);
READ_PARCEL_WITH_RET(data, Int32, pid, E_READ_PARCEL_ERROR);
ProxyRunningLock(proxyLock, uid, pid);
return ERR_OK;
}
int32_t PowerMgrStub::RebootDeviceStub(MessageParcel& data)
{
std::string reason = Str16ToStr8(data.ReadString16());
RebootDevice(reason);
return ERR_OK;
}
int32_t PowerMgrStub::ShutDownDeviceStub(MessageParcel& data)
{
std::string reason = Str16ToStr8(data.ReadString16());
ShutDownDevice(reason);
return ERR_OK;
}
int32_t PowerMgrStub::WakeupDeviceStub(MessageParcel& data)
{
int64_t time = 0;
uint32_t reason = 0;
READ_PARCEL_WITH_RET(data, Int64, time, E_READ_PARCEL_ERROR);
READ_PARCEL_WITH_RET(data, Uint32, reason, E_READ_PARCEL_ERROR);
std::string details = Str16ToStr8(data.ReadString16());
WakeupDevice(time, static_cast<WakeupDeviceType>(reason), details);
return ERR_OK;
}
int32_t PowerMgrStub::SuspendDeviceStub(MessageParcel& data)
{
int64_t time = 0;
uint32_t reason = 0;
bool suspendImmed = true;
READ_PARCEL_WITH_RET(data, Int64, time, E_READ_PARCEL_ERROR);
READ_PARCEL_WITH_RET(data, Uint32, reason, E_READ_PARCEL_ERROR);
READ_PARCEL_WITH_RET(data, Bool, suspendImmed, E_READ_PARCEL_ERROR);
SuspendDevice(time, static_cast<SuspendDeviceType>(reason), suspendImmed);
return ERR_OK;
}
int32_t PowerMgrStub::RefreshActivityStub(MessageParcel& data)
{
int64_t time = 0;
uint32_t type = 0;
bool needChangeBacklight = true;
READ_PARCEL_WITH_RET(data, Int64, time, E_READ_PARCEL_ERROR);
READ_PARCEL_WITH_RET(data, Uint32, type, E_READ_PARCEL_ERROR);
READ_PARCEL_WITH_RET(data, Bool, needChangeBacklight, E_READ_PARCEL_ERROR);
RefreshActivity(time, static_cast<UserActivityType>(type), needChangeBacklight);
return ERR_OK;
}
int32_t PowerMgrStub::ForceSuspendDeviceStub(MessageParcel& data, MessageParcel& reply)
{
bool ret = false;
int64_t time = 0;
READ_PARCEL_WITH_RET(data, Int64, time, E_READ_PARCEL_ERROR);
ret = ForceSuspendDevice(time);
if (!reply.WriteBool(ret)) {
POWER_HILOGE(MODULE_SERVICE, "PowerMgrStub:: ForceSuspendDevice Writeback Fail!");
return E_WRITE_PARCEL_ERROR;
}
return ERR_OK;
}
int32_t PowerMgrStub::IsScreeOnStub(MessageParcel& reply)
{
bool ret = false;
ret = IsScreenOn();
if (!reply.WriteBool(ret)) {
POWER_HILOGE(MODULE_SERVICE, "PowerMgrStub:: IsScreenOn Writeback Fail!");
return E_WRITE_PARCEL_ERROR;
}
return ERR_OK;
}
int32_t PowerMgrStub::RegisterPowerStateCallbackStub(MessageParcel& data)
{
sptr<IRemoteObject> obj = data.ReadRemoteObject();
RETURN_IF_WITH_RET((obj == nullptr), E_READ_PARCEL_ERROR);
sptr<IPowerStateCallback> callback = iface_cast<IPowerStateCallback>(obj);
RETURN_IF_WITH_RET((callback == nullptr), E_READ_PARCEL_ERROR);
RegisterPowerStateCallback(callback);
return ERR_OK;
}
int32_t PowerMgrStub::UnRegisterPowerStateCallbackStub(MessageParcel& data)
{
sptr<IRemoteObject> obj = data.ReadRemoteObject();
RETURN_IF_WITH_RET((obj == nullptr), E_READ_PARCEL_ERROR);
sptr<IPowerStateCallback> callback = iface_cast<IPowerStateCallback>(obj);
RETURN_IF_WITH_RET((callback == nullptr), E_READ_PARCEL_ERROR);
UnRegisterPowerStateCallback(callback);
return ERR_OK;
}
int32_t PowerMgrStub::RegisterShutdownCallbackStub(MessageParcel& data)
{
sptr<IRemoteObject> obj = data.ReadRemoteObject();
RETURN_IF_WITH_RET((obj == nullptr), E_READ_PARCEL_ERROR);
sptr<IShutdownCallback> callback = iface_cast<IShutdownCallback>(obj);
RETURN_IF_WITH_RET((callback == nullptr), E_READ_PARCEL_ERROR);
RegisterShutdownCallback(callback);
return ERR_OK;
}
int32_t PowerMgrStub::UnRegisterShutdownCallbackStub(MessageParcel& data)
{
sptr<IRemoteObject> obj = data.ReadRemoteObject();
RETURN_IF_WITH_RET((obj == nullptr), E_READ_PARCEL_ERROR);
sptr<IShutdownCallback> callback = iface_cast<IShutdownCallback>(obj);
RETURN_IF_WITH_RET((callback == nullptr), E_READ_PARCEL_ERROR);
UnRegisterShutdownCallback(callback);
return ERR_OK;
}
} // namespace PowerMgr
} // namespace OHOS

View File

@ -0,0 +1,48 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "power_state_callback_proxy.h"
#include <ipc_types.h>
#include <message_parcel.h>
#include "power_common.h"
namespace OHOS {
namespace PowerMgr {
void PowerStateCallbackProxy::OnPowerStateChanged(PowerState state)
{
sptr<IRemoteObject> remote = Remote();
RETURN_IF(remote == nullptr);
MessageParcel data;
MessageParcel reply;
MessageOption option;
if (!data.WriteInterfaceToken(PowerStateCallbackProxy::GetDescriptor())) {
POWER_HILOGE(MODULE_INNERKIT, "PowerMgrProxy::%{public}s write descriptor failed!", __func__);
return;
}
WRITE_PARCEL_NO_RET(data, Uint32, static_cast<uint32_t>(state));
int ret = remote->SendRequest(static_cast<int>(IPowerStateCallback::POWER_STATE_CHANGED),
data, reply, option);
if (ret != ERR_OK) {
POWER_HILOGE(MODULE_INNERKIT, "PowerMgrProxy::%{public}s SendRequest is failed, error code: %d", __func__, ret);
}
}
} // namespace PowerMgr
} // namespace OHOS

View File

@ -0,0 +1,54 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "power_state_callback_stub.h"
#include <message_parcel.h>
#include "power_common.h"
#include "power_state_callback_proxy.h"
namespace OHOS {
namespace PowerMgr {
int PowerStateCallbackStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply,
MessageOption &option)
{
POWER_HILOGD(MODULE_SERVICE, "PowerMgrStub::OnRemoteRequest, cmd = %d, flags= %d", code, option.GetFlags());
std::u16string descripter = PowerStateCallbackStub::GetDescriptor();
std::u16string remoteDescripter = data.ReadInterfaceToken();
if (descripter != remoteDescripter) {
POWER_HILOGE(MODULE_SERVICE, "PowerMgrStub::OnRemoteRequest failed, descriptor is not matched!");
return E_GET_POWER_SERVICE_FAILED;
}
switch (code) {
case static_cast<int>(IPowerStateCallback::POWER_STATE_CHANGED): {
return OnPowerStateChangedStub(data);
}
default:
return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
}
return ERR_OK;
}
int32_t PowerStateCallbackStub::OnPowerStateChangedStub(MessageParcel& data)
{
uint32_t type;
READ_PARCEL_WITH_RET(data, Uint32, type, E_READ_PARCEL_ERROR);
OnPowerStateChanged(static_cast<PowerState>(type));
return ERR_OK;
}
} // namespace PowerMgr
} // namespace OHOS

36
utils/BUILD.gn Normal file
View File

@ -0,0 +1,36 @@
# 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.
import("//base/powermgr/power_manager/powermgr.gni")
config("utils_config") {
include_dirs = [
"native/include",
"//utils/native/base/include",
]
}
ohos_source_set("powermgr_utils") {
sources = [
"native/src/permission.cpp",
"native/src/sys_param.cpp",
]
public_configs = [ ":utils_config" ]
deps = [ "//utils/native/base:utils" ]
external_deps = [ "startup_l2:syspara" ]
part_name = "${powermgr_native_part_name}"
}

View File

@ -0,0 +1,109 @@
/*
* 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 POWERMGR_HILOG_WRAPPER_H
#define POWERMGR_HILOG_WRAPPER_H
#define CONFIG_HILOG
#ifdef CONFIG_HILOG
#include "hilog/log.h"
namespace OHOS {
namespace PowerMgr {
#define __FILENAME__ (__builtin_strrchr(__FILE__, '/') ? __builtin_strrchr(__FILE__, '/') + 1 : __FILE__)
#define __FORMATED(fmt, ...) "[%{public}s] %{public}s# " fmt, __FILENAME__, __FUNCTION__, ##__VA_ARGS__
#ifdef POWER_HILOGF
#undef POWER_HILOGF
#endif
#ifdef POWER_HILOGE
#undef POWER_HILOGE
#endif
#ifdef POWER_HILOGW
#undef POWER_HILOGW
#endif
#ifdef POWER_HILOGI
#undef POWER_HILOGI
#endif
#ifdef POWER_HILOGD
#undef POWER_HILOGD
#endif
// param of log interface, such as POWER_HILOGF.
enum PowerMgrSubModule {
MODULE_INNERKIT = 0,
MODULE_SERVICE,
MODULE_JAVAKIT, // java kit, defined to avoid repeated use of domain.
MODULE_JNI,
MODULE_BATT_INNERKIT, // below used by battery service
MODULE_BATT_SERVICE,
MODULE_BATTERYD,
MODULE_COMMON, // used both by battery and powermgr
MODULE_JS_NAPI,
POWERMGR_MODULE_BUTT,
};
// 0xD002900: subsystem:PowerMgr module:PowerManager, 8 bits reserved.
static constexpr unsigned int BASE_POWERMGR_DOMAIN_ID = 0xD002900;
enum PowerMgrDomainId {
POWERMGR_INNERKIT_DOMAIN = BASE_POWERMGR_DOMAIN_ID + MODULE_INNERKIT,
POWERMGR_SERVICE_DOMAIN,
POWERMGR_JAVAKIT_DOMAIN,
BATT_INNERKIT_DOMAIN,
BATT_SERVICE_DOMAIN,
BATTERYD_DOMAIN,
COMMON_DOMAIN,
POWERMGR_JS_NAPI,
POWERMGR_BUTT,
};
static constexpr OHOS::HiviewDFX::HiLogLabel POWER_MGR_LABEL[POWERMGR_MODULE_BUTT] = {
{LOG_CORE, POWERMGR_INNERKIT_DOMAIN, "PowerMgrClient"},
{LOG_CORE, POWERMGR_SERVICE_DOMAIN, "PowerMgrService"},
{LOG_CORE, POWERMGR_JAVAKIT_DOMAIN, "PowerMgrJavaService"},
{LOG_CORE, POWERMGR_INNERKIT_DOMAIN, "PowerMgrJni"},
{LOG_CORE, BATT_INNERKIT_DOMAIN, "BatterySrvClient"},
{LOG_CORE, BATT_SERVICE_DOMAIN, "BatteryService"},
{LOG_CORE, BATTERYD_DOMAIN, "Batteryd"},
{LOG_CORE, COMMON_DOMAIN, "PowerMgrCommon"},
{LOG_CORE, POWERMGR_JS_NAPI, "PowerMgrJSNAPI"},
};
// In order to improve performance, do not check the module range.
// Besides, make sure module is less than POWERMGR_MODULE_BUTT.
#define POWER_HILOGF(module, ...) (void)OHOS::HiviewDFX::HiLog::Fatal(POWER_MGR_LABEL[module], __FORMATED(__VA_ARGS__))
#define POWER_HILOGE(module, ...) (void)OHOS::HiviewDFX::HiLog::Error(POWER_MGR_LABEL[module], __FORMATED(__VA_ARGS__))
#define POWER_HILOGW(module, ...) (void)OHOS::HiviewDFX::HiLog::Warn(POWER_MGR_LABEL[module], __FORMATED(__VA_ARGS__))
#define POWER_HILOGI(module, ...) (void)OHOS::HiviewDFX::HiLog::Info(POWER_MGR_LABEL[module], __FORMATED(__VA_ARGS__))
#define POWER_HILOGD(module, ...) (void)OHOS::HiviewDFX::HiLog::Debug(POWER_MGR_LABEL[module], __FORMATED(__VA_ARGS__))
} // namespace PowerMgr
} // namespace OHOS
#else
#define POWER_HILOGF(...)
#define POWER_HILOGE(...)
#define POWER_HILOGW(...)
#define POWER_HILOGI(...)
#define POWER_HILOGD(...)
#endif // CONFIG_HILOG
#endif // POWERMGR_HILOG_WRAPPER_H

View File

@ -0,0 +1,30 @@
/*
* 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 POWERMGR_PERMISSION_H
#define POWERMGR_PERMISSION_H
#include <string>
namespace OHOS {
namespace PowerMgr {
class Permission {
public:
static bool CheckSelfPermission(const std::string& perm);
static bool CheckCallingPermission(const std::string& perm);
};
} // namespace PowerMgr
} // namespace OHOS
#endif // POWERMGR_PERMISSION_H

View File

@ -0,0 +1,77 @@
/*
* 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 POWERMGR_POWER_COMMON_H
#define POWERMGR_POWER_COMMON_H
#include <cstdint>
#include <type_traits>
#include "hilog_wrapper.h"
#include "power_mgr_errors.h"
namespace OHOS {
namespace PowerMgr {
#define RETURN_IF_WITH_RET(cond, retval) if (cond) {return (retval);}
#define RETURN_IF(cond) if (cond) {return;}
#define RETURN_IF_WITH_LOG(cond, loginfo) \
do { \
if (cond) { \
POWER_HILOGE(MODULE_COMMON, "%{public}s "#loginfo" ", __func__); \
return; \
} \
} while (0) \
#define READ_PARCEL_NO_RET(parcel, type, out) \
do { \
if (!(parcel).Read##type(out)) { \
POWER_HILOGE(MODULE_COMMON, "%{public}s read "#out" failed", __func__); \
return; \
} \
} while (0) \
#define WRITE_PARCEL_NO_RET(parcel, type, data) \
do { \
if (!(parcel).Write##type(data)) { \
POWER_HILOGE(MODULE_COMMON, "%{public}s write "#data" failed", __func__); \
return; \
} \
} while (0) \
#define READ_PARCEL_WITH_RET(parcel, type, out, retval) \
do { \
if (!(parcel).Read##type(out)) { \
POWER_HILOGE(MODULE_COMMON, "%{public}s read "#out" failed", __func__); \
return (retval); \
} \
} while (0) \
#define WRITE_PARCEL_WITH_RET(parcel, type, data, retval) \
do { \
if (!(parcel).Write##type(data)) { \
POWER_HILOGE(MODULE_COMMON, "%{public}s write "#data" failed", __func__); \
return (retval); \
} \
} while (0)
template<typename E>
constexpr auto ToUnderlying(E e) noexcept
{
return static_cast<std::underlying_type_t<E>>(e);
}
} // namespace PowerMgr
} // namespace OHOS
#endif // POWERMGR_POWER_COMMON_H

View File

@ -0,0 +1,48 @@
/*
* 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 POWERMGR_POWER_MGR_ERRORS_H
#define POWERMGR_POWER_MGR_ERRORS_H
#include <errors.h>
namespace OHOS {
namespace PowerMgr {
enum {
/**
* Module type: Power Manager Service
*/
POWER_MODULE_TYPE_SERVICE = 0,
/**
* Module type: Power Manager Kit
*/
POWER_MODULE_TYPE_KIT = 1
};
// offset of powermgr error, only be used in this file.
constexpr ErrCode POWERFWK_SERVICE_ERR_OFFSET = ErrCodeOffset(SUBSYS_POWERMNG, POWER_MODULE_TYPE_SERVICE);
enum {
E_WRITE_PARCEL_ERROR = POWERFWK_SERVICE_ERR_OFFSET,
E_READ_PARCEL_ERROR,
E_GET_SYSTEM_ABILITY_MANAGER_FAILED,
E_GET_POWER_SERVICE_FAILED,
E_ADD_DEATH_RECIPIENT_FAILED,
E_INNER_ERR
};
} // namespace PowerMgr
} // namespace OHOS
#endif // POWERMGR_POWER_MGR_ERRORS_H

View File

@ -0,0 +1,74 @@
/*
* 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 POWERMGR_SP_SINGLETON_H
#define POWERMGR_SP_SINGLETON_H
#include "nocopyable.h"
#include <mutex>
#include <memory>
#include <refbase.h>
namespace OHOS {
namespace PowerMgr {
#define DECLARE_DELAYED_SP_SINGLETON(MyClass)\
public:\
~MyClass();\
private:\
friend DelayedSpSingleton<MyClass>;\
MyClass();
template<typename T>
class DelayedSpSingleton : public NoCopyable {
public:
static sptr<T> GetInstance();
static void DestroyInstance();
private:
static sptr<T> instance_;
static std::mutex mutex_;
};
template<typename T>
sptr<T> DelayedSpSingleton<T>::instance_ = nullptr;
template<typename T>
std::mutex DelayedSpSingleton<T>::mutex_;
template<typename T>
sptr<T> DelayedSpSingleton<T>::GetInstance()
{
if (!instance_) {
std::lock_guard<std::mutex> lock(mutex_);
if (instance_ == nullptr) {
instance_ = new T();
}
}
return instance_;
}
template<typename T>
void DelayedSpSingleton<T>::DestroyInstance()
{
std::lock_guard<std::mutex> lock(mutex_);
if (instance_) {
instance_.clear();
instance_ = nullptr;
}
}
} // namespace PowerMgr
} // namespace OHOS
#endif

View File

@ -0,0 +1,55 @@
/*
* 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 POWERMGR_SYS_PARAM_H
#define POWERMGR_SYS_PARAM_H
#include <string>
namespace OHOS {
namespace PowerMgr {
enum class DeviceType : int32_t {
DEVICE_UNKNOWN = -1,
DEVICE_PHONE = 0,
DEVICE_TV,
DEVICE_SPEAKER,
DEVICE_GLASSES,
DEVICE_WATCH,
DEVICE_CAR,
DEVICE_EARPHONE,
DEVICE_PC,
DEVICE_TABLET,
};
class SysParam {
public:
static inline DeviceType GetDeviceTypeParam()
{
return DEVICE_TYPE;
}
static inline bool IsDeviceType(DeviceType type)
{
return type == DEVICE_TYPE;
}
private:
static DeviceType InitDeviceType();
static const DeviceType DEVICE_TYPE;
};
} // namespace PowerMgr
} // namespace OHOS
#endif // POWERMGR_SYS_PARAM_H

View File

@ -0,0 +1,32 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "permission.h"
using namespace std;
namespace OHOS {
namespace PowerMgr {
bool Permission::CheckSelfPermission(const string& perm __unused)
{
return true;
}
bool Permission::CheckCallingPermission(const string& perm __unused)
{
return true;
}
} // namespace PowerMgr
} // namespace OHOS

View File

@ -0,0 +1,43 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "sys_param.h"
#include <unordered_map>
#include <parameter.h>
using namespace std;
namespace OHOS {
namespace PowerMgr {
const DeviceType SysParam::DEVICE_TYPE = InitDeviceType();
DeviceType SysParam::InitDeviceType()
{
static const unordered_map<string, DeviceType> DEVICE_TYPE_MAP {
{ "default", DeviceType::DEVICE_PHONE },
{ "phone", DeviceType::DEVICE_PHONE },
{ "watch", DeviceType::DEVICE_WATCH },
{ "tv", DeviceType::DEVICE_TV },
{ "car", DeviceType::DEVICE_CAR },
{ "tablet", DeviceType::DEVICE_TABLET },
};
static string type = GetDeviceType();
auto it = DEVICE_TYPE_MAP.find(type);
return (it != DEVICE_TYPE_MAP.end()) ? it->second : DeviceType::DEVICE_UNKNOWN;
}
} // namespace PowerMgr
} // namespace OHOS