update OpenHarmony 2.0 Canary

This commit is contained in:
mamingshuai 2021-06-02 00:03:48 +08:00
parent 66a9a70f6a
commit 93accfc09f
56 changed files with 4940 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_battery_manager
#### Description
Battery 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/)

56
README.md Normal file → Executable file
View File

@ -1,37 +1,43 @@
# powermgr_battery_manager
# battery\_manager<a name="EN-US_TOPIC_0000001124094823"></a>
#### 介绍
Battery manager | 电池服务模块
- [Introduction](#section11660541593)
- [Directory Structure](#section19472752217)
- [Repositories Involved](#section63151229062)
#### 软件架构
软件架构说明
## Introduction<a name="section11660541593"></a>
Battery Manager provides the following functionalities:
#### 安装教程
1. Obtaining battery information
2. Obtaining the battery charging status and the remaining battery power
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/battery_manager
├── hdi # HDI code
│ ├── api # HDI APIs
│ └── client # HDI client
│ └── service # HDI service
├── 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

45
README_zh.md Executable file
View File

@ -0,0 +1,45 @@
# 电池服务组件<a name="ZH-CN_TOPIC_0000001124094823"></a>
- [简介](#section11660541593)
- [目录](#section19472752217)
- [相关仓](#section63151229062)
## 简介<a name="section11660541593"></a>
电池服务组件提供如下功能:
1. 电池信息查询。
2. 充放电状态查询。
**图 1** 电源管理子系统架构图<a name="fig106301571239"></a>
![](figures/power-management-subsystem-architecture.png "电源管理子系统架构图")
## 目录<a name="section19472752217"></a>
```
base/powermgr/battery_manager
├── hdi # HDI层
│ ├── api # HDI接口
│ └── client # HDI客户端
│ └── service # HDI服务端
├── 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

17
batterymgr.gni Normal file
View File

@ -0,0 +1,17 @@
# 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")
battery_manager_path = "//base/powermgr/battery_manager"
utils_path = "${battery_manager_path}/utils"

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

21
hdi/BUILD.gn Normal file
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("//build/ohos.gni")
group("hdi_group") {
deps = [
"client:batteryd_client",
"service:batteryd",
]
}

View File

@ -0,0 +1,50 @@
/*
* 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 BATTERYD_API_H
#define BATTERYD_API_H
#include <stdlib.h>
enum BatterydCmd {
CMD_BIND_BATTERY_SUBSCRIBER = 0,
CMD_UNBIND_BATTERY_SUBSCRIBER,
CMD_NOTIFY_SUBSCRIBER,
CMD_GET_CAPACITY,
CMD_GET_VOLTAGE,
CMD_GET_TEMPERATURE,
CMD_GET_HEALTH_STATE,
CMD_GET_PLUGGED_TYPE,
CMD_GET_CHARGE_STATE,
CMD_GET_PRESENT,
CMD_GET_TECHNOLOGY
};
// Keep it same as the inner kit battery_info.h
struct BatterydInfo {
int32_t capacity_;
int32_t voltage_;
int32_t temperature_;
int32_t healthState_;
int32_t pluggedType_;
int32_t pluggedMaxCurrent_;
int32_t pluggedMaxVoltage_;
int32_t chargeState_;
int32_t chargeCounter_;
int8_t present_;
const char *technology_;
};
#endif // BATTERYD_API_H

49
hdi/client/BUILD.gn Normal file
View File

@ -0,0 +1,49 @@
# 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/battery_manager/batterymgr.gni")
import("//build/ohos.gni")
import("//drivers/adapter/uhdf2/uhdf.gni")
config("batteryd_client_public_config") {
include_dirs = [
"include",
"${battery_manager_path}/hdi/api/include",
"${battery_manager_path}/interfaces/innerkits/native/include",
]
}
ohos_shared_library("batteryd_client") {
sources = [
"src/batteryd_client.cpp",
"src/batteryd_subscriber.cpp",
]
configs = [ "${utils_path}:utils_config" ]
public_configs = [ ":batteryd_client_public_config" ]
deps = [
"${hdf_uhdf_path}/hdi:libhdi",
"${hdf_uhdf_path}/host:libhdf_host",
"${hdf_uhdf_path}/osal:libhdf_utils",
"//utils/native/base:utils",
]
external_deps = [
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
]
part_name = "battery_manager_native"
}

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 BATTERYD_CLIENT_H
#define BATTERYD_CLIENT_H
#include "battery_info.h"
#include "batteryd_subscriber.h"
#include "sp_singleton.h"
namespace OHOS {
namespace PowerMgr {
class BatterydClient {
public:
static ErrCode BindBatterydSubscriber(const sptr<BatterydSubscriber> &subscriber);
static ErrCode UnbindBatterydSubscriber();
static int32_t GetCapacity();
static int32_t GetVoltage();
static int32_t GetTemperature();
static BatteryHealthState GetHealthState();
static BatteryPluggedType GetPluggedType();
static BatteryChargeState GetChargeState();
static bool GetPresent();
static std::string GetTechnology();
private:
static sptr<IRemoteObject> GetBatterydService();
static ErrCode DoDispatch(uint32_t cmd, MessageParcel &data, MessageParcel &reply);
};
} // namespace PowerMgr
} // namespace OHOS
#endif // BATTERYD_CLIENT_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 BATTERYD_SUBSCRIBER_H
#define BATTERYD_SUBSCRIBER_H
#include "battery_info.h"
#include "batteryd_api.h"
#include "ipc_object_stub.h"
namespace OHOS {
namespace PowerMgr {
class BatterydSubscriber : public IPCObjectStub {
public:
explicit BatterydSubscriber() : IPCObjectStub(u"ohos.powermgr.IBatterydSubscriber") {};
virtual ~BatterydSubscriber() = default;
virtual int32_t Update(const BatteryInfo &info) = 0;
int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override;
private:
static const BatteryInfo &ParserBatteryInfo(MessageParcel &data, MessageParcel &reply, MessageOption &option);
};
} // namespace PowerMgr
} // namespace OHOS
#endif // BATTERYD_SUBSCRIBER_H

View File

@ -0,0 +1,194 @@
/*
* 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 "batteryd_client.h"
#include "batteryd_api.h"
#include "power_common.h"
#include "iservmgr_hdi.h"
namespace OHOS {
namespace PowerMgr {
using OHOS::HDI::ServiceManager::V1_0::IServiceManager;
namespace {
const std::string BATTERYD_SERVICE = "batteryd";
}
sptr<IRemoteObject> BatterydClient::GetBatterydService()
{
auto serviceManager = IServiceManager::Get();
if (serviceManager == nullptr) {
POWER_HILOGW(MODULE_BATTERYD, "service manager is nullptr");
return nullptr;
}
auto batterydService = serviceManager->GetService(BATTERYD_SERVICE.c_str());
if (batterydService == nullptr) {
POWER_HILOGW(MODULE_BATTERYD, "batteryd service is nullptr");
return nullptr;
}
return batterydService;
}
ErrCode BatterydClient::DoDispatch(uint32_t cmd, MessageParcel &data, MessageParcel &reply)
{
POWER_HILOGD(MODULE_BATTERYD, "Start to dispatch cmd: %{public}d", cmd);
auto batteryd = GetBatterydService();
if (batteryd == nullptr) {
return ERR_NO_INIT;
}
MessageOption option;
auto ret = batteryd->SendRequest(cmd, data, reply, option);
if (ret != ERR_OK) {
POWER_HILOGE(MODULE_BATTERYD, "failed to send request, cmd: %{public}d, ret: %{public}d", cmd, ret);
return ret;
}
return ERR_OK;
}
ErrCode BatterydClient::BindBatterydSubscriber(const sptr<BatterydSubscriber> &subscriber)
{
POWER_HILOGD(MODULE_BATTERYD, "BindBatterydSubscriber enter");
if (subscriber == nullptr) {
POWER_HILOGW(MODULE_BATTERYD, "subscriber is nullptr");
return ERR_INVALID_VALUE;
}
MessageParcel data;
MessageParcel reply;
data.WriteRemoteObject(subscriber);
return DoDispatch(CMD_BIND_BATTERY_SUBSCRIBER, data, reply);
}
ErrCode BatterydClient::UnbindBatterydSubscriber()
{
POWER_HILOGD(MODULE_BATTERYD, "UnbindBatterydSubscriber enter");
MessageParcel data;
MessageParcel reply;
return DoDispatch(CMD_UNBIND_BATTERY_SUBSCRIBER, data, reply);
}
int32_t BatterydClient::GetCapacity()
{
POWER_HILOGD(MODULE_BATTERYD, "GetCapacity enter");
MessageParcel data;
MessageParcel reply;
ErrCode ret = DoDispatch(CMD_GET_CAPACITY, data, reply);
if (FAILED(ret)) {
POWER_HILOGW(MODULE_BATTERYD, "CMD_GET_CAPACITY failed, return INVALID_BATT_INT_VALUE");
return INVALID_BATT_INT_VALUE;
}
int32_t capacity = reply.ReadInt32();
return capacity;
}
int32_t BatterydClient::GetVoltage()
{
POWER_HILOGD(MODULE_BATTERYD, "GetVoltage enter");
MessageParcel data;
MessageParcel reply;
ErrCode ret = DoDispatch(CMD_GET_VOLTAGE, data, reply);
if (FAILED(ret)) {
POWER_HILOGW(MODULE_BATTERYD, "CMD_GET_VOLTAGE failed, return INVALID_BATT_INT_VALUE");
return INVALID_BATT_INT_VALUE;
}
int32_t voltage = reply.ReadInt32();
return voltage;
}
int32_t BatterydClient::GetTemperature()
{
POWER_HILOGD(MODULE_BATTERYD, "GetTemperature enter");
MessageParcel data;
MessageParcel reply;
ErrCode ret = DoDispatch(CMD_GET_TEMPERATURE, data, reply);
if (FAILED(ret)) {
POWER_HILOGW(MODULE_BATTERYD, "CMD_GET_TEMPERATURE failed, return INVALID_BATT_TEMP_VALUE");
return INVALID_BATT_TEMP_VALUE;
}
int32_t temperature = reply.ReadInt32();
return temperature;
}
BatteryHealthState BatterydClient::GetHealthState()
{
POWER_HILOGD(MODULE_BATTERYD, "GetHealthState enter");
MessageParcel data;
MessageParcel reply;
ErrCode ret = DoDispatch(CMD_GET_HEALTH_STATE, data, reply);
if (FAILED(ret)) {
POWER_HILOGW(MODULE_BATTERYD, "CMD_GET_HEALTH_STATE failed, return HEALTH_STATE_UNKNOWN");
return BatteryHealthState::HEALTH_STATE_UNKNOWN;
}
int32_t healthState = reply.ReadInt32();
return (BatteryHealthState)healthState;
}
BatteryPluggedType BatterydClient::GetPluggedType()
{
POWER_HILOGD(MODULE_BATTERYD, "GetPluggedType enter");
MessageParcel data;
MessageParcel reply;
ErrCode ret = DoDispatch(CMD_GET_PLUGGED_TYPE, data, reply);
if (FAILED(ret)) {
POWER_HILOGW(MODULE_BATTERYD, "CMD_GET_PLUGGED_TYPE failed, return PLUGGED_TYPE_NONE");
return BatteryPluggedType::PLUGGED_TYPE_NONE;
}
int32_t pluggedType = reply.ReadInt32();
return (BatteryPluggedType)pluggedType;
}
BatteryChargeState BatterydClient::GetChargeState()
{
POWER_HILOGD(MODULE_BATTERYD, "GetChargeState enter");
MessageParcel data;
MessageParcel reply;
ErrCode ret = DoDispatch(CMD_GET_CHARGE_STATE, data, reply);
if (FAILED(ret)) {
POWER_HILOGW(MODULE_BATTERYD, "CMD_GET_CHARGE_STATE failed, return CHARGE_STATE_NONE");
return BatteryChargeState::CHARGE_STATE_NONE;
}
int32_t chargeState = reply.ReadInt32();
return (BatteryChargeState)chargeState;
}
bool BatterydClient::GetPresent()
{
POWER_HILOGD(MODULE_BATTERYD, "GetPresent enter");
MessageParcel data;
MessageParcel reply;
ErrCode ret = DoDispatch(CMD_GET_PRESENT, data, reply);
if (FAILED(ret)) {
POWER_HILOGW(MODULE_BATTERYD, "CMD_GET_PRESENT failed, return INVALID_BATT_BOOL_VALUE");
return INVALID_BATT_BOOL_VALUE;
}
bool present = (bool)reply.ReadInt8();
return present;
}
std::string BatterydClient::GetTechnology()
{
POWER_HILOGD(MODULE_BATTERYD, "GetTechnology enter");
MessageParcel data;
MessageParcel reply;
ErrCode ret = DoDispatch(CMD_GET_TECHNOLOGY, data, reply);
if (FAILED(ret)) {
POWER_HILOGW(MODULE_BATTERYD, "CMD_GET_TECHNOLOGY failed, return INVALID_STRING_VALUE");
return INVALID_STRING_VALUE;
}
std::string technology = reply.ReadCString();
return technology;
}
} // namespace PowerMgr
} // namespace OHOS

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.
*/
#include "batteryd_subscriber.h"
#include "power_common.h"
namespace OHOS {
namespace PowerMgr {
int BatterydSubscriber::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply,
MessageOption &option)
{
switch (code) {
case CMD_NOTIFY_SUBSCRIBER: {
const BatteryInfo &info = ParserBatteryInfo(data, reply, option);
return Update(info);
}
default: {
POWER_HILOGW(MODULE_BATTERYD, "no specific cmd for code: %{public}d", code);
return ERR_INVALID_OPERATION;
}
}
}
const BatteryInfo &BatterydSubscriber::ParserBatteryInfo(MessageParcel &data, MessageParcel &reply,
MessageOption &option)
{
auto builder = std::make_shared<BatteryInfo::Builder>();
auto *info = builder->SetCapacity(data.ReadInt32())
->SetVoltage(data.ReadInt32())
->SetTemperature(data.ReadInt32())
->SetHealthState((BatteryHealthState)data.ReadInt32())
->SetPluggedType((BatteryPluggedType)data.ReadInt32())
->SetPluggedMaxCurrent(data.ReadInt32())
->SetPluggedMaxVoltage(data.ReadInt32())
->SetChargeState((BatteryChargeState)data.ReadInt32())
->SetChargeCounter(data.ReadInt32())
->SetPresent((bool)data.ReadInt8())
->SetTechnology(data.ReadCString())
->Build();
return *info;
}
} // namespace PowerMgr
} // namespace OHOS

58
hdi/service/BUILD.gn Normal file
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/battery_manager/batterymgr.gni")
import("//build/ohos.gni")
import("//drivers/adapter/uhdf2/uhdf.gni")
config("batteryd_private_config") {
include_dirs = [
"//drivers/ability/sbuf/include",
"//drivers/framework/include",
"//drivers/framework/include/core",
]
}
config("batteryd_public_config") {
include_dirs = [
"include",
"${battery_manager_path}/hdi/api/include",
]
}
ohos_shared_library("batteryd") {
sources = [
"src/batteryd.c",
"src/batteryd_dispatcher.c",
"src/batteryd_parser.c",
"src/batteryd_publisher.c",
]
configs = [
"${utils_path}:utils_config",
":batteryd_private_config",
]
public_configs = [ ":batteryd_public_config" ]
deps = [
"${hdf_uhdf_path}/host:libhdf_host",
"${hdf_uhdf_path}/ipc:libhdf_ipc_adapter",
"${hdf_uhdf_path}/osal:libhdf_utils",
"//utils/native/base:utils",
]
external_deps = [ "hiviewdfx_hilog_native:libhilog" ]
part_name = "battery_manager_native"
}

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 BATTERYD_H
#define BATTERYD_H
#include "batteryd_api.h"
#include "core/hdf_device_desc.h"
struct BatterydService {
struct IDeviceIoService ioService;
struct HdfDeviceObject *device;
struct BatterydSubscriber *subscriber;
int32_t ueventFd;
};
int32_t BindBatterySubscriber(struct BatterydService *service, struct BatterydSubscriber *subscriber);
int32_t UnbindBatterySubscriber(struct BatterydService *service);
#endif // BATTERYD_H

View File

@ -0,0 +1,23 @@
/*
* 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 BATTERYD_DISPATCHER_H
#define BATTERYD_DISPATCHER_H
#include "core/hdf_device_desc.h"
int32_t BatterydDispatch(struct HdfDeviceIoClient *client, int cmdId, struct HdfSBuf *data, struct HdfSBuf *reply);
#endif // BATTERYD_DISPATCHER_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 BATTERYD_PARSER_H
#define BATTERYD_PARSER_H
#include "batteryd_api.h"
int32_t InitBatterydSysfs(void);
int32_t ParseCapacity(int32_t *capacity);
int32_t ParseVoltage(int32_t *voltage);
int32_t ParseTemperature(int32_t *temperature);
int32_t ParseHealthState(int32_t *healthState);
int32_t ParsePluggedType(int32_t *pluggedType);
int32_t ParseChargeState(int32_t *chargeState);
int32_t ParsePresent(int8_t *present);
int32_t ParseTechnology(char *technology, size_t size);
void ParseUeventToBatterydInfo(const char *msg, struct BatterydInfo *info);
#endif // BATTERYD_PARSER_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 BATTERYD_PUBLISHER_H
#define BATTERYD_PUBLISHER_H
#include "batteryd_api.h"
#include "batteryd.h"
struct BatterydSubscriber {
struct HdfRemoteService *remoteService;
};
void NotifySubscriber(const struct BatterydSubscriber *subscriber, const struct BatterydInfo *batteryInfo);
#endif // BATTERYD_PUBLISHER_H

249
hdi/service/src/batteryd.c Normal file
View File

@ -0,0 +1,249 @@
/*
* 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 "batteryd.h"
#include <unistd.h>
#include <sys/socket.h>
#include <linux/netlink.h>
#include "batteryd_dispatcher.h"
#include "batteryd_parser.h"
#include "batteryd_publisher.h"
#include "osal/osal_mem.h"
#include "osal/osal_thread.h"
#include "utils/hdf_log.h"
#define HDF_LOG_TAG batteryd
#define ERR_INVALID_FD (-1)
#define ERR_OPERATION_FAILED (-1)
#define UEVENT_BUFF_SIZE (64 * 1024)
#define UEVENT_RESERVED_SIZE (2)
#define UEVENT_MSG_LEN (2 * 1024)
#define SUBSYSTEM_POWER_SUPPLY "SUBSYSTEM=power_supply"
static int32_t BatterydBind(struct HdfDeviceObject *device);
static int32_t BatterydInit(struct HdfDeviceObject *device);
static void BatterydRelease(struct HdfDeviceObject *device);
struct HdfDriverEntry g_batterydEntry = {
.moduleVersion = 1,
.moduleName = "batteryd",
.Bind = BatterydBind,
.Init = BatterydInit,
.Release = BatterydRelease,
};
HDF_INIT(g_batterydEntry);
static int32_t BatterydBind(struct HdfDeviceObject *device)
{
HDF_LOGD("%{public}s enter", __func__);
struct BatterydService *service = NULL;
if (device == NULL) {
HDF_LOGW("%{public}s device is NULL", __func__);
return HDF_ERR_INVALID_OBJECT;
}
service = (struct BatterydService *)OsalMemCalloc(sizeof(*service));
if (service == NULL) {
HDF_LOGE("%{public}s: calloc address error", __func__);
return HDF_ERR_MALLOC_FAIL;
}
service->device = device;
service->ioService.Dispatch = BatterydDispatch;
device->service = &(service->ioService);
return HDF_SUCCESS;
}
static int32_t OpenUeventSocket(void)
{
int32_t ret;
int32_t bufferSize = UEVENT_BUFF_SIZE;
struct sockaddr_nl address = {
.nl_pid = getpid(),
.nl_family = AF_NETLINK,
.nl_groups = 0xffffffff
};
int32_t fd = socket(PF_NETLINK, SOCK_DGRAM | SOCK_CLOEXEC, NETLINK_KOBJECT_UEVENT);
if (fd == ERR_INVALID_FD) {
HDF_LOGE("%{public}s open uevent socket failed, fd is invalid", __func__);
return ERR_INVALID_FD;
}
ret = setsockopt(fd, SOL_SOCKET, SO_RCVBUFFORCE, &bufferSize, sizeof(bufferSize));
if (ret == ERR_OPERATION_FAILED) {
HDF_LOGE("%{public}s set socket opt failed, ret: %{public}d", __func__, ret);
close(fd);
return ERR_INVALID_FD;
}
ret = bind(fd, (struct sockaddr *)(&address), sizeof(struct sockaddr_nl));
if (ret == ERR_OPERATION_FAILED) {
HDF_LOGE("%{public}s bind socket address failed, ret: %{public}d", __func__, ret);
close(fd);
return ERR_INVALID_FD;
}
return fd;
}
static int32_t InitUevent(struct BatterydService *service)
{
int32_t fd = OpenUeventSocket();
if (fd == ERR_INVALID_FD) {
HDF_LOGE("%{public}s open uevent socket failed, fd is invalid", __func__);
return HDF_ERR_BAD_FD;
}
service->ueventFd = fd;
return HDF_SUCCESS;
}
static bool IsPowerSupplyEvent(const char *msg)
{
while (*msg) {
if (!strcmp(msg, SUBSYSTEM_POWER_SUPPLY)) {
return true;
}
while (*msg++) {} // move to next
}
return false;
}
static int LoopingThreadEntry(void *arg)
{
int32_t len;
char msg[UEVENT_MSG_LEN + UEVENT_RESERVED_SIZE] = {0};
struct BatterydService *service = (struct BatterydService *)arg;
HDF_LOGD("%{public}s enter, start batteryd looping", __func__);
while (true) {
do {
len = recv(service->ueventFd, msg, UEVENT_MSG_LEN, 0);
if (len < 0 || len >= UEVENT_MSG_LEN) {
HDF_LOGD("%{public}s recv return msg is invalid, len: %{public}d", __func__, len);
continue;
}
// msg separator
msg[len] = '\0';
msg[len + 1] = '\0';
if (!IsPowerSupplyEvent(msg)) {
continue;
}
struct BatterydInfo *batteryInfo = (struct BatterydInfo *)OsalMemCalloc(sizeof(*batteryInfo));
if (batteryInfo == NULL) {
HDF_LOGE("%{public}s: calloc battery info error", __func__);
continue;
}
ParseUeventToBatterydInfo(msg, batteryInfo);
NotifySubscriber(service->subscriber, batteryInfo);
OsalMemFree(batteryInfo);
} while (len > 0);
HDF_LOGD("%{public}s recv error, len: %{public}d", __func__, len);
}
}
static int32_t StartLoopingThread(struct BatterydService *service)
{
int32_t ret;
OSAL_DECLARE_THREAD(loopingThread);
ret = OsalThreadCreate(&loopingThread, (OsalThreadEntry)LoopingThreadEntry, service);
if (ret != HDF_SUCCESS) {
HDF_LOGE("%{public}s osal create looping thread failed, ret: %{public}d", __func__, ret);
return ret;
}
struct OsalThreadParam threadParam = {
.name = "batteryd_looping_thread",
.stackSize = 0x4000,
.priority = OSAL_THREAD_PRI_DEFAULT
};
ret = OsalThreadStart(&loopingThread, &threadParam);
if (ret != HDF_SUCCESS) {
HDF_LOGE("%{public}s osal start looping thread failed, ret: %{public}d", __func__, ret);
OsalThreadDestroy(&loopingThread);
return ret;
}
return ret;
}
static int32_t BatterydInit(struct HdfDeviceObject *device)
{
HDF_LOGD("%{public}s enter", __func__);
int32_t ret;
if (device == NULL || device->service == NULL) {
HDF_LOGW("%{public}s device or device->service is NULL", __func__);
return HDF_ERR_INVALID_OBJECT;
}
struct BatterydService *service = (struct BatterydService *)device->service;
if (service == NULL) {
HDF_LOGE("%{public}s get batteryd service failed", __func__);
return HDF_ERR_INVALID_OBJECT;
}
ret = InitBatterydSysfs();
if (ret != HDF_SUCCESS) {
HDF_LOGE("%{public}s init batteryd sysfs failed, ret: %{public}d", __func__, ret);
return ret;
}
ret = InitUevent(service);
if (ret != HDF_SUCCESS) {
HDF_LOGE("%{public}s init uevent failed, ret: %{public}d", __func__, ret);
return ret;
}
ret = StartLoopingThread(service);
if (ret != HDF_SUCCESS) {
HDF_LOGE("%{public}s start loop thread failed, ret: %{public}d", __func__, ret);
return ret;
}
return ret;
}
static void BatterydRelease(struct HdfDeviceObject *device)
{
HDF_LOGD("%{public}s enter", __func__);
if (device == NULL) {
return;
}
struct BatterydService *service = (struct BatterydService *)device->service;
if (service == NULL) {
HDF_LOGW("%{public}s batteryd service is NULL, no need to release", __func__);
return;
}
OsalMemFree(service);
}
int32_t BindBatterySubscriber(struct BatterydService *service, struct BatterydSubscriber *subscriber)
{
if (service == NULL) {
HDF_LOGW("%{public}s service is NULL", __func__);
return HDF_ERR_INVALID_PARAM;
}
service->subscriber = subscriber;
return HDF_SUCCESS;
}
int32_t UnbindBatterySubscriber(struct BatterydService *service)
{
if (service == NULL) {
HDF_LOGW("%{public}s service is NULL", __func__);
return HDF_ERR_INVALID_PARAM;
}
if (service->subscriber != NULL) {
OsalMemFree(service->subscriber);
service->subscriber = NULL;
}
return HDF_SUCCESS;
}

View File

@ -0,0 +1,207 @@
/*
* 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 "batteryd_dispatcher.h"
#include "batteryd.h"
#include "batteryd_publisher.h"
#include "batteryd_parser.h"
#include "osal/osal_mem.h"
#include "utils/hdf_log.h"
#define HDF_LOG_TAG batteryd_dispatcher
#define MAX_BUFF_SIZE 128
static int32_t DispatchBindBatterySubscriber(struct BatterydService *service, struct HdfSBuf *data);
static int32_t DispatchUnbindBatterySubscriber(struct BatterydService *service);
static int32_t DispatchGetCapacity(struct HdfSBuf *reply);
static int32_t DispatchGetVoltage(struct HdfSBuf *reply);
static int32_t DispatchGetTemperature(struct HdfSBuf *reply);
static int32_t DispatchGetHealthState(struct HdfSBuf *reply);
static int32_t DispatchGetPluggedType(struct HdfSBuf *reply);
static int32_t DispatchGetChargeState(struct HdfSBuf *reply);
static int32_t DispatchGetPresent(struct HdfSBuf *reply);
static int32_t DispatchGetTechnology(struct HdfSBuf *reply);
int32_t BatterydDispatch(struct HdfDeviceIoClient *client, int cmdId, struct HdfSBuf *data, struct HdfSBuf *reply)
{
HDF_LOGD("%{public}s enter", __func__);
if (client == NULL || client->device == NULL) {
HDF_LOGE("%{public}s: client or client->device is NULL", __func__);
return HDF_ERR_INVALID_PARAM;
}
struct BatterydService *service = (struct BatterydService *)client->device->service;
if (service == NULL) {
HDF_LOGE("%{public}s: service is NULL", __func__);
return HDF_FAILURE;
}
switch (cmdId) {
case CMD_BIND_BATTERY_SUBSCRIBER: {
return DispatchBindBatterySubscriber(service, data);
}
case CMD_UNBIND_BATTERY_SUBSCRIBER: {
return DispatchUnbindBatterySubscriber(service);
}
case CMD_GET_CAPACITY: {
return DispatchGetCapacity(reply);
}
case CMD_GET_VOLTAGE: {
return DispatchGetVoltage(reply);
}
case CMD_GET_TEMPERATURE: {
return DispatchGetTemperature(reply);
}
case CMD_GET_HEALTH_STATE: {
return DispatchGetHealthState(reply);
}
case CMD_GET_PLUGGED_TYPE: {
return DispatchGetPluggedType(reply);
}
case CMD_GET_CHARGE_STATE: {
return DispatchGetChargeState(reply);
}
case CMD_GET_PRESENT: {
return DispatchGetPresent(reply);
}
case CMD_GET_TECHNOLOGY: {
return DispatchGetTechnology(reply);
}
default: {
HDF_LOGE("%{public}s: invalid cmdId %{public}d", __func__, cmdId);
return HDF_FAILURE;
}
}
}
static int32_t DispatchBindBatterySubscriber(struct BatterydService *service, struct HdfSBuf *data)
{
struct BatterydSubscriber *subscriber = NULL;
struct HdfRemoteService *remoteService = HdfSBufReadRemoteService(data);
if (remoteService == NULL) {
HDF_LOGW("%{public}s: remoteService is NULL", __func__);
return HDF_ERR_INVALID_PARAM;
}
subscriber = (struct BatterydSubscriber *)OsalMemCalloc(sizeof(*subscriber));
if (subscriber == NULL) {
HDF_LOGE("%{public}s: calloc subscriber error", __func__);
return HDF_ERR_MALLOC_FAIL;
}
subscriber->remoteService = remoteService;
return BindBatterySubscriber(service, subscriber);
}
static int32_t DispatchUnbindBatterySubscriber(struct BatterydService *service)
{
return UnbindBatterySubscriber(service);
}
static int32_t DispatchGetCapacity(struct HdfSBuf *reply)
{
int32_t ret;
int32_t capacity = 0;
ret = ParseCapacity(&capacity);
if (ret != HDF_SUCCESS) {
return ret;
}
HdfSbufWriteInt32(reply, capacity);
return HDF_SUCCESS;
}
static int32_t DispatchGetVoltage(struct HdfSBuf *reply)
{
int32_t ret;
int32_t voltage = 0;
ret = ParseVoltage(&voltage);
if (ret != HDF_SUCCESS) {
return ret;
}
HdfSbufWriteInt32(reply, voltage);
return HDF_SUCCESS;
}
static int32_t DispatchGetTemperature(struct HdfSBuf *reply)
{
int32_t ret;
int32_t temperature = 0;
ret = ParseTemperature(&temperature);
if (ret != HDF_SUCCESS) {
return ret;
}
HdfSbufWriteInt32(reply, temperature);
return HDF_SUCCESS;
}
static int32_t DispatchGetHealthState(struct HdfSBuf *reply)
{
int32_t ret;
int32_t healthState = 0;
ret = ParseHealthState(&healthState);
if (ret != HDF_SUCCESS) {
return ret;
}
HdfSbufWriteInt32(reply, healthState);
return HDF_SUCCESS;
}
static int32_t DispatchGetPluggedType(struct HdfSBuf *reply)
{
int32_t ret;
int32_t pluggedType = 0;
ret = ParsePluggedType(&pluggedType);
if (ret != HDF_SUCCESS) {
return ret;
}
HdfSbufWriteInt32(reply, pluggedType);
return HDF_SUCCESS;
}
static int32_t DispatchGetChargeState(struct HdfSBuf *reply)
{
int32_t ret;
int32_t chargeState = 0;
ret = ParseChargeState(&chargeState);
if (ret != HDF_SUCCESS) {
return ret;
}
HdfSbufWriteInt32(reply, chargeState);
return HDF_SUCCESS;
}
static int32_t DispatchGetPresent(struct HdfSBuf *reply)
{
int32_t ret;
int8_t present = 0;
ret = ParsePresent(&present);
if (ret != HDF_SUCCESS) {
return ret;
}
HdfSbufWriteInt8(reply, present);
return HDF_SUCCESS;
}
static int32_t DispatchGetTechnology(struct HdfSBuf *reply)
{
int32_t ret;
char technology[MAX_BUFF_SIZE] = {0};
ret = ParseTechnology(technology, sizeof(technology));
if (ret != HDF_SUCCESS) {
return ret;
}
HdfSbufWriteString(reply, technology);
return HDF_SUCCESS;
}

View File

@ -0,0 +1,564 @@
/*
* 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 "batteryd_parser.h"
#include <dirent.h>
#include <fcntl.h>
#include <limits.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <securec.h>
#include <unistd.h>
#include "batteryd.h"
#include "utils/hdf_log.h"
#include "osal/osal_mem.h"
#define HDF_LOG_TAG batteryd_parser
#define MAX_SYSFS_SIZE 64
#define MAX_BUFF_SIZE 128
#define INVALID_BATT_INT_VALUE (-1)
#define POWER_SUPPLY_BASE_PATH "/sys/class/power_supply"
#define POWER_SUPPLY_BATTERY "Battery"
#define BATTERY_KEY_CAPACITY "POWER_SUPPLY_CAPACITY="
#define BATTERY_KEY_VOLTAGE "POWER_SUPPLY_VOLTAGE_NOW="
#define BATTERY_KEY_TEMPERATURE "POWER_SUPPLY_TEMP="
#define BATTERY_KEY_HEALTH "POWER_SUPPLY_HEALTH="
#define BATTERY_KEY_CHARGE_STATUS "POWER_SUPPLY_STATUS="
#define BATTERY_KEY_PRESENT "POWER_SUPPLY_PRESENT="
#define BATTERY_KEY_TECHNOLOGY "POWER_SUPPLY_TECHNOLOGY="
#define BATTERY_KEY_CHARGE_COUNTER "POWER_SUPPLY_CHARGE_COUNTER="
struct PowerSupplySysfsInfo {
char *name;
char typePath[PATH_MAX];
char onlinePath[PATH_MAX];
char currentMaxPath[PATH_MAX];
char voltageMaxPath[PATH_MAX];
};
static struct PowerSupplySysfsInfo g_powerSupplySysfsInfos[MAX_SYSFS_SIZE];
struct BatterySysfsInfo {
char *name;
char capacityPath[PATH_MAX];
char voltagePath[PATH_MAX];
char temperaturePath[PATH_MAX];
char healthStatePath[PATH_MAX];
char chargeStatePath[PATH_MAX];
char presentPath[PATH_MAX];
char technologyPath[PATH_MAX];
};
static struct BatterySysfsInfo g_batterySysfsInfo;
// Keep it same as the BatteryHealthState in battery_info.h
enum BatteryHealthState {
BATTERY_HEALTH_UNKNOWN = 0,
BATTERY_HEALTH_GOOD,
BATTERY_HEALTH_OVERHEAT,
BATTERY_HEALTH_OVERVOLTAGE,
BATTERY_HEALTH_COLD,
BATTERY_HEALTH_DEAD,
BATTERY_HEALTH_RESERVED,
};
// Keep it same as the BatteryChargeState in battery_info.h
enum BatteryChargeState {
CHARGE_STATE_NONE = 0,
CHARGE_STATE_ENABLE,
CHARGE_STATE_DISABLE,
CHARGE_STATE_FULL,
CHARGE_STATE_RESERVED,
};
// Keep it same as the BatteryPluggedType in battery_info.h
enum BatteryPluggedType {
PLUGGED_TYPE_NONE = 0,
PLUGGED_TYPE_AC,
PLUGGED_TYPE_USB,
PLUGGED_TYPE_WIRELESS,
PLUGGED_TYPE_BUTT
};
struct StringEnumMap {
char *str;
int32_t enumVal;
};
struct StringEnumMap g_healthStateEnumMap[] = {
{"Good", BATTERY_HEALTH_GOOD},
{"Cold", BATTERY_HEALTH_COLD},
{"Warm", BATTERY_HEALTH_GOOD}, // JEITA specification
{"Cool", BATTERY_HEALTH_GOOD}, // JEITA specification
{"Hot", BATTERY_HEALTH_OVERHEAT}, // JEITA specification
{"Overheat", BATTERY_HEALTH_OVERHEAT},
{"Over voltage", BATTERY_HEALTH_OVERVOLTAGE},
{"Dead", BATTERY_HEALTH_DEAD},
{"Unknown", BATTERY_HEALTH_UNKNOWN},
{"Unspecified failure", BATTERY_HEALTH_UNKNOWN},
{NULL, BATTERY_HEALTH_UNKNOWN},
};
struct StringEnumMap g_chargeStateEnumMap[] = {
{"Discharging", CHARGE_STATE_NONE},
{"Charging", CHARGE_STATE_ENABLE},
{"Full", CHARGE_STATE_FULL},
{"Not charging", CHARGE_STATE_DISABLE},
{"Unknown", CHARGE_STATE_RESERVED},
{NULL, CHARGE_STATE_RESERVED},
};
struct StringEnumMap g_pluggedTypeEnumMap[] = {
{"USB", PLUGGED_TYPE_USB},
{"USB_PD_DRP", PLUGGED_TYPE_USB},
{"Wireless", PLUGGED_TYPE_WIRELESS},
{"Mains", PLUGGED_TYPE_AC},
{"UPS", PLUGGED_TYPE_AC},
{"USB_ACA", PLUGGED_TYPE_AC},
{"USB_C", PLUGGED_TYPE_AC},
{"USB_CDP", PLUGGED_TYPE_AC},
{"USB_DCP", PLUGGED_TYPE_AC},
{"USB_HVDCP", PLUGGED_TYPE_AC},
{"USB_PD", PLUGGED_TYPE_AC},
{"Unknown", PLUGGED_TYPE_BUTT},
{NULL, PLUGGED_TYPE_BUTT},
};
struct BatteryAssigner {
const char *prefix;
const size_t prefixLen;
void (*Assigner)(const char *, struct BatterydInfo *);
};
inline static int32_t ParseInt(const char *str)
{
return strtol(str, NULL, 10);
}
inline static void TrimNewLine(char *str)
{
if (str == NULL) {
return;
}
str[strcspn(str, "\n")] = 0;
}
inline static void CapacityAssigner(const char *str, struct BatterydInfo *info)
{
info->capacity_ = ParseInt(str); // default in percent format
}
inline static void VoltageAssigner(const char *str, struct BatterydInfo *info)
{
info->voltage_ = ParseInt(str) / 1000; // convert to millivolt(mV) format
}
inline static void TemperatureAssigner(const char *str, struct BatterydInfo *info)
{
info->temperature_ = ParseInt(str);
}
static int32_t HealthStateEnumConverter(const char *str)
{
for (int i = 0; g_healthStateEnumMap[i].str; ++i) {
if (strcmp(str, g_healthStateEnumMap[i].str) == 0) {
return g_healthStateEnumMap[i].enumVal;
}
}
return BATTERY_HEALTH_UNKNOWN;
}
inline static void HealthStateAssigner(const char *str, struct BatterydInfo *info)
{
info->healthState_ = HealthStateEnumConverter(str);
}
static int32_t ChargeStateEnumConverter(const char *str)
{
for (int i = 0; g_chargeStateEnumMap[i].str; ++i) {
if (strcmp(str, g_chargeStateEnumMap[i].str) == 0) {
return g_chargeStateEnumMap[i].enumVal;
}
}
return CHARGE_STATE_RESERVED;
}
inline static void ChargeStateAssigner(const char *str, struct BatterydInfo *info)
{
info->chargeState_ = ChargeStateEnumConverter(str);
}
inline static void PresentAssigner(const char *str, struct BatterydInfo *info)
{
info->present_ = ParseInt(str);
}
inline static void TechnologyAssigner(const char *str, struct BatterydInfo *info)
{
info->technology_ = str;
}
inline static void ChargeCounterAssigner(const char *str, struct BatterydInfo *info)
{
info->chargeCounter_ = ParseInt(str);
}
static struct BatteryAssigner g_batteryAssigners[] = {
{BATTERY_KEY_CAPACITY, sizeof(BATTERY_KEY_CAPACITY) - 1, CapacityAssigner},
{BATTERY_KEY_VOLTAGE, sizeof(BATTERY_KEY_VOLTAGE) - 1, VoltageAssigner},
{BATTERY_KEY_TEMPERATURE, sizeof(BATTERY_KEY_TEMPERATURE) - 1, TemperatureAssigner},
{BATTERY_KEY_HEALTH, sizeof(BATTERY_KEY_HEALTH) - 1, HealthStateAssigner},
{BATTERY_KEY_CHARGE_STATUS, sizeof(BATTERY_KEY_CHARGE_STATUS) - 1, ChargeStateAssigner},
{BATTERY_KEY_PRESENT, sizeof(BATTERY_KEY_PRESENT) - 1, PresentAssigner},
{BATTERY_KEY_TECHNOLOGY, sizeof(BATTERY_KEY_TECHNOLOGY) - 1, TechnologyAssigner},
{BATTERY_KEY_CHARGE_COUNTER, sizeof(BATTERY_KEY_CHARGE_COUNTER) - 1, ChargeCounterAssigner},
{NULL, 0, NULL} // end of the array
};
static void FormatPath(char *path, size_t size, const char *format, const char *basePath, const char *name)
{
int ret = snprintf_s(path, PATH_MAX, size - 1, format, basePath, name);
if (ret == -1) {
HDF_LOGW("%{public}s: failed to format path of %{public}s", __func__, name);
}
}
static void FormatSysfsPaths(struct PowerSupplySysfsInfo *info)
{
// Format paths for plugged power supply types
FormatPath(info->typePath, sizeof(info->typePath), "%s/%s/type", POWER_SUPPLY_BASE_PATH, info->name);
FormatPath(info->onlinePath, sizeof(info->onlinePath), "%s/%s/online", POWER_SUPPLY_BASE_PATH, info->name);
FormatPath(info->currentMaxPath, sizeof(info->currentMaxPath), "%s/%s/current_max", POWER_SUPPLY_BASE_PATH,
info->name);
FormatPath(info->voltageMaxPath, sizeof(info->voltageMaxPath), "%s/%s/voltage_max", POWER_SUPPLY_BASE_PATH,
info->name);
if (strcmp(info->name, POWER_SUPPLY_BATTERY) != 0) {
return;
}
// Format paths for battery only
g_batterySysfsInfo.name = info->name;
FormatPath(g_batterySysfsInfo.capacityPath, sizeof(g_batterySysfsInfo.capacityPath), "%s/%s/capacity",
POWER_SUPPLY_BASE_PATH, info->name);
FormatPath(g_batterySysfsInfo.voltagePath, sizeof(g_batterySysfsInfo.voltagePath), "%s/%s/voltage_now",
POWER_SUPPLY_BASE_PATH, info->name);
FormatPath(g_batterySysfsInfo.temperaturePath, sizeof(g_batterySysfsInfo.temperaturePath), "%s/%s/temp",
POWER_SUPPLY_BASE_PATH, info->name);
FormatPath(g_batterySysfsInfo.healthStatePath, sizeof(g_batterySysfsInfo.healthStatePath), "%s/%s/health",
POWER_SUPPLY_BASE_PATH, info->name);
FormatPath(g_batterySysfsInfo.chargeStatePath, sizeof(g_batterySysfsInfo.chargeStatePath), "%s/%s/status",
POWER_SUPPLY_BASE_PATH, info->name);
FormatPath(g_batterySysfsInfo.presentPath, sizeof(g_batterySysfsInfo.presentPath), "%s/%s/present",
POWER_SUPPLY_BASE_PATH, info->name);
FormatPath(g_batterySysfsInfo.technologyPath, sizeof(g_batterySysfsInfo.technologyPath), "%s/%s/technology",
POWER_SUPPLY_BASE_PATH, info->name);
}
int32_t InitBatterydSysfs(void)
{
DIR *dir = NULL;
struct dirent *entry = NULL;
int32_t index = 0;
dir = opendir(POWER_SUPPLY_BASE_PATH);
if (dir == NULL) {
HDF_LOGE("%{public}s: cannot open POWER_SUPPLY_BASE_PATH", __func__);
return HDF_ERR_IO;
}
while (true) {
entry = readdir(dir);
if (entry == NULL) {
break;
}
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
if (entry->d_type == DT_DIR || entry->d_type == DT_LNK) {
struct PowerSupplySysfsInfo sysfsInfo = {0};
sysfsInfo.name = entry->d_name;
HDF_LOGD("%{public}s: init sysfs info of %{public}s", __func__, sysfsInfo.name);
if (index >= MAX_SYSFS_SIZE) {
HDF_LOGE("%{public}s: too many plugged types", __func__);
break;
}
FormatSysfsPaths(&sysfsInfo);
g_powerSupplySysfsInfos[index] = sysfsInfo;
index++;
}
}
closedir(dir);
return HDF_SUCCESS;
}
static int32_t ReadSysfsFile(const char *path, char *buf, size_t size)
{
int32_t ret;
int fd = open(path, O_RDONLY);
if (fd < HDF_SUCCESS) {
HDF_LOGE("%{public}s: failed to open %{private}s", __func__, path);
return HDF_ERR_IO;
}
ret = read(fd, buf, size);
if (ret < HDF_SUCCESS) {
HDF_LOGE("%{public}s: failed to read %{private}s", __func__, path);
close(fd);
return HDF_ERR_IO;
}
close(fd);
buf[size - 1] = '\0';
return HDF_SUCCESS;
}
static int32_t ReadBatterySysfsToBuff(const char *path, char *buf, size_t size)
{
int32_t ret;
if (g_batterySysfsInfo.name == NULL) {
HDF_LOGW("%{public}s: battery sysfs info is not exist", __func__);
return HDF_ERR_INVALID_OBJECT;
}
ret = ReadSysfsFile(path, buf, size);
if (ret != HDF_SUCCESS) {
HDF_LOGW("%{public}s: read path %{private}s failed, ret: %{public}d", __func__, path, ret);
return ret;
}
return HDF_SUCCESS;
}
int32_t ParseCapacity(int32_t *capacity)
{
int32_t ret;
int32_t value;
char buf[MAX_BUFF_SIZE] = {0};
ret = ReadBatterySysfsToBuff(g_batterySysfsInfo.capacityPath, buf, sizeof(buf));
if (ret != HDF_SUCCESS) {
return ret;
}
value = ParseInt(buf);
HDF_LOGD("%{public}s: capacity is %{public}d", __func__, value);
*capacity = value;
return HDF_SUCCESS;
}
int32_t ParseVoltage(int32_t *voltage)
{
int32_t ret;
int32_t value;
char buf[MAX_BUFF_SIZE] = {0};
ret = ReadBatterySysfsToBuff(g_batterySysfsInfo.voltagePath, buf, sizeof(buf));
if (ret != HDF_SUCCESS) {
return ret;
}
value = ParseInt(buf);
HDF_LOGD("%{public}s: voltage is %{public}d", __func__, value);
*voltage = value;
return HDF_SUCCESS;
}
int32_t ParseTemperature(int32_t *temperature)
{
int32_t ret;
int32_t value;
char buf[MAX_BUFF_SIZE] = {0};
ret = ReadBatterySysfsToBuff(g_batterySysfsInfo.temperaturePath, buf, sizeof(buf));
if (ret != HDF_SUCCESS) {
return ret;
}
value = ParseInt(buf);
HDF_LOGD("%{public}s: temperature is %{public}d", __func__, value);
*temperature = value;
return HDF_SUCCESS;
}
int32_t ParseHealthState(int32_t *healthState)
{
int32_t ret;
int32_t value;
char buf[MAX_BUFF_SIZE] = {0};
ret = ReadBatterySysfsToBuff(g_batterySysfsInfo.healthStatePath, buf, sizeof(buf));
if (ret != HDF_SUCCESS) {
return ret;
}
value = ParseInt(buf);
HDF_LOGD("%{public}s: healthState is %{public}d", __func__, value);
*healthState = value;
return HDF_SUCCESS;
}
void GetPluggedTypeName(char *buf, size_t size)
{
int32_t ret;
int32_t online;
for (int i = 0; i < MAX_SYSFS_SIZE && g_powerSupplySysfsInfos[i].name; ++i) {
if (strcmp(g_powerSupplySysfsInfos[i].name, POWER_SUPPLY_BATTERY) == 0) {
// ignore the battery type
continue;
}
ret = ReadSysfsFile(g_powerSupplySysfsInfos[i].onlinePath, buf, size);
if (ret != HDF_SUCCESS) {
HDF_LOGW("%{public}s: read online path failed, ret: %{public}d", __func__, ret);
continue;
}
online = ParseInt(buf);
if (!online) {
continue;
}
HDF_LOGD("%{public}s: %{public}s is online", __func__, g_powerSupplySysfsInfos[i].name);
ret = ReadSysfsFile(g_powerSupplySysfsInfos[i].typePath, buf, size);
if (ret != HDF_SUCCESS) {
HDF_LOGW("%{public}s: read type path failed, ret: %{public}d", __func__, ret);
continue;
}
TrimNewLine(buf);
break;
}
}
static int32_t PluggedTypeEnumConverter(const char *str)
{
for (int i = 0; g_pluggedTypeEnumMap[i].str; ++i) {
if (strcmp(str, g_pluggedTypeEnumMap[i].str) == 0) {
return g_pluggedTypeEnumMap[i].enumVal;
}
}
return PLUGGED_TYPE_BUTT;
}
int32_t ParsePluggedType(int32_t *pluggedType)
{
int32_t type;
char buf[MAX_BUFF_SIZE] = {0};
GetPluggedTypeName(buf, sizeof(buf));
type = PluggedTypeEnumConverter(buf);
if (type == PLUGGED_TYPE_BUTT) {
HDF_LOGW("%{public}s: not support the online type %{public}s", __func__, buf);
return HDF_ERR_NOT_SUPPORT;
}
HDF_LOGD("%{public}s: return online plugged type %{public}d", __func__, type);
*pluggedType = type;
return HDF_SUCCESS;
}
int32_t ParseChargeState(int32_t *chargeState)
{
int32_t ret;
int32_t value;
char buf[MAX_BUFF_SIZE] = {0};
ret = ReadBatterySysfsToBuff(g_batterySysfsInfo.chargeStatePath, buf, sizeof(buf));
if (ret != HDF_SUCCESS) {
return ret;
}
value = ParseInt(buf);
HDF_LOGD("%{public}s: chargeState is %{public}d", __func__, value);
*chargeState = value;
return HDF_SUCCESS;
}
int32_t ParsePresent(int8_t *present)
{
int32_t ret;
int8_t value;
char buf[MAX_BUFF_SIZE] = {0};
ret = ReadBatterySysfsToBuff(g_batterySysfsInfo.presentPath, buf, sizeof(buf));
if (ret != HDF_SUCCESS) {
return ret;
}
value = (int8_t)ParseInt(buf);
HDF_LOGD("%{public}s: present is %{public}d", __func__, value);
*present = value;
return HDF_SUCCESS;
}
int32_t ParseTechnology(char *buf, size_t size)
{
int32_t ret;
ret = ReadBatterySysfsToBuff(g_batterySysfsInfo.technologyPath, buf, size);
if (ret != HDF_SUCCESS) {
return ret;
}
HDF_LOGD("%{public}s: technology is %{public}s", __func__, buf);
return HDF_SUCCESS;
}
int32_t ParsePluggedMaxCurrent(int32_t *maxCurrent)
{
int32_t ret;
int32_t value;
char buf[MAX_BUFF_SIZE] = {0};
GetPluggedTypeName(buf, sizeof(buf));
for (int i = 0; i < MAX_SYSFS_SIZE && g_powerSupplySysfsInfos[i].name; ++i) {
if (strcmp(buf, g_powerSupplySysfsInfos[i].name) != 0) {
continue;
}
ret = ReadBatterySysfsToBuff(g_powerSupplySysfsInfos[i].currentMaxPath, buf, sizeof(buf));
if (ret != HDF_SUCCESS) {
return ret;
}
value = ParseInt(buf);
HDF_LOGD("%{public}s: maxCurrent is %{public}d", __func__, value);
*maxCurrent = value;
return HDF_SUCCESS;
}
return HDF_ERR_NOT_SUPPORT;
}
int32_t ParsePluggedMaxVoltage(int32_t *maxVoltage)
{
int32_t ret;
int32_t value;
char buf[MAX_BUFF_SIZE] = {0};
GetPluggedTypeName(buf, sizeof(buf));
for (int i = 0; i < MAX_SYSFS_SIZE && g_powerSupplySysfsInfos[i].name; ++i) {
if (strcmp(buf, g_powerSupplySysfsInfos[i].name) != 0) {
continue;
}
ret = ReadBatterySysfsToBuff(g_powerSupplySysfsInfos[i].voltageMaxPath, buf, sizeof(buf));
if (ret != HDF_SUCCESS) {
return ret;
}
value = ParseInt(buf);
HDF_LOGD("%{public}s: maxCurrent is %{public}d", __func__, value);
*maxVoltage = value;
return HDF_SUCCESS;
}
return HDF_ERR_NOT_SUPPORT;
}
void ParseUeventToBatterydInfo(const char *msg, struct BatterydInfo *info)
{
while (*msg) {
for (int i = 0; g_batteryAssigners[i].prefix; ++i) {
if (!strncmp(msg, g_batteryAssigners[i].prefix, g_batteryAssigners[i].prefixLen)) {
HDF_LOGD("%{public}s: msg: %{public}s", __func__, msg);
msg += g_batteryAssigners[i].prefixLen;
g_batteryAssigners[i].Assigner(msg, info);
break;
}
}
while (*msg++) {} // move to next
}
info->pluggedType_ = PLUGGED_TYPE_NONE;
ParsePluggedType(&info->pluggedType_);
info->pluggedMaxCurrent_ = INVALID_BATT_INT_VALUE;
ParsePluggedMaxCurrent(&info->pluggedMaxCurrent_);
info->pluggedMaxVoltage_ = INVALID_BATT_INT_VALUE;
ParsePluggedMaxVoltage(&info->pluggedMaxVoltage_);
}

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 "batteryd_publisher.h"
#include "hdf_remote_service.h"
#include "utils/hdf_log.h"
#define HDF_LOG_TAG batteryd_publisher
void NotifySubscriber(const struct BatterydSubscriber *subscriber, const struct BatterydInfo *batteryInfo)
{
HDF_LOGD("%{public}s: enter", __func__);
if (subscriber == NULL) {
HDF_LOGD("%{public}s: subscriber is NULL", __func__);
return;
}
int ret;
struct HdfRemoteService *service = subscriber->remoteService;
struct HdfSBuf *data = HdfSBufTypedObtain(SBUF_IPC);
struct HdfSBuf *reply = HdfSBufTypedObtain(SBUF_IPC);
if (data == NULL || reply == NULL) {
HDF_LOGE("%{public}s failed to obtain hdf sbuf", __func__);
HdfSBufRecycle(data);
HdfSBufRecycle(reply);
return;
}
HDF_LOGD("%{public}s BatteryInfo: capacity=%{public}d, voltage=%{public}d, temperature=%{public}d, " \
"healthState=%{public}d, pluggedType=%{public}d, pluggedMaxCurrent=%{public}d, " \
"pluggedMaxVoltage=%{public}d, chargeState=%{public}d, chargeCounter=%{public}d, present=%{public}d, " \
"technology=%{public}s", __func__, batteryInfo->capacity_, batteryInfo->voltage_,
batteryInfo->temperature_, batteryInfo->healthState_, batteryInfo->pluggedType_,
batteryInfo->pluggedMaxCurrent_, batteryInfo->pluggedMaxVoltage_, batteryInfo->chargeState_,
batteryInfo->chargeCounter_, batteryInfo->present_, batteryInfo->technology_);
HdfSbufWriteInt32(data, batteryInfo->capacity_);
HdfSbufWriteInt32(data, batteryInfo->voltage_);
HdfSbufWriteInt32(data, batteryInfo->temperature_);
HdfSbufWriteInt32(data, batteryInfo->healthState_);
HdfSbufWriteInt32(data, batteryInfo->pluggedType_);
HdfSbufWriteInt32(data, batteryInfo->pluggedMaxCurrent_);
HdfSbufWriteInt32(data, batteryInfo->pluggedMaxVoltage_);
HdfSbufWriteInt32(data, batteryInfo->chargeState_);
HdfSbufWriteInt32(data, batteryInfo->chargeCounter_);
HdfSbufWriteInt8(data, batteryInfo->present_);
HdfSbufWriteString(data, batteryInfo->technology_);
ret = service->dispatcher->Dispatch(service, CMD_NOTIFY_SUBSCRIBER, data, reply);
if (ret != HDF_SUCCESS) {
HDF_LOGE("%{public}s failed to notify subscriber, ret: %{public}d", __func__, ret);
} else {
HDF_LOGD("%{public}s: succeed to notify subscriber", __func__);
}
HdfSBufRecycle(data);
HdfSBufRecycle(reply);
}

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.
import("//base/powermgr/battery_manager/batterymgr.gni")
config("batterysrv_private_config") {
include_dirs = [
"${battery_manager_path}/services/zidl/include",
"//utils/system/safwk/native/include",
]
}
config("batterysrv_public_config") {
include_dirs = [ "native/include" ]
}
ohos_shared_library("batterysrv_client") {
sources = [
"${battery_manager_path}/services/zidl/src/battery_srv_proxy.cpp",
"native/src/battery_srv_client.cpp",
]
configs = [
"${utils_path}:utils_config",
":batterysrv_private_config",
":batterysrv_public_config",
]
public_configs = [ ":batterysrv_public_config" ]
deps = [ "//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 = "battery_manager_native"
}

View File

@ -0,0 +1,305 @@
/*
* 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 BATTERY_SRV_BATERY_INFO_H
#define BATTERY_SRV_BATERY_INFO_H
#include <string>
namespace OHOS {
namespace PowerMgr {
static constexpr int32_t INVALID_BATT_INT_VALUE = -1;
static constexpr int32_t INVALID_BATT_TEMP_VALUE = 100;
static const std::string INVALID_STRING_VALUE = "Invalid";
static constexpr bool INVALID_BATT_BOOL_VALUE = true;
/**
* Type for acquire BatteryChargeState.
*/
enum class BatteryChargeState : uint32_t {
/**
* Battery is discharge.
*/
CHARGE_STATE_NONE,
/**
* Battery is charging.
*/
CHARGE_STATE_ENABLE,
/**
* Battery is not charging.
*/
CHARGE_STATE_DISABLE,
/**
* Battery charge full.
*/
CHARGE_STATE_FULL,
/**
* The bottom of the enum.
*/
CHARGE_STATE_BUTT
};
/**
* Type for acquire BatteryHealthState.
*/
enum class BatteryHealthState : uint32_t {
/**
* Health Status: unknown.
*/
HEALTH_STATE_UNKNOWN,
/**
* Health Status: good.
*/
HEALTH_STATE_GOOD,
/**
* Health Status: over heat.
*/
HEALTH_STATE_OVERHEAT,
/**
* Health Status: over voltage.
*/
HEALTH_STATE_OVERVOLTAGE,
/**
* Health Status: COLD.
*/
HEALTH_STATE_COLD,
/**
* Health Status: Dead.
*/
HEALTH_STATE_DEAD,
/**
* The bottom of the enum.
*/
HEALTH_STATE_BUTT
};
/**
* Type for acquire BatteryPluggedType.
*/
enum class BatteryPluggedType : uint32_t {
/**
* Power source is unplugged.
*/
PLUGGED_TYPE_NONE,
/**
* Power source is an AC charger.
*/
PLUGGED_TYPE_AC,
/**
* Power source is a USB DC charger.
*/
PLUGGED_TYPE_USB,
/**
* Power source is wireless charger.
*/
PLUGGED_TYPE_WIRELESS,
/**
* The bottom of the enum.
*/
PLUGGED_TYPE_BUTT
};
class BatteryInfo {
public:
enum {
COMMON_EVENT_CODE_CAPACITY = 0,
COMMON_EVENT_CODE_VOLTAGE = 1,
COMMON_EVENT_CODE_TEMPERATURE = 2,
COMMON_EVENT_CODE_HEALTH_STATE = 3,
COMMON_EVENT_CODE_PLUGGED_TYPE = 4,
COMMON_EVENT_CODE_PLUGGED_MAX_CURRENT = 5,
COMMON_EVENT_CODE_PLUGGED_MAX_VOLTAGE = 6,
COMMON_EVENT_CODE_CHARGE_STATE = 7,
COMMON_EVENT_CODE_CHARGE_COUNTER = 8,
COMMON_EVENT_CODE_PRESENT = 9,
COMMON_EVENT_CODE_TECHNOLOGY = 10,
};
class Builder {
public:
Builder()
{
this->info_ = new BatteryInfo;
};
~Builder()
{
delete info_;
};
Builder *SetCapacity(int32_t capacity)
{
this->info_->capacity_ = capacity;
return this;
}
Builder *SetVoltage(int32_t voltage)
{
this->info_->voltage_ = voltage;
return this;
}
Builder *SetTemperature(int32_t temperature)
{
this->info_->temperature_ = temperature;
return this;
}
Builder *SetHealthState(BatteryHealthState healthState)
{
this->info_->healthState_ = healthState;
return this;
}
Builder *SetPluggedType(BatteryPluggedType pluggedType)
{
this->info_->pluggedType_ = pluggedType;
return this;
}
Builder *SetPluggedMaxCurrent(int32_t maxCurrent)
{
this->info_->pluggedMaxCurrent_ = maxCurrent;
return this;
}
Builder *SetPluggedMaxVoltage(int32_t maxVoltage)
{
this->info_->pluggedMaxVoltage_ = maxVoltage;
return this;
}
Builder *SetChargeState(BatteryChargeState chargeState)
{
this->info_->chargeState_ = chargeState;
return this;
}
Builder *SetChargeCounter(int32_t chargeCounter)
{
this->info_->chargeCounter_ = chargeCounter;
return this;
}
Builder *SetPresent(bool present)
{
this->info_->present_ = present;
return this;
}
Builder *SetTechnology(const std::string &technology)
{
this->info_->technology_ = technology;
return this;
}
const BatteryInfo *Build()
{
return info_;
}
private:
BatteryInfo *info_;
};
BatteryInfo() = default;
~BatteryInfo() = default;
const int32_t &GetCapacity() const
{
return capacity_;
}
const int32_t &GetVoltage() const
{
return voltage_;
}
const int32_t &GetTemperature() const
{
return temperature_;
}
BatteryHealthState GetHealthState() const
{
return healthState_;
}
BatteryPluggedType GetPluggedType() const
{
return pluggedType_;
}
const int32_t &GetPluggedMaxCurrent() const
{
return pluggedMaxCurrent_;
}
const int32_t &GetPluggedMaxVoltage() const
{
return pluggedMaxVoltage_;
}
BatteryChargeState GetChargeState() const
{
return chargeState_;
}
const int32_t &GetChargeCounter() const
{
return chargeCounter_;
}
bool IsPresent() const
{
return present_;
}
const std::string &GetTechnology() const
{
return technology_;
}
private:
int32_t capacity_ = INVALID_BATT_INT_VALUE;
int32_t voltage_ = INVALID_BATT_INT_VALUE;
int32_t temperature_ = INVALID_BATT_TEMP_VALUE;
BatteryHealthState healthState_ = BatteryHealthState::HEALTH_STATE_BUTT;
BatteryPluggedType pluggedType_ = BatteryPluggedType::PLUGGED_TYPE_BUTT;
int32_t pluggedMaxCurrent_ = INVALID_BATT_INT_VALUE;
int32_t pluggedMaxVoltage_ = INVALID_BATT_INT_VALUE;
BatteryChargeState chargeState_ = BatteryChargeState::CHARGE_STATE_BUTT;
int32_t chargeCounter_ = INVALID_BATT_INT_VALUE;
bool present_ = INVALID_BATT_BOOL_VALUE;
std::string technology_ = INVALID_STRING_VALUE;
};
} // namespace PowerMgr
} // namespace OHOS
#endif // BATTERY_SRV_BATERY_INFO_H

View File

@ -0,0 +1,88 @@
/*
* 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_BATTERY_SRV_CLIENT_H
#define POWERMGR_BATTERY_SRV_CLIENT_H
#include <singleton.h>
#include <memory>
#include <mutex>
#include "iremote_object.h"
#include "ibattery_srv.h"
namespace OHOS {
namespace PowerMgr {
class BatterySrvClient final : public DelayedRefSingleton<BatterySrvClient> {
DECLARE_DELAYED_REF_SINGLETON(BatterySrvClient)
public:
DISALLOW_COPY_AND_MOVE(BatterySrvClient);
/**
* Return the capacity of the battery, in mAh.
*/
int32_t GetCapacity();
/**
* Return the charging status, such as CHARGE_STATE_NONE, CHARGE_STATE_ENABLE,
* CHARGE_STATE_DISABLE, CHARGE_STATE_FULL,...
*/
BatteryChargeState GetChargingStatus();
/**
* Return the Health state of the battery, such as HEALTH_STATE_UNKNOWN,
* HEALTH_STATE_GOOD, HEALTH_STATE_OVERHEAT,....
*/
BatteryHealthState GetHealthStatus();
/**
* Return the charger type plugged, such as PLUGGED_TYPE_NONE,
* PLUGGED_TYPE_AC, PLUGGED_TYPE_USB,....
*/
BatteryPluggedType GetPluggedType();
/**
* Return the voltage of the battery, in mv.
*/
int32_t GetVoltage();
/**
* Return the present state of the battery, true or false.
*/
bool GetPresent();
/**
* Return the technology of the battery, such as Li-ion.
*/
std::string GetTechnology();
/**
* Return the temperature of the battery, in 0.1.
*/
int32_t GetBatteryTemperature();
private:
class BatterySrvDeathRecipient : public IRemoteObject::DeathRecipient {
public:
BatterySrvDeathRecipient() = default;
~BatterySrvDeathRecipient() = default;
void OnRemoteDied(const wptr<IRemoteObject>& remote);
private:
DISALLOW_COPY_AND_MOVE(BatterySrvDeathRecipient);
};
ErrCode Connect();
sptr<IBatterySrv> proxy_ {nullptr};
sptr<IRemoteObject::DeathRecipient> deathRecipient_ {nullptr};
void ResetProxy(const wptr<IRemoteObject>& remote);
std::mutex mutex_;
};
} // namespace PowerMgr
} // namespace OHOS
#endif // BATTERY_SRV_CLIENT_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_INNERKITS_IBATTERY_SRV_H
#define POWERMGR_INNERKITS_IBATTERY_SRV_H
#include <string>
#include "iremote_broker.h"
#include "iremote_object.h"
#include "battery_info.h"
namespace OHOS {
namespace PowerMgr {
class IBatterySrv : public IRemoteBroker {
public:
enum {
BATT_GET_CAPACITY = 0,
BATT_GET_CHARGING_STATUS,
BATT_GET_HEALTH_STATUS,
BATT_GET_PLUG_TYPE,
BATT_GET_VOLTAGE,
BATT_GET_PRESENT,
BATT_GET_TEMPERATURE,
BATT_GET_TECHNOLOGY,
};
virtual int32_t GetCapacity() = 0;
virtual BatteryChargeState GetChargingStatus() = 0;
virtual BatteryHealthState GetHealthStatus() = 0;
virtual BatteryPluggedType GetPluggedType() = 0;
virtual int32_t GetVoltage() = 0;
virtual bool GetPresent() = 0;
virtual std::string GetTechnology() = 0;
virtual int32_t GetBatteryTemperature() = 0;
public:
DECLARE_INTERFACE_DESCRIPTOR(u"ohos.powermgr.IBatterySrv");
};
} // space PowerMgr
} // namespace OHOS
#endif // POWERMGR_INNERKITS_IBATTERY_SRV_H

View File

@ -0,0 +1,144 @@
/*
* 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 "battery_srv_client.h"
#include "string_ex.h"
#include "datetime_ex.h"
#include "ipc_skeleton.h"
#include "iservice_registry.h"
#include "if_system_ability_manager.h"
#include "system_ability_definition.h"
#include "power_common.h"
namespace OHOS {
namespace PowerMgr {
BatterySrvClient::BatterySrvClient() {}
BatterySrvClient::~BatterySrvClient() {}
ErrCode BatterySrvClient::Connect()
{
std::lock_guard<std::mutex> lock(mutex_);
if (proxy_ != nullptr) {
return ERR_OK;
}
sptr<ISystemAbilityManager> sm = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (sm == nullptr) {
POWER_HILOGE(MODULE_BATT_INNERKIT, "%{public}s:fail to get Registry", __func__);
return E_GET_SYSTEM_ABILITY_MANAGER_FAILED;
}
sptr<IRemoteObject> remoteObject_ = sm->CheckSystemAbility(POWER_MANAGER_BATT_SERVICE_ID);
if (remoteObject_ == nullptr) {
POWER_HILOGE(MODULE_BATT_INNERKIT, "GetSystemAbility failed.");
return E_GET_POWER_SERVICE_FAILED;
}
proxy_ = iface_cast<IBatterySrv>(remoteObject_);
POWER_HILOGI(MODULE_BATT_INNERKIT, "%{public}s :Connect PowerMgrService ok.", __func__);
return ERR_OK;
}
void BatterySrvClient::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 BatterySrvClient::BatterySrvDeathRecipient::OnRemoteDied(const wptr<IRemoteObject>& remote)
{
if (remote == nullptr) {
POWER_HILOGE(MODULE_BATT_INNERKIT, "BatterySrvDeathRecipient::OnRemoteDied failed, remote is nullptr.");
return;
}
BatterySrvClient::GetInstance().ResetProxy(remote);
POWER_HILOGI(MODULE_BATT_INNERKIT, "BatterySrvDeathRecipient::Recv death notice.");
}
int32_t BatterySrvClient::GetCapacity()
{
int32_t capacity = INVALID_BATT_INT_VALUE;
RETURN_IF_WITH_RET(Connect() != ERR_OK, capacity);
capacity = proxy_->GetCapacity();
POWER_HILOGI(MODULE_BATT_INNERKIT, " Calling GetCapacity Success!");
return capacity;
}
BatteryChargeState BatterySrvClient::GetChargingStatus()
{
BatteryChargeState chargingstate = BatteryChargeState::CHARGE_STATE_BUTT;
RETURN_IF_WITH_RET(Connect() != ERR_OK, chargingstate);
chargingstate = proxy_->GetChargingStatus();
POWER_HILOGI(MODULE_BATT_INNERKIT, " Calling GetChargingStatus Success!");
return chargingstate;
}
BatteryHealthState BatterySrvClient::GetHealthStatus()
{
BatteryHealthState healthState = BatteryHealthState::HEALTH_STATE_BUTT;
RETURN_IF_WITH_RET(Connect() != ERR_OK, healthState);
healthState = proxy_->GetHealthStatus();
POWER_HILOGI(MODULE_BATT_INNERKIT, " Calling GetHealthStatus Success!");
return healthState;
}
BatteryPluggedType BatterySrvClient::GetPluggedType()
{
BatteryPluggedType pluggedType = BatteryPluggedType::PLUGGED_TYPE_BUTT;
RETURN_IF_WITH_RET(Connect() != ERR_OK, pluggedType);
pluggedType = proxy_->GetPluggedType();
POWER_HILOGI(MODULE_BATT_INNERKIT, " Calling GetPluggedType Success!");
return pluggedType;
}
int32_t BatterySrvClient::GetVoltage()
{
int32_t voltage = INVALID_BATT_INT_VALUE;
RETURN_IF_WITH_RET(Connect() != ERR_OK, voltage);
voltage = proxy_->GetVoltage();
POWER_HILOGI(MODULE_BATT_INNERKIT, " Calling GetVoltage Success!");
return voltage;
}
bool BatterySrvClient::GetPresent()
{
bool present = INVALID_BATT_BOOL_VALUE;
RETURN_IF_WITH_RET(Connect() != ERR_OK, present);
present = proxy_->GetPresent();
POWER_HILOGI(MODULE_BATT_INNERKIT, " Calling GetPresent Success!");
return present;
}
std::string BatterySrvClient::GetTechnology()
{
std::string technology;
RETURN_IF_WITH_RET(Connect() != ERR_OK, technology);
technology = proxy_->GetTechnology();
POWER_HILOGI(MODULE_BATT_INNERKIT, " Calling GetTechnology Success!");
return technology;
}
int32_t BatterySrvClient::GetBatteryTemperature()
{
int32_t temperature = INVALID_BATT_TEMP_VALUE;
RETURN_IF_WITH_RET(Connect() != ERR_OK, temperature);
temperature = proxy_->GetBatteryTemperature();
POWER_HILOGI(MODULE_BATT_INNERKIT, " Calling GetBatteryTemperature Success!");
return temperature;
}
} // namespace PowerMgr
} // namespace OHOS

View File

@ -0,0 +1,170 @@
/*
* 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.
*/
/**
* Obtains battery information of a device.
*
* <p>Battery information includes the remaining battery power,
* voltage, temperature, model, and charger type.
*
* @SysCap SystemCapability.PowerMgr.BatteryManager
* @devices phone, tablet
* @since 6
*/
declare namespace batteryInfo {
/**
* Battery state of charge (SoC) of the current device.
* @devices phone, tablet
*/
const batterySOC: number;
/**
* Battery charging status of the current device.
* @devices phone, tablet
*/
const chargingStatus: BatteryChargeState;
/**
* Battery health state of the current device.
* @devices phone, tablet
*/
const healthStatus: BatteryHealthState;
/**
* Charger type of the current device.
* @devices phone, tablet
*/
const pluggedType: BatteryPluggedType;
/**
* Battery voltage of the current device.
* @devices phone, tablet
*/
const voltage: number;
/**
* Battery technology of the current device.
* @devices phone, tablet
*/
const technology: string;
/**
* Battery temperature of the current device.
* @devices phone, tablet
*/
const batteryTemperature: number;
/**
* Indicates the charger type of a device.
*
* @SysCap SystemCapability.PowerMgr.BatteryManager
* @devices phone, tablet
* @since 6
*/
export enum BatteryPluggedType {
/**
* Unknown type
* @devices phone, tablet
*/
NONE,
/**
* AC charger
* @devices phone, tablet
*/
AC,
/**
* USB charger
* @devices phone, tablet
*/
USB,
/**
* Wireless charger
* @devices phone, tablet
*/
WIRELESS
}
/**
* Indicates the battery charging status of a device.
*
* @SysCap SystemCapability.PowerMgr.BatteryManager
* @devices phone, tablet
* @since 6
*/
export enum BatteryChargeState {
/**
* Unknown state.
* @devices phone, tablet
*/
NONE,
/**
* The battery is being charged.
* @devices phone, tablet
*/
ENABLE,
/**
* The battery is not being charged.
* @devices phone, tablet
*/
DISABLE,
/**
* The battery is fully charged.
* @devices phone, tablet
*/
FULL
}
/**
* Indicates the battery health status of a device.
*
* @SysCap SystemCapability.PowerMgr.BatteryManager
* @devices phone, tablet
* @since 6
*/
export enum BatteryHealthState {
/**
* Unknown state.
* @devices phone, tablet
*/
UNKNOWN,
/**
* The battery is in healthy state.
* @devices phone, tablet
*/
GOOD,
/**
* The battery is overheated.
* @devices phone, tablet
*/
OVERHEAT,
/**
* The battery voltage is over high.
* @devices phone, tablet
*/
OVERVOLTAGE,
/**
* The battery temperature is low.
* @devices phone, tablet
*/
COLD,
/**
* The battery is dead.
* @devices phone, tablet
*/
DEAD
}
}
export default batteryInfo;

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/battery_manager/batterymgr.gni")
config("batterynapi_private_config") {
include_dirs = [
"//foundation/ace/napi/native_engine",
"//foundation/ace/napi/interfaces/kits",
"//utils/system/safwk/native/include",
"//third_party/node/src",
"//base/powermgr/battery_manager/interfaces/innerkits/native/include",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include",
"//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include",
]
}
ohos_shared_library("batteryinfo") {
sources = [ "battery_info.cpp" ]
configs = [
"${utils_path}:utils_config",
":batterynapi_private_config",
]
deps = [
"//base/powermgr/battery_manager/interfaces/innerkits:batterysrv_client",
"//foundation/ace/napi:ace_napi",
]
external_deps = [
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
]
relative_install_dir = "module"
subsystem_name = "powermgr"
part_name = "battery_manager_native"
}

View File

@ -0,0 +1,288 @@
/*
* 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 <cstdio>
#include <cstdlib>
#include <string>
#include "battery_info.h"
#include "battery_srv_client.h"
#include "hilog_wrapper.h"
#include "napi/native_api.h"
#include "napi/native_node_api.h"
using namespace OHOS::PowerMgr;
static BatterySrvClient &g_battClient = BatterySrvClient::GetInstance();
static napi_value BatterySOC(napi_env env, napi_callback_info info)
{
napi_value napiValue = nullptr;
int32_t capacity = g_battClient.GetCapacity();
NAPI_CALL(env, napi_create_int32(env, capacity, &napiValue));
POWER_HILOGD(MODULE_JS_NAPI, "capacity %{public}d", capacity);
return napiValue;
}
static napi_value GetChargingState(napi_env env, napi_callback_info info)
{
napi_value napiValue = nullptr;
int32_t chargeState = (int32_t)g_battClient.GetChargingStatus();
NAPI_CALL(env, napi_create_int32(env, chargeState, &napiValue));
POWER_HILOGD(MODULE_JS_NAPI, "chargeState %{public}d", chargeState);
return napiValue;
}
static napi_value GetHealthState(napi_env env, napi_callback_info info)
{
napi_value napiValue = nullptr;
int32_t healthStatus = (int32_t)g_battClient.GetHealthStatus();
NAPI_CALL(env, napi_create_int32(env, healthStatus, &napiValue));
POWER_HILOGD(MODULE_JS_NAPI, "healthStatus %{public}d", healthStatus);
return napiValue;
}
static napi_value GetPluggedType(napi_env env, napi_callback_info info)
{
napi_value napiValue = nullptr;
int32_t pluggedType = (int32_t)g_battClient.GetPluggedType();
NAPI_CALL(env, napi_create_int32(env, pluggedType, &napiValue));
POWER_HILOGD(MODULE_JS_NAPI, "pluggedType %{public}d", pluggedType);
return napiValue;
}
static napi_value GetVoltage(napi_env env, napi_callback_info info)
{
napi_value napiValue = nullptr;
int32_t voltage = g_battClient.GetVoltage();
NAPI_CALL(env, napi_create_int32(env, voltage, &napiValue));
POWER_HILOGD(MODULE_JS_NAPI, "%{public}d", voltage);
return napiValue;
}
static napi_value GetTechnology(napi_env env, napi_callback_info info)
{
napi_value napiValue = nullptr;
auto technology = g_battClient.GetTechnology();
const char *technologyStr = technology.c_str();
NAPI_CALL(env, napi_create_string_utf8(env, technologyStr, strlen(technologyStr), &napiValue));
POWER_HILOGD(MODULE_JS_NAPI, "technology %{public}s", technologyStr);
return napiValue;
}
static napi_value GetBatteryTemperature(napi_env env, napi_callback_info info)
{
napi_value napiValue = nullptr;
int32_t temperature = g_battClient.GetBatteryTemperature();
NAPI_CALL(env, napi_create_int32(env, temperature, &napiValue));
POWER_HILOGD(MODULE_JS_NAPI, "%{public}d", temperature);
return napiValue;
}
static napi_value EnumHealthClassConstructor(napi_env env, napi_callback_info info)
{
napi_value thisArg = nullptr;
void *data = nullptr;
napi_get_cb_info(env, info, nullptr, nullptr, &thisArg, &data);
napi_value global = nullptr;
napi_get_global(env, &global);
return thisArg;
}
static napi_value CreateEnumHealthState(napi_env env, napi_value exports)
{
napi_value unknown = nullptr;
napi_value good = nullptr;
napi_value overheat = nullptr;
napi_value overvoltage = nullptr;
napi_value cold = nullptr;
napi_value dead = nullptr;
napi_create_int32(env, (int32_t)BatteryHealthState::HEALTH_STATE_UNKNOWN, &unknown);
napi_create_int32(env, (int32_t)BatteryHealthState::HEALTH_STATE_GOOD, &good);
napi_create_int32(env, (int32_t)BatteryHealthState::HEALTH_STATE_OVERHEAT, &overheat);
napi_create_int32(env, (int32_t)BatteryHealthState::HEALTH_STATE_OVERVOLTAGE, &overvoltage);
napi_create_int32(env, (int32_t)BatteryHealthState::HEALTH_STATE_COLD, &cold);
napi_create_int32(env, (int32_t)BatteryHealthState::HEALTH_STATE_DEAD, &dead);
napi_property_descriptor desc[] = {
DECLARE_NAPI_STATIC_PROPERTY("UNKNOWN", unknown),
DECLARE_NAPI_STATIC_PROPERTY("GOOD", good),
DECLARE_NAPI_STATIC_PROPERTY("OVERHEAT", overheat),
DECLARE_NAPI_STATIC_PROPERTY("OVERVOLTAGE", overvoltage),
DECLARE_NAPI_STATIC_PROPERTY("COLD", cold),
DECLARE_NAPI_STATIC_PROPERTY("DEAD", dead),
};
napi_value result = nullptr;
napi_define_class(env, "BatteryHealthState", NAPI_AUTO_LENGTH, EnumHealthClassConstructor, nullptr,
sizeof(desc) / sizeof(*desc), desc, &result);
napi_set_named_property(env, exports, "BatteryHealthState", result);
return exports;
}
static napi_value EnumChargeClassConstructor(napi_env env, napi_callback_info info)
{
napi_value thisArg = nullptr;
void *data = nullptr;
napi_get_cb_info(env, info, nullptr, nullptr, &thisArg, &data);
napi_value global = nullptr;
napi_get_global(env, &global);
return thisArg;
}
static napi_value CreateEnumChargeState(napi_env env, napi_value exports)
{
napi_value none = nullptr;
napi_value enable = nullptr;
napi_value disable = nullptr;
napi_value full = nullptr;
napi_create_int32(env, (int32_t)BatteryChargeState::CHARGE_STATE_NONE, &none);
napi_create_int32(env, (int32_t)BatteryChargeState::CHARGE_STATE_ENABLE, &enable);
napi_create_int32(env, (int32_t)BatteryChargeState::CHARGE_STATE_DISABLE, &disable);
napi_create_int32(env, (int32_t)BatteryChargeState::CHARGE_STATE_FULL, &full);
napi_property_descriptor desc[] = {
DECLARE_NAPI_STATIC_PROPERTY("NONE", none),
DECLARE_NAPI_STATIC_PROPERTY("ENABLE", enable),
DECLARE_NAPI_STATIC_PROPERTY("DISABLE", disable),
DECLARE_NAPI_STATIC_PROPERTY("FULL", full),
};
napi_value result = nullptr;
napi_define_class(env, "BatteryChargeState", NAPI_AUTO_LENGTH, EnumChargeClassConstructor, nullptr,
sizeof(desc) / sizeof(*desc), desc, &result);
napi_set_named_property(env, exports, "BatteryChargeState", result);
return exports;
}
static napi_value EnumPluggedClassConstructor(napi_env env, napi_callback_info info)
{
napi_value thisArg = nullptr;
void *data = nullptr;
napi_get_cb_info(env, info, nullptr, nullptr, &thisArg, &data);
napi_value global = nullptr;
napi_get_global(env, &global);
return thisArg;
}
static napi_value CreateEnumPluggedType(napi_env env, napi_value exports)
{
napi_value none = nullptr;
napi_value ac = nullptr;
napi_value usb = nullptr;
napi_value wireless = nullptr;
napi_create_int32(env, (int32_t)BatteryPluggedType::PLUGGED_TYPE_NONE, &none);
napi_create_int32(env, (int32_t)BatteryPluggedType::PLUGGED_TYPE_AC, &ac);
napi_create_int32(env, (int32_t)BatteryPluggedType::PLUGGED_TYPE_USB, &usb);
napi_create_int32(env, (int32_t)BatteryPluggedType::PLUGGED_TYPE_WIRELESS, &wireless);
napi_property_descriptor desc[] = {
DECLARE_NAPI_STATIC_PROPERTY("NONE", none),
DECLARE_NAPI_STATIC_PROPERTY("AC", ac),
DECLARE_NAPI_STATIC_PROPERTY("USB", usb),
DECLARE_NAPI_STATIC_PROPERTY("WIRELESS", wireless),
};
napi_value result = nullptr;
napi_define_class(env, "BatteryPluggedType", NAPI_AUTO_LENGTH, EnumPluggedClassConstructor, nullptr,
sizeof(desc) / sizeof(*desc), desc, &result);
napi_set_named_property(env, exports, "BatteryPluggedType", result);
return exports;
}
EXTERN_C_START
/*
* function for module exports
*/
static napi_value BatteryInit(napi_env env, napi_value exports)
{
POWER_HILOGD(MODULE_JS_NAPI, "enter");
napi_property_descriptor desc[] = {
DECLARE_NAPI_GETTER("batterySOC", BatterySOC),
DECLARE_NAPI_GETTER("chargingStatus", GetChargingState),
DECLARE_NAPI_GETTER("healthStatus", GetHealthState),
DECLARE_NAPI_GETTER("pluggedType", GetPluggedType),
DECLARE_NAPI_GETTER("voltage", GetVoltage),
DECLARE_NAPI_GETTER("technology", GetTechnology),
DECLARE_NAPI_GETTER("batteryTemperature", GetBatteryTemperature),
};
NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc));
CreateEnumPluggedType(env, exports);
CreateEnumChargeState(env, exports);
CreateEnumHealthState(env, exports);
POWER_HILOGD(MODULE_JS_NAPI, "return");
return exports;
}
EXTERN_C_END
/*
* Module definition
*/
static napi_module g_module = {
.nm_version = 1,
.nm_flags = 0,
.nm_filename = "batteryInfo",
.nm_register_func = BatteryInit,
.nm_modname = "batteryInfo",
.nm_priv = ((void *)0),
.reserved = {0}
};
/*
* Module registration
*/
extern "C" __attribute__((constructor)) void RegisterModule(void)
{
napi_module_register(&g_module);
}

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.
*/
import app from '@system.app'
import Context from '@ohos.napi_context'
import batteryInfo from '@ohos.batteryInfo';
import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index'
describe('appInfoTest', function () {
console.log("*************Battery Unit Test Begin*************");
it('battery_soc_test', 0, function () {
var batterySoc = batteryInfo.batterySOC;
console.info('batterySoc = ' + batterySoc);
expect(batterySoc >= 0 && batterySoc <= 100).assertEqual('1')
})
it('charging_status_test', 0, function () {
var chargingStatus = batteryInfo.chargingStatus;
console.info('chargingStatus = ' + chargingStatus);
expect(chargingStatus >= 0 && chargingStatus <= 3).assertEqual('1')
})
it('health_status_test', 0, function () {
var healthStatus = batteryInfo.healthStatus;
console.info('healthStatus = ' + healthStatus);
expect(healthStatus >= 0 && healthStatus <= 5).assertEqual('1')
})
it('plugged_type_test', 0, function () {
var pluggedType = batteryInfo.pluggedType;
console.info('pluggedType = ' + pluggedType);
expect(pluggedType >= 0 && pluggedType <= 3).assertEqual('1')
})
it('voltage_test', 0, function () {
var voltage = batteryInfo.voltage;
console.info('voltage = ' + voltage);
expect(voltage >= 0).assertEqual('1')
})
it('technology_test', 0, function () {
var technology = batteryInfo.technology;
console.info('technology = ' + technology);
expect(0).assertEqual('0')
})
it('battery_temperature_test', 0, function () {
var batteryTemperature = batteryInfo.batteryTemperature;
console.info('batteryTemperature = ' + batteryTemperature);
expect(batteryTemperature <= 100).assertEqual('1')
})
it('enum_health_state_test_unknown', 0, function () {
var batteryHealthState = batteryInfo.BatteryHealthState.UNKNOWN;
console.info('batteryHealthState = ' + batteryHealthState);
expect(batteryHealthState == 0).assertEqual('1')
})
it('enum_health_state_test_good', 0, function () {
var batteryHealthState = batteryInfo.BatteryHealthState.GOOD;
console.info('batteryHealthState = ' + batteryHealthState);
expect(batteryHealthState == 1).assertEqual('1')
})
it('enum_health_state_test_overheat', 0, function () {
var batteryHealthState = batteryInfo.BatteryHealthState.OVERHEAT;
console.info('batteryHealthState = ' + batteryHealthState);
expect(batteryHealthState == 2).assertEqual('1')
})
it('enum_health_state_test_overvoltage', 0, function () {
var batteryHealthState = batteryInfo.BatteryHealthState.OVERVOLTAGE;
console.info('batteryHealthState = ' + batteryHealthState);
expect(batteryHealthState == 3).assertEqual('1')
})
it('enum_health_state_test_cold', 0, function () {
var batteryHealthState = batteryInfo.BatteryHealthState.COLD;
console.info('batteryHealthState = ' + batteryHealthState);
expect(batteryHealthState == 4).assertEqual('1')
})
it('enum_health_state_test_dead', 0, function () {
var batteryHealthState = batteryInfo.BatteryHealthState.DEAD;
console.info('batteryHealthState = ' + batteryHealthState);
expect(batteryHealthState == 5).assertEqual('1')
})
it('enum_charge_state_test_none', 0, function () {
var batteryChargeState = batteryInfo.BatteryChargeState.NONE;
console.info('batteryChargeState = ' + batteryChargeState);
expect(batteryChargeState == 0).assertEqual('1')
})
it('enum_charge_state_test_enable', 0, function () {
var batteryChargeState = batteryInfo.BatteryChargeState.ENABLE;
console.info('batteryChargeState = ' + batteryChargeState);
expect(batteryChargeState == 1).assertEqual('1')
})
it('enum_charge_state_test_disable', 0, function () {
var batteryChargeState = batteryInfo.BatteryChargeState.DISABLE;
console.info('batteryChargeState = ' + batteryChargeState);
expect(batteryChargeState == 2).assertEqual('1')
})
it('enum_charge_state_test_full', 0, function () {
var batteryChargeState = batteryInfo.BatteryChargeState.FULL;
console.info('batteryChargeState = ' + batteryChargeState);
expect(batteryChargeState == 3).assertEqual('1')
})
it('enum_plugged_type_test_none', 0, function () {
var batteryPluggedType = batteryInfo.BatteryPluggedType.NONE;
console.info('batteryPluggedType = ' + batteryPluggedType);
expect(batteryPluggedType == 0).assertEqual('1')
})
it('enum_plugged_type_test_ac', 0, function () {
var batteryPluggedType = batteryInfo.BatteryPluggedType.AC;
console.info('batteryPluggedType = ' + batteryPluggedType);
expect(batteryPluggedType == 1).assertEqual('1')
})
it('enum_plugged_type_test_usb', 0, function () {
var batteryPluggedType = batteryInfo.BatteryPluggedType.USB;
console.info('batteryPluggedType = ' + batteryPluggedType);
expect(batteryPluggedType == 2).assertEqual('1')
})
it('enum_plugged_type_test_wireless', 0, function () {
var batteryPluggedType = batteryInfo.BatteryPluggedType.WIRELESS;
console.info('batteryPluggedType = ' + batteryPluggedType);
expect(batteryPluggedType == 3).assertEqual('1')
})
})

33
ohos.build Normal file
View File

@ -0,0 +1,33 @@
{
"subsystem": "powermgr",
"parts": {
"battery_manager_native": {
"system_capabilities": [
"SystemCapability.PowerMgr.BatteryManager"
],
"module_list": [
"//base/powermgr/battery_manager/hdi:hdi_group",
"//base/powermgr/battery_manager/interfaces/innerkits:batterysrv_client",
"//base/powermgr/battery_manager/sa_profile:batterymgr_sa_profile",
"//base/powermgr/battery_manager/services:batteryservice",
"//base/powermgr/battery_manager/interfaces/kits/js/napi:batteryinfo"
],
"inner_kits": [
{
"name": "//base/powermgr/battery_manager/interfaces/innerkits:batterysrv_client",
"header": {
"header_files": [
"battery_srv_client.h",
"ibattery_srv.h",
"battery_info.h"
],
"header_base": "//base/powermgr/battery_manager/interfaces/innerkits/native/include"
}
}
],
"test_list": [
"//base/powermgr/battery_manager/services/native/test:unittest"
]
}
}
}

24
sa_profile/3302.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>3302</name>
<libpath>libbatteryservice.z.so</libpath>
<run-on-create>true</run-on-create>
<distributed>false</distributed>
<dump-level>1</dump-level>
</systemability>
</info>

19
sa_profile/BUILD.gn Normal file
View File

@ -0,0 +1,19 @@
# 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/sa_profile/sa_profile.gni")
ohos_sa_profile("batterymgr_sa_profile") {
sources = [ "3302.xml" ]
part_name = "battery_manager_native"
}

62
services/BUILD.gn Normal file
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.
import("//base/powermgr/battery_manager/batterymgr.gni")
config("batterysrv_private_config") {
include_dirs = [ "//utils/system/safwk/native/include" ]
}
config("batterysrv_public_config") {
include_dirs = [
"native/include",
"${battery_manager_path}/services/zidl/include",
]
}
ohos_shared_library("batteryservice") {
sources = [
"${battery_manager_path}/services/zidl/src/battery_srv_stub.cpp",
"native/src/battery_service.cpp",
"native/src/battery_service_subscriber.cpp",
"native/src/batterysrv_event_handler.cpp",
]
configs = [
"${utils_path}:utils_config",
":batterysrv_private_config",
]
public_configs = [ ":batterysrv_public_config" ]
deps = [
"${battery_manager_path}/hdi/client:batteryd_client",
"${battery_manager_path}/interfaces/innerkits:batterysrv_client",
"//utils/native/base:utils",
]
external_deps = [
"aafwk_standard:base",
"aafwk_standard:want",
"appexecfwk_standard:appexecfwk_base",
"appexecfwk_standard:libeventhandler",
"ces_standard:cesfwk_innerkits",
"ces_standard:cesfwk_kits",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"safwk:system_ability_fwk",
"samgr_L2:samgr_proxy",
]
part_name = "battery_manager_native"
}

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_BATTERY_SERVICE_H
#define POWERMGR_BATTERY_SERVICE_H
#include "sp_singleton.h"
#include "system_ability.h"
#include "iremote_object.h"
#include "ibattery_srv.h"
#include "batteryd_api.h"
#include "batteryd_client.h"
#include "batteryd_subscriber.h"
#include "battery_service_subscriber.h"
#include "battery_srv_stub.h"
#include "batterysrv_event_handler.h"
namespace OHOS {
namespace PowerMgr {
class BatteryService final : public SystemAbility,
public BatterySrvStub {
DECLARE_SYSTEM_ABILITY(BatteryService)
DECLARE_DELAYED_SP_SINGLETON(BatteryService);
public:
virtual void OnStart() override;
virtual void OnStop() override;
bool IsServiceReady() const
{
return ready_;
}
std::shared_ptr<BatterysrvEventHandler> GetHandler() const
{
return handler_;
}
int32_t GetCapacity() override;
BatteryChargeState GetChargingStatus() override;
BatteryHealthState GetHealthStatus() override;
BatteryPluggedType GetPluggedType() override;
int32_t GetVoltage() override;
bool GetPresent() override;
std::string GetTechnology() override;
int32_t GetBatteryTemperature() override;
private:
bool Init();
bool InitBatteryd();
bool IsCommonEventServiceAbilityExist();
bool ready_ {false};
int32_t commEventRetryTimes_ {0};
std::mutex mutex_;
std::shared_ptr<AppExecFwk::EventRunner> eventRunner_;
std::shared_ptr<BatterysrvEventHandler> handler_;
sptr<BatteryServiceSubscriber> batterydSubscriber_;
};
} // namespace PowerMgr
} // namespace OHOS
#endif // POWERMGR_BATTERY_SERVICE_H

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 BATTERY_SERVICE_SUBSCRIBER_H
#define BATTERY_SERVICE_SUBSCRIBER_H
#include "batteryd_subscriber.h"
namespace OHOS {
namespace PowerMgr {
class BatteryServiceSubscriber : public BatterydSubscriber {
public:
BatteryServiceSubscriber();
~BatteryServiceSubscriber() = default;
int32_t Update(const BatteryInfo &info) override;
private:
static bool HandleBatteryChangedEvent(const BatteryInfo &info);
};
} // namespace PowerMgr
} // namespace OHOS
#endif // BATTERY_SERVICE_SUBSCRIBER_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_BATTERYSRV_EVENT_HANDLER_H
#define POWERMGR_BATTERYSRV_EVENT_HANDLER_H
#include "refbase.h"
#include "event_handler.h"
namespace OHOS {
namespace PowerMgr {
class BatteryService;
class BatterysrvEventHandler : public AppExecFwk::EventHandler {
public:
BatterysrvEventHandler(const std::shared_ptr<AppExecFwk::EventRunner> &runner,
const wptr<BatteryService> &service);
~BatterysrvEventHandler() = default;
void ProcessEvent(const AppExecFwk::InnerEvent::Pointer &event) override;
private:
wptr<BatteryService> service_;
};
} // namespace PowerMgr
} // namespace OHOS
#endif // POWERMGR_BATTERYSRV_EVENT_HANDLER_H

View File

@ -0,0 +1,167 @@
/*
* 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 "battery_service.h"
#include <unistd.h>
#include "file_ex.h"
#include "if_system_ability_manager.h"
#include "iservice_registry.h"
#include "system_ability_definition.h"
#include "power_common.h"
namespace OHOS {
namespace PowerMgr {
namespace {
const std::string BATTERY_SERVICE_NAME = "BatteryService";
constexpr int32_t COMMEVENT_REGISTER_RETRY_TIMES = 10;
constexpr int32_t COMMEVENT_REGISTER_WAIT_DELAY_US = 20000;
}
const bool G_REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(
DelayedSpSingleton<BatteryService>::GetInstance().GetRefPtr());
BatteryService::BatteryService()
: SystemAbility(POWER_MANAGER_BATT_SERVICE_ID, true) {}
BatteryService::~BatteryService() {}
void BatteryService::OnStart()
{
POWER_HILOGI(MODULE_BATT_SERVICE, "OnStart enter");
if (ready_) {
POWER_HILOGE(MODULE_BATT_SERVICE, "OnStart is ready, nothing to do");
return;
}
if (!(Init())) {
POWER_HILOGE(MODULE_BATT_SERVICE, "OnStart call init fail");
return;
}
if (!(InitBatteryd())) {
POWER_HILOGE(MODULE_BATT_SERVICE, "OnStart call initBatteryd fail");
return;
}
ready_ = true;
POWER_HILOGI(MODULE_BATT_SERVICE, "OnStart and add system ability success");
}
bool BatteryService::Init()
{
POWER_HILOGI(MODULE_BATT_SERVICE, "Init start");
if (!eventRunner_) {
eventRunner_ = AppExecFwk::EventRunner::Create(BATTERY_SERVICE_NAME);
if (eventRunner_ == nullptr) {
POWER_HILOGE(MODULE_BATT_SERVICE, "Init failed due to create EventRunner");
return false;
}
}
if (!handler_) {
handler_ = std::make_shared<BatterysrvEventHandler>(eventRunner_,
DelayedSpSingleton<BatteryService>::GetInstance());
if (handler_ == nullptr) {
POWER_HILOGE(MODULE_BATT_SERVICE, "Init failed due to create handler error");
return false;
}
}
while (commEventRetryTimes_ <= COMMEVENT_REGISTER_RETRY_TIMES) {
if (!IsCommonEventServiceAbilityExist()) {
commEventRetryTimes_++;
usleep(COMMEVENT_REGISTER_WAIT_DELAY_US);
} else {
commEventRetryTimes_ = 0;
break;
}
}
POWER_HILOGI(MODULE_BATT_SERVICE, "Init success");
return true;
}
bool BatteryService::InitBatteryd()
{
batterydSubscriber_ = new BatteryServiceSubscriber();
ErrCode ret = BatterydClient::BindBatterydSubscriber(batterydSubscriber_);
POWER_HILOGD(MODULE_BATT_SERVICE, "InitBatteryd ret: %{public}d", ret);
return SUCCEEDED(ret);
}
void BatteryService::OnStop()
{
POWER_HILOGI(MODULE_BATT_SERVICE, "stop service");
if (!ready_) {
return;
}
eventRunner_.reset();
handler_.reset();
ready_ = false;
BatterydClient::UnbindBatterydSubscriber();
}
bool BatteryService::IsCommonEventServiceAbilityExist()
{
sptr<ISystemAbilityManager> sm = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (!sm) {
POWER_HILOGI(MODULE_BATT_SERVICE,
"IsCommonEventServiceAbilityExist Get ISystemAbilityManager failed, no SystemAbilityManager");
return false;
}
sptr<IRemoteObject> remote = sm->CheckSystemAbility(COMMON_EVENT_SERVICE_ABILITY_ID);
if (!remote) {
POWER_HILOGE(MODULE_BATT_SERVICE, "No CesServiceAbility");
return false;
}
return true;
}
int32_t BatteryService::GetCapacity()
{
return BatterydClient::GetCapacity();
}
BatteryChargeState BatteryService::GetChargingStatus()
{
return BatterydClient::GetChargeState();
}
BatteryHealthState BatteryService::GetHealthStatus()
{
return BatterydClient::GetHealthState();
}
BatteryPluggedType BatteryService::GetPluggedType()
{
return BatterydClient::GetPluggedType();
}
int32_t BatteryService::GetVoltage()
{
return BatterydClient::GetVoltage();
}
bool BatteryService::GetPresent()
{
return BatterydClient::GetPresent();
}
std::string BatteryService::GetTechnology()
{
return BatterydClient::GetTechnology();
}
int32_t BatteryService::GetBatteryTemperature()
{
return BatterydClient::GetTemperature();
}
} // namespace PowerMgr
} // namespace OHOS

View File

@ -0,0 +1,83 @@
/*
* 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 "battery_service_subscriber.h"
#include "common_event_data.h"
#include "common_event_manager.h"
#include "common_event_support.h"
#include "ohos/aafwk/content/want.h"
#include "power_common.h"
#include "string_ex.h"
using namespace OHOS::AAFwk;
using namespace OHOS::EventFwk;
namespace OHOS {
namespace PowerMgr {
BatteryServiceSubscriber::BatteryServiceSubscriber() {}
int32_t BatteryServiceSubscriber::Update(const BatteryInfo &info)
{
POWER_HILOGD(MODULE_BATT_SERVICE, "BatteryInfo: capacity=%{public}d, voltage=%{public}d, " \
"temperature=%{public}d, healthState=%{public}d, pluggedType=%{public}d, " \
"pluggedMaxCurrent=%{public}d, pluggedMaxVoltage=%{public}d, " \
"chargeState=%{public}d, chargeCounter=%{public}d, present=%{public}d, " \
"technology=%{public}s",
info.GetCapacity(), info.GetVoltage(), info.GetTemperature(), info.GetHealthState(),
info.GetPluggedType(), info.GetPluggedMaxCurrent(), info.GetPluggedMaxVoltage(), info.GetChargeState(),
info.GetChargeCounter(), info.IsPresent(), info.GetTechnology().c_str());
bool ret = HandleBatteryChangedEvent(info);
return ret ? ERR_OK : ERR_NO_INIT;
}
bool BatteryServiceSubscriber::HandleBatteryChangedEvent(const BatteryInfo &info)
{
Want want;
want.SetAction(CommonEventSupport::COMMON_EVENT_BATTERY_CHANGED);
CommonEventData data;
data.SetWant(want);
data.SetCode(BatteryInfo::COMMON_EVENT_CODE_CAPACITY);
data.SetData(ToString(info.GetCapacity()));
data.SetCode(BatteryInfo::COMMON_EVENT_CODE_VOLTAGE);
data.SetData(ToString(info.GetVoltage()));
data.SetCode(BatteryInfo::COMMON_EVENT_CODE_TEMPERATURE);
data.SetData(ToString(info.GetTemperature()));
data.SetCode(BatteryInfo::COMMON_EVENT_CODE_HEALTH_STATE);
data.SetData(ToString(static_cast<uint32_t>(info.GetHealthState())));
data.SetCode(BatteryInfo::COMMON_EVENT_CODE_PLUGGED_TYPE);
data.SetData(ToString(static_cast<uint32_t>(info.GetPluggedType())));
data.SetCode(BatteryInfo::COMMON_EVENT_CODE_PLUGGED_MAX_CURRENT);
data.SetData(ToString(info.GetPluggedMaxCurrent()));
data.SetCode(BatteryInfo::COMMON_EVENT_CODE_PLUGGED_MAX_VOLTAGE);
data.SetData(ToString(info.GetPluggedMaxVoltage()));
data.SetCode(BatteryInfo::COMMON_EVENT_CODE_CHARGE_STATE);
data.SetData(ToString(static_cast<uint32_t>(info.GetChargeState())));
data.SetCode(BatteryInfo::COMMON_EVENT_CODE_CHARGE_COUNTER);
data.SetData(ToString(info.GetChargeCounter()));
data.SetCode(BatteryInfo::COMMON_EVENT_CODE_PRESENT);
data.SetData(ToString(info.IsPresent()));
data.SetCode(BatteryInfo::COMMON_EVENT_CODE_TECHNOLOGY);
data.SetData(info.GetTechnology());
CommonEventPublishInfo publishInfo;
publishInfo.SetOrdered(true);
bool isSuccess = CommonEventManager::PublishCommonEvent(data, publishInfo);
if (!isSuccess) {
POWER_HILOGD(MODULE_BATT_SERVICE, "failed to publish BATTERY_CHANGED event");
}
return isSuccess;
}
} // namespace PowerMgr
} // namespace OHOS

View File

@ -0,0 +1,31 @@
/*
* 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 "batterysrv_event_handler.h"
#include "power_common.h"
#include "battery_service.h"
namespace OHOS {
namespace PowerMgr {
BatterysrvEventHandler::BatterysrvEventHandler(const std::shared_ptr<AppExecFwk::EventRunner> &runner,
const wptr<BatteryService> &service)
: AppExecFwk::EventHandler(runner), service_(service)
{
POWER_HILOGD(MODULE_BATT_SERVICE, "BatterysrvEventHandler::BatterysrvEventHandler instance created.");
}
void BatterysrvEventHandler::ProcessEvent([[maybe_unused]] const AppExecFwk::InnerEvent::Pointer &event) {}
} // 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("//build/test.gni")
group("unittest") {
testonly = true
if (is_large_system) {
deps = [ "unittest/common:unittest" ]
}
}

View File

@ -0,0 +1,63 @@
# 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/battery_manager/batterymgr.gni")
import("//build/test.gni")
module_output_path = "battery_manager_native/batterysrv"
###############################################################################
config("module_private_config") {
visibility = [ ":*" ]
include_dirs = [
"include",
"//utils/system/safwk/native/include",
]
}
##############################unittest##########################################
ohos_unittest("test_batterysrv") {
module_out_path = module_output_path
sources = [ "src/battery_service_test.cpp" ]
configs = [
"${utils_path}:utils_config",
":module_private_config",
]
deps = [
"${battery_manager_path}/interfaces/innerkits:batterysrv_client",
"${battery_manager_path}/services:batteryservice",
"//third_party/googletest:gtest_main",
"//utils/native/base:utils",
]
external_deps = [
"aafwk_standard:base",
"aafwk_standard:intent",
"appexecfwk_standard:appexecfwk_base",
"appexecfwk_standard:libeventhandler",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"samgr_L2:samgr_proxy",
]
}
group("unittest") {
testonly = true
deps = []
deps += [ ":test_batterysrv" ]
}

View File

@ -0,0 +1,29 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef BATTERY_SERVICE_TEST_H
#define BATTERY_SERVICE_TEST_H
#include <gtest/gtest.h>
class BatteryServiceTest : public testing::Test {
public:
static void SetUpTestCase();
static void TearDownTestCase();
void SetUp();
void TearDown();
bool IsBatterySupported();
};
#endif // BATTERY_SERVICE_TEST_H

View File

@ -0,0 +1,204 @@
/*
* 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 "battery_service_test.h"
#include <csignal>
#include "battery_srv_client.h"
#include "battery_service.h"
#include "power_common.h"
#include "iservice_registry.h"
#include "if_system_ability_manager.h"
#include "system_ability_definition.h"
#include "ipc_skeleton.h"
#include "string_ex.h"
#include "sys_param.h"
#include <iostream>
using namespace testing::ext;
using namespace OHOS::PowerMgr;
using namespace OHOS;
using namespace std;
void BatteryServiceTest::SetUpTestCase(void)
{
}
void BatteryServiceTest::TearDownTestCase(void)
{
}
void BatteryServiceTest::SetUp(void)
{
}
void BatteryServiceTest::TearDown(void)
{
}
bool BatteryServiceTest::IsBatterySupported()
{
auto& BatterySrvClient = BatterySrvClient::GetInstance();
auto presentState = BatterySrvClient.GetPresent();
auto isCar = SysParam::IsDeviceType(DeviceType::DEVICE_CAR);
auto isTv = SysParam::IsDeviceType(DeviceType::DEVICE_TV);
POWER_HILOGI(MODULE_BATT_SERVICE, "BatteryServiceTest::isCar = %{public}d, isTv = %{public}d, present=%{public}d",
isCar, isTv, presentState);
if (!presentState || isCar || isTv) {
return false;
}
return true;
}
/**
* @tc.name: BatteryService001
* @tc.desc: Test functions to get status of Present
* @tc.type: FUNC
*/
HWTEST_F (BatteryServiceTest, BatteryService001, TestSize.Level1)
{
auto& BatterySrvClient = BatterySrvClient::GetInstance();
auto present = BatterySrvClient.GetPresent();
POWER_HILOGI(MODULE_BATT_SERVICE, "BatteryServiceTest::present=%{public}d", present);
if (BatteryServiceTest::IsBatterySupported()) {
ASSERT_TRUE(present);
} else {
ASSERT_FALSE(present);
}
POWER_HILOGD(MODULE_BATT_SERVICE, "BatteryService::BatteryService001 end.");
}
/**
* @tc.name: BatteryService002
* @tc.desc: Test functions to get status of BatteryService
* @tc.type: FUNC
*/
HWTEST_F (BatteryServiceTest, BatteryService002, TestSize.Level1)
{
auto& BatterySrvClient = BatterySrvClient::GetInstance();
auto chargingStatus = BatterySrvClient.GetChargingStatus();
POWER_HILOGI(MODULE_BATT_SERVICE, "BatteryServiceTest::status=%{public}d", chargingStatus);
if (BatteryServiceTest::IsBatterySupported()) {
ASSERT_TRUE(chargingStatus != BatteryChargeState::CHARGE_STATE_BUTT);
} else {
POWER_HILOGE(MODULE_BATT_SERVICE, "BatteryServiceTest::test is disabled, do nothing");
}
POWER_HILOGD(MODULE_BATT_SERVICE, "BatteryService::BatteryService002 end.");
}
/**
* @tc.name: BatteryService003
* @tc.desc: Test functions to get value of BatteryService
* @tc.type: FUNC
*/
HWTEST_F (BatteryServiceTest, BatteryService003, TestSize.Level1)
{
auto& BatterySrvClient = BatterySrvClient::GetInstance();
auto healthStatus = BatterySrvClient.GetHealthStatus();
POWER_HILOGI(MODULE_BATT_SERVICE, "BatteryServiceTest::health=%{public}d", healthStatus);
if (BatteryServiceTest::IsBatterySupported()) {
ASSERT_TRUE(healthStatus != BatteryHealthState::HEALTH_STATE_BUTT);
}
POWER_HILOGD(MODULE_BATT_SERVICE, "BatteryService::BatteryService003 end.");
}
/**
* @tc.name: BatteryService004
* @tc.desc: Test functions of BatteryService
* @tc.type: FUNC
*/
HWTEST_F (BatteryServiceTest, BatteryService004, TestSize.Level1)
{
auto& BatterySrvClient = BatterySrvClient::GetInstance();
auto capacity = BatterySrvClient.GetCapacity();
POWER_HILOGI(MODULE_BATT_SERVICE, "BatteryServiceTest::soc=%{public}d", capacity);
if (BatteryServiceTest::IsBatterySupported()) {
ASSERT_TRUE(capacity != INVALID_BATT_INT_VALUE);
}
POWER_HILOGD(MODULE_BATT_SERVICE, "BatteryService::BatteryService004 end.");
}
/**
* @tc.name: BatteryService005
* @tc.desc: Test functions of BatteryService
* @tc.type: FUNC
*/
HWTEST_F (BatteryServiceTest, BatteryService005, TestSize.Level1)
{
auto& BatterySrvClient = BatterySrvClient::GetInstance();
auto voltage = BatterySrvClient.GetVoltage();
POWER_HILOGI(MODULE_BATT_SERVICE, "BatteryServiceTest::voltage=%{public}d", voltage);
if (BatteryServiceTest::IsBatterySupported()) {
ASSERT_TRUE(voltage != INVALID_BATT_INT_VALUE);
}
POWER_HILOGD(MODULE_BATT_SERVICE, "BatteryService::BatteryService005 end.");
}
/**
* @tc.name: BatteryService006
* @tc.desc: Test functions of BatteryService
* @tc.type: FUNC
*/
HWTEST_F (BatteryServiceTest, BatteryService006, TestSize.Level1)
{
auto& BatterySrvClient = BatterySrvClient::GetInstance();
auto temp = BatterySrvClient.GetBatteryTemperature();
POWER_HILOGI(MODULE_BATT_SERVICE, "BatteryServiceTest::temp=%{public}d", temp);
if (BatteryServiceTest::IsBatterySupported()) {
ASSERT_TRUE(temp != INVALID_BATT_TEMP_VALUE);
}
POWER_HILOGD(MODULE_BATT_SERVICE, "BatteryService::BatteryService006 end.");
}
/**
* @tc.name: BatteryService007
* @tc.desc: Test functions of BatteryService
* @tc.type: FUNC
*/
HWTEST_F (BatteryServiceTest, BatteryService007, TestSize.Level1)
{
auto& BatterySrvClient = BatterySrvClient::GetInstance();
auto technology = BatterySrvClient.GetTechnology();
POWER_HILOGI(MODULE_BATT_SERVICE, "BatteryServiceTest::technology=%{public}s", technology.c_str());
if (BatteryServiceTest::IsBatterySupported()) {
ASSERT_TRUE(technology != INVALID_STRING_VALUE);
}
POWER_HILOGD(MODULE_BATT_SERVICE, "BatteryService::BatteryService007 end.");
}
/**
* @tc.name: BatteryService008
* @tc.desc: Test functions of BatteryService
* @tc.type: FUNC
*/
HWTEST_F (BatteryServiceTest, BatteryService008, TestSize.Level1)
{
auto& BatterySrvClient = BatterySrvClient::GetInstance();
auto type = BatterySrvClient.GetPluggedType();
POWER_HILOGI(MODULE_BATT_SERVICE, "BatteryServiceTest::type=%{public}d", type);
if (BatteryServiceTest::IsBatterySupported()) {
ASSERT_TRUE(type != BatteryPluggedType::PLUGGED_TYPE_BUTT);
}
POWER_HILOGD(MODULE_BATT_SERVICE, "BatteryService::BatteryService008 end.");
}

View File

@ -0,0 +1,19 @@
/*
* Copyright 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.
*/
interface OhOs.PowerMgr.IBatterySrv {
/* the function about BatteryService */
}

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 BATTERY_SRV_PROXY_H
#define BATTERY_SRV_PROXY_H
#include "ibattery_srv.h"
#include "nocopyable.h"
#include "iremote_proxy.h"
namespace OHOS {
namespace PowerMgr {
class BatterySrvProxy : public IRemoteProxy<IBatterySrv> {
public:
explicit BatterySrvProxy(const sptr<IRemoteObject>& impl)
: IRemoteProxy<IBatterySrv>(impl) {}
~BatterySrvProxy() = default;
DISALLOW_COPY_AND_MOVE(BatterySrvProxy);
virtual int32_t GetCapacity() override;
virtual BatteryChargeState GetChargingStatus() override;
virtual BatteryHealthState GetHealthStatus() override;
virtual BatteryPluggedType GetPluggedType() override;
virtual int32_t GetVoltage() override;
virtual bool GetPresent() override;
virtual std::string GetTechnology() override;
virtual int32_t GetBatteryTemperature() override;
private:
static inline BrokerDelegator<BatterySrvProxy> delegator_;
};
} // namespace PowerMgr
} // namespace OHOS
#endif // BATTERY_SRV_PROXY_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.
*/
#ifndef BATTERY_SRV_STUB_H
#define BATTERY_SRV_STUB_H
#include "ibattery_srv.h"
#include "nocopyable.h"
#include "iremote_stub.h"
namespace OHOS {
namespace PowerMgr {
class BatterySrvStub : public IRemoteStub<IBatterySrv> {
public:
DISALLOW_COPY_AND_MOVE(BatterySrvStub);
BatterySrvStub() = default;
virtual ~BatterySrvStub() = default;
int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override;
private:
int32_t GetCapacityStub(MessageParcel& reply);
int32_t GetChargingStatusStub(MessageParcel& reply);
int32_t GetHealthStatusStub(MessageParcel& reply);
int32_t GetPluggedTypeStub(MessageParcel& reply);
int32_t GetVoltageStub(MessageParcel& reply);
int32_t GetPresentStub(MessageParcel& reply);
int32_t GetTechnologyStub(MessageParcel& reply);
int32_t GetBatteryTemperatureStub(MessageParcel& reply);
};
} // namespace PowerMgr
} // namespace OHOS
#endif // BATTERY_SRV_STUB_H

View File

@ -0,0 +1,223 @@
/*
* 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 "battery_srv_proxy.h"
#include "ipc_types.h"
#include "message_parcel.h"
#include "power_common.h"
namespace OHOS {
namespace PowerMgr {
int32_t BatterySrvProxy::GetCapacity()
{
sptr<IRemoteObject> remote = Remote();
RETURN_IF_WITH_RET(remote == nullptr, INVALID_BATT_INT_VALUE);
MessageParcel data;
MessageParcel reply;
MessageOption option;
if (!data.WriteInterfaceToken(BatterySrvProxy::GetDescriptor())) {
POWER_HILOGE(MODULE_INNERKIT, "BatterySrvProxy::%{public}s write descriptor failed!", __func__);
return INVALID_BATT_INT_VALUE;
}
int ret = remote->SendRequest(static_cast<int>(IBatterySrv::BATT_GET_CAPACITY),
data, reply, option);
if (ret != ERR_OK) {
POWER_HILOGE(MODULE_BATT_INNERKIT, "BatterySrvProxy::%{public}s SendRequest is failed, error code: %d",
__func__, ret);
return INVALID_BATT_INT_VALUE;
}
int32_t capacity = INVALID_BATT_INT_VALUE;
READ_PARCEL_WITH_RET(reply, Int32, capacity, INVALID_BATT_INT_VALUE);
return capacity;
}
BatteryChargeState BatterySrvProxy::GetChargingStatus()
{
sptr<IRemoteObject> remote = Remote();
RETURN_IF_WITH_RET(remote == nullptr, BatteryChargeState::CHARGE_STATE_BUTT);
MessageParcel data;
MessageParcel reply;
MessageOption option;
if (!data.WriteInterfaceToken(BatterySrvProxy::GetDescriptor())) {
POWER_HILOGE(MODULE_INNERKIT, "BatterySrvProxy::%{public}s write descriptor failed!", __func__);
return BatteryChargeState::CHARGE_STATE_BUTT;
}
int ret = remote->SendRequest(static_cast<int>(IBatterySrv::BATT_GET_CHARGING_STATUS),
data, reply, option);
if (ret != ERR_OK) {
POWER_HILOGE(MODULE_BATT_INNERKIT, "BatterySrvProxy::%{public}s SendRequest is failed, error code: %d",
__func__, ret);
return BatteryChargeState::CHARGE_STATE_BUTT;
}
uint32_t chargingState = static_cast<uint32_t>(BatteryChargeState::CHARGE_STATE_BUTT);
READ_PARCEL_WITH_RET(reply, Uint32, chargingState, BatteryChargeState::CHARGE_STATE_BUTT);
return static_cast<BatteryChargeState>(chargingState);
}
BatteryHealthState BatterySrvProxy::GetHealthStatus()
{
sptr<IRemoteObject> remote = Remote();
RETURN_IF_WITH_RET(remote == nullptr, BatteryHealthState::HEALTH_STATE_BUTT);
MessageParcel data;
MessageParcel reply;
MessageOption option;
if (!data.WriteInterfaceToken(BatterySrvProxy::GetDescriptor())) {
POWER_HILOGE(MODULE_INNERKIT, "BatterySrvProxy::%{public}s write descriptor failed!", __func__);
return BatteryHealthState::HEALTH_STATE_BUTT;
}
int ret = remote->SendRequest(static_cast<int>(IBatterySrv::BATT_GET_HEALTH_STATUS),
data, reply, option);
if (ret != ERR_OK) {
POWER_HILOGE(MODULE_BATT_INNERKIT, "BatterySrvProxy::%{public}s SendRequest is failed, error code: %d",
__func__, ret);
return BatteryHealthState::HEALTH_STATE_BUTT;
}
uint32_t healthStatus = static_cast<uint32_t>(BatteryHealthState::HEALTH_STATE_BUTT);
READ_PARCEL_WITH_RET(reply, Uint32, healthStatus, BatteryHealthState::HEALTH_STATE_BUTT);
return static_cast<BatteryHealthState>(healthStatus);
}
BatteryPluggedType BatterySrvProxy::GetPluggedType()
{
sptr<IRemoteObject> remote = Remote();
RETURN_IF_WITH_RET(remote == nullptr, BatteryPluggedType::PLUGGED_TYPE_BUTT);
MessageParcel data;
MessageParcel reply;
MessageOption option;
if (!data.WriteInterfaceToken(BatterySrvProxy::GetDescriptor())) {
POWER_HILOGE(MODULE_INNERKIT, "BatterySrvProxy::%{public}s write descriptor failed!", __func__);
return BatteryPluggedType::PLUGGED_TYPE_BUTT;
}
int ret = remote->SendRequest(static_cast<int>(IBatterySrv::BATT_GET_PLUG_TYPE),
data, reply, option);
if (ret != ERR_OK) {
POWER_HILOGE(MODULE_BATT_INNERKIT, "BatterySrvProxy::%{public}s SendRequest is failed, error code: %d",
__func__, ret);
return BatteryPluggedType::PLUGGED_TYPE_BUTT;
}
uint32_t pluggedType = static_cast<uint32_t>(BatteryPluggedType::PLUGGED_TYPE_BUTT);
READ_PARCEL_WITH_RET(reply, Uint32, pluggedType, BatteryPluggedType::PLUGGED_TYPE_BUTT);
return static_cast<BatteryPluggedType>(pluggedType);
}
int32_t BatterySrvProxy::GetVoltage()
{
sptr<IRemoteObject> remote = Remote();
RETURN_IF_WITH_RET(remote == nullptr, INVALID_BATT_INT_VALUE);
MessageParcel data;
MessageParcel reply;
MessageOption option;
if (!data.WriteInterfaceToken(BatterySrvProxy::GetDescriptor())) {
POWER_HILOGE(MODULE_INNERKIT, "BatterySrvProxy::%{public}s write descriptor failed!", __func__);
return INVALID_BATT_INT_VALUE;
}
int ret = remote->SendRequest(static_cast<int>(IBatterySrv::BATT_GET_VOLTAGE),
data, reply, option);
if (ret != ERR_OK) {
POWER_HILOGE(MODULE_BATT_INNERKIT, "BatterySrvProxy::%{public}s SendRequest is failed, error code: %d",
__func__, ret);
return INVALID_BATT_INT_VALUE;
}
int32_t voltage = INVALID_BATT_INT_VALUE;
READ_PARCEL_WITH_RET(reply, Int32, voltage, INVALID_BATT_INT_VALUE);
return voltage;
}
bool BatterySrvProxy::GetPresent()
{
sptr<IRemoteObject> remote = Remote();
RETURN_IF_WITH_RET(remote == nullptr, INVALID_BATT_BOOL_VALUE);
MessageParcel data;
MessageParcel reply;
MessageOption option;
if (!data.WriteInterfaceToken(BatterySrvProxy::GetDescriptor())) {
POWER_HILOGE(MODULE_INNERKIT, "BatterySrvProxy::%{public}s write descriptor failed!", __func__);
return INVALID_BATT_BOOL_VALUE;
}
int ret = remote->SendRequest(static_cast<int>(IBatterySrv::BATT_GET_PRESENT),
data, reply, option);
if (ret != ERR_OK) {
POWER_HILOGE(MODULE_BATT_INNERKIT, "BatterySrvProxy::%{public}s SendRequest is failed, error code: %d",
__func__, ret);
return INVALID_BATT_BOOL_VALUE;
}
bool present = INVALID_BATT_BOOL_VALUE;
READ_PARCEL_WITH_RET(reply, Bool, present, INVALID_BATT_BOOL_VALUE);
return present;
}
std::string BatterySrvProxy::GetTechnology()
{
std::string technology = INVALID_STRING_VALUE;
sptr<IRemoteObject> remote = Remote();
RETURN_IF_WITH_RET(remote == nullptr, INVALID_STRING_VALUE);
MessageParcel data;
MessageParcel reply;
MessageOption option;
if (!data.WriteInterfaceToken(BatterySrvProxy::GetDescriptor())) {
POWER_HILOGE(MODULE_INNERKIT, "BatterySrvProxy::%{public}s write descriptor failed!", __func__);
return INVALID_STRING_VALUE;
}
int ret = remote->SendRequest(static_cast<int>(IBatterySrv::BATT_GET_TECHNOLOGY),
data, reply, option);
if (ret != ERR_OK) {
POWER_HILOGE(MODULE_BATT_INNERKIT, "BatterySrvProxy::%{public}s SendRequest is failed, error code: %d",
__func__, ret);
return INVALID_STRING_VALUE;
}
READ_PARCEL_WITH_RET(reply, String, technology, INVALID_STRING_VALUE);
return technology;
}
int32_t BatterySrvProxy::GetBatteryTemperature()
{
sptr<IRemoteObject> remote = Remote();
RETURN_IF_WITH_RET(remote == nullptr, INVALID_BATT_TEMP_VALUE);
MessageParcel data;
MessageParcel reply;
MessageOption option;
if (!data.WriteInterfaceToken(BatterySrvProxy::GetDescriptor())) {
POWER_HILOGE(MODULE_INNERKIT, "BatterySrvProxy::%{public}s write descriptor failed!", __func__);
return INVALID_BATT_TEMP_VALUE;
}
int ret = remote->SendRequest(static_cast<int>(IBatterySrv::BATT_GET_TEMPERATURE),
data, reply, option);
if (ret != ERR_OK) {
POWER_HILOGE(MODULE_BATT_INNERKIT, "BatterySrvProxy::%{public}s SendRequest is failed, error code: %d",
__func__, ret);
return INVALID_BATT_TEMP_VALUE;
}
int32_t temperature = INVALID_BATT_TEMP_VALUE;
READ_PARCEL_WITH_RET(reply, Int32, temperature, INVALID_BATT_TEMP_VALUE);
return temperature;
}
} // namespace PowerMgr
} // namespace OHOS

View File

@ -0,0 +1,120 @@
/*
* 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 "battery_srv_stub.h"
#include "message_parcel.h"
#include "power_common.h"
#include "battery_srv_proxy.h"
namespace OHOS {
namespace PowerMgr {
int BatterySrvStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option)
{
POWER_HILOGD(MODULE_BATT_SERVICE, "BatterySrvStub::OnRemoteRequest, cmd = %d, flags = %d", code, option.GetFlags());
std::u16string descriptor = BatterySrvStub::GetDescriptor();
std::u16string remoteDescriptor = data.ReadInterfaceToken();
if (descriptor != remoteDescriptor) {
POWER_HILOGE(MODULE_SERVICE, "BatterySrvStub::OnRemoteRequest failed, descriptor is not matched!");
return E_GET_POWER_SERVICE_FAILED;
}
switch (code) {
case static_cast<int>(IBatterySrv::BATT_GET_CAPACITY): {
return GetCapacityStub(reply);
}
case static_cast<int>(IBatterySrv::BATT_GET_CHARGING_STATUS): {
return GetChargingStatusStub(reply);
}
case static_cast<int>(IBatterySrv::BATT_GET_HEALTH_STATUS): {
return GetHealthStatusStub(reply);
}
case static_cast<int>(IBatterySrv::BATT_GET_PLUG_TYPE): {
return GetPluggedTypeStub(reply);
}
case static_cast<int>(IBatterySrv::BATT_GET_VOLTAGE): {
return GetVoltageStub(reply);
}
case static_cast<int>(IBatterySrv::BATT_GET_PRESENT): {
return GetPresentStub(reply);
}
case static_cast<int>(IBatterySrv::BATT_GET_TEMPERATURE): {
return GetBatteryTemperatureStub(reply);
}
case static_cast<int>(IBatterySrv::BATT_GET_TECHNOLOGY): {
return GetTechnologyStub(reply);
}
default: {
return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
}
}
}
int32_t BatterySrvStub::GetCapacityStub(MessageParcel &reply)
{
int32_t ret = GetCapacity();
WRITE_PARCEL_WITH_RET(reply, Int32, ret, E_WRITE_PARCEL_ERROR);
return ERR_OK;
}
int32_t BatterySrvStub::GetChargingStatusStub(MessageParcel &reply)
{
BatteryChargeState ret = GetChargingStatus();
WRITE_PARCEL_WITH_RET(reply, Uint32, static_cast<uint32_t>(ret), E_WRITE_PARCEL_ERROR);
return ERR_OK;
}
int32_t BatterySrvStub::GetHealthStatusStub(MessageParcel &reply)
{
BatteryHealthState ret = GetHealthStatus();
WRITE_PARCEL_WITH_RET(reply, Uint32, static_cast<uint32_t>(ret), E_WRITE_PARCEL_ERROR);
return ERR_OK;
}
int32_t BatterySrvStub::GetPluggedTypeStub(MessageParcel &reply)
{
BatteryPluggedType ret = GetPluggedType();
WRITE_PARCEL_WITH_RET(reply, Uint32, static_cast<uint32_t>(ret), E_WRITE_PARCEL_ERROR);
return ERR_OK;
}
int32_t BatterySrvStub::GetVoltageStub(MessageParcel &reply)
{
int32_t ret = GetVoltage();
WRITE_PARCEL_WITH_RET(reply, Int32, ret, E_WRITE_PARCEL_ERROR);
return ERR_OK;
}
int32_t BatterySrvStub::GetPresentStub(MessageParcel &reply)
{
bool ret = GetPresent();
WRITE_PARCEL_WITH_RET(reply, Bool, ret, E_WRITE_PARCEL_ERROR);
return ERR_OK;
}
int32_t BatterySrvStub::GetTechnologyStub(MessageParcel &reply)
{
std::string ret = GetTechnology();
WRITE_PARCEL_WITH_RET(reply, String, ret, E_WRITE_PARCEL_ERROR);
return ERR_OK;
}
int32_t BatterySrvStub::GetBatteryTemperatureStub(MessageParcel &reply)
{
int32_t ret = GetBatteryTemperature();
WRITE_PARCEL_WITH_RET(reply, Int32, ret, E_WRITE_PARCEL_ERROR);
return ERR_OK;
}
} // namespace PowerMgr
} // namespace OHOS

21
utils/BUILD.gn Normal file
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/battery_manager/batterymgr.gni")
config("utils_config") {
include_dirs = [
"native/include",
"//utils/native/base/include",
]
}

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 HILOG_WRAPPER_H
#define 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 used, define to avoid repeat used 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:PowerMgr, reserved 8 bit.
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, // 0xD002902
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, module should 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 // HILOG_WRAPPER_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 POWER_COMMON_H
#define 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 // 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 POWER_MGR_ERRORS_H
#define 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 // 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 SP_SINGLETON_H
#define 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 // SP_SINGLETON_H