add distributed_hardware_fwk base code to sig

Signed-off-by: hwzhangchuang <zhangchuang.zhang@huawei.com>
This commit is contained in:
hwzhangchuang 2022-02-28 19:29:56 +08:00
parent afc512320c
commit 536b611b9a
128 changed files with 10510 additions and 39 deletions

178
LICENSE Normal file
View File

@ -0,0 +1,178 @@
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

65
OAT.xml Normal file
View File

@ -0,0 +1,65 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- Copyright (c) 2022 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.
Notes:
This is project config file for OpenHarmony OSS Audit Tool, if you have any questions or concerns, please email chenyaxun.
-->
<!-- OAT(OSS Audit Tool) configuration guide:
basedir: Root dir, the basedir + project path is the real source file location.
licensefile:
1.If the project don't have "LICENSE" in root dir, please define all the license files in this project in , OAT will check license files according to this rule.
tasklist(only for batch mode):
1. task: Define oat check thread, each task will start a new thread.
2. task name: Only an name, no practical effect.
3. task policy: Default policy for projects under this task, this field is required and the specified policy must defined in policylist.
4. task filter: Default filefilter for projects under this task, this field is required and the specified filefilter must defined in filefilterlist.
5. task project: Projects to be checked, the path field define the source root dir of the project.
policyList:
1. policy: All policyitems will be merged to default OAT.xml rules, the name of policy doesn't affect OAT check process.
2. policyitem: The fields type, name, path, desc is required, and the fields rule, group, filefilter is optional,the default value is:
<policyitem type="" name="" path="" desc="" rule="may" group="defaultGroup" filefilter="defaultPolicyFilter"/>
3. policyitem type:
"compatibility" is used to check license compatibility in the specified path;
"license" is used to check source license header in the specified path;
"copyright" is used to check source copyright header in the specified path;
"import" is used to check source dependency in the specified path, such as import ... ,include ...
"filetype" is used to check file type in the specified path, supported file types: archive, binary
"filename" is used to check whether the specified file exists in the specified path(support projectroot in default OAT.xml), supported file names: LICENSE, README, README.OpenSource
4. policyitem name: This field is used for define the license, copyright, "*" means match all, the "!" prefix means could not match this value. For example, "!GPL" means can not use GPL license.
5. policyitem path: This field is used for define the source file scope to apply this policyitem, the "!" prefix means exclude the files. For example, "!.*/lib/.*" means files in lib dir will be exclude while process this policyitem.
6. policyitem rule and group: These two fields are used together to merge policy results. "may" policyitems in the same group means any one in this group passed, the result will be passed.
7. policyitem filefilter: Used to bind filefilter which define filter rules.
8. filefilter: Filter rules, the type filename is used to filter file name, the type filepath is used to filter file path.
Note:If the text contains special characters, please escape them according to the following rules:
" == &gt;
& == &gt;
' == &gt;
< == &gt;
> == &gt;
-->
<configuration>
<oatconfig>
<filefilterlist>
<filefilter name="binaryFileTypePolicyFilter" desc="Filters for project binary file" >
<filteritem type="filepath" name="figures/distributedhardwarefwk_arch.png" desc="pictures for project readme document"/>
</filefilter>
</filefilterlist>
</oatconfig>
</configuration>

View File

@ -1,39 +0,0 @@
# distributed_hardware_fwk
#### 介绍
{**以下是 Gitee 平台说明,您可以替换此简介**
Gitee 是 OSCHINA 推出的基于 Git 的代码托管平台(同时支持 SVN。专为开发者提供稳定、高效、安全的云端软件开发协作平台
无论是个人、团队、或是企业,都能够用 Gitee 实现代码托管、项目管理、协作开发。企业项目请看 [https://gitee.com/enterprises](https://gitee.com/enterprises)}
#### 软件架构
软件架构说明
#### 安装教程
1. xxxx
2. xxxx
3. xxxx
#### 使用说明
1. xxxx
2. xxxx
3. xxxx
#### 参与贡献
1. Fork 本仓库
2. 新建 Feat_xxx 分支
3. 提交代码
4. 新建 Pull Request
#### 特技
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/)

73
README_zh.md Normal file
View File

@ -0,0 +1,73 @@
# **分布式硬件管理框架**
## **简介**
分布式硬件管理框架是为分布式硬件子系统提供信息管理能力的部件。分布式硬件管理框架为分布式硬件子系统提供统一的硬件接入、查询和使能等能力。
其系统架构图如下图所示:
![](figures/distributedhardwarefwk_arch.png)
**硬件接入管理(AccessManager)**硬件接入管理模块对接设备管理DeviceManger子系统用于处理设备的上下线事件响应。
**硬件资源管理(ResourceManager)**:对接分布式数据服务,用于存储信任体系内,本机和周边设备同步过来的设备硬件信息。
**分布式硬件部件管理(ComponentManager)**:对接各分布式硬件实例化的部件,实现对分布式硬件的动态加载和使能/去使能等操作。
**本地硬件信息管理(LocalHardwareManager)**用于采集本地硬件信息并通过ResourceManager进行硬件信息的持久化存储同时通过对接硬件驱动用于感知本地硬件的插拔等操作感知是否新增或移除可用硬件将动态变化的硬件设备也纳入分布式硬件管理。
**部件加载管理(ComponentLoader)**用于解析部件配置文件按需加载部件驱动的实现so获取驱动外部接口函数句柄以及实现版本供其他业务使用。
**版本管理(VersionManager)**:用于管理超级终端内,各个设备的分布式硬件平台和分布式硬件部件的版本号,供分布式硬件业务各个部件业务使用。
## **目录**
```
/foundation/distributedhardware/distributedhardwarefwk
├── common # 分布式硬件管理框架为各个部件提供的公共接口类
├── sa_profile # 分布式硬件管理框架的SA配置信息
├── services # 分布式硬件管理框架的SA具体实现
│   └── distributedhardwarefwkservice # 分布式硬件管理框架的服务层
│   └── AccessManager # 硬件接入管理
│ └── distributedhardwarefwkserviceimpl # 分布式硬件管理框架的服务实现层
│ ├── ResourceManager # 硬件资源管理
│ ├── ComponentManager # 分布式硬件部件管理
│ ├── LocalHardwareManager # 本地硬件信息管理
│ ├── ComponentLoader # 部件加载管理
│ └── VersionManager # 版本管理
└── utils # 分布式硬件管理框架为各个部件提供的工具类
```
## **约束**
**语言限制**C++语言。
**组网环境**:必须确保设备在同一个局域网中。
**操作系统限制**OpenHarmony操作系统。
## **说明**
### **一、接口说明**
1.分布式硬件管理框架不提供北向接口,由各个硬件提供管理接口供开发者调用。
2.分布式硬件管理框架只提供接口供各个分布式硬件(例如分布式相机、分布式屏幕)实现,分布式硬件管理框架统一调用这些接口,实现分布式硬件的虚拟硬件驱动注册等功能。
### **二、流程说明**
#### **1. 设备开机启动**
系统拉起分布式硬件管理框架的SA服务AccessManager会进行初始化AccessManager初始化DeviceManger并且注册上下线监听。
#### **2. 设备组网上线**
(1) DeviceManger触发上线监听回调。
(2) ResourceManager、ComponentLoader、LocalHardwareManager、VersionManager 、ComponentManager各个模块依次初始化。
(3) 分布式硬件管理框架内部会构造上线任务,使能各个分布式硬件部件。
以分布式相机为例,某设备上线后,分布式硬件管理框架同步到上线设备的相机硬件信息并使能,使能成功后在系统中会新增分布式相机驱动并通知到相机框架,相机框架统一管理本地相机和分布式相机驱动;上层应用通过相机框架接口可以查询到分布式相机,并按照和本地相机相同的接口使用分布式相机。
#### **3. 设备下线**
(1) DeviceManger触发下线监听回调。
(2) 分布式硬件管理框架内部会构造下线任务,去使能各个分布式硬件部件。
以分布式相机为例,某设备下线后,分布式硬件管理框架去使能下线设备的相机硬件,本地移除分布式相机驱动并通知到相机框架,此时下线设备的分布式相机不可用。
### **涉及仓**
****
**分步式硬件管理框架**
[distributed_hardware_fwk](https://gitee.com/openharmony/distributed_hardware_fwk)

54
bundle.json Normal file
View File

@ -0,0 +1,54 @@
{
"name": "@ohos/distributed_hardware_fwk",
"description": "distributed hardware framework",
"version": "3.1",
"author": {},
"repository": "https://gitee.com/openharmony/distributed_hardware_fwk",
"license": "Apache License 2.0",
"publishAs": "code-segment",
"segment": {
"destPath": "foundation/distributedhardware/distributedhardwarefwk/"
},
"dirs": {},
"scripts": {},
"component": {
"name": "distributed_hardware_fwk",
"subsystem": "distributedhardware",
"syscap": [ "SystemCapability.distributedhardware.distributed_hardware_fwk" ],
"features": [],
"adapted_system_type": [ "standard" ],
"rom": "128K",
"ram": "6M",
"deps": {
"components": [
"appexecfwk_base",
"appexecfwk_core",
"libeventhandler",
"libhilog",
"distributeddata_inner",
"ipc_core",
"system_ability_fwk",
"samgr_proxy",
"syspara",
"softbus_client"
],
"third_party": [
"json",
"googletest"
]
},
"build": {
"sub_component": [
"//foundation/distributedhardware/distributedhardwarefwk/utils:distributedhardwareutils",
"//foundation/distributedhardware/distributedhardwarefwk/services/distributedhardwarefwkservice:distributedhardwarefwksvr",
"//foundation/distributedhardware/distributedhardwarefwk/services/distributedhardwarefwkserviceimpl:distributedhardwarefwksvr_impl",
"//foundation/distributedhardware/distributedhardwarefwk/sa_profile:dhfwk_sa_profile"
],
"test": [
"//foundation/distributedhardware/distributedhardwarefwk/utils/test/unittest:utils_test",
"//foundation/distributedhardware/distributedhardwarefwk/services/distributedhardwarefwkserviceimpl/test/unittest:svrimpl_test",
"//foundation/distributedhardware/distributedhardwarefwk/services/distributedhardwarefwkservice/test/unittest:test"
]
}
}
}

View File

@ -0,0 +1,38 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DISTRIBUTED_HARDWARE_LOG_H
#define OHOS_DISTRIBUTED_HARDWARE_LOG_H
#include <string>
#include "dh_log.h"
namespace OHOS {
namespace DistributedHardware {
#define DHLOGD(fmt, ...) DHLog(DH_LOG_DEBUG, \
(std::string("[") + DH_LOG_TAG + "][" + __FUNCTION__ + "]:" + fmt).c_str(), ##__VA_ARGS__)
#define DHLOGI(fmt, ...) DHLog(DH_LOG_INFO, \
(std::string("[") + DH_LOG_TAG + "][" + __FUNCTION__ + "]:" + fmt).c_str(), ##__VA_ARGS__)
#define DHLOGW(fmt, ...) DHLog(DH_LOG_WARN, \
(std::string("[") + DH_LOG_TAG + "][" + __FUNCTION__ + "]:" + fmt).c_str(), ##__VA_ARGS__)
#define DHLOGE(fmt, ...) DHLog(DH_LOG_ERROR, \
(std::string("[") + DH_LOG_TAG + "][" + __FUNCTION__ + "]:" + fmt).c_str(), ##__VA_ARGS__)
}
}
#endif

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 OHOS_DISTRIBUTED_HARDWARE_CONSTANTS_H
#define OHOS_DISTRIBUTED_HARDWARE_CONSTANTS_H
#include <string>
#include <unistd.h>
namespace OHOS {
namespace DistributedHardware {
constexpr int32_t LOG_MAX_LEN = 4096;
constexpr int32_t ENABLE_TIMEOUT_MS = 1000;
constexpr int32_t DISABLE_TIMEOUT_MS = 500;
const std::u16string DHMS_STUB_INTERFACE_TOKEN = u"ohos.distributedhardware.accessToken";
const std::string COMPONENTSLOAD_PROFILE_PATH = R"(/etc/distributed_hardware_components_cfg.json)";
const std::string APP_ID = "dtbhardware_manager_service";
const std::string GLOBAL_CAPABILITY_ID = "global_capability_info";
const std::string RESOURCE_SEPARATOR = "###";
const std::string DH_ID = "dh_id";
const std::string DEV_ID = "dev_id";
const std::string DEV_NAME = "dev_name";
const std::string DEV_TYPE = "dev_type";
const std::string DH_TYPE = "dh_type";
const std::string DH_ATTRS = "dh_attrs";
const std::string DH_LOG_TITLE_TAG = "DHFWK";
const std::string DH_TASK_NAME_PREFIX = "Task_";
const std::string DH_FWK_PKG_NAME = "DBinderBus_" + std::to_string(getpid());
const std::string DH_COMPONENT_VERSIONS = "componentVersions";
const std::string DH_COMPONENT_TYPE = "dhType";
const std::string DH_COMPONENT_SINK_VER = "version";
const std::string DH_COMPONENT_DEFAULT_VERSION = "1.0";
}
}
#endif

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 OHOS_DISTRIBUTED_HARDWARE_DEVICE_TYPE_H
#define OHOS_DISTRIBUTED_HARDWARE_DEVICE_TYPE_H
#include <string>
namespace OHOS {
namespace DistributedHardware {
enum class DHType : uint32_t {
UNKNOWN = 0x0, // unknown device
CAMERA = 0x01, // Camera
MIC = 0x02, // Mic
SPEAKER = 0x04, // Speaker
DISPLAY = 0x08, // Display
GPS = 0x10, // GPS
BUTTON = 0x20, // Key board
HFP = 0x40, // HFP External device
A2D = 0x80, // A2DP External device
VIRMODEM_MIC = 0x100, // Cellular call MIC
VIRMODEM_SPEAKER = 0x200, // Cellular call Speaker
MAX_DH = 0x80000000
};
struct DeviceInfo {
std::string deviceId;
std::string deviceName;
uint16_t deviceType;
explicit DeviceInfo(std::string deviceId, std::string deviceName, uint16_t deviceType)
: deviceId(deviceId), deviceName(deviceName), deviceType(deviceType) {}
};
}
}
#endif

View File

@ -0,0 +1,91 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DISTRIBUTED_HARDWARE_ERRNO
#define OHOS_DISTRIBUTED_HARDWARE_ERRNO
#include <cstdint>
namespace OHOS {
namespace DistributedHardware {
/*
* The distributed hardware module define errno, range: [-10000, -19999]
* Here's common errno, range: [-10000, -10199]
*/
constexpr int32_t DH_FWK_SUCCESS = 0;
constexpr int32_t ERR_DH_FWK_PARA_INVALID = -10000;
constexpr int32_t ERR_DH_FWK_REMOTE_NETWORK_ID_IS_EMPTY = -10001;
constexpr int32_t ERR_DH_FWK_REMOTE_DEVICE_ID_IS_EMPTY = -10002;
constexpr int32_t ERR_DH_FWK_TYPE_NOT_EXIST = -10003;
/* VersionManager errno, range: [-10200, -10299] */
constexpr int32_t ERR_DH_FWK_VERSION_DEVICE_ID_NOT_EXIST = -10200;
/* ComponentManager errno, range: [-10300, -10399] */
constexpr int32_t ERR_DH_FWK_COMPONENT_INIT_SOURCE_FAILED = -10300;
constexpr int32_t ERR_DH_FWK_COMPONENT_INIT_SINK_FAILED = -10301;
constexpr int32_t ERR_DH_FWK_COMPONENT_ENABLE_FAILED = -10302;
constexpr int32_t ERR_DH_FWK_COMPONENT_DISABLE_FAILED = -10303;
constexpr int32_t ERR_DH_FWK_COMPONENT_ENABLE_TIMEOUT = -10304;
constexpr int32_t ERR_DH_FWK_COMPONENT_DISABLE_TIMEOUT = -10305;
constexpr int32_t ERR_DH_FWK_COMPONENT_REGISTER_FAILED = -10306;
constexpr int32_t ERR_DH_FWK_COMPONENT_UNREGISTER_FAILED = -10007;
constexpr int32_t DH_FWK_COMPONENT_GET_REMOTE_SA_FAILED = -10008;
/* ResourceManager errno, range: [-10400, -10499] */
constexpr int32_t ERR_DH_FWK_RESOURCE_DB_ADAPTER_POINTER_NULL = -10400;
constexpr int32_t ERR_DH_FWK_RESOURCE_KV_STORAGE_POINTER_NULL = -10401;
constexpr int32_t ERR_DH_FWK_RESOURCE_DB_ADAPTER_OPERATION_FAIL = -10402;
constexpr int32_t ERR_DH_FWK_RESOURCE_KV_STORAGE_OPERATION_FAIL = -10403;
constexpr int32_t ERR_DH_FWK_RESOURCE_CAPABILITY_MAP_NOT_FOUND = -10404;
constexpr int32_t ERR_DH_FWK_RESOURCE_DB_MANUAL_SYNC_FAIL = -10405;
constexpr int32_t ERR_DH_FWK_RESOURCE_INIT_DB_FAILED = -10406;
constexpr int32_t ERR_DH_FWK_RESOURCE_UNINIT_DB_FAILED = -10407;
constexpr int32_t ERR_DH_FWK_RESOURCE_REGISTER_DB_FAILED = -10408;
constexpr int32_t ERR_DH_FWK_RESOURCE_UNREGISTER_DB_FAILED = -10409;
constexpr int32_t ERR_DH_FWK_RESOURCE_KEY_IS_EMPTY = -10410;
/* DistributedHardwareManager errno, range: [-10500, -10599] */
constexpr int32_t ERR_DH_FWK_HARDWARE_MANAGER_DEVICE_REPEAT_ONLINE = -10500;
constexpr int32_t ERR_DH_FWK_HARDWARE_MANAGER_DEVICE_REPEAT_OFFLINE = -10501;
constexpr int32_t ERR_DH_FWK_HARDWARE_MANAGER_LOAD_IMPL_FAILED = -10502;
constexpr int32_t ERR_DH_FWK_HARDWARE_MANAGER_LIB_IMPL_OPEN_FAILED = -10503;
constexpr int32_t ERR_DH_FWK_HARDWARE_MANAGER_LIB_IMPL_GET_INSTANCE_FAILED = -10504;
constexpr int32_t ERR_DH_FWK_HARDWARE_MANAGER_LIB_IMPL_IS_NULL = -10505;
/* ComponentLoader errno, range: [-10600, -10699] */
constexpr int32_t ERR_DH_FWK_LOADER_HANDLER_IS_NULL = -10600;
constexpr int32_t ERR_DH_FWK_LOADER_COMPONENT_PROFILE_IS_EMPTY = -10601;
constexpr int32_t ERR_DH_FWK_LOADER_GET_LOCAL_VERSION_FAIL = -10602;
constexpr int32_t ERR_DH_FWK_LOADER_DLCLOSE_FAIL = -10603;
/* Task errno, range: [-10700, -10799] */
constexpr int32_t ERR_DH_FWK_TASK_TIMEOUT = -10700;
/* DistributedHardwareService errno, range: [-10800, -10899] */
constexpr int32_t ERR_DH_FWK_SERVICE_IPC_WRITE_PARA_FAIL = -10800;
constexpr int32_t ERR_DH_FWK_SERVICE_IPC_SEND_REQUEST_FAIL = -10801;
constexpr int32_t ERR_DH_FWK_SERVICE_IPC_READ_PARA_FAIL = -10802;
constexpr int32_t ERR_DH_FWK_SERVICE_STRING_IS_EMPTY = -10803;
constexpr int32_t ERR_DH_FWK_SERVICE_LOCAL_VERSION_NOT_EXIST = -10804;
/* AccessManager errno, range: [-10900, -10999] */
constexpr int32_t ERR_DH_FWK_ACCESS_INIT_DM_FAILED = -10900;
constexpr int32_t ERR_DH_FWK_ACCESS_UNINIT_DM_FAILED = -10901;
constexpr int32_t ERR_DH_FWK_ACCESS_REGISTER_DM_FAILED = -10902;
constexpr int32_t ERR_DH_FWK_ACCESS_UNREGISTER_DM_FAILED = -10903;
}
}
#endif

View File

@ -0,0 +1,40 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_IDISTRIBUTED_HARDWARE_H
#define OHOS_IDISTRIBUTED_HARDWARE_H
#include <unordered_map>
#include "iremote_broker.h"
#include "device_type.h"
namespace OHOS {
namespace DistributedHardware {
class IDistributedHardware : public OHOS::IRemoteBroker {
public:
DECLARE_INTERFACE_DESCRIPTOR(u"ohos.distributedhardware.distributedhardwarefwk");
IDistributedHardware() = default;
virtual ~IDistributedHardware() = default;
virtual int32_t QuerySinkVersion(std::unordered_map<DHType, std::string> &versionMap) = 0;
public:
enum {
QUERY_SINK_VERSION = 1
};
};
}
}
#endif

View File

@ -0,0 +1,40 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DISTRIBUTED_HARDWARE_IDISTRIBUTED_HARDWARE_MANAGER_H
#define OHOS_DISTRIBUTED_HARDWARE_IDISTRIBUTED_HARDWARE_MANAGER_H
#include <string>
#include <unordered_map>
#include "device_type.h"
namespace OHOS {
namespace DistributedHardware {
class IDistributedHardwareManager {
public:
virtual ~IDistributedHardwareManager() {};
virtual int32_t Initialize() = 0;
virtual int32_t Release() = 0;
virtual int32_t SendOnLineEvent(const std::string &networkId, const std::string &deviceId,
uint16_t deviceType) = 0;
virtual int32_t SendOffLineEvent(const std::string &networkId, const std::string &deviceId,
uint16_t deviceType) = 0;
virtual size_t GetOnLineCount() = 0;
virtual int32_t GetComponentVersion(std::unordered_map<DHType, std::string> &versionMap) = 0;
};
}
}
#endif

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 OHOS_DISTRIBUTED_HARDWARE_IDISTRIBUTED_HARDWARE_SINK_H
#define OHOS_DISTRIBUTED_HARDWARE_IDISTRIBUTED_HARDWARE_SINK_H
#include <string>
namespace OHOS {
namespace DistributedHardware {
const std::string COMPONENT_LOADER_GET_SINK_HANDLER = "GetSinkHardwareHandler";
class SubscribeCallback {
public:
virtual int32_t OnSubscribeCallback(const std::string &dhId, int32_t status, const std::string &data) = 0;
};
class IDistributedHardwareSink {
public:
virtual int32_t InitSink(const std::string &params) = 0;
virtual int32_t ReleaseSink() = 0;
virtual int32_t SubscribeLocalHardware(const std::string &dhId, const std::string &params) = 0;
virtual int32_t UnsubscribeLocalHardware(const std::string &dhId) = 0;
};
extern "C" __attribute__((visibility("default"))) IDistributedHardwareSink* GetSinkHardwareHandler();
}
}
#endif

View File

@ -0,0 +1,56 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DISTRIBUTED_HARDWARE_IDISTRIBUTED_HARDWARE_SOURCE_H
#define OHOS_DISTRIBUTED_HARDWARE_IDISTRIBUTED_HARDWARE_SOURCE_H
#include <memory>
#include <string>
namespace OHOS {
namespace DistributedHardware {
const std::string COMPONENT_LOADER_GET_SOURCE_HANDLER = "GetSourceHardwareHandler";
class RegisterCallback {
public:
virtual int32_t OnRegisterResult(const std::string &devId, const std::string &dhId, int32_t status,
const std::string &data) = 0;
};
class UnregisterCallback {
public:
virtual int32_t OnUnregisterResult(const std::string &devId, const std::string &dhId, int32_t status,
const std::string &data) = 0;
};
struct EnableParam {
std::string version;
std::string attrs;
};
class IDistributedHardwareSource {
public:
virtual int32_t InitSource(const std::string &params) = 0;
virtual int32_t ReleaseSource() = 0;
virtual int32_t RegisterDistributedHardware(const std::string &devId, const std::string &dhId,
const EnableParam &param, std::shared_ptr<RegisterCallback> callback) = 0;
virtual int32_t UnregisterDistributedHardware(const std::string &devId, const std::string &dhId,
std::shared_ptr<UnregisterCallback> callback) = 0;
virtual int32_t ConfigDistributedHardware(const std::string &devId, const std::string &dhId, const std::string &key,
const std::string &value) = 0;
};
extern "C" __attribute__((visibility("default"))) IDistributedHardwareSource* GetSourceHardwareHandler();
}
}
#endif

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.
*/
#ifndef OHOS_DISTRIBUTED_HARDWARE_IHARDWARE_HANDLER_H
#define OHOS_DISTRIBUTED_HARDWARE_IHARDWARE_HANDLER_H
#include <map>
#include <memory>
#include <string>
#include <vector>
namespace OHOS {
namespace DistributedHardware {
const std::string COMPONENT_LOADER_GET_HARDWARE_HANDLER = "GetHardwareHandler";
struct DHItem {
std::string dhId;
std::string attrs;
};
class PluginListener {
public:
virtual void PluginHardware(std::string dhId, std::string attrs) = 0;
virtual void UnPluginHardware(std::string dhId) = 0;
};
class IHardwareHandler {
public:
virtual int32_t Initialize() = 0;
virtual std::vector<DHItem> Query() = 0;
virtual std::map<std::string, std::string> QueryExtraInfo() = 0;
virtual bool IsSupportPlugin() = 0;
virtual void RegisterPluginListener(std::shared_ptr<PluginListener> listener) = 0;
};
extern "C" __attribute__((visibility("default"))) IHardwareHandler* GetHardwareHandler();
}
}
#endif

View File

@ -0,0 +1,44 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DISTRIBUTED_HARDWARE_SINGLE_INSTANCE_H
#define OHOS_DISTRIBUTED_HARDWARE_SINGLE_INSTANCE_H
namespace OHOS {
namespace DistributedHardware {
#define DECLARE_SINGLE_INSTANCE_BASE(className) \
public: \
static className & GetInstance(); \
private: \
className(const className&) = delete; \
className& operator= (const className&) = delete; \
className(className&&) = delete; \
className& operator= (className&&) = delete; \
#define DECLARE_SINGLE_INSTANCE(className) \
DECLARE_SINGLE_INSTANCE_BASE(className) \
private: \
className() = default; \
virtual ~className() = default; \
#define IMPLEMENT_SINGLE_INSTANCE(className) \
className & className::GetInstance() \
{ \
static className instance; \
return instance; \
}
}
}
#endif

View File

@ -0,0 +1,24 @@
# 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.
distributedhardwarefwk_path = "//foundation/distributedhardware/distributedhardwarefwk"
common_path = "${distributedhardwarefwk_path}/common"
utils_path = "${distributedhardwarefwk_path}/utils"
services_path = "${distributedhardwarefwk_path}/services"
innerkits_path = "${distributedhardwarefwk_path}/interfaces/inner_kits"
build_flags = [ "-Werror" ]

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

27
sa_profile/4801.xml Normal file
View File

@ -0,0 +1,27 @@
<?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>dhardware</process>
<systemability> <!-- Declare a sytem ability and its profile -->
<name>4801</name> <!-- Declare the name of system ability -->
<libpath>libdistributedhardwarefwksvr.z.so</libpath> <!-- Declare the path of .so file which includes the system ability; Note: 1 .so file can have 1 to N system abilities. -->
<depend>4802</depend> <!-- Declare the name of system abilities which the system ability depends on, using ";" as separator among names. If there are dependencies, it needs to check if all those dependencies are avliable in service manager before starting the system ability. -->
<depend-time-out>60000</depend-time-out> <!-- Check all dependencies are avaliable before the timeout period ended. The MAX_DEPENDENCY_TIMEOUT is 60s. -->
<run-on-create>true</run-on-create> <!-- "true" means the system ability would start imediately, "false" means the system ability would start on demand. -->
<distributed>true</distributed> <!-- "true" means the system ability supports distributed scheduling while "false" is not. -->
<dump-level>1</dump-level> <!-- Declare the dump level. 1-high; 2-media; 3-low -->
</systemability>
</info>

20
sa_profile/BUILD.gn Normal file
View File

@ -0,0 +1,20 @@
# Copyright (c) 2021 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import("//build/ohos/sa_profile/sa_profile.gni")
ohos_sa_profile("dhfwk_sa_profile") {
sources = [ "4801.xml" ]
part_name = "distributed_hardware_fwk"
}

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.
import("//build/ohos.gni")
import("//build/ohos_var.gni")
import("//foundation/distributedhardware/distributedhardwarefwk/distributedhardwarefwk.gni")
ohos_shared_library("distributedhardwarefwksvr") {
include_dirs = [
"//utils/native/base/include",
"//utils/system/safwk/native/include",
"include",
"include/accessmanager",
"${common_path}/log/include",
"${common_path}/utils/include",
"${utils_path}/include/log",
"${utils_path}/include",
"//foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp/include",
"//foundation/distributedhardware/devicemanager/common/include",
"${services_path}/distributedhardwarefwkserviceimpl/include",
]
sources = [
"src/distributed_hardware_service.cpp",
"src/distributed_hardware_stub.cpp",
"src/distributed_hardware_manager_factory.cpp",
"src/accessmanager/access_manager.cpp",
]
deps = [
"${utils_path}:distributedhardwareutils",
"//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager",
"//foundation/aafwk/standard/services/abilitymgr:abilityms",
"//utils/native/base:utils",
"//foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp:devicemanagersdk",
":distributedhardware_fwk.cfg",
"${services_path}/distributedhardwarefwkserviceimpl:distributedhardwarefwksvr_impl"
]
defines = [
"HI_LOG_ENABLE",
"DH_LOG_TAG=\"dhfwksvr\"",
"LOG_DOMAIN=0xD004100",
]
external_deps = [
"bundle_framework:appexecfwk_base",
"bundle_framework:appexecfwk_core",
"eventhandler:libeventhandler",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"safwk:system_ability_fwk",
"samgr_standard:samgr_proxy",
"startup_l2:syspara",
]
subsystem_name = "distributedhardware"
part_name = "distributed_hardware_fwk"
}
ohos_prebuilt_etc("distributedhardware_fwk.cfg") {
relative_install_dir = "init"
source = "distributedhardware_fwk.cfg"
part_name = "distributed_hardware_fwk"
subsystem_name = "distributedhardware"
}

View File

@ -0,0 +1,15 @@
{
"jobs" : [{
"name" : "post-fs-data",
"cmds" : [
"start distributedhardware_fwk"
]
}
],
"services" : [{
"name" : "distributedhardware_fwk",
"path" : ["/system/bin/sa_main", "/system/profile/dhardware.xml"],
"uid" : "system",
"gid" : ["system"]
}]
}

View File

@ -0,0 +1,65 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DISTRIBUTED_HARDWARE_ACCESS_MANAGER_H
#define OHOS_DISTRIBUTED_HARDWARE_ACCESS_MANAGER_H
#include <string>
#include <mutex>
#include <shared_mutex>
#include <unordered_map>
#include <unordered_set>
#include "device_manager.h"
#include "dm_device_info.h"
#include "device_type.h"
namespace OHOS {
namespace DistributedHardware {
class AccessManager : public std::enable_shared_from_this<AccessManager>,
public DmInitCallback,
public DeviceStateCallback {
public:
AccessManager(const AccessManager &) = delete;
AccessManager &operator = (const AccessManager &) = delete;
AccessManager(AccessManager &&) = delete;
AccessManager &operator = (AccessManager &&) = delete;
virtual ~AccessManager();
static std::shared_ptr<AccessManager> GetInstance();
int32_t Init();
int32_t UnInit();
bool IsDeviceOnline(const std::string &deviceId);
virtual void OnRemoteDied() override;
virtual void OnDeviceOnline(const DmDeviceInfo &deviceInfo) override;
virtual void OnDeviceOffline(const DmDeviceInfo &deviceInfo) override;
virtual void OnDeviceReady(const DmDeviceInfo &deviceInfo) override;
virtual void OnDeviceChanged(const DmDeviceInfo &deviceInfo) override;
private:
AccessManager() = default;
int32_t RegisterDevStateCallback();
int32_t UnRegisterDevStateCallback();
int32_t InitDeviceManager();
int32_t UnInitDeviceManager();
/* Send device online event which is already online */
void SendTrustedDeviceOnline();
std::mutex accessMutex_;
};
}
}
#endif

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 OHOS_DISTRIBUTED_HARDWARE_MANAGER_FACTORY_H
#define OHOS_DISTRIBUTED_HARDWARE_MANAGER_FACTORY_H
#include <mutex>
#include "idistributed_hardware_manager.h"
#include "single_instance.h"
namespace OHOS {
namespace DistributedHardware {
class DistributedHardwareManagerFactory {
DECLARE_SINGLE_INSTANCE(DistributedHardwareManagerFactory);
public:
bool IsInit();
int32_t SendOnLineEvent(const std::string &networkId, const std::string &deviceId, uint16_t deviceType);
int32_t SendOffLineEvent(const std::string &networkId, const std::string &deviceId, uint16_t deviceType);
int32_t GetComponentVersion(std::unordered_map<DHType, std::string> &versionMap);
private:
bool Init();
void UnInit();
int32_t LoadLibrary();
void CloseLibrary();
private:
void *handler_ { nullptr };
IDistributedHardwareManager *distributedHardwareMgrPtr_ { nullptr };
std::mutex mutex_;
};
}
}
#endif

View File

@ -0,0 +1,52 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DISTRIBUTED_HARDWARE_SERVICE_H
#define OHOS_DISTRIBUTED_HARDWARE_SERVICE_H
#include "system_ability.h"
#include "ipc_object_stub.h"
#include "distributed_hardware_stub.h"
#include "single_instance.h"
namespace OHOS {
namespace DistributedHardware {
enum class ServiceRunningState {
STATE_NOT_START,
STATE_RUNNING
};
class DistributedHardwareService : public SystemAbility, public DistributedHardwareStub {
DECLARE_SYSTEM_ABILITY(DistributedHardwareService);
public:
DistributedHardwareService(int32_t saId, bool runOnCreate);
~DistributedHardwareService() = default;
int32_t QuerySinkVersion(std::unordered_map<DHType, std::string> &versionMap) override;
protected:
void OnStart() override;
void OnStop() override;
private:
bool Init();
private:
bool registerToService_ = false;
ServiceRunningState state_ = ServiceRunningState::STATE_NOT_START;
};
}
}
#endif

View File

@ -0,0 +1,30 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "iremote_stub.h"
#include "idistributed_hardware.h"
namespace OHOS {
namespace DistributedHardware {
class DistributedHardwareStub : public IRemoteStub<IDistributedHardware> {
public:
int32_t OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override;
private:
std::string ToJson(const std::unordered_map<DHType, std::string> &versionMap) const;
};
}
}

View File

@ -0,0 +1,164 @@
/*
* 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 "access_manager.h"
#include <unistd.h>
#include <vector>
#include "anonymous_string.h"
#include "constants.h"
#include "dh_utils_tool.h"
#include "distributed_hardware_errno.h"
#include "distributed_hardware_log.h"
#include "distributed_hardware_manager_factory.h"
namespace OHOS {
namespace DistributedHardware {
#undef DH_LOG_TAG
#define DH_LOG_TAG "AccessManager"
constexpr int32_t DH_RETRY_INIT_DM_COUNT = 6;
constexpr int32_t DH_RETRY_INIT_DM_INTERVAL_US = 1000 * 500;
AccessManager::~AccessManager()
{
UnInit();
}
std::shared_ptr<AccessManager> AccessManager::GetInstance()
{
static std::shared_ptr<AccessManager> instance(new AccessManager);
return instance;
}
int32_t AccessManager::Init()
{
DHLOGI("start");
if (InitDeviceManager() != DH_FWK_SUCCESS) {
DHLOGE("InitDeviceManager failed");
return ERR_DH_FWK_ACCESS_INIT_DM_FAILED;
}
if (RegisterDevStateCallback() != DH_FWK_SUCCESS) {
DHLOGE("RegisterDevStateCallback failed");
return ERR_DH_FWK_ACCESS_REGISTER_DM_FAILED;
}
SendTrustedDeviceOnline();
return DH_FWK_SUCCESS;
}
int32_t AccessManager::UnInit()
{
DHLOGI("start");
if (UnInitDeviceManager() != DH_FWK_SUCCESS) {
DHLOGE("UnInitDeviceManager failed");
return ERR_DH_FWK_ACCESS_UNINIT_DM_FAILED;
}
if (UnRegisterDevStateCallback() != DH_FWK_SUCCESS) {
DHLOGE("UnRegisterDevStateCallback failed");
return ERR_DH_FWK_ACCESS_UNREGISTER_DM_FAILED;
}
return DH_FWK_SUCCESS;
}
int32_t AccessManager::InitDeviceManager()
{
DHLOGI("start");
return DeviceManager::GetInstance().InitDeviceManager(DH_FWK_PKG_NAME, shared_from_this());
}
int32_t AccessManager::UnInitDeviceManager()
{
DHLOGI("start");
return DeviceManager::GetInstance().UnInitDeviceManager(DH_FWK_PKG_NAME);
}
int32_t AccessManager::RegisterDevStateCallback()
{
return DeviceManager::GetInstance().RegisterDevStateCallback(DH_FWK_PKG_NAME, "", shared_from_this());
}
int32_t AccessManager::UnRegisterDevStateCallback()
{
return DeviceManager::GetInstance().UnRegisterDevStateCallback(DH_FWK_PKG_NAME);
}
void AccessManager::OnRemoteDied()
{
for (int32_t tryCount = 0; tryCount < DH_RETRY_INIT_DM_COUNT; ++tryCount) {
usleep(DH_RETRY_INIT_DM_INTERVAL_US);
if (Init() == DH_FWK_SUCCESS) {
DHLOGI("DeviceManager onDied, try to init success, tryCount = %d", tryCount);
return;
}
DHLOGW("DeviceManager onDied, try to init failed, tryCount = %d", tryCount);
}
DHLOGE("DeviceManager onDied, try to init has reached the maximum, but still failed");
return;
}
void AccessManager::OnDeviceOnline(const DmDeviceInfo &deviceInfo)
{
std::lock_guard<std::mutex> lock(accessMutex_);
DHLOGI("start, networkId = %s, deviceName = %s, deviceTypeId = %d", GetAnonyString(deviceInfo.deviceId).c_str(),
deviceInfo.deviceName, deviceInfo.deviceTypeId);
auto networkId = std::string(deviceInfo.deviceId); // deviceId of DM actually is networkId
auto deviceId = GetUUIDByNetworkId(networkId);
auto ret =
DistributedHardwareManagerFactory::GetInstance().SendOnLineEvent(networkId, deviceId, deviceInfo.deviceTypeId);
DHLOGI("online result = %d, networkId = %s, deviceId = %s", ret, GetAnonyString(networkId).c_str(),
GetAnonyString(deviceId).c_str());
}
void AccessManager::OnDeviceOffline(const DmDeviceInfo &deviceInfo)
{
std::lock_guard<std::mutex> lock(accessMutex_);
DHLOGI("start, networkId = %s, deviceName = %s, deviceTypeId = %d", GetAnonyString(deviceInfo.deviceId).c_str(),
deviceInfo.deviceName, deviceInfo.deviceTypeId);
auto networkId = std::string(deviceInfo.deviceId); // deviceId of DM actually is networkId
auto deviceId = GetUUIDByNetworkId(networkId);
auto ret =
DistributedHardwareManagerFactory::GetInstance().SendOffLineEvent(networkId, deviceId, deviceInfo.deviceTypeId);
DHLOGI("offline result = %d, networkId = %s, deviceId = %s", ret, GetAnonyString(networkId).c_str(),
GetAnonyString(deviceId).c_str());
}
void AccessManager::OnDeviceReady(const DmDeviceInfo &deviceInfo)
{
return;
}
void AccessManager::OnDeviceChanged(const DmDeviceInfo &deviceInfo)
{
return;
}
void AccessManager::SendTrustedDeviceOnline()
{
std::vector<DmDeviceInfo> deviceList;
DeviceManager::GetInstance().GetTrustedDeviceList(DH_FWK_PKG_NAME, "", deviceList);
for (const auto &deviceInfo : deviceList) {
const auto networkId = std::string(deviceInfo.deviceId);
const auto deviceId = GetUUIDByNetworkId(networkId);
DHLOGI("Send trusted device online, networkId = %s, deviceId = %s", GetAnonyString(networkId).c_str(),
GetAnonyString(deviceId).c_str());
DistributedHardwareManagerFactory::GetInstance().SendOnLineEvent(networkId, deviceId, deviceInfo.deviceTypeId);
}
}
}
}

View File

@ -0,0 +1,190 @@
/*
* 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 "distributed_hardware_manager_factory.h"
#include <dlfcn.h>
#include <memory>
#include "distributed_hardware_errno.h"
#include "distributed_hardware_log.h"
namespace OHOS {
namespace DistributedHardware {
const char* LIB_NAME = "libdistributedhardwarefwksvr_impl.z.so";
const std::string FUNC_GET_INSTANCE = "GetDistributedHardwareManagerInstance";
#undef DH_LOG_TAG
#define DH_LOG_TAG "DistributedHardwareManagerFactory"
using GetMgrFunc = IDistributedHardwareManager *(*)();
IMPLEMENT_SINGLE_INSTANCE(DistributedHardwareManagerFactory);
bool DistributedHardwareManagerFactory::Init()
{
DHLOGI("start");
auto loadResult = LoadLibrary();
if (loadResult != DH_FWK_SUCCESS) {
DHLOGE("LoadLibrary failed, errCode = %d", loadResult);
return false;
}
auto initResult = distributedHardwareMgrPtr_->Initialize();
if (initResult != DH_FWK_SUCCESS) {
DHLOGE("Initialize failed, errCode = %d", initResult);
return false;
}
DHLOGD("success");
return true;
}
void DistributedHardwareManagerFactory::UnInit()
{
DHLOGI("start");
// release all the resources synchronously
distributedHardwareMgrPtr_->Release();
CloseLibrary();
DHLOGD("success");
}
bool DistributedHardwareManagerFactory::IsInit()
{
std::lock_guard<std::mutex> lock(mutex_);
if (distributedHardwareMgrPtr_ == nullptr) {
DHLOGE("distributedHardwareMgr is not Initialize");
return false;
}
return true;
}
int32_t DistributedHardwareManagerFactory::SendOnLineEvent(const std::string &networkId, const std::string &deviceId,
uint16_t deviceType)
{
if (networkId.empty()) {
DHLOGE("networkId is empty");
return ERR_DH_FWK_REMOTE_NETWORK_ID_IS_EMPTY;
}
if (deviceId.empty()) {
DHLOGE("deviceId is empty");
return ERR_DH_FWK_REMOTE_DEVICE_ID_IS_EMPTY;
}
std::lock_guard<std::mutex> lock(mutex_);
if (distributedHardwareMgrPtr_ == nullptr && !Init()) {
DHLOGE("distributedHardwareMgr is null");
return ERR_DH_FWK_HARDWARE_MANAGER_LOAD_IMPL_FAILED;
}
auto onlineResult = distributedHardwareMgrPtr_->SendOnLineEvent(networkId, deviceId, deviceType);
if (onlineResult != DH_FWK_SUCCESS) {
DHLOGE("online failed, errCode = %d", onlineResult);
return onlineResult;
}
return DH_FWK_SUCCESS;
}
int32_t DistributedHardwareManagerFactory::SendOffLineEvent(const std::string &networkId, const std::string &deviceId,
uint16_t deviceType)
{
if (networkId.empty()) {
DHLOGE("networkId is empty");
return ERR_DH_FWK_REMOTE_NETWORK_ID_IS_EMPTY;
}
if (deviceId.empty()) {
DHLOGE("deviceId is empty");
return ERR_DH_FWK_REMOTE_DEVICE_ID_IS_EMPTY;
}
std::lock_guard<std::mutex> lock(mutex_);
if (distributedHardwareMgrPtr_ == nullptr) {
DHLOGE("distributedHardwareMgr is null");
return ERR_DH_FWK_HARDWARE_MANAGER_LOAD_IMPL_FAILED;
}
auto offlineResult = distributedHardwareMgrPtr_->SendOffLineEvent(networkId, deviceId, deviceType);
if (offlineResult != DH_FWK_SUCCESS) {
DHLOGE("offline failed, errCode = %d", offlineResult);
return offlineResult;
}
if (distributedHardwareMgrPtr_->GetOnLineCount() == 0) {
DHLOGI("all devices are offline, start to free the resource");
UnInit();
}
return DH_FWK_SUCCESS;
}
int32_t DistributedHardwareManagerFactory::LoadLibrary()
{
DHLOGI("start.");
if (handler_ != nullptr && distributedHardwareMgrPtr_ != nullptr) {
DHLOGE("DistributedHardwareManager handler has loaded.");
return DH_FWK_SUCCESS;
}
handler_ = dlopen(LIB_NAME, RTLD_NOW);
if (handler_ == nullptr) {
DHLOGE("open %s failed.", LIB_NAME);
return ERR_DH_FWK_HARDWARE_MANAGER_LIB_IMPL_OPEN_FAILED;
}
auto getManager = reinterpret_cast<GetMgrFunc>(dlsym(handler_, FUNC_GET_INSTANCE.c_str()));
if (getManager == nullptr) {
DHLOGE("can not find %s.", FUNC_GET_INSTANCE.c_str());
CloseLibrary();
return ERR_DH_FWK_HARDWARE_MANAGER_LIB_IMPL_GET_INSTANCE_FAILED;
}
distributedHardwareMgrPtr_ = getManager();
if (distributedHardwareMgrPtr_ == nullptr) {
DHLOGE("distributedHardwareMgrPtr is null.");
CloseLibrary();
return ERR_DH_FWK_HARDWARE_MANAGER_LIB_IMPL_IS_NULL;
}
DHLOGI("load %s success.", LIB_NAME);
return DH_FWK_SUCCESS;
}
void DistributedHardwareManagerFactory::CloseLibrary()
{
if (handler_ == nullptr) {
DHLOGI("%s is already closed.", LIB_NAME);
return;
}
distributedHardwareMgrPtr_ = nullptr;
dlclose(handler_);
handler_ = nullptr;
DHLOGI("%s is closed.", LIB_NAME);
}
int32_t DistributedHardwareManagerFactory::GetComponentVersion(std::unordered_map<DHType, std::string> &versionMap)
{
DHLOGI("start");
std::lock_guard<std::mutex> lock(mutex_);
if (distributedHardwareMgrPtr_ == nullptr) {
DHLOGE("distributedHardwareMgr is null");
return ERR_DH_FWK_HARDWARE_MANAGER_LIB_IMPL_IS_NULL;
}
return distributedHardwareMgrPtr_->GetComponentVersion(versionMap);
}
}
}

View File

@ -0,0 +1,85 @@
/*
* 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 "distributed_hardware_service.h"
#include "if_system_ability_manager.h"
#include "ipc_skeleton.h"
#include "ipc_types.h"
#include "iservice_registry.h"
#include "string_ex.h"
#include "system_ability_definition.h"
#include "access_manager.h"
#include "distributed_hardware_errno.h"
#include "distributed_hardware_log.h"
namespace OHOS {
namespace DistributedHardware {
REGISTER_SYSTEM_ABILITY_BY_ID(DistributedHardwareService, DISTRIBUTED_HARDWARE_SA_ID, true);
DistributedHardwareService::DistributedHardwareService(int32_t saId, bool runOnCreate)
: SystemAbility(saId, runOnCreate)
{
}
void DistributedHardwareService::OnStart()
{
DHLOGI("DistributedHardwareService::OnStart start");
if (state_ == ServiceRunningState::STATE_RUNNING) {
DHLOGI("DistributedHardwareService has already started.");
return;
}
if (!Init()) {
DHLOGE("failed to init DistributedHardwareService");
return;
}
state_ = ServiceRunningState::STATE_RUNNING;
DHLOGI("DistributedHardwareService::OnStart start service success.");
}
bool DistributedHardwareService::Init()
{
DHLOGI("DistributedHardwareService::Init ready to init.");
if (!registerToService_) {
bool ret = Publish(this);
if (!ret) {
DHLOGE("DistributedHardwareService::Init Publish failed!");
return false;
}
registerToService_ = true;
}
auto ret = AccessManager::GetInstance()->Init();
if (ret != DH_FWK_SUCCESS) {
DHLOGI("DistributedHardwareService::Init failed.");
return false;
}
DHLOGI("DistributedHardwareService::Init init success.");
return true;
}
void DistributedHardwareService::OnStop()
{
DHLOGI("DistributedHardwareService::OnStop ready to stop service.");
state_ = ServiceRunningState::STATE_NOT_START;
registerToService_ = false;
}
int32_t DistributedHardwareService::QuerySinkVersion(std::unordered_map<DHType, std::string> &versionMap)
{
return 0;
}
}
}

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 "distributed_hardware_stub.h"
#include <unordered_set>
#include "anonymous_string.h"
#include "constants.h"
#include "distributed_hardware_errno.h"
#include "distributed_hardware_log.h"
#include "distributed_hardware_manager_factory.h"
#include "nlohmann/json.hpp"
namespace OHOS {
namespace DistributedHardware {
int32_t DistributedHardwareStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply,
MessageOption &option)
{
switch (code) {
case QUERY_SINK_VERSION: {
std::unordered_map<DHType, std::string> versionMap;
auto ret = DistributedHardwareManagerFactory::GetInstance().GetComponentVersion(versionMap);
if (ret != DH_FWK_SUCCESS) {
DHLOGE("GetComponentVersion failed, errCode = %d", ret);
return ret;
}
if (versionMap.empty()) {
DHLOGE("versionMap is empty");
return ERR_DH_FWK_SERVICE_LOCAL_VERSION_NOT_EXIST;
}
auto version = ToJson(versionMap);
if (!reply.WriteString(version)) {
DHLOGE("write version failed");
return ERR_DH_FWK_SERVICE_IPC_WRITE_PARA_FAIL;
}
return DH_FWK_SUCCESS;
}
default:
return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
}
return 0;
}
std::string DistributedHardwareStub::ToJson(const std::unordered_map<DHType, std::string> &versionMap) const
{
nlohmann::json jsonObj;
for (const auto &item : versionMap) {
nlohmann::json json;
json[DH_COMPONENT_TYPE] = item.first;
json[DH_COMPONENT_SINK_VER] = item.second;
jsonObj[DH_COMPONENT_VERSIONS].emplace_back(json);
}
return jsonObj.dump();
}
}
}

View File

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

View File

@ -0,0 +1,73 @@
# 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")
import("//foundation/distributedhardware/distributedhardwarefwk/distributedhardwarefwk.gni")
module_out_path = "distributed_hardware_fwk/access_manager_test"
config("module_private_config") {
include_dirs = [
"//utils/native/base/include",
"//utils/system/safwk/native/include",
"//foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp/include",
"//foundation/distributedhardware/devicemanager/common/include",
"${utils_path}/include",
"${utils_path}/include/log",
"${common_path}/utils/include",
"${common_path}/log/include",
"${services_path}/distributedhardwarefwkservice/include",
"${services_path}/distributedhardwarefwkservice/include/accessmanager",
]
}
ohos_unittest("AccessManagerTest") {
module_out_path = module_out_path
sources = [
"${services_path}/distributedhardwarefwkservice/src/distributed_hardware_manager_factory.cpp",
"${services_path}/distributedhardwarefwkservice/src/accessmanager/access_manager.cpp",
]
sources += ["access_manager_test.cpp"]
configs = [":module_private_config"]
deps = [
"//third_party/googletest:gtest_main",
"${utils_path}:distributedhardwareutils",
"//foundation/distributedhardware/distributedhardwarefwk/services/distributedhardwarefwkservice:distributedhardwarefwksvr",
"//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk",
"//foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp:devicemanagersdk",
]
defines = [
"HI_LOG_ENABLE",
"DH_LOG_TAG=\"dhfwksvr\"",
"LOG_DOMAIN=0xD004100",
]
external_deps = [
"bundle_framework:appexecfwk_base",
"bundle_framework:appexecfwk_core",
"ipc:ipc_core",
"safwk:system_ability_fwk",
"samgr_standard:samgr_proxy",
"startup_l2:syspara",
]
}
group("unittest") {
testonly = true
deps = [ ":AccessManagerTest" ]
}

View File

@ -0,0 +1,264 @@
/*
* 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 <algorithm>
#include <chrono>
#include <thread>
#include <vector>
#include "gtest/gtest.h"
#include "access_manager.h"
#include "distributed_hardware_errno.h"
#include "distributed_hardware_manager_factory.h"
using namespace testing::ext;
namespace OHOS {
namespace DistributedHardware {
namespace {
enum class Status : uint32_t {
DEVICE_ONLINE = 0,
DEVICE_OFFLINE = 1,
};
constexpr int32_t INTERVAL_TIME_MS = 1;
constexpr uint16_t TEST_DEV_TYPE_PAD = 0x11;
/* save networkId and deviceId */
const std::vector<std::pair<std::string, std::string>> TEST_DEVICES = {
{ "11111111111111111111111111111111", "22222222222222222222222222222222" },
{ "33333333333333333333333333333333", "44444444444444444444444444444444" },
{ "55555555555555555555555555555555", "66666666666666666666666666666666" },
{ "77777777777777777777777777777777", "88888888888888888888888888888888" },
};
}
class AccessManagerTest : public testing::Test {
public:
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
std::mutex testAccessMutex_;
};
void AccessManagerTest::SetUp() {}
void AccessManagerTest::TearDown()
{
// clear all the online devices
for (const auto &dev : TEST_DEVICES) {
DistributedHardwareManagerFactory::GetInstance().SendOffLineEvent(dev.first, dev.second, TEST_DEV_TYPE_PAD);
}
// clear DM register status
AccessManager::GetInstance()->UnInit();
}
void AccessManagerTest::SetUpTestCase() {}
void AccessManagerTest::TearDownTestCase() {}
/**
* @tc.name: Init_001
* @tc.desc: Verify the sub function.
* @tc.type: FUNC
* @tc.require: AR000GHSJK
*/
HWTEST_F(AccessManagerTest, Init_001, TestSize.Level1)
{
auto ret = AccessManager::GetInstance()->Init();
EXPECT_EQ(DH_FWK_SUCCESS, ret);
}
/**
* @tc.name: Uninit_001
* @tc.desc: Verify the sub function.
* @tc.type: FUNC
* @tc.require: AR000GHSJK
*/
HWTEST_F(AccessManagerTest, UnInit_001, TestSize.Level1)
{
auto ret = AccessManager::GetInstance()->UnInit();
EXPECT_EQ(ERR_DH_FWK_ACCESS_UNINIT_DM_FAILED, ret);
}
/**
* @tc.name: Uninit_001
* @tc.desc: Verify the sub function.
* @tc.type: FUNC
* @tc.require: AR000GHSJK
*/
HWTEST_F(AccessManagerTest, UnInit_002, TestSize.Level1)
{
auto ret = AccessManager::GetInstance()->Init();
EXPECT_EQ(DH_FWK_SUCCESS, ret);
ret = AccessManager::GetInstance()->UnInit();
EXPECT_EQ(DH_FWK_SUCCESS, ret);
}
/**
* @tc.name: SendOnLineEvent_001
* @tc.desc: Verify the online success
* @tc.type: FUNC
* @tc.require: AR000GHSJK
*/
HWTEST_F(AccessManagerTest, SendOnLineEvent_001, TestSize.Level1)
{
ASSERT_FALSE(DistributedHardwareManagerFactory::GetInstance().IsInit());
for (const auto &dev : TEST_DEVICES) {
auto ret =
DistributedHardwareManagerFactory::GetInstance().SendOnLineEvent(dev.first, dev.second, TEST_DEV_TYPE_PAD);
ASSERT_EQ(DH_FWK_SUCCESS, ret);
ASSERT_TRUE(DistributedHardwareManagerFactory::GetInstance().IsInit());
}
}
/**
* @tc.name: SendOnLineEvent_002
* @tc.desc: Verify the online failed
* @tc.type: FUNC
* @tc.require: AR000GHSJK
*/
HWTEST_F(AccessManagerTest, SendOnLineEvent_002, TestSize.Level1)
{
ASSERT_FALSE(DistributedHardwareManagerFactory::GetInstance().IsInit());
auto ret =
DistributedHardwareManagerFactory::GetInstance().SendOnLineEvent("", TEST_DEVICES[0].second, TEST_DEV_TYPE_PAD);
ASSERT_EQ(ERR_DH_FWK_REMOTE_NETWORK_ID_IS_EMPTY, ret);
ASSERT_FALSE(DistributedHardwareManagerFactory::GetInstance().IsInit());
ret =
DistributedHardwareManagerFactory::GetInstance().SendOnLineEvent(TEST_DEVICES[0].first, "", TEST_DEV_TYPE_PAD);
ASSERT_EQ(ERR_DH_FWK_REMOTE_DEVICE_ID_IS_EMPTY, ret);
ASSERT_FALSE(DistributedHardwareManagerFactory::GetInstance().IsInit());
}
/**
* @tc.name: SendOffLineEvent_001
* @tc.desc: Verify the offline success
* @tc.type: FUNC
* @tc.require: AR000GHSJM
*/
HWTEST_F(AccessManagerTest, SendOffLineEvent_001, TestSize.Level1)
{
ASSERT_FALSE(DistributedHardwareManagerFactory::GetInstance().IsInit());
for (const auto &dev : TEST_DEVICES) {
auto ret =
DistributedHardwareManagerFactory::GetInstance().SendOnLineEvent(dev.first, dev.second, TEST_DEV_TYPE_PAD);
ASSERT_EQ(DH_FWK_SUCCESS, ret);
ASSERT_TRUE(DistributedHardwareManagerFactory::GetInstance().IsInit());
}
for (const auto &dev : TEST_DEVICES) {
auto ret =
DistributedHardwareManagerFactory::GetInstance().SendOffLineEvent(dev.first, dev.second, TEST_DEV_TYPE_PAD);
ASSERT_EQ(DH_FWK_SUCCESS, ret);
}
ASSERT_FALSE(DistributedHardwareManagerFactory::GetInstance().IsInit());
}
/**
* @tc.name: SendOffLineEvent_002
* @tc.desc: Verify the offline failed
* @tc.type: FUNC
* @tc.require: AR000GHSJM
*/
HWTEST_F(AccessManagerTest, SendOffLineEvent_002, TestSize.Level1)
{
ASSERT_FALSE(DistributedHardwareManagerFactory::GetInstance().IsInit());
auto ret = DistributedHardwareManagerFactory::GetInstance().SendOffLineEvent("", TEST_DEVICES[0].second,
TEST_DEV_TYPE_PAD);
ASSERT_EQ(ERR_DH_FWK_REMOTE_NETWORK_ID_IS_EMPTY, ret);
ASSERT_FALSE(DistributedHardwareManagerFactory::GetInstance().IsInit());
ret =
DistributedHardwareManagerFactory::GetInstance().SendOffLineEvent(TEST_DEVICES[0].first, "", TEST_DEV_TYPE_PAD);
ASSERT_EQ(ERR_DH_FWK_REMOTE_DEVICE_ID_IS_EMPTY, ret);
ASSERT_FALSE(DistributedHardwareManagerFactory::GetInstance().IsInit());
}
/**
* @tc.name: SendOffLineEvent_003
* @tc.desc: Verify the SendOnLineEvent for Multi-thread
* @tc.type: FUNC
* @tc.require: AR000GHSJM
*/
HWTEST_F(AccessManagerTest, SendOffLineEvent_003, TestSize.Level0)
{
auto handler = [this](Status status, std::string networkId, std::string devId, int32_t expect) {
if (status == Status::DEVICE_ONLINE) {
std::lock_guard<std::mutex> lock(testAccessMutex_);
std::this_thread::sleep_for(std::chrono::milliseconds(100));
auto onlineResult =
DistributedHardwareManagerFactory::GetInstance().SendOnLineEvent(networkId, devId, TEST_DEV_TYPE_PAD);
EXPECT_EQ(expect, onlineResult);
} else {
std::lock_guard<std::mutex> lock(testAccessMutex_);
std::this_thread::sleep_for(std::chrono::milliseconds(90));
auto offlineResult =
DistributedHardwareManagerFactory::GetInstance().SendOffLineEvent(networkId, devId, TEST_DEV_TYPE_PAD);
EXPECT_EQ(expect, offlineResult);
}
};
std::vector<std::thread> threadVec;
threadVec.emplace_back(
std::thread(handler, Status::DEVICE_ONLINE, TEST_DEVICES[0].first, TEST_DEVICES[0].second, DH_FWK_SUCCESS));
std::this_thread::sleep_for(std::chrono::milliseconds(INTERVAL_TIME_MS));
threadVec.emplace_back(
std::thread(handler, Status::DEVICE_ONLINE, TEST_DEVICES[1].first, TEST_DEVICES[1].second, DH_FWK_SUCCESS));
std::this_thread::sleep_for(std::chrono::milliseconds(INTERVAL_TIME_MS));
threadVec.emplace_back(std::thread(handler, Status::DEVICE_ONLINE, TEST_DEVICES[0].first, TEST_DEVICES[0].second,
ERR_DH_FWK_HARDWARE_MANAGER_DEVICE_REPEAT_ONLINE));
std::this_thread::sleep_for(std::chrono::milliseconds(INTERVAL_TIME_MS));
threadVec.emplace_back(
std::thread(handler, Status::DEVICE_ONLINE, TEST_DEVICES[2].first, TEST_DEVICES[2].second, DH_FWK_SUCCESS));
std::this_thread::sleep_for(std::chrono::milliseconds(INTERVAL_TIME_MS));
threadVec.emplace_back(
std::thread(handler, Status::DEVICE_ONLINE, TEST_DEVICES[3].first, TEST_DEVICES[3].second, DH_FWK_SUCCESS));
std::this_thread::sleep_for(std::chrono::milliseconds(INTERVAL_TIME_MS));
threadVec.emplace_back(
std::thread(handler, Status::DEVICE_OFFLINE, TEST_DEVICES[3].first, TEST_DEVICES[3].second, DH_FWK_SUCCESS));
std::this_thread::sleep_for(std::chrono::milliseconds(INTERVAL_TIME_MS));
threadVec.emplace_back(std::thread(handler, Status::DEVICE_OFFLINE, TEST_DEVICES[3].first, TEST_DEVICES[3].second,
ERR_DH_FWK_HARDWARE_MANAGER_DEVICE_REPEAT_OFFLINE));
std::this_thread::sleep_for(std::chrono::milliseconds(INTERVAL_TIME_MS));
threadVec.emplace_back(
std::thread(handler, Status::DEVICE_OFFLINE, TEST_DEVICES[1].first, TEST_DEVICES[1].second, DH_FWK_SUCCESS));
std::this_thread::sleep_for(std::chrono::milliseconds(INTERVAL_TIME_MS));
threadVec.emplace_back(
std::thread(handler, Status::DEVICE_OFFLINE, TEST_DEVICES[0].first, TEST_DEVICES[0].second, DH_FWK_SUCCESS));
std::this_thread::sleep_for(std::chrono::milliseconds(INTERVAL_TIME_MS));
threadVec.emplace_back(
std::thread(handler, Status::DEVICE_OFFLINE, TEST_DEVICES[2].first, TEST_DEVICES[2].second, DH_FWK_SUCCESS));
for_each(threadVec.begin(), threadVec.end(), [](std::thread &t) { t.join(); });
}
}
}

View File

@ -0,0 +1,91 @@
# Copyright (c) 2021 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import("//build/ohos.gni")
import("//build/ohos_var.gni")
import("//foundation/distributedhardware/distributedhardwarefwk/distributedhardwarefwk.gni")
ohos_shared_library("distributedhardwarefwksvr_impl") {
include_dirs = [
"//utils/native/base/include",
"//utils/system/safwk/native/include",
"//third_party/json/include",
"include",
"include/componentloader",
"include/versionmanager",
"include/componentmanager",
"include/task",
"include/utils",
"include/localhardwaremanager",
"include/resourcemanager",
"${common_path}/log/include",
"${common_path}/utils/include",
"${utils_path}/include",
"${utils_path}/include/log",
"${utils_path}/include/eventbus",
]
sources = [
"src/distributed_hardware_manager.cpp",
"src/distributed_hardware_proxy.cpp",
"src/componentloader/component_loader.cpp",
"src/task/disable_task.cpp",
"src/task/enable_task.cpp",
"src/task/offline_task.cpp",
"src/task/online_task.cpp",
"src/task/task_board.cpp",
"src/task/task_executor.cpp",
"src/task/task_factory.cpp",
"src/task/task.cpp",
"src/utils/dh_context.cpp",
"src/versionmanager/version_manager.cpp",
"src/componentmanager/component_manager.cpp",
"src/componentmanager/component_enable.cpp",
"src/componentmanager/component_disable.cpp",
"src/localhardwaremanager/local_hardware_manager.cpp",
"src/resourcemanager/capability_info.cpp",
"src/resourcemanager/capability_info_manager.cpp",
"src/resourcemanager/db_adapter.cpp",
"src/resourcemanager/capability_utils.cpp"
]
deps = [
"${utils_path}:distributedhardwareutils",
"//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk",
"//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager",
"//foundation/aafwk/standard/services/abilitymgr:abilityms",
"//utils/native/base:utils",
]
defines = [
"HI_LOG_ENABLE",
"DH_LOG_TAG=\"dhfwksvr\"",
"LOG_DOMAIN=0xD004100",
]
external_deps = [
"bundle_framework:appexecfwk_base",
"bundle_framework:appexecfwk_core",
"eventhandler:libeventhandler",
"hiviewdfx_hilog_native:libhilog",
"distributeddatamgr:distributeddata_inner",
"ipc:ipc_core",
"safwk:system_ability_fwk",
"samgr_standard:samgr_proxy",
"startup_l2:syspara",
]
subsystem_name = "distributedhardware"
part_name = "distributed_hardware_fwk"
}

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 OHOS_DISTRIBUTED_HARDWARE_COMPONENT_LOADER_H
#define OHOS_DISTRIBUTED_HARDWARE_COMPONENT_LOADER_H
#include <atomic>
#include <map>
#include <vector>
#include "single_instance.h"
#include "distributed_hardware_errno.h"
#include "device_type.h"
#include "ihardware_handler.h"
#include "idistributed_hardware_sink.h"
#include "idistributed_hardware_source.h"
#include "utils/impl_utils.h"
namespace OHOS {
namespace DistributedHardware {
struct CompConfig {
std::string name;
DHType type;
std::string compHandlerLoc;
std::string compHandlerVersion;
std::string compSourceLoc;
std::string compSourceVersion;
std::string compSinkLoc;
std::string compSinkVersion;
};
struct CompHandler {
void *sourceHandler;
void *sinkHandler;
void *hardwareHandler;
};
const std::string COMPONENTSLOAD_DISTRIBUTED_COMPONENTS = "distributed_components";
class ComponentLoader {
DECLARE_SINGLE_INSTANCE_BASE(ComponentLoader);
public:
ComponentLoader() : isLocalVersionInit_(false) {}
~ComponentLoader() {}
public:
int32_t Init();
int32_t GetHardwareHandler(const DHType dhType, IHardwareHandler *&hardwareHandlerPtr);
int32_t GetSource(const DHType dhType, IDistributedHardwareSource *&sourcePtr);
int32_t GetSink(const DHType dhType, IDistributedHardwareSink *&sinkPtr);
int32_t UnInit();
int32_t ReleaseHardwareHandler(const DHType dhType);
int32_t ReleaseSource(const DHType dhType);
int32_t ReleaseSink(const DHType dhType);
std::vector<DHType> GetAllCompTypes();
int32_t GetLocalDHVersion(DHVersion &dhVersion);
private:
void *GetHandler(const std::string &soName);
void GetAllHandler(std::map<DHType, CompConfig> &dhtypeMap);
int32_t ReleaseHandler(void *&handler);
int32_t GetCompPathAndVersion(const std::string &jsonStr, std::map<DHType, CompConfig> &dhtypeMap);
CompVersion GetCompVersionFromComConfig(const CompConfig& cCfg);
int32_t ParseConfig();
bool IsDHTypeExist(DHType dhType);
std::string Readfile(const std::string &filePath);
private:
DHVersion localDHVersion_;
std::map<DHType, CompHandler> compHandlerMap_;
std::atomic<bool> isLocalVersionInit_;
};
}
}
#endif

View File

@ -0,0 +1,42 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DISTRIBUTED_HARDWARE_COMPONENT_DISABLE_H
#define OHOS_DISTRIBUTED_HARDWARE_COMPONENT_DISABLE_H
#include <condition_variable>
#include <mutex>
#include "idistributed_hardware_source.h"
namespace OHOS {
namespace DistributedHardware {
class ComponentDisable : public std::enable_shared_from_this<ComponentDisable>, public UnregisterCallback {
public:
ComponentDisable();
virtual ~ComponentDisable();
int32_t Disable(const std::string &networkId, const std::string &dhId,
IDistributedHardwareSource *handler);
int32_t OnUnregisterResult(const std::string &networkId, const std::string &dhId, int32_t status,
const std::string &data) override;
private:
int32_t status_;
std::mutex mutex_;
std::condition_variable conVar_;
};
}
}
#endif

View File

@ -0,0 +1,42 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DISTRIBUTED_HARDWARE_COMPONENT_ENABLE_H
#define OHOS_DISTRIBUTED_HARDWARE_COMPONENT_ENABLE_H
#include <condition_variable>
#include <mutex>
#include "idistributed_hardware_source.h"
namespace OHOS {
namespace DistributedHardware {
class ComponentEnable : public std::enable_shared_from_this<ComponentEnable>, public RegisterCallback {
public:
ComponentEnable();
virtual ~ComponentEnable();
int32_t Enable(const std::string &devId, const std::string &dhId, const EnableParam &param,
IDistributedHardwareSource *handler);
int32_t OnRegisterResult(const std::string &devId, const std::string &dhId, int32_t status,
const std::string &data) override;
private:
int32_t status_;
std::mutex mutex_;
std::condition_variable conVar_;
};
}
}
#endif

View File

@ -0,0 +1,78 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DISTRIBUTED_HARDWARE_COMPONENT_MANAGER_H
#define OHOS_DISTRIBUTED_HARDWARE_COMPONENT_MANAGER_H
#include <map>
#include <unordered_map>
#include <mutex>
#include <future>
#include "single_instance.h"
#include "device_type.h"
#include "idistributed_hardware.h"
#include "idistributed_hardware_sink.h"
#include "idistributed_hardware_source.h"
namespace OHOS {
namespace DistributedHardware {
class ComponentManager {
DECLARE_SINGLE_INSTANCE_BASE(ComponentManager);
public:
ComponentManager() {}
~ComponentManager();
public:
int32_t Init();
int32_t UnInit();
int32_t Enable(const std::string &networkId, const std::string &devId, const std::string &dhId);
int32_t Disable(const std::string &networkId, const std::string &devId, const std::string &dhId);
private:
enum class Action : int32_t {
START_SOURCE,
START_SINK,
STOP_SOURCE,
STOP_SINK
};
using ActionResult = std::unordered_map<DHType, std::shared_future<int32_t>>;
DHType GetDHType(const std::string &devId, const std::string &dhId) const;
bool InitCompSource();
bool InitCompSink();
ActionResult StartSource();
ActionResult StopSource();
ActionResult StartSink();
ActionResult StopSink();
bool WaitForResult(const Action &action, ActionResult result);
int32_t GetEnableParam(const std::string &networkId, const std::string &devId, const std::string &dhId,
DHType dhType, EnableParam &param);
std::string GetSinkVersion(const std::string &networkId, const std::string &devId, DHType dhType);
std::string GetVersionFromCache(const std::string &devId, DHType dhType);
int32_t UpdateVersionCache(const std::string &networkId, const std::string &devId);
sptr<IDistributedHardware> GetRemoteDHMS(const std::string &networkId) const;
private:
std::map<DHType, IDistributedHardwareSource*> compSource_;
std::map<DHType, IDistributedHardwareSink*> compSink_;
std::unordered_map<std::string, std::unordered_map<DHType, std::string>> sinkVersions_;
std::mutex sinkVersionMutex_;
};
}
}
#endif

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 OHOS_DISTRIBUTED_HARDWARE_MANAGER_H
#define OHOS_DISTRIBUTED_HARDWARE_MANAGER_H
#include "idistributed_hardware_manager.h"
#include "single_instance.h"
#include "device_type.h"
namespace OHOS {
namespace DistributedHardware {
class DistributedHardwareManager : public IDistributedHardwareManager {
DECLARE_SINGLE_INSTANCE(DistributedHardwareManager);
public:
int32_t Initialize() override;
int32_t Release() override;
int32_t SendOnLineEvent(const std::string &networkId, const std::string &deviceId, uint16_t deviceType) override;
int32_t SendOffLineEvent(const std::string &networkId, const std::string &deviceId, uint16_t deviceType) override;
size_t GetOnLineCount() override;
int32_t GetComponentVersion(std::unordered_map<DHType, std::string> &versionMap) override;
};
}
}
#endif

View File

@ -0,0 +1,44 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DISTRIBUTED_HARDWARE_PROXY_H
#define OHOS_DISTRIBUTED_HARDWARE_PROXY_H
#include <cstdint>
#include "iremote_proxy.h"
#include "refbase.h"
#include "idistributed_hardware.h"
namespace OHOS {
namespace DistributedHardware {
class DistributedHardwareProxy : public IRemoteProxy<IDistributedHardware> {
public:
explicit DistributedHardwareProxy(const sptr<IRemoteObject>& impl)
: IRemoteProxy<IDistributedHardware>(impl)
{
}
virtual ~DistributedHardwareProxy() {}
int32_t QuerySinkVersion(std::unordered_map<DHType, std::string> &versionMap) override;
private:
std::unordered_map<DHType, std::string> FromJson(const std::string &json) const;
static inline BrokerDelegator<DistributedHardwareProxy> delegator_;
};
}
}
#endif

View File

@ -0,0 +1,52 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DISTRIBUTED_HARDWARE_LOCAL_HARDWARE_MANAGER_H
#define OHOS_DISTRIBUTED_HARDWARE_LOCAL_HARDWARE_MANAGER_H
#include <map>
#include <memory>
#include <vector>
#include "device_type.h"
#include "ihardware_handler.h"
#include "single_instance.h"
namespace OHOS {
namespace DistributedHardware {
namespace {
constexpr int32_t QUERY_INTERVAL_TIME = 1000 * 1000; // 1s
constexpr int32_t QUERY_RETRY_MAX_TIMES = 30;
}
class LocalHardwareManager {
DECLARE_SINGLE_INSTANCE_BASE(LocalHardwareManager);
public:
LocalHardwareManager();
~LocalHardwareManager();
void Init();
void UnInit();
private:
void QueryLocalHardware(const DHType dhType, IHardwareHandler *hardwareHandler);
void AddLocalCapabilityInfo(const std::vector<DHItem> &dhItems, const DHType dhType);
private:
std::map<DHType, IHardwareHandler*> compToolFuncsMap_;
};
}
}
#endif

View File

@ -0,0 +1,91 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DISTRIBUTED_HARDWARE_CAPABILITY_INFO_H
#define OHOS_DISTRIBUTED_HARDWARE_CAPABILITY_INFO_H
#include <list>
#include <memory>
#include <map>
#include "nlohmann/json.hpp"
#include "device_type.h"
namespace OHOS {
namespace DistributedHardware {
class CapabilityInfo {
public:
CapabilityInfo()
: dhId_(""),
deviceId_(""),
deviceName_(""),
deviceType_(0),
dhType_(DHType::UNKNOWN),
dhAttrs_("")
{}
CapabilityInfo(std::string dhId, std::string devId, std::string devName, uint16_t devType, DHType dhType,
std::string dhAttrs)
: dhId_(dhId), deviceId_(devId), deviceName_(devName), deviceType_(devType), dhType_(dhType), dhAttrs_(dhAttrs)
{}
virtual ~CapabilityInfo() {}
std::string GetDHId() const;
void SetDHId(const std::string &dhId);
std::string GetDeviceId() const;
void SetDeviceId(const std::string &deviceId);
std::string GetDeviceName() const;
void SetDeviceName(const std::string &deviceName);
uint16_t GetDeviceType() const;
void SetDeviceType(uint16_t deviceType);
DHType GetDHType() const;
void SetDHType(const DHType dhType);
std::string GetDHAttrs() const;
void SetDHAttrs(const std::string &dhAttrs);
virtual std::string GetKey() const;
virtual std::string GetAnonymousKey() const;
virtual int32_t FromJsonString(const std::string &jsonStr);
virtual std::string ToJsonString();
private:
std::string dhId_;
std::string deviceId_;
std::string deviceName_;
uint16_t deviceType_;
DHType dhType_;
std::string dhAttrs_;
};
void ToJson(nlohmann::json &jsonObject, const CapabilityInfo &capability);
void FromJson(const nlohmann::json &jsonObject, CapabilityInfo &capability);
using CapabilityInfoMap = std::map<std::string, std::shared_ptr<CapabilityInfo>>;
}
}
#endif

View File

@ -0,0 +1,55 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DISTRIBUTED_HARDWARE_CAPABILITY_INFO_EVENT_H
#define OHOS_DISTRIBUTED_HARDWARE_CAPABILITY_INFO_EVENT_H
#include <string>
#include "distributed_hardware_log.h"
#include "event.h"
#include "event_sender.h"
namespace OHOS {
namespace DistributedHardware {
class CapabilityInfoEvent : public Event {
TYPEINDENT(CapabilityInfoEvent)
public:
enum class EventType : uint32_t {
UNDEFINED = 0,
RECOVER = 1,
};
public:
CapabilityInfoEvent(EventSender &sender) : Event(sender)
{
action_ = EventType::UNDEFINED;
}
CapabilityInfoEvent(EventSender &sender, EventType action) : Event(sender), action_(action) {}
virtual ~CapabilityInfoEvent() {}
EventType GetAction() const
{
return action_;
}
private:
EventType action_;
};
}
}
#endif

View File

@ -0,0 +1,115 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DISTRIBUTED_HARDWARE_CAPABILITY_INFO_MANAGER_H
#define OHOS_DISTRIBUTED_HARDWARE_CAPABILITY_INFO_MANAGER_H
#include <condition_variable>
#include <map>
#include <set>
#include "kvstore_observer.h"
#include "capability_info.h"
#include "capability_info_event.h"
#include "capability_utils.h"
#include "db_adapter.h"
#include "event.h"
#include "eventbus_handler.h"
#include "event_bus.h"
#include "event_sender.h"
#include "single_instance.h"
using OHOS::DistributedKv::Entry;
class DBAdapter;
namespace OHOS {
namespace DistributedHardware {
namespace {
constexpr int32_t MANUAL_SYNC_TIMEOUT = 1;
}
class CapabilityInfoManager : public std::enable_shared_from_this<CapabilityInfoManager>,
public EventSender,
public DistributedKv::KvStoreObserver,
public EventBusHandler<CapabilityInfoEvent> {
public:
CapabilityInfoManager(const CapabilityInfoManager &) = delete;
CapabilityInfoManager &operator = (const CapabilityInfoManager &) = delete;
CapabilityInfoManager(CapabilityInfoManager &&) = delete;
CapabilityInfoManager &operator = (CapabilityInfoManager &&) = delete;
static std::shared_ptr<CapabilityInfoManager> GetInstance();
virtual ~CapabilityInfoManager();
int32_t Init();
int32_t UnInit();
/* update the database record to memory */
int32_t SyncDeviceInfoFromDB(const std::string &deviceId);
/* update the database record to memory in abnormal scene */
int32_t SyncRemoteCapabilityInfos();
/* Add Distributed hardware information, Save in memory and database */
int32_t AddCapability(const std::vector<std::shared_ptr<CapabilityInfo>> &resInfos);
/* Save CapabilityInfo in memory */
int32_t AddCapabilityInMem(const std::vector<std::shared_ptr<CapabilityInfo>> &resInfos);
/* Deleting Database Records */
int32_t RemoveCapabilityInfoInDB(const std::string &deviceId);
/* Deleting Database Records by key */
int32_t RemoveCapabilityInfoByKey(const std::string &key);
/* Delete data from memory cache */
int32_t RemoveCapabilityInfoInMem(const std::string &deviceId);
/* Queries distributed hardware information based on filter criteria. */
std::map<std::string, std::shared_ptr<CapabilityInfo>> QueryCapabilityByFilters(
const std::map<CapabilityInfoFilter, std::string> &filters);
bool IsCapabilityMatchFilter(const std::shared_ptr<CapabilityInfo> &cap, const CapabilityInfoFilter &filter,
const std::string &value);
bool HasCapability(const std::string &deviceId, const std::string &dhId);
void GetCapabilitiesByDeviceId(const std::string &deviceId,
std::vector<std::shared_ptr<CapabilityInfo>> &resInfos);
/* Queries capability information based on deviceId and dhId. */
int32_t GetCapability(const std::string &deviceId, const std::string &dhId,
std::shared_ptr<CapabilityInfo> &capPtr);
int32_t GetDataByKey(const std::string &key, std::shared_ptr<CapabilityInfo>& capInfoPtr);
/* Queries batch records in the database based on the prefix of the key. */
int32_t GetDataByKeyPrefix(const std::string &keyPrefix, CapabilityInfoMap &capabilityMap);
/* Init the count of manual sync times */
void CreateManualSyncCount(const std::string &deviceId);
/* Clearing the count of manual sync times */
void RemoveManualSyncCount(const std::string &deviceId);
/* Actively synchronizes data */
int32_t ManualSync(const std::string &networkId);
/* Manual sync notify */
void NotifySyncCompleted();
/* Database data changes callback */
virtual void OnChange(const DistributedKv::ChangeNotification &changeNotification) override;
virtual void OnChange(const DistributedKv::ChangeNotification &changeNotification,
std::shared_ptr<DistributedKv::KvStoreSnapshot> snapshot) override;
/* EventBus async processing callback */
void OnEvent(CapabilityInfoEvent &e) override;
private:
CapabilityInfoManager();
void HandleCapabilityAddChange(const std::vector<Entry> &insertRecords);
void HandleCapabilityUpdateChange(const std::vector<Entry> &updateRecords);
void HandleCapabilityDeleteChange(const std::vector<Entry> &deleteRecords);
private:
mutable std::mutex capInfoMgrMutex_;
int32_t manualSyncResult_;
std::condition_variable manualSyncCondVar_;
std::shared_ptr<DBAdapter> dbAdapterPtr_;
CapabilityInfoMap globalCapInfoMap_;
};
}
}
#endif

View File

@ -0,0 +1,42 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DISTRIBUTED_HARDWARE_CAPABILITY_UTILS_H
#define OHOS_DISTRIBUTED_HARDWARE_CAPABILITY_UTILS_H
#include <string>
#include <vector>
#include "capability_info.h"
namespace OHOS {
namespace DistributedHardware {
enum CapabilityInfoFilter : uint32_t {
FILTER_DH_ID = 0,
FILTER_DEVICE_ID = 1,
FILTER_DEVICE_NAME = 2,
FILTER_DEVICE_TYPE = 3,
FILTER_DH_TYPE = 4,
FILTER_DH_ATTRS = 5
};
class CapabilityUtils {
public:
static int32_t GetCapabilityByValue(const std::string &value, std::shared_ptr<CapabilityInfo> &capPtr);
static std::string GetCapabilityKey(const std::string &deviceId, const std::string &dhId);
static bool IsCapKeyMatchDeviceId(const std::string &key, const std::string &deviceId);
};
}
}
#endif

View File

@ -0,0 +1,89 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DISTRIBUTED_HARDWARE_DB_ADAPTER_H
#define OHOS_DISTRIBUTED_HARDWARE_DB_ADAPTER_H
#include <map>
#include <memory>
#include <mutex>
#include <string>
#include <unordered_map>
#include <vector>
#include "distributed_kv_data_manager.h"
#include "capability_info.h"
#include "capability_info_manager.h"
#include "event_sender.h"
namespace OHOS {
namespace DistributedHardware {
namespace {
constexpr int32_t MAX_INIT_RETRY_TIMES = 20;
constexpr int32_t INIT_RETRY_SLEEP_INTERVAL = 200 * 1000; // 200ms
constexpr int32_t MANUAL_SYNC_TIMES = 6;
constexpr int32_t MANUAL_SYNC_INTERVAL = 100 * 1000; // 100ms
constexpr int32_t DIED_CHECK_MAX_TIMES = 300;
constexpr int32_t DIED_CHECK_INTERVAL = 100 * 1000; // 100ms
}
class DBAdapter : public std::enable_shared_from_this<DBAdapter>,
public EventSender,
public DistributedKv::KvStoreSyncCallback,
public DistributedKv::KvStoreDeathRecipient {
public:
DBAdapter(const std::string &appId, const std::string &storeId,
const std::shared_ptr<DistributedKv::KvStoreObserver> &changeListener);
virtual ~DBAdapter();
int32_t Init();
void UnInit();
int32_t ReInit();
void SyncCompleted(const std::map<std::string, DistributedKv::Status> &results) override;
int32_t GetDataByKey(const std::string &key, std::string &data);
int32_t GetDataByKeyPrefix(const std::string &keyPrefix, std::vector<std::string> &values);
int32_t PutData(const std::string &key, std::string &value);
int32_t PutDataBatch(const std::vector<std::string> &keys, const std::vector<std::string> &values);
void CreateManualSyncCount(const std::string &deviceId);
void RemoveManualSyncCount(const std::string &deviceId);
int32_t ManualSync(const std::string &networkId);
void SyncDBForRecover();
virtual void OnRemoteDied() override;
void DeleteKvStore();
int32_t RemoveDeviceData(const std::string &deviceId);
int32_t RemoveDataByKey(const std::string &key);
private:
int32_t RegisterChangeListener();
int32_t UnRegisterChangeListener();
void RegisterKvStoreDeathListener();
void UnRegisterKvStoreDeathListener();
void RegisterManualSyncListener();
void UnRegisterManualSyncListener();
DistributedKv::Status GetKvStorePtr();
private:
DistributedKv::AppId appId_;
DistributedKv::StoreId storeId_;
DistributedKv::DistributedKvDataManager kvDataMgr_;
std::shared_ptr<DistributedKv::SingleKvStore> kvStoragePtr_;
std::shared_ptr<DistributedKv::KvStoreObserver> dataChangeListener_;
std::mutex dbAdapterMutex_;
std::unordered_map<std::string, int32_t> manualSyncCountMap_;
};
}
}
#endif

View File

@ -0,0 +1,36 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DISTRIBUTED_HARDWARE_DISABLE_TASK_H
#define OHOS_DISTRIBUTED_HARDWARE_DISABLE_TASK_H
#include "task.h"
namespace OHOS {
namespace DistributedHardware {
class DisableTask : public Task {
public:
DisableTask() = delete;
DisableTask(const std::string &networkId, const std::string &devId, const std::string &dhId);
virtual ~DisableTask();
virtual void DoTask();
private:
/* synchronous function for unregister distributed hardware, return on asynchronous unregister finish */
int32_t UnRegisterHardware();
};
}
}
#endif

View File

@ -0,0 +1,36 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DISTRIBUTED_HARDWARE_ENABLE_TASK_H
#define OHOS_DISTRIBUTED_HARDWARE_ENABLE_TASK_H
#include "task.h"
namespace OHOS {
namespace DistributedHardware {
class EnableTask : public Task {
public:
EnableTask() = delete;
EnableTask(const std::string &networkId, const std::string &devId, const std::string &dhId);
virtual ~EnableTask();
virtual void DoTask();
private:
/* synchronous function for register distributed hardware, return on asynchronous register finish */
int32_t RegisterHardware();
};
}
}
#endif

View File

@ -0,0 +1,54 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DISTRIBUTED_HARDWARE_OFFLINE_TASK_H
#define OHOS_DISTRIBUTED_HARDWARE_OFFLINE_TASK_H
#include <condition_variable>
#include <mutex>
#include "task.h"
namespace OHOS {
namespace DistributedHardware {
class OffLineTask : public Task {
public:
OffLineTask() = delete;
OffLineTask(const std::string &networkId, const std::string &devId, const std::string &dhId);
virtual ~OffLineTask();
virtual void DoTask();
virtual void NotifyFatherFinish(std::string taskId);
virtual void AddChildrenTask(std::shared_ptr<Task> childrenTask);
private:
/* OffLineTask should wait until all Disable task finish, we run it in a independent thread */
void DoTaskInner();
/* create disable tasks for off line device */
void CreateDisableTask();
/* wait until all disable tasks finish or timeout */
void WaitDisableTaskFinish();
/* clear off line device info */
void ClearOffLineInfo();
private:
/* condition for children task finish */
std::condition_variable finishCondVar_;
std::mutex unFinishTaskMtx_;
std::set<std::string> unFinishChildrenTasks_;
};
}
}
#endif

View File

@ -0,0 +1,36 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DISTRIBUTED_HARDWARE_ONLINE_TASK_H
#define OHOS_DISTRIBUTED_HARDWARE_ONLINE_TASK_H
#include "task.h"
namespace OHOS {
namespace DistributedHardware {
class OnLineTask : public Task {
public:
OnLineTask() = delete;
OnLineTask(const std::string &networkId, const std::string &devId, const std::string &dhId);
virtual ~OnLineTask();
virtual void DoTask();
private:
void DoSyncInfo();
void CreateEnableTask();
};
}
}
#endif

View File

@ -0,0 +1,70 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DISTRIBUTED_HARDWARE_TASK_H
#define OHOS_DISTRIBUTED_HARDWARE_TASK_H
#include <memory>
#include <mutex>
#include <set>
#include <string>
#include <vector>
#include "impl_utils.h"
namespace OHOS {
namespace DistributedHardware {
class Task : public std::enable_shared_from_this<Task> {
public:
Task() = delete;
Task(const std::string &networkId, const std::string &devId, const std::string &dhId);
virtual ~Task();
virtual void DoTask() = 0;
std::string GetId();
std::string GetNetworkId();
std::string GetDevId();
std::string GetDhId();
TaskType GetTaskType();
void SetTaskType(TaskType taskType);
void SetTaskSteps(std::vector<TaskStep> taskSteps);
const std::vector<TaskStep> GetTaskSteps();
TaskState GetTaskState();
void SetTaskState(TaskState taskState);
virtual void AddChildrenTask(std::shared_ptr<Task> childrenTask);
const std::vector<std::shared_ptr<Task>> GetChildrenTasks();
const std::weak_ptr<Task> GetFatherTask();
void SetFatherTask(std::shared_ptr<Task> fatherTask);
private:
std::string id_;
std::string networkId_;
std::string devId_;
std::string dhId_;
TaskType taskType_ { TaskType::UNKNOWN };
std::vector<TaskStep> taskSteps_;
std::weak_ptr<Task> fatherTask_;
std::mutex taskMtx_;
std::vector<std::shared_ptr<Task>> childrenTasks_;
TaskState taskState_ { TaskState::INIT };
};
}
}
#endif

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 OHOS_DISTRIBUTED_HARDWARE_TASK_BOARD_H
#define OHOS_DISTRIBUTED_HARDWARE_TASK_BOARD_H
#include <condition_variable>
#include <memory>
#include <mutex>
#include <string>
#include <unordered_map>
#include "single_instance.h"
#include "task.h"
namespace OHOS {
namespace DistributedHardware {
class TaskBoard {
DECLARE_SINGLE_INSTANCE(TaskBoard);
public:
bool IsAllTaskFinish();
void AddTask(std::shared_ptr<Task> task);
void RemoveTask(std::string taskId);
int32_t WaitForALLTaskFinish();
private:
void RemoveTaskInner(std::string taskId);
private:
std::condition_variable conVar_;
std::mutex tasksMtx_;
std::unordered_map<std::string, std::shared_ptr<Task>> tasks_;
};
}
}
#endif

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 OHOS_DISTRIBUTED_HARDWARE_TASK_EXECUTOR_H
#define OHOS_DISTRIBUTED_HARDWARE_TASK_EXECUTOR_H
#include <condition_variable>
#include <mutex>
#include <queue>
#include "task.h"
#include "single_instance.h"
namespace OHOS {
namespace DistributedHardware {
class TaskExecutor {
DECLARE_SINGLE_INSTANCE_BASE(TaskExecutor);
public:
explicit TaskExecutor();
~TaskExecutor();
void PushTask(const std::shared_ptr<Task>& task);
private:
std::shared_ptr<Task> PopTask();
void TriggerTask();
private:
std::queue<std::shared_ptr<Task>> taskQueue_;
std::mutex taskQueueMtx_;
std::condition_variable condVar_;
bool taskThreadFlag_;
};
}
}
#endif

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 OHOS_DISTRIBUTED_HARDWARE_TASK_FACTORY_H
#define OHOS_DISTRIBUTED_HARDWARE_TASK_FACTORY_H
#include <memory>
#include "single_instance.h"
#include "task.h"
namespace OHOS {
namespace DistributedHardware {
class TaskFactory {
DECLARE_SINGLE_INSTANCE(TaskFactory);
public:
std::shared_ptr<Task> CreateTask(TaskType taskType, const std::string &networkId, const std::string &devId,
const std::string &dhId, std::shared_ptr<Task> fatherTask);
};
}
}
#endif

View File

@ -0,0 +1,56 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DISTRIBUTED_HARDWARE_DHCONTEXT_H
#define OHOS_DISTRIBUTED_HARDWARE_DHCONTEXT_H
#include <memory>
#include <string>
#include <unordered_set>
#include <shared_mutex>
#include "device_type.h"
#include "event_bus.h"
#include "single_instance.h"
namespace OHOS {
namespace DistributedHardware {
class DHContext {
DECLARE_SINGLE_INSTANCE_BASE(DHContext);
public:
DHContext();
~DHContext();
std::shared_ptr<EventBus> GetEventBus();
const DeviceInfo& GetDeviceInfo();
/* Save online device UUID and networkId when devices online */
void AddOnlineDevice(const std::string &devId, const std::string &networkId);
void RemoveOnlineDevice(const std::string &devId);
bool IsDeviceOnline(const std::string &devId);
size_t GetOnlineCount();
std::string GetNetworkIdByUUID(const std::string &devId);
private:
std::shared_ptr<EventBus> eventBus_;
DeviceInfo devInfo_ { "", "", 0 };
std::mutex devMutex_;
/* Save online device UUID and networkId */
std::unordered_map<std::string, std::string> onlineDeviceMap_;
std::shared_mutex onlineDevMutex_;
};
}
}
#endif

View File

@ -0,0 +1,65 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DISTRIBUTED_HARDWARE_IMPL_UTILS_H
#define OHOS_DISTRIBUTED_HARDWARE_IMPL_UTILS_H
#include <unordered_map>
#include "device_type.h"
namespace OHOS {
namespace DistributedHardware {
enum class TaskType : int32_t {
UNKNOWN = 0,
ENABLE = 1,
DISABLE = 2,
ON_LINE = 3,
OFF_LINE = 4
};
enum class TaskStep : int32_t {
DO_ENABLE = 1,
DO_DISABLE = 2,
SYNC_ONLINE_INFO = 3,
REGISTER_ONLINE_DISTRIBUTED_HARDWARE = 4,
UNREGISTER_OFFLINE_DISTRIBUTED_HARDWARE = 5,
CLEAR_OFFLINE_INFO = 6,
WAIT_UNREGISTGER_COMPLETE = 7
};
enum class TaskState : int32_t {
INIT = 0,
RUNNING = 1,
SUCCESS = 2,
FAIL = 3
};
struct CompVersion {
std::string name;
DHType dhType;
std::string handlerVersion;
std::string sourceVersion;
std::string sinkVersion;
};
struct DHVersion {
std::string devId;
std::string dhVersion;
std::unordered_map<DHType, CompVersion> compVersions;
};
}
}
#endif

View File

@ -0,0 +1,52 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DISTRIBUTED_HARDWARE_VERSION_MANAGER_H
#define OHOS_DISTRIBUTED_HARDWARE_VERSION_MANAGER_H
#include <mutex>
#include <vector>
#include <string>
#include "single_instance.h"
#include "distributed_hardware_errno.h"
#include "device_type.h"
#include "utils/impl_utils.h"
namespace OHOS {
namespace DistributedHardware {
const std::string DH_LOCAL_VERSION = "1.0";
class VersionManager {
DECLARE_SINGLE_INSTANCE_BASE(VersionManager);
public:
VersionManager() {}
~VersionManager() {}
int32_t Init();
void UnInit();
int32_t AddDHVersion(const std::string &devId, const DHVersion &dhVersion);
int32_t RemoveDHVersion(const std::string &devId);
int32_t GetDHVersion(const std::string &devId, DHVersion &dhVersion);
int32_t GetCompVersion(const std::string &devId, const DHType dhType, CompVersion &compVersion);
std::string GetLocalDeviceVersion();
void ShowLocalVersion(const DHVersion &dhVersion) const;
private:
std::unordered_map<std::string, DHVersion> dhVersions_;
std::mutex versionMutex_;
};
}
}
#endif

View File

@ -0,0 +1,322 @@
/*
* 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 "componentloader/component_loader.h"
#include <dlfcn.h>
#include <fstream>
#include <string>
#include "nlohmann/json.hpp"
#include "constants.h"
#include "distributed_hardware_log.h"
using nlohmann::json;
namespace OHOS {
namespace DistributedHardware {
#undef DH_LOG_TAG
#define DH_LOG_TAG "ComponentLoader"
IMPLEMENT_SINGLE_INSTANCE(ComponentLoader);
using GetHardwareClass = IHardwareHandler *(*)();
using GetSourceHardwareClass = IDistributedHardwareSource *(*)();
using GetSinkHardwareClass = IDistributedHardwareSink *(*)();
namespace {
const std::string DEFAULT_NAME = "";
const std::string DEFAULT_HANDLER_LOC = "";
const std::string DEFAULT_SOURCE_LOC = "";
const std::string DEFAULT_SINK_LOC = "";
const std::string DEFAULT_TYPE = "UNKNOWN";
const std::string DEFAULT_VERSION = "1.0";
}
std::map<std::string, DHType> g_mapDhTypeName = {
{ "UNKNOWN", DHType::UNKNOWN },
{ "CAMERA", DHType::CAMERA },
{ "MIC", DHType::MIC },
{ "SPEAKER", DHType::SPEAKER },
{ "DISPLAY", DHType::DISPLAY },
{ "GPS", DHType::GPS },
{ "BUTTON", DHType::BUTTON },
{ "HFP", DHType::HFP },
{ "A2D", DHType::A2D },
{ "VIRMODEM_MIC", DHType::VIRMODEM_MIC },
{ "VIRMODEM_SPEAKER", DHType::VIRMODEM_SPEAKER },
};
int32_t ComponentLoader::Init()
{
return ParseConfig();
}
std::vector<DHType> ComponentLoader::GetAllCompTypes()
{
std::vector<DHType> DHTypeALL;
for (std::map<DHType, CompHandler>::iterator it = compHandlerMap_.begin(); it != compHandlerMap_.end(); it++) {
DHTypeALL.push_back(it->first);
}
return DHTypeALL;
}
void from_json(const nlohmann::json &j, CompConfig &cCfg)
{
cCfg.name = j.value("name", DEFAULT_NAME);
cCfg.type = g_mapDhTypeName[j.value("type", DEFAULT_TYPE)];
cCfg.compHandlerLoc = j.value("comp_handler_loc", DEFAULT_HANDLER_LOC);
cCfg.compHandlerVersion = j.value("comp_handler_version", DEFAULT_VERSION);
cCfg.compSourceLoc = j.value("comp_source_loc", DEFAULT_SOURCE_LOC);
cCfg.compSourceVersion = j.value("comp_source_version", DEFAULT_VERSION);
cCfg.compSinkLoc = j.value("comp_sink_loc", DEFAULT_SINK_LOC);
cCfg.compSinkVersion = j.value("comp_sink_version", DEFAULT_VERSION);
}
CompVersion ComponentLoader::GetCompVersionFromComConfig(const CompConfig& cCfg)
{
CompVersion compVersions;
compVersions.dhType = cCfg.type;
compVersions.name = cCfg.name;
compVersions.handlerVersion = cCfg.compHandlerVersion;
compVersions.sinkVersion = cCfg.compSinkVersion;
compVersions.sourceVersion = cCfg.compSourceVersion;
return compVersions;
}
int32_t ComponentLoader::GetCompPathAndVersion(const std::string &jsonStr, std::map<DHType, CompConfig> &dhtypeMap)
{
auto jsonCfg = json::parse(jsonStr);
if (jsonCfg.find(COMPONENTSLOAD_DISTRIBUTED_COMPONENTS) == jsonCfg.end()) {
DHLOGE("not find distributed_components");
return ERR_DH_FWK_PARA_INVALID;
}
std::vector<CompConfig> vecJsnCfg =
jsonCfg.at(COMPONENTSLOAD_DISTRIBUTED_COMPONENTS).get<std::vector<CompConfig>>();
DHLOGI("get distributed_components CompConfig size is %d", vecJsnCfg.size());
for (std::vector<CompConfig>::iterator iter = vecJsnCfg.begin(); iter != vecJsnCfg.end(); iter++) {
dhtypeMap.insert(std::pair<DHType, CompConfig>((*iter).type, (*iter)));
localDHVersion_.compVersions.insert(
std::pair<DHType, CompVersion>((*iter).type, GetCompVersionFromComConfig(*iter)));
}
isLocalVersionInit_.store(true);
return DH_FWK_SUCCESS;
}
int32_t ComponentLoader::GetLocalDHVersion(DHVersion &dhVersion)
{
if (!isLocalVersionInit_.load()) {
DHLOGE("get local DHVersion fail");
return ERR_DH_FWK_LOADER_GET_LOCAL_VERSION_FAIL;
}
dhVersion = localDHVersion_;
return DH_FWK_SUCCESS;
}
void *ComponentLoader::GetHandler(const std::string &soName)
{
if (soName.length() <= 0) {
DHLOGE("%s soName length is 0");
return nullptr;
}
char path[PATH_MAX + 1] = {0x00};
if (soName.length() == 0 || soName.length() > PATH_MAX || realpath(soName.c_str(), path) == NULL) {
DHLOGE("File canonicalization failed");
return nullptr;
}
void *pHandler = dlopen(path, RTLD_LAZY);
if (pHandler == nullptr) {
DHLOGE("%s handler load failed.", path);
return nullptr;
}
return pHandler;
}
void ComponentLoader::GetAllHandler(std::map<DHType, CompConfig> &dhtypeMap)
{
std::map<DHType, CompConfig>::iterator itor;
for (itor = dhtypeMap.begin(); itor != dhtypeMap.end(); itor++) {
CompHandler comHandler;
comHandler.hardwareHandler = GetHandler(itor->second.compHandlerLoc);
comHandler.sinkHandler = GetHandler(itor->second.compSinkLoc);
comHandler.sourceHandler = GetHandler(itor->second.compSourceLoc);
compHandlerMap_.insert(std::pair<DHType, CompHandler>(itor->second.type, comHandler));
}
}
int32_t ComponentLoader::GetHardwareHandler(const DHType dhType, IHardwareHandler *&hardwareHandlerPtr)
{
if (compHandlerMap_[dhType].hardwareHandler == nullptr) {
DHLOGE("hardwareHandler is null.");
return ERR_DH_FWK_LOADER_HANDLER_IS_NULL;
}
GetHardwareClass getHardwareClassHandler = (GetHardwareClass)dlsym(compHandlerMap_[dhType].hardwareHandler,
COMPONENT_LOADER_GET_HARDWARE_HANDLER.c_str());
if (getHardwareClassHandler == nullptr) {
DHLOGE("get getHardwareClassHandler is null.");
dlclose(compHandlerMap_[dhType].hardwareHandler);
compHandlerMap_[dhType].hardwareHandler = nullptr;
return ERR_DH_FWK_LOADER_HANDLER_IS_NULL;
}
hardwareHandlerPtr = getHardwareClassHandler();
return DH_FWK_SUCCESS;
}
int32_t ComponentLoader::GetSource(const DHType dhType, IDistributedHardwareSource *&sourcePtr)
{
if (compHandlerMap_[dhType].sourceHandler == nullptr) {
DHLOGE("sourceHandler is null.");
return ERR_DH_FWK_LOADER_HANDLER_IS_NULL;
}
GetSourceHardwareClass getSourceHardClassHandler = (GetSourceHardwareClass)dlsym(
compHandlerMap_[dhType].sourceHandler, COMPONENT_LOADER_GET_SOURCE_HANDLER.c_str());
if (getSourceHardClassHandler == nullptr) {
DHLOGE("get getSourceHardClassHandler is null.");
dlclose(compHandlerMap_[dhType].sourceHandler);
compHandlerMap_[dhType].sourceHandler = nullptr;
return ERR_DH_FWK_LOADER_HANDLER_IS_NULL;
}
sourcePtr = getSourceHardClassHandler();
return DH_FWK_SUCCESS;
}
int32_t ComponentLoader::GetSink(const DHType dhType, IDistributedHardwareSink *&sinkPtr)
{
if (compHandlerMap_[dhType].sinkHandler == nullptr) {
DHLOGE("sinkHandler is null.");
return ERR_DH_FWK_LOADER_HANDLER_IS_NULL;
}
GetSinkHardwareClass getSinkHardwareClassHandler =
(GetSinkHardwareClass)dlsym(compHandlerMap_[dhType].sinkHandler, COMPONENT_LOADER_GET_SINK_HANDLER.c_str());
if (getSinkHardwareClassHandler == nullptr) {
DHLOGE("get getSinkHardwareClassHandler is null.");
dlclose(compHandlerMap_[dhType].sinkHandler);
compHandlerMap_[dhType].sinkHandler = nullptr;
return ERR_DH_FWK_LOADER_HANDLER_IS_NULL;
}
sinkPtr = getSinkHardwareClassHandler();
return DH_FWK_SUCCESS;
}
std::string ComponentLoader::Readfile(const std::string &filePath)
{
std::ifstream infile;
std::string sLine;
std::string sAll = "";
infile.open(filePath);
if (!infile.is_open()) {
DHLOGE("filePath: %s Readfile fail", filePath.c_str());
return sAll;
}
while (getline(infile, sLine)) {
sAll.append(sLine);
}
infile.close();
return sAll;
}
int32_t ComponentLoader::ParseConfig()
{
std::map<DHType, CompConfig> dhtypeMap;
int32_t ret;
DHLOGI("ParseConfig start");
std::string jsonStr = Readfile(COMPONENTSLOAD_PROFILE_PATH);
if (jsonStr.length() <= 0) {
DHLOGE("profile is empty return");
return ERR_DH_FWK_LOADER_COMPONENT_PROFILE_IS_EMPTY;
}
ret = GetCompPathAndVersion(jsonStr, dhtypeMap);
GetAllHandler(dhtypeMap);
return ret;
}
int32_t ComponentLoader::ReleaseHandler(void *&handler)
{
if (handler == nullptr) {
DHLOGE("handler is null.");
return ERR_DH_FWK_LOADER_HANDLER_IS_NULL;
}
if (dlclose(handler) != 0) {
DHLOGE("dlclose failed.");
return ERR_DH_FWK_LOADER_DLCLOSE_FAIL;
}
handler = nullptr;
return DH_FWK_SUCCESS;
}
int32_t ComponentLoader::UnInit()
{
DHLOGI("release all handler");
int32_t ret = DH_FWK_SUCCESS;
for (std::map<DHType, CompHandler>::iterator iter = compHandlerMap_.begin();
iter != compHandlerMap_.end(); iter++) {
ret += ReleaseHardwareHandler(iter->first);
ret += ReleaseSource(iter->first);
ret += ReleaseSink(iter->first);
}
compHandlerMap_.clear();
return ret;
}
int32_t ComponentLoader::ReleaseHardwareHandler(const DHType dhType)
{
if (!IsDHTypeExist(dhType)) {
return ERR_DH_FWK_TYPE_NOT_EXIST;
}
int32_t ret = ReleaseHandler(compHandlerMap_[dhType].hardwareHandler);
if (ret) {
DHLOGE("fail, dhType: %#X", dhType);
}
return ret;
}
int32_t ComponentLoader::ReleaseSource(const DHType dhType)
{
if (!IsDHTypeExist(dhType)) {
return ERR_DH_FWK_TYPE_NOT_EXIST;
}
int32_t ret = ReleaseHandler(compHandlerMap_[dhType].sourceHandler);
if (ret) {
DHLOGE("fail, dhType: %#X", dhType);
}
return ret;
}
int32_t ComponentLoader::ReleaseSink(const DHType dhType)
{
if (!IsDHTypeExist(dhType)) {
return ERR_DH_FWK_TYPE_NOT_EXIST;
}
int32_t ret = ReleaseHandler(compHandlerMap_[dhType].sinkHandler);
if (ret) {
DHLOGE("fail, dhType: %#X", dhType);
}
return ret;
}
bool ComponentLoader::IsDHTypeExist(DHType dhType)
{
if (compHandlerMap_.find(dhType) == compHandlerMap_.end()) {
DHLOGE("fail, dhType: %#X not exist", dhType);
return false;
}
return true;
}
}
}

View File

@ -0,0 +1,78 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "component_disable.h"
#include <limits>
#include "anonymous_string.h"
#include "constants.h"
#include "distributed_hardware_errno.h"
#include "distributed_hardware_log.h"
namespace OHOS {
namespace DistributedHardware {
#undef DH_LOG_TAG
#define DH_LOG_TAG "ComponentDisable"
ComponentDisable::ComponentDisable() : status_(std::numeric_limits<int32_t>::max()) {}
ComponentDisable::~ComponentDisable() {}
int32_t ComponentDisable::Disable(const std::string &networkId, const std::string &dhId,
IDistributedHardwareSource *handler)
{
DHLOGD("networkId = %s dhId = %s.", GetAnonyString(networkId).c_str(), dhId.c_str());
if (handler == nullptr) {
DHLOGE("handler is null, networkId = %s dhId = %s.", GetAnonyString(networkId).c_str(), dhId.c_str());
return ERR_DH_FWK_PARA_INVALID;
}
auto ret = handler->UnregisterDistributedHardware(networkId, dhId, shared_from_this());
if (ret != DH_FWK_SUCCESS) {
DHLOGE("UnregisterDistributedHardware failed, networkId = %s dhId = %s.", GetAnonyString(networkId).c_str(),
dhId.c_str());
return ERR_DH_FWK_COMPONENT_UNREGISTER_FAILED;
}
// wait for callback until timeout
std::unique_lock<std::mutex> lock(mutex_);
auto waitStatus = conVar_.wait_for(lock, std::chrono::milliseconds(DISABLE_TIMEOUT_MS),
[this]() { return status_ != std::numeric_limits<int32_t>::max(); });
if (!waitStatus) {
DHLOGE("disable timeout, networkId = %s dhId = %s.", GetAnonyString(networkId).c_str(), dhId.c_str());
return ERR_DH_FWK_COMPONENT_DISABLE_TIMEOUT;
}
return (status_ == DH_FWK_SUCCESS) ? DH_FWK_SUCCESS : ERR_DH_FWK_COMPONENT_DISABLE_FAILED;
}
int32_t ComponentDisable::OnUnregisterResult(const std::string &networkId, const std::string &dhId, int32_t status,
const std::string &data)
{
if (status == DH_FWK_SUCCESS) {
DHLOGI("disable success, networkId = %s, dhId = %s, data = %s.", GetAnonyString(networkId).c_str(),
dhId.c_str(), data.c_str());
} else {
DHLOGE("disable failed, networkId = %s, dhId = %s, status = %d, data = %s.", GetAnonyString(networkId).c_str(),
dhId.c_str(), status, data.c_str());
}
std::unique_lock<std::mutex> lock(mutex_);
status_ = status;
conVar_.notify_all();
return status_;
}
}
}

View File

@ -0,0 +1,78 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "component_enable.h"
#include <limits>
#include "anonymous_string.h"
#include "constants.h"
#include "distributed_hardware_errno.h"
#include "distributed_hardware_log.h"
namespace OHOS {
namespace DistributedHardware {
#undef DH_LOG_TAG
#define DH_LOG_TAG "ComponentEnable"
ComponentEnable::ComponentEnable() : status_(std::numeric_limits<int32_t>::max()) {}
ComponentEnable::~ComponentEnable() {}
int32_t ComponentEnable::Enable(const std::string &networkId, const std::string &dhId, const EnableParam &param,
IDistributedHardwareSource *handler)
{
DHLOGD("networkId = %s dhId = %s.", GetAnonyString(networkId).c_str(), dhId.c_str());
if (handler == nullptr) {
DHLOGE("handler is null, networkId = %s dhId = %s.", GetAnonyString(networkId).c_str(), dhId.c_str());
return ERR_DH_FWK_PARA_INVALID;
}
auto ret = handler->RegisterDistributedHardware(networkId, dhId, param, shared_from_this());
if (ret != DH_FWK_SUCCESS) {
DHLOGE("RegisterDistributedHardware failed, networkId = %s dhId = %s.", GetAnonyString(networkId).c_str(),
dhId.c_str());
return ERR_DH_FWK_COMPONENT_REGISTER_FAILED;
}
// wait for callback until timeout
std::unique_lock<std::mutex> lock(mutex_);
auto waitStatus = conVar_.wait_for(lock, std::chrono::milliseconds(ENABLE_TIMEOUT_MS),
[this]() { return status_ != std::numeric_limits<int32_t>::max(); });
if (!waitStatus) {
DHLOGE("enable timeout, networkId = %s dhId = %s", GetAnonyString(networkId).c_str(), dhId.c_str());
return ERR_DH_FWK_COMPONENT_ENABLE_TIMEOUT;
}
return (status_ == DH_FWK_SUCCESS) ? DH_FWK_SUCCESS : ERR_DH_FWK_COMPONENT_ENABLE_FAILED;
}
int32_t ComponentEnable::OnRegisterResult(const std::string &networkId, const std::string &dhId, int32_t status,
const std::string &data)
{
if (status == DH_FWK_SUCCESS) {
DHLOGI("enable success, networkId = %s, dhId = %s, data = %s.", GetAnonyString(networkId).c_str(),
dhId.c_str(), data.c_str());
} else {
DHLOGE("enable failed, networkId = %s, dhId = %s, status = %d, data = %s.", GetAnonyString(networkId).c_str(),
dhId.c_str(), status, data.c_str());
}
std::unique_lock<std::mutex> lock(mutex_);
status_ = status;
conVar_.notify_all();
return status_;
}
}
}

View File

@ -0,0 +1,350 @@
/*
* 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 "component_manager.h"
#include <future>
#include <string>
#include "anonymous_string.h"
#include "capability_info_manager.h"
#include "component_disable.h"
#include "component_enable.h"
#include "component_loader.h"
#include "constants.h"
#include "dh_context.h"
#include "distributed_hardware_errno.h"
#include "distributed_hardware_log.h"
#include "ipc_object_stub.h"
#include "iservice_registry.h"
#include "system_ability_definition.h"
#include "version_manager.h"
namespace OHOS {
namespace DistributedHardware {
#undef DH_LOG_TAG
#define DH_LOG_TAG "ComponentManager"
IMPLEMENT_SINGLE_INSTANCE(ComponentManager);
ComponentManager::~ComponentManager()
{
DHLOGD("start.");
}
int32_t ComponentManager::Init()
{
DHLOGI("start.");
if (!InitCompSource()) {
DHLOGE("InitCompSource failed.");
return ERR_DH_FWK_COMPONENT_INIT_SOURCE_FAILED;
}
if (!InitCompSink()) {
DHLOGE("InitCompSink failed.");
compSource_.clear();
return ERR_DH_FWK_COMPONENT_INIT_SINK_FAILED;
}
auto sourceResult = StartSource();
auto sinkResult = StartSink();
if (!WaitForResult(Action::START_SOURCE, sourceResult)) {
DHLOGE("StartSource failed, some virtual components maybe cannot work, but want to continue");
}
if (!WaitForResult(Action::START_SINK, sinkResult)) {
DHLOGE("StartSink failed, some virtual components maybe cannot work, but want to continue");
}
DHLOGI("Init component success");
return DH_FWK_SUCCESS;
}
int32_t ComponentManager::UnInit()
{
DHLOGI("start.");
auto sourceResult = StopSource();
auto sinkResult = StopSink();
if (!WaitForResult(Action::STOP_SOURCE, sourceResult)) {
DHLOGE("StopSource failed, but want to continue");
}
if (!WaitForResult(Action::STOP_SINK, sinkResult)) {
DHLOGE("StopSource failed, but want to continue");
}
compSource_.clear();
compSink_.clear();
{
std::lock_guard<std::mutex> lock(sinkVersionMutex_);
sinkVersions_.clear();
}
DHLOGI("Release component success");
return DH_FWK_SUCCESS;
}
ComponentManager::ActionResult ComponentManager::StartSource()
{
DHLOGI("start.");
std::unordered_map<DHType, std::shared_future<int32_t>> futures;
std::string devId = DHContext::GetInstance().GetDeviceInfo().deviceId;
for (const auto &item : compSource_) {
CompVersion compversion;
VersionManager::GetInstance().GetCompVersion(devId, item.first, compversion);
auto params = compversion.sourceVersion;
auto future = std::async(std::launch::async, [item, params]() { return item.second->InitSource(params); });
futures.emplace(item.first, future.share());
}
return futures;
}
ComponentManager::ActionResult ComponentManager::StartSink()
{
DHLOGI("start.");
std::unordered_map<DHType, std::shared_future<int32_t>> futures;
std::string devId = DHContext::GetInstance().GetDeviceInfo().deviceId;
for (const auto &item : compSink_) {
CompVersion compversion;
VersionManager::GetInstance().GetCompVersion(devId, item.first, compversion);
auto params = compversion.sinkVersion;
auto future = std::async(std::launch::async, [item, params]() { return item.second->InitSink(params); });
futures.emplace(item.first, future.share());
}
return futures;
}
ComponentManager::ActionResult ComponentManager::StopSource()
{
DHLOGI("start.");
std::unordered_map<DHType, std::shared_future<int32_t>> futures;
for (const auto &item : compSource_) {
auto future = std::async(std::launch::async, [item]() { return item.second->ReleaseSource(); });
futures.emplace(item.first, future.share());
}
return futures;
}
ComponentManager::ActionResult ComponentManager::StopSink()
{
DHLOGI("start.");
std::unordered_map<DHType, std::shared_future<int32_t>> futures;
for (const auto &item : compSink_) {
auto future = std::async(std::launch::async, [item]() { return item.second->ReleaseSink(); });
futures.emplace(item.first, future.share());
}
return futures;
}
bool ComponentManager::WaitForResult(const Action &action, ActionResult actionsResult)
{
DHLOGD("start.");
auto ret = true;
for (auto &iter : actionsResult) {
auto result = iter.second.get();
DHLOGI("action = %d, compType = %#X, ret = %d.", static_cast<int32_t>(action), iter.first, result);
if (result != DH_FWK_SUCCESS) {
ret = false;
DHLOGE("there is error, but want to continue.");
}
}
DHLOGD("end.");
return ret;
}
bool ComponentManager::InitCompSource()
{
auto compTypes = ComponentLoader::GetInstance().GetAllCompTypes();
for (const auto &type : compTypes) {
IDistributedHardwareSource *sourcePtr = nullptr;
auto ret = ComponentLoader::GetInstance().GetSource(type, sourcePtr);
if (ret != DH_FWK_SUCCESS) {
DHLOGW("GetSource failed, compType = %#X, ret = %d.", type, ret);
continue;
}
if (sourcePtr == nullptr) {
DHLOGW("sourcePtr is null, compType = %#X.", type);
continue;
}
compSource_.insert(std::make_pair(type, sourcePtr));
}
return !compSource_.empty();
}
bool ComponentManager::InitCompSink()
{
auto compTypes = ComponentLoader::GetInstance().GetAllCompTypes();
for (const auto &type : compTypes) {
IDistributedHardwareSink *sinkPtr = nullptr;
auto ret = ComponentLoader::GetInstance().GetSink(type, sinkPtr);
if (ret != DH_FWK_SUCCESS) {
DHLOGW("GetSink failed, compType = %#X, ret = %d.", type, ret);
continue;
}
if (sinkPtr == nullptr) {
DHLOGW("sinkPtr is null, compType = %#X.", type);
continue;
}
compSink_.insert(std::make_pair(type, sinkPtr));
}
return !compSink_.empty();
}
int32_t ComponentManager::Enable(const std::string &networkId, const std::string &devId, const std::string &dhId)
{
DHLOGI("start.");
auto dhType = GetDHType(devId, dhId);
auto find = compSource_.find(dhType);
if (find == compSource_.end()) {
DHLOGE("can not find handler for dhId = %s.", dhId.c_str());
return ERR_DH_FWK_PARA_INVALID;
}
EnableParam param;
auto ret = GetEnableParam(networkId, devId, dhId, dhType, param);
if (ret != DH_FWK_SUCCESS) {
DHLOGE("GetEnableParam failed, devId = %s, dhId = %s, errCode = %d", GetAnonyString(devId).c_str(),
dhId.c_str(), ret);
return ret;
}
auto compEnable = std::make_shared<ComponentEnable>();
auto result = compEnable->Enable(networkId, dhId, param, find->second);
DHLOGI("enable result is %d, devId = %s, dhId = %s", result, GetAnonyString(devId).c_str(), dhId.c_str());
return result;
}
int32_t ComponentManager::Disable(const std::string &networkId, const std::string &devId, const std::string &dhId)
{
auto dhType = GetDHType(devId, dhId);
auto find = compSource_.find(dhType);
if (find == compSource_.end()) {
DHLOGE("can not find handler for dhId = %s.", dhId.c_str());
return ERR_DH_FWK_PARA_INVALID;
}
auto compDisable = std::make_shared<ComponentDisable>();
auto result = compDisable->Disable(networkId, dhId, find->second);
DHLOGI("disable result is %d, devId = %s, dhId = %s", result, GetAnonyString(devId).c_str(), dhId.c_str());
return result;
}
DHType ComponentManager::GetDHType(const std::string &devId, const std::string &dhId) const
{
std::shared_ptr<CapabilityInfo> capability = nullptr;
auto ret = CapabilityInfoManager::GetInstance()->GetCapability(devId, dhId, capability);
if ((ret == DH_FWK_SUCCESS) && (capability != nullptr)) {
return capability->GetDHType();
}
DHLOGE("get dhType failed, devId = %s, dhId = %s", GetAnonyString(devId).c_str(), dhId.c_str());
return DHType::UNKNOWN;
}
int32_t ComponentManager::GetEnableParam(const std::string &networkId, const std::string &devId,
const std::string &dhId, DHType dhType, EnableParam &param)
{
std::shared_ptr<CapabilityInfo> capability = nullptr;
auto ret = CapabilityInfoManager::GetInstance()->GetCapability(devId, dhId, capability);
if ((ret != DH_FWK_SUCCESS) || (capability == nullptr)) {
DHLOGE("GetCapability failed, devId =%s, dhId = %s, errCode = %d", GetAnonyString(devId).c_str(), dhId.c_str(),
ret);
return ret;
}
param.attrs = capability->GetDHAttrs();
param.version = GetSinkVersion(networkId, devId, dhType);
DHLOGI("success. devId =%s, dhId = %s, version = %s", GetAnonyString(devId).c_str(), dhId.c_str(),
param.version.c_str());
return DH_FWK_SUCCESS;
}
std::string ComponentManager::GetSinkVersion(const std::string &networkId, const std::string &devId, DHType dhType)
{
DHLOGI("networkId = %s ", networkId.c_str());
auto sinkVersion = GetVersionFromCache(devId, dhType);
if (!sinkVersion.empty()) {
DHLOGI("GetVersionFromCache success, sinkVersion = %s, devId = %s, dhType = %#X", sinkVersion.c_str(),
GetAnonyString(devId).c_str(), dhType);
return sinkVersion;
}
auto updateResult = UpdateVersionCache(networkId, devId);
if (updateResult != DH_FWK_SUCCESS) {
DHLOGE("UpdateVersionCache failed, devId = %s, errCode = %d", GetAnonyString(devId).c_str(), updateResult);
return "";
}
sinkVersion = GetVersionFromCache(devId, dhType);
return sinkVersion;
}
std::string ComponentManager::GetVersionFromCache(const std::string &devId, DHType dhType)
{
std::lock_guard<std::mutex> lock(sinkVersionMutex_);
auto iter = sinkVersions_.find(devId);
if (iter == sinkVersions_.end()) {
DHLOGE("can not find component version for devId = %s", GetAnonyString(devId).c_str());
return "";
}
auto find = iter->second.find(dhType);
if (find == iter->second.end()) {
DHLOGE("can not find component version for devId = %s, dhType = %#X", devId.c_str(), dhType);
return "";
}
return find->second;
}
int32_t ComponentManager::UpdateVersionCache(const std::string &networkId, const std::string &devId)
{
sptr<IDistributedHardware> dhms = GetRemoteDHMS(networkId);
if (dhms == nullptr) {
DHLOGI("GetRemoteDHMS failed, networkId = %s", GetAnonyString(networkId).c_str());
return DH_FWK_COMPONENT_GET_REMOTE_SA_FAILED;
}
std::unordered_map<DHType, std::string> versions;
auto ret = dhms->QuerySinkVersion(versions);
if (ret != DH_FWK_SUCCESS) {
DHLOGE("QuerySinkVersion failed, errCode = %d", ret);
return ret;
}
{
std::lock_guard<std::mutex> lock(sinkVersionMutex_);
sinkVersions_.emplace(devId, versions);
}
DHLOGI("QuerySinkVersion success");
return DH_FWK_SUCCESS;
}
sptr<IDistributedHardware> ComponentManager::GetRemoteDHMS(const std::string &networkId) const
{
DHLOGI("start, networkId = %s", GetAnonyString(networkId).c_str());
if (networkId.empty()) {
DHLOGE("networkId is empty");
return nullptr;
}
auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (samgr == nullptr) {
DHLOGE("GetSystemAbilityManager failed");
return nullptr;
}
auto object = samgr->CheckSystemAbility(DISTRIBUTED_HARDWARE_SA_ID, networkId);
if (object == nullptr) {
DHLOGE("CheckSystemAbility failed");
return nullptr;
}
return iface_cast<IDistributedHardware>(object);
}
}
}

View File

@ -0,0 +1,164 @@
/*
* 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 "distributed_hardware_manager.h"
#include "anonymous_string.h"
#include "capability_info_manager.h"
#include "component_loader.h"
#include "component_manager.h"
#include "dh_context.h"
#include "dh_utils_tool.h"
#include "distributed_hardware_errno.h"
#include "distributed_hardware_log.h"
#include "local_hardware_manager.h"
#include "task_board.h"
#include "task_executor.h"
#include "task_factory.h"
#include "version_manager.h"
namespace OHOS {
namespace DistributedHardware {
#undef DH_LOG_TAG
#define DH_LOG_TAG "DistributedHardwareManager"
#ifdef __cplusplus
#define EXTERNC extern "C"
#else
#define EXTERNC
#endif
EXTERNC __attribute__((visibility("default"))) IDistributedHardwareManager *GetDistributedHardwareManagerInstance()
{
return &DistributedHardwareManager::GetInstance();
}
IMPLEMENT_SINGLE_INSTANCE(DistributedHardwareManager);
int32_t DistributedHardwareManager::Initialize()
{
DHLOGI("start");
CapabilityInfoManager::GetInstance()->Init();
ComponentLoader::GetInstance().Init();
LocalHardwareManager::GetInstance().Init();
VersionManager::GetInstance().Init();
ComponentManager::GetInstance().Init();
return DH_FWK_SUCCESS;
}
int32_t DistributedHardwareManager::Release()
{
DHLOGI("start");
TaskBoard::GetInstance().WaitForALLTaskFinish();
ComponentManager::GetInstance().UnInit();
VersionManager::GetInstance().UnInit();
LocalHardwareManager::GetInstance().UnInit();
ComponentLoader::GetInstance().UnInit();
CapabilityInfoManager::GetInstance()->UnInit();
return DH_FWK_SUCCESS;
}
int32_t DistributedHardwareManager::SendOnLineEvent(const std::string &networkId, const std::string &deviceId,
uint16_t deviceType)
{
(void)deviceType;
if (networkId.empty()) {
DHLOGE("networkId is empty");
return ERR_DH_FWK_REMOTE_NETWORK_ID_IS_EMPTY;
}
if (deviceId.empty()) {
DHLOGE("deviceId is empty, networkId = %s", GetAnonyString(networkId).c_str());
return ERR_DH_FWK_REMOTE_DEVICE_ID_IS_EMPTY;
}
DHLOGI("networkId = %s, deviceId = %s", GetAnonyString(networkId).c_str(), GetAnonyString(deviceId).c_str());
if (DHContext::GetInstance().IsDeviceOnline(deviceId)) {
DHLOGW("device is already online, deviceId = %s", GetAnonyString(deviceId).c_str());
return ERR_DH_FWK_HARDWARE_MANAGER_DEVICE_REPEAT_ONLINE;
}
auto task = TaskFactory::GetInstance().CreateTask(TaskType::ON_LINE, networkId, deviceId, "", nullptr);
TaskExecutor::GetInstance().PushTask(task);
DHContext::GetInstance().AddOnlineDevice(deviceId, networkId);
CapabilityInfoManager::GetInstance()->CreateManualSyncCount(deviceId);
return DH_FWK_SUCCESS;
}
int32_t DistributedHardwareManager::SendOffLineEvent(const std::string &networkId, const std::string &deviceId,
uint16_t deviceType)
{
(void)deviceType;
if (networkId.empty()) {
DHLOGE("networkId is empty");
return ERR_DH_FWK_REMOTE_NETWORK_ID_IS_EMPTY;
}
if (deviceId.empty()) {
DHLOGE("deviceId is empty, networkId = %s", GetAnonyString(networkId).c_str());
return ERR_DH_FWK_REMOTE_DEVICE_ID_IS_EMPTY;
}
DHLOGI("networkId = %s, deviceId = %s", GetAnonyString(networkId).c_str(), GetAnonyString(deviceId).c_str());
if (!DHContext::GetInstance().IsDeviceOnline(deviceId)) {
DHLOGW("device is already offline, deviceId = %s", GetAnonyString(deviceId).c_str());
return ERR_DH_FWK_HARDWARE_MANAGER_DEVICE_REPEAT_OFFLINE;
}
auto task = TaskFactory::GetInstance().CreateTask(TaskType::OFF_LINE, networkId, deviceId, "", nullptr);
TaskExecutor::GetInstance().PushTask(task);
DHContext::GetInstance().RemoveOnlineDevice(deviceId);
CapabilityInfoManager::GetInstance()->RemoveManualSyncCount(deviceId);
return DH_FWK_SUCCESS;
}
size_t DistributedHardwareManager::GetOnLineCount()
{
return DHContext::GetInstance().GetOnlineCount();
}
int32_t DistributedHardwareManager::GetComponentVersion(std::unordered_map<DHType, std::string> &versionMap)
{
DHLOGI("start");
DHVersion dhVersion;
int32_t ret = ComponentLoader::GetInstance().GetLocalDHVersion(dhVersion);
if (ret != DH_FWK_SUCCESS) {
DHLOGE("GetLocalDHVersion fail, errCode = %d", ret);
return ret;
}
for (auto iter = dhVersion.compVersions.cbegin(); iter != dhVersion.compVersions.cend(); ++iter) {
versionMap.emplace(iter->first, iter->second.sinkVersion);
}
return DH_FWK_SUCCESS;
}
}
}

View File

@ -0,0 +1,73 @@
/*
* Copyright (c) 2022 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 "distributed_hardware_proxy.h"
#include <unordered_set>
#include "anonymous_string.h"
#include "constants.h"
#include "distributed_hardware_errno.h"
#include "distributed_hardware_log.h"
#include "nlohmann/json.hpp"
#include "parcel.h"
namespace OHOS {
namespace DistributedHardware {
#undef DH_LOG_TAG
#define DH_LOG_TAG "DistributedHardwareProxy"
const std::unordered_set<DHType> DH_TYPE_SET {
DHType::UNKNOWN, DHType::CAMERA, DHType::MIC, DHType::SPEAKER, DHType::DISPLAY, DHType::GPS,
DHType::BUTTON, DHType::HFP, DHType::A2D, DHType::VIRMODEM_MIC, DHType::VIRMODEM_SPEAKER, DHType::MAX_DH,
};
int32_t DistributedHardwareProxy::QuerySinkVersion(std::unordered_map<DHType, std::string> &versionMap)
{
MessageParcel data;
MessageParcel reply;
MessageOption option;
int32_t error = Remote()->SendRequest(QUERY_SINK_VERSION, data, reply, option);
if (error != NO_ERROR) {
DHLOGE("SendRequest failed, errCode = %d", error);
return ERR_DH_FWK_SERVICE_IPC_SEND_REQUEST_FAIL;
}
auto sinkVersion = reply.ReadString();
if (sinkVersion.empty()) {
DHLOGE("sinkVersion is empty");
return ERR_DH_FWK_SERVICE_STRING_IS_EMPTY;
}
versionMap = FromJson(sinkVersion);
DHLOGI("success, sinkVersion = %s", sinkVersion.c_str());
return DH_FWK_SUCCESS;
}
void from_json(const nlohmann::json &jsonObj, std::unordered_map<DHType, std::string> &versionMap)
{
for (const auto &item : jsonObj.value(DH_COMPONENT_VERSIONS, nlohmann::json {})) {
DHType dhType = (DH_TYPE_SET.find(item.value(DH_COMPONENT_TYPE, DHType::UNKNOWN)) != DH_TYPE_SET.end()) ?
item.value(DH_COMPONENT_TYPE, DHType::UNKNOWN) :
DHType::UNKNOWN;
std::string sinkVersion = item.value(DH_COMPONENT_SINK_VER, DH_COMPONENT_DEFAULT_VERSION);
versionMap.emplace(std::pair<DHType, std::string>(dhType, sinkVersion));
}
}
std::unordered_map<DHType, std::string> DistributedHardwareProxy::FromJson(const std::string &json) const
{
return nlohmann::json::parse(json).get<std::unordered_map<DHType, std::string>>();
}
}
}

View File

@ -0,0 +1,100 @@
/*
* 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 "local_hardware_manager.h"
#include <unistd.h>
#include "capability_info_manager.h"
#include "component_loader.h"
#include "device_type.h"
#include "dh_context.h"
#include "distributed_hardware_errno.h"
namespace OHOS {
namespace DistributedHardware {
#undef DH_LOG_TAG
#define DH_LOG_TAG "LocalHardwareManager"
IMPLEMENT_SINGLE_INSTANCE(LocalHardwareManager)
LocalHardwareManager::LocalHardwareManager() {}
LocalHardwareManager::~LocalHardwareManager() {}
void LocalHardwareManager::Init()
{
std::vector<DHType> allCompTypes = ComponentLoader::GetInstance().GetAllCompTypes();
for (auto dhType : allCompTypes) {
IHardwareHandler *hardwareHandler = nullptr;
int32_t status = ComponentLoader::GetInstance().GetHardwareHandler(dhType, hardwareHandler);
if (status != DH_FWK_SUCCESS || hardwareHandler == nullptr) {
DHLOGE("GetHardwareHandler %#X failed", dhType);
continue;
}
if (hardwareHandler->Initialize() != DH_FWK_SUCCESS) {
DHLOGE("Initialize %#X failed", dhType);
continue;
}
QueryLocalHardware(dhType, hardwareHandler);
if (!hardwareHandler->IsSupportPlugin()) {
DHLOGI("hardwareHandler is not support hot swap plugin, release!");
ComponentLoader::GetInstance().ReleaseHardwareHandler(dhType);
hardwareHandler = nullptr;
} else {
compToolFuncsMap_[dhType] = hardwareHandler;
}
}
}
void LocalHardwareManager::UnInit()
{
DHLOGI("start");
compToolFuncsMap_.clear();
}
void LocalHardwareManager::QueryLocalHardware(const DHType dhType, IHardwareHandler *hardwareHandler)
{
std::vector<DHItem> dhItems;
int32_t retryTimes = QUERY_RETRY_MAX_TIMES;
while (retryTimes > 0) {
DHLOGI("Query hardwareHandler retry times left: %d, dhType: %#X", retryTimes, dhType);
dhItems = hardwareHandler->Query();
if (dhItems.empty()) {
DHLOGE("Query hardwareHandler and obtain empty, dhType: %#X", dhType);
usleep(QUERY_INTERVAL_TIME);
} else {
DHLOGI("Query hardwareHandler success, dhType: %#X!", dhType);
AddLocalCapabilityInfo(dhItems, dhType);
break;
}
retryTimes--;
}
}
void LocalHardwareManager::AddLocalCapabilityInfo(const std::vector<DHItem> &dhItems, const DHType dhType)
{
std::vector<std::shared_ptr<CapabilityInfo>> capabilityInfos;
std::string deviceId = DHContext::GetInstance().GetDeviceInfo().deviceId;
std::string devName = DHContext::GetInstance().GetDeviceInfo().deviceName;
uint16_t devType = DHContext::GetInstance().GetDeviceInfo().deviceType;
for (auto dhItem : dhItems) {
std::shared_ptr<CapabilityInfo> dhCapabilityInfo =
std::make_shared<CapabilityInfo>(dhItem.dhId, deviceId, devName, devType, dhType, dhItem.attrs);
capabilityInfos.push_back(dhCapabilityInfo);
}
CapabilityInfoManager::GetInstance()->AddCapability(capabilityInfos);
}
}
}

View File

@ -0,0 +1,155 @@
/*
* 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 "capability_info.h"
#include <string>
#include "nlohmann/json.hpp"
#include "anonymous_string.h"
#include "constants.h"
#include "distributed_hardware_errno.h"
namespace OHOS {
namespace DistributedHardware {
#undef DH_LOG_TAG
#define DH_LOG_TAG "CapabilityInfo"
std::string CapabilityInfo::GetDHId() const
{
return dhId_;
}
void CapabilityInfo::SetDHId(const std::string &dhId)
{
this->dhId_ = dhId;
}
std::string CapabilityInfo::GetDeviceId() const
{
return deviceId_;
}
void CapabilityInfo::SetDeviceId(const std::string &deviceId)
{
this->deviceId_ = deviceId;
}
std::string CapabilityInfo::GetDeviceName() const
{
return deviceName_;
}
void CapabilityInfo::SetDeviceName(const std::string &deviceName)
{
this->deviceName_ = deviceName;
}
uint16_t CapabilityInfo::GetDeviceType() const
{
return deviceType_;
}
void CapabilityInfo::SetDeviceType(uint16_t deviceType)
{
this->deviceType_ = deviceType;
}
DHType CapabilityInfo::GetDHType() const
{
return dhType_;
}
void CapabilityInfo::SetDHType(const DHType dhType)
{
this->dhType_ = dhType;
}
std::string CapabilityInfo::GetDHAttrs() const
{
return dhAttrs_;
}
void CapabilityInfo::SetDHAttrs(const std::string &dhAttrs)
{
this->dhAttrs_ = dhAttrs;
}
std::string CapabilityInfo::GetKey() const
{
std::string kvStoreKey;
kvStoreKey.append(deviceId_);
kvStoreKey.append(RESOURCE_SEPARATOR);
kvStoreKey.append(dhId_);
return kvStoreKey;
}
std::string CapabilityInfo::GetAnonymousKey() const
{
std::string kvStoreKey;
kvStoreKey.append(GetAnonyString(deviceId_));
kvStoreKey.append(RESOURCE_SEPARATOR);
kvStoreKey.append(GetAnonyString(dhId_));
return kvStoreKey;
}
int32_t CapabilityInfo::FromJsonString(const std::string &jsonStr)
{
nlohmann::json jsonObj = nlohmann::json::parse(jsonStr);
FromJson(jsonObj, *this);
return DH_FWK_SUCCESS;
}
std::string CapabilityInfo::ToJsonString()
{
nlohmann::json jsonObj;
ToJson(jsonObj, *this);
return jsonObj.dump();
}
void ToJson(nlohmann::json &jsonObject, const CapabilityInfo &capability)
{
jsonObject[DH_ID] = capability.GetDHId();
jsonObject[DEV_ID] = capability.GetDeviceId();
jsonObject[DEV_NAME] = capability.GetDeviceName();
jsonObject[DEV_TYPE] = capability.GetDeviceType();
jsonObject[DH_TYPE] = capability.GetDHType();
jsonObject[DH_ATTRS] = capability.GetDHAttrs();
}
void FromJson(const nlohmann::json &jsonObject, CapabilityInfo &capability)
{
if (jsonObject.find(DH_ID) != jsonObject.end()) {
capability.SetDHId(jsonObject.at(DH_ID).get<std::string>());
}
if (jsonObject.find(DEV_ID) != jsonObject.end()) {
capability.SetDeviceId(jsonObject.at(DEV_ID).get<std::string>());
}
if (jsonObject.find(DEV_NAME) != jsonObject.end()) {
capability.SetDeviceName(jsonObject.at(DEV_NAME).get<std::string>());
}
if (jsonObject.find(DEV_TYPE) != jsonObject.end()) {
capability.SetDeviceType(jsonObject.at(DEV_TYPE).get<uint16_t>());
}
if (jsonObject.find(DH_TYPE) != jsonObject.end()) {
capability.SetDHType(jsonObject.at(DH_TYPE).get<DHType>());
}
if (jsonObject.find(DH_ATTRS) != jsonObject.end()) {
capability.SetDHAttrs(jsonObject.at(DH_ATTRS).get<std::string>());
}
}
}
}

View File

@ -0,0 +1,528 @@
/*
* 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 "capability_info_manager.h"
#include <algorithm>
#include <cctype>
#include <iterator>
#include <memory>
#include "anonymous_string.h"
#include "capability_info_event.h"
#include "capability_utils.h"
#include "constants.h"
#include "dh_context.h"
#include "dh_utils_tool.h"
#include "distributed_hardware_errno.h"
#include "distributed_hardware_log.h"
#include "distributed_hardware_manager.h"
#include "event_bus.h"
#include "task_executor.h"
#include "task_factory.h"
using OHOS::DistributedKv::Entry;
namespace OHOS {
namespace DistributedHardware {
#undef DH_LOG_TAG
#define DH_LOG_TAG "CapabilityInfoManager"
CapabilityInfoManager::CapabilityInfoManager()
: manualSyncResult_(ERR_DH_FWK_RESOURCE_DB_MANUAL_SYNC_FAIL), dbAdapterPtr_(nullptr)
{}
CapabilityInfoManager::~CapabilityInfoManager()
{
DHLOGI("CapabilityInfoManager Destruction!");
}
std::shared_ptr<CapabilityInfoManager> CapabilityInfoManager::GetInstance()
{
static std::shared_ptr<CapabilityInfoManager> instance(new CapabilityInfoManager);
return instance;
}
int32_t CapabilityInfoManager::Init()
{
DHLOGI("CapabilityInfoManager instance init!");
std::lock_guard<std::mutex> lock(capInfoMgrMutex_);
dbAdapterPtr_ = std::make_shared<DBAdapter>(APP_ID, GLOBAL_CAPABILITY_ID, shared_from_this());
if (dbAdapterPtr_->Init() != DH_FWK_SUCCESS) {
DHLOGE("Init dbAdapterPtr_ failed");
return ERR_DH_FWK_RESOURCE_INIT_DB_FAILED;
}
CapabilityInfoEvent capabilityInfoEvent(*this);
DHContext::GetInstance().GetEventBus()->AddHandler<CapabilityInfoEvent>(capabilityInfoEvent.GetType(), *this);
DHLOGI("CapabilityInfoManager instance init success");
return DH_FWK_SUCCESS;
}
int32_t CapabilityInfoManager::UnInit()
{
DHLOGI("CapabilityInfoManager UnInit");
std::lock_guard<std::mutex> lock(capInfoMgrMutex_);
if (dbAdapterPtr_ == nullptr) {
DHLOGE("dbAdapterPtr_ is null");
return ERR_DH_FWK_RESOURCE_UNINIT_DB_FAILED;
}
dbAdapterPtr_->UnInit();
dbAdapterPtr_.reset();
return DH_FWK_SUCCESS;
}
int32_t CapabilityInfoManager::SyncDeviceInfoFromDB(const std::string &deviceId)
{
DHLOGI("Sync DeviceInfo from DB, deviceId: %s", GetAnonyString(deviceId).c_str());
std::lock_guard<std::mutex> lock(capInfoMgrMutex_);
if (dbAdapterPtr_ == nullptr) {
DHLOGE("dbAdapterPtr_ is null");
return ERR_DH_FWK_RESOURCE_DB_ADAPTER_POINTER_NULL;
}
std::vector<std::string> dataVector;
if (dbAdapterPtr_->GetDataByKeyPrefix(deviceId, dataVector) != DH_FWK_SUCCESS) {
DHLOGE("Query data from DB by deviceId failed, id: %s", GetAnonyString(deviceId).c_str());
return ERR_DH_FWK_RESOURCE_DB_ADAPTER_OPERATION_FAIL;
}
for (const auto &data : dataVector) {
std::shared_ptr<CapabilityInfo> capabilityInfo;
if (CapabilityUtils::GetCapabilityByValue(data, capabilityInfo) != DH_FWK_SUCCESS) {
DHLOGE("Get capability ptr by value failed");
continue;
}
globalCapInfoMap_[capabilityInfo->GetKey()] = capabilityInfo;
}
return DH_FWK_SUCCESS;
}
int32_t CapabilityInfoManager::SyncRemoteCapabilityInfos()
{
DHLOGI("Sync full remote device info from DB");
std::lock_guard<std::mutex> lock(capInfoMgrMutex_);
if (dbAdapterPtr_ == nullptr) {
DHLOGE("dbAdapterPtr_ is null");
return ERR_DH_FWK_RESOURCE_DB_ADAPTER_POINTER_NULL;
}
std::vector<std::string> dataVector;
if (dbAdapterPtr_->GetDataByKeyPrefix("", dataVector) != DH_FWK_SUCCESS) {
DHLOGE("Query all data from DB failed");
return ERR_DH_FWK_RESOURCE_DB_ADAPTER_OPERATION_FAIL;
}
for (const auto &data : dataVector) {
std::shared_ptr<CapabilityInfo> capabilityInfo;
if (CapabilityUtils::GetCapabilityByValue(data, capabilityInfo) != DH_FWK_SUCCESS) {
DHLOGE("Get capability ptr by value failed");
continue;
}
const std::string &deviceId = capabilityInfo->GetDeviceId();
const std::string &localDeviceId = DHContext::GetInstance().GetDeviceInfo().deviceId;
if (deviceId.compare(localDeviceId) == 0) {
DHLOGE("local device info not need sync from db");
continue;
}
if (!DHContext::GetInstance().IsDeviceOnline(deviceId)) {
DHLOGE("offline device, no need sync to memory, deviceId : %s ",
GetAnonyString(deviceId).c_str());
continue;
}
globalCapInfoMap_[capabilityInfo->GetKey()] = capabilityInfo;
}
return DH_FWK_SUCCESS;
}
int32_t CapabilityInfoManager::AddCapability(const std::vector<std::shared_ptr<CapabilityInfo>> &resInfos)
{
std::lock_guard<std::mutex> lock(capInfoMgrMutex_);
if (dbAdapterPtr_ == nullptr) {
DHLOGE("dbAdapterPtr_ is null");
return ERR_DH_FWK_RESOURCE_DB_ADAPTER_POINTER_NULL;
}
std::vector<std::string> keys;
std::vector<std::string> values;
for (auto &resInfo : resInfos) {
if (!resInfo) {
continue;
}
const std::string key = resInfo->GetKey();
DHLOGI("AddCapability, Key: %s", resInfo->GetAnonymousKey().c_str());
keys.push_back(key);
values.push_back(resInfo->ToJsonString());
globalCapInfoMap_[key] = resInfo;
}
if (dbAdapterPtr_->PutDataBatch(keys, values) != DH_FWK_SUCCESS) {
DHLOGE("Fail to storage batch to kv");
return ERR_DH_FWK_RESOURCE_DB_ADAPTER_OPERATION_FAIL;
}
return DH_FWK_SUCCESS;
}
int32_t CapabilityInfoManager::AddCapabilityInMem(const std::vector<std::shared_ptr<CapabilityInfo>> &resInfos)
{
std::lock_guard<std::mutex> lock(capInfoMgrMutex_);
for (auto &resInfo : resInfos) {
if (!resInfo) {
continue;
}
const std::string key = resInfo->GetKey();
DHLOGI("AddCapabilityInMem, Key: %s", resInfo->GetAnonymousKey().c_str());
globalCapInfoMap_[key] = resInfo;
}
return DH_FWK_SUCCESS;
}
int32_t CapabilityInfoManager::RemoveCapabilityInfoInDB(const std::string &deviceId)
{
DHLOGI("Remove capability device info, deviceId: %s", GetAnonyString(deviceId).c_str());
std::lock_guard<std::mutex> lock(capInfoMgrMutex_);
if (dbAdapterPtr_ == nullptr) {
DHLOGE("dbAdapterPtr_ is null");
return ERR_DH_FWK_RESOURCE_DB_ADAPTER_POINTER_NULL;
}
if (deviceId.empty()) {
DHLOGE("RemoveCapabilityInfoInDB failed, deviceId is empty");
return ERR_DH_FWK_PARA_INVALID;
}
// 1. Clear the cache in the memory.
for (auto iter = globalCapInfoMap_.begin(); iter != globalCapInfoMap_.end();) {
if (!CapabilityUtils::IsCapKeyMatchDeviceId(iter->first, deviceId)) {
iter++;
continue;
}
DHLOGI("Clear globalCapInfoMap_ iter: %s", GetAnonyString(iter->first).c_str());
globalCapInfoMap_.erase(iter++);
}
// 2. Delete the corresponding record from the database(use UUID).
if (dbAdapterPtr_->RemoveDeviceData(deviceId) != DH_FWK_SUCCESS) {
DHLOGE("Remove capability Device Data failed, deviceId: %s", GetAnonyString(deviceId).c_str());
return ERR_DH_FWK_RESOURCE_DB_ADAPTER_OPERATION_FAIL;
}
return DH_FWK_SUCCESS;
}
int32_t CapabilityInfoManager::RemoveCapabilityInfoByKey(const std::string &key)
{
DHLOGI("Remove capability device info, key: %s", GetAnonyString(key).c_str());
std::lock_guard<std::mutex> lock(capInfoMgrMutex_);
if (dbAdapterPtr_ == nullptr) {
DHLOGE("dbAdapterPtr_ is null");
return ERR_DH_FWK_RESOURCE_DB_ADAPTER_POINTER_NULL;
}
if (key.empty()) {
DHLOGE("key is empty");
return ERR_DH_FWK_RESOURCE_KEY_IS_EMPTY;
}
// 1. Clear the cache in the memory.
if (globalCapInfoMap_.find(key) != globalCapInfoMap_.end()) {
globalCapInfoMap_.erase(key);
}
// 2. Delete the corresponding record from the database.(use key)
if (dbAdapterPtr_->RemoveDataByKey(key) != DH_FWK_SUCCESS) {
DHLOGE("Remove capability Device Data failed, key: %s", GetAnonyString(key).c_str());
return ERR_DH_FWK_RESOURCE_DB_ADAPTER_OPERATION_FAIL;
}
return DH_FWK_SUCCESS;
}
int32_t CapabilityInfoManager::RemoveCapabilityInfoInMem(const std::string &deviceId)
{
DHLOGI("remove capability device info in memory, deviceId: %s", GetAnonyString(deviceId).c_str());
std::lock_guard<std::mutex> lock(capInfoMgrMutex_);
if (deviceId.empty()) {
DHLOGE("RemoveCapabilityInfoInMem failed, deviceId is empty");
return ERR_DH_FWK_PARA_INVALID;
}
for (auto iter = globalCapInfoMap_.begin(); iter != globalCapInfoMap_.end();) {
if (!CapabilityUtils::IsCapKeyMatchDeviceId(iter->first, deviceId)) {
iter++;
continue;
}
globalCapInfoMap_.erase(iter++);
}
return DH_FWK_SUCCESS;
}
std::map<std::string, std::shared_ptr<CapabilityInfo>> CapabilityInfoManager::QueryCapabilityByFilters(
const std::map<CapabilityInfoFilter, std::string> &filters)
{
std::lock_guard<std::mutex> lock(capInfoMgrMutex_);
std::map<std::string, std::shared_ptr<CapabilityInfo>> capMap;
bool isMatch = true;
for (auto &info : globalCapInfoMap_) {
isMatch = true;
for (auto &filter : filters) {
if (!IsCapabilityMatchFilter(info.second, filter.first, filter.second)) {
isMatch = false;
break;
}
}
if (isMatch) {
capMap.emplace(info.first, info.second);
}
}
return capMap;
}
void CapabilityInfoManager::CreateManualSyncCount(const std::string &deviceId)
{
std::lock_guard<std::mutex> lock(capInfoMgrMutex_);
if (dbAdapterPtr_ == nullptr) {
DHLOGE("dbAdapterPtr_ is null");
return;
}
dbAdapterPtr_->CreateManualSyncCount(deviceId);
}
void CapabilityInfoManager::RemoveManualSyncCount(const std::string &deviceId)
{
std::lock_guard<std::mutex> lock(capInfoMgrMutex_);
if (dbAdapterPtr_ == nullptr) {
DHLOGE("dbAdapterPtr_ is null");
return;
}
dbAdapterPtr_->RemoveManualSyncCount(deviceId);
}
int32_t CapabilityInfoManager::ManualSync(const std::string &networkId)
{
DHLOGI("ManualSync start, networkId: %s", GetAnonyString(networkId).c_str());
std::unique_lock<std::mutex> lock(capInfoMgrMutex_);
if (dbAdapterPtr_ == nullptr) {
DHLOGE("dbAdapterPtr_ is null");
return ERR_DH_FWK_RESOURCE_DB_ADAPTER_POINTER_NULL;
}
manualSyncResult_ = ERR_DH_FWK_RESOURCE_DB_MANUAL_SYNC_FAIL;
if (dbAdapterPtr_->ManualSync(networkId) != DH_FWK_SUCCESS) {
DHLOGE("ManualSync failed");
return ERR_DH_FWK_RESOURCE_DB_ADAPTER_OPERATION_FAIL;
}
manualSyncCondVar_.wait_for(lock, std::chrono::seconds(MANUAL_SYNC_TIMEOUT),
[this] { return this->manualSyncResult_ == DH_FWK_SUCCESS; });
return manualSyncResult_;
}
void CapabilityInfoManager::NotifySyncCompleted()
{
DHLOGI("CapabilityInfoManager SyncCompleted NotifySyncCompleted");
std::lock_guard<std::mutex> lock(capInfoMgrMutex_);
manualSyncResult_ = DH_FWK_SUCCESS;
manualSyncCondVar_.notify_one();
}
void CapabilityInfoManager::OnChange(const DistributedKv::ChangeNotification &changeNotification)
{
DHLOGI("CapabilityInfoManager: DB data OnChange");
if (!changeNotification.GetInsertEntries().empty()) {
DHLOGI("Handle capability data add change");
HandleCapabilityAddChange(changeNotification.GetInsertEntries());
}
if (!changeNotification.GetUpdateEntries().empty()) {
DHLOGI("Handle capability data update change");
HandleCapabilityUpdateChange(changeNotification.GetUpdateEntries());
}
if (!changeNotification.GetDeleteEntries().empty()) {
DHLOGI("Handle capability data delete change");
HandleCapabilityDeleteChange(changeNotification.GetDeleteEntries());
}
}
void CapabilityInfoManager::OnChange(const DistributedKv::ChangeNotification &changeNotification,
std::shared_ptr<DistributedKv::KvStoreSnapshot> snapshot)
{}
void CapabilityInfoManager::OnEvent(CapabilityInfoEvent &ev)
{
switch (ev.GetAction()) {
case CapabilityInfoEvent::EventType::RECOVER:
SyncRemoteCapabilityInfos();
break;
default:
DHLOGE("Event is undefined, type is %d", ev.GetAction());
break;
}
}
void CapabilityInfoManager::HandleCapabilityAddChange(const std::vector<Entry> &insertRecords)
{
std::lock_guard<std::mutex> lock(capInfoMgrMutex_);
for (const auto &item : insertRecords) {
const std::string value = item.value.ToString();
std::shared_ptr<CapabilityInfo> capPtr;
if (CapabilityUtils::GetCapabilityByValue(value, capPtr) != DH_FWK_SUCCESS) {
DHLOGE("Get capability by value failed");
continue;
}
const auto keyString = capPtr->GetKey();
DHLOGI("Add capability key: %s", capPtr->GetAnonymousKey().c_str());
globalCapInfoMap_[keyString] = capPtr;
std::string deviceId = capPtr->GetDeviceId();
std::string networkId = DHContext::GetInstance().GetNetworkIdByUUID(deviceId);
if (networkId.empty()) {
DHLOGI("Find network failed and never enable, deviceId: %s", GetAnonyString(deviceId).c_str());
continue;
}
auto task = TaskFactory::GetInstance().CreateTask(TaskType::ENABLE, networkId, deviceId,
capPtr->GetDHId(), nullptr);
TaskExecutor::GetInstance().PushTask(task);
}
}
void CapabilityInfoManager::HandleCapabilityUpdateChange(const std::vector<Entry> &updateRecords)
{
std::lock_guard<std::mutex> lock(capInfoMgrMutex_);
for (const auto &item : updateRecords) {
const std::string value = item.value.ToString();
std::shared_ptr<CapabilityInfo> capPtr;
if (CapabilityUtils::GetCapabilityByValue(value, capPtr) != DH_FWK_SUCCESS) {
DHLOGE("Get capability by value failed");
continue;
}
const auto keyString = capPtr->GetKey();
DHLOGI("Update capability key: %s", capPtr->GetAnonymousKey().c_str());
globalCapInfoMap_[keyString] = capPtr;
}
}
void CapabilityInfoManager::HandleCapabilityDeleteChange(const std::vector<Entry> &deleteRecords)
{
std::lock_guard<std::mutex> lock(capInfoMgrMutex_);
for (const auto &item : deleteRecords) {
const std::string value = item.value.ToString();
std::shared_ptr<CapabilityInfo> capPtr;
if (CapabilityUtils::GetCapabilityByValue(value, capPtr) != DH_FWK_SUCCESS) {
DHLOGE("Get capability by value failed");
continue;
}
const auto keyString = capPtr->GetKey();
DHLOGI("Delete capability key: %s", capPtr->GetAnonymousKey().c_str());
globalCapInfoMap_.erase(keyString);
}
}
bool CapabilityInfoManager::IsCapabilityMatchFilter(const std::shared_ptr<CapabilityInfo> &cap,
const CapabilityInfoFilter &filter, const std::string &value)
{
bool isMatch = false;
switch (filter) {
case CapabilityInfoFilter::FILTER_DH_ID: {
isMatch = cap->GetDHId().compare(value) == 0;
break;
}
case CapabilityInfoFilter::FILTER_DEVICE_ID: {
isMatch = cap->GetDeviceId().compare(value) == 0;
break;
}
case CapabilityInfoFilter::FILTER_DEVICE_NAME: {
isMatch = cap->GetDeviceName().compare(value) == 0;
break;
}
case CapabilityInfoFilter::FILTER_DEVICE_TYPE: {
auto devType = static_cast<uint16_t>(std::stoi(value));
isMatch = cap->GetDeviceType() == devType;
break;
}
case CapabilityInfoFilter::FILTER_DH_TYPE: {
DHType dhType = (DHType)std::stoi(value);
isMatch = cap->GetDHType() == dhType;
break;
}
case CapabilityInfoFilter::FILTER_DH_ATTRS: {
isMatch = cap->GetDHAttrs().compare(value) == 0;
break;
}
default: {
isMatch = false;
break;
}
}
return isMatch;
}
void CapabilityInfoManager::GetCapabilitiesByDeviceId(const std::string &deviceId,
std::vector<std::shared_ptr<CapabilityInfo>> &resInfos)
{
std::lock_guard<std::mutex> lock(capInfoMgrMutex_);
for (auto &capabilityInfo : globalCapInfoMap_) {
if (CapabilityUtils::IsCapKeyMatchDeviceId(capabilityInfo.first, deviceId)) {
resInfos.emplace_back(capabilityInfo.second);
}
}
}
bool CapabilityInfoManager::HasCapability(const std::string &deviceId, const std::string &dhId)
{
std::lock_guard<std::mutex> lock(capInfoMgrMutex_);
std::string kvKey = CapabilityUtils::GetCapabilityKey(deviceId, dhId);
if (globalCapInfoMap_.find(kvKey) == globalCapInfoMap_.end()) {
return false;
}
return true;
}
int32_t CapabilityInfoManager::GetCapability(const std::string &deviceId, const std::string &dhId,
std::shared_ptr<CapabilityInfo> &capPtr)
{
std::lock_guard<std::mutex> lock(capInfoMgrMutex_);
std::string key = CapabilityUtils::GetCapabilityKey(deviceId, dhId);
if (globalCapInfoMap_.find(key) == globalCapInfoMap_.end()) {
DHLOGE("Can not find capability In globalCapInfoMap_: %s", GetAnonyString(deviceId).c_str());
return ERR_DH_FWK_RESOURCE_CAPABILITY_MAP_NOT_FOUND;
}
capPtr = globalCapInfoMap_[key];
return DH_FWK_SUCCESS;
}
int32_t CapabilityInfoManager::GetDataByKey(const std::string &key, std::shared_ptr<CapabilityInfo> &capInfoPtr)
{
std::lock_guard<std::mutex> lock(capInfoMgrMutex_);
if (dbAdapterPtr_ == nullptr) {
DHLOGI("dbAdapterPtr_ is null");
return ERR_DH_FWK_RESOURCE_DB_ADAPTER_POINTER_NULL;
}
std::string data;
if (dbAdapterPtr_->GetDataByKey(key, data) != DH_FWK_SUCCESS) {
DHLOGE("Query capability info from db failed, key: %s", GetAnonyString(key).c_str());
return ERR_DH_FWK_RESOURCE_DB_ADAPTER_OPERATION_FAIL;
}
return CapabilityUtils::GetCapabilityByValue(data, capInfoPtr);
}
int32_t CapabilityInfoManager::GetDataByKeyPrefix(const std::string &keyPrefix, CapabilityInfoMap &capabilityMap)
{
std::lock_guard<std::mutex> lock(capInfoMgrMutex_);
if (dbAdapterPtr_ == nullptr) {
DHLOGI("dbAdapterPtr_ is null");
return ERR_DH_FWK_RESOURCE_DB_ADAPTER_POINTER_NULL;
}
std::vector<std::string> dataVector;
if (dbAdapterPtr_->GetDataByKeyPrefix(keyPrefix, dataVector) != DH_FWK_SUCCESS) {
DHLOGE("Query capability info from db failed, key: %s", GetAnonyString(keyPrefix).c_str());
return ERR_DH_FWK_RESOURCE_DB_ADAPTER_OPERATION_FAIL;
}
for (const auto &data : dataVector) {
std::shared_ptr<CapabilityInfo> capabilityInfo;
if (CapabilityUtils::GetCapabilityByValue(data, capabilityInfo) != DH_FWK_SUCCESS) {
DHLOGE("Get capability ptr by value failed");
continue;
}
if (capabilityInfo->FromJsonString(data) != DH_FWK_SUCCESS) {
DHLOGE("Wrong data: %s", GetAnonyString(data).c_str());
continue;
}
capabilityMap[capabilityInfo->GetKey()] = capabilityInfo;
}
return DH_FWK_SUCCESS;
}
}
}

View File

@ -0,0 +1,54 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "capability_utils.h"
#include <algorithm>
#include <map>
#include <memory>
#include "nlohmann/json.hpp"
#include "capability_info.h"
#include "constants.h"
#include "distributed_hardware_log.h"
namespace OHOS {
namespace DistributedHardware {
#undef DH_LOG_TAG
#define DH_LOG_TAG "CapabilityUtils"
int32_t CapabilityUtils::GetCapabilityByValue(const std::string &value, std::shared_ptr<CapabilityInfo> &capPtr)
{
capPtr = std::make_shared<CapabilityInfo>();
return capPtr->FromJsonString(value);
}
std::string CapabilityUtils::GetCapabilityKey(const std::string &deviceId, const std::string &dhId)
{
return deviceId + RESOURCE_SEPARATOR + dhId;
}
bool CapabilityUtils::IsCapKeyMatchDeviceId(const std::string &key, const std::string &deviceId)
{
std::size_t separatorPos = key.find(RESOURCE_SEPARATOR);
if (separatorPos == std::string::npos) {
return false;
}
std::string keyDevId = key.substr(0, separatorPos);
return keyDevId.compare(deviceId) == 0;
}
}
}

View File

@ -0,0 +1,413 @@
/*
* 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 "db_adapter.h"
#include <memory>
#include <unistd.h>
#include "anonymous_string.h"
#include "capability_info.h"
#include "capability_info_manager.h"
#include "capability_utils.h"
#include "constants.h"
#include "dh_context.h"
#include "distributed_hardware_errno.h"
#include "distributed_hardware_log.h"
#include "event_bus.h"
using OHOS::DistributedKv::Entry;
using OHOS::DistributedKv::Key;
using OHOS::DistributedKv::KvStoreDeathRecipient;
using OHOS::DistributedKv::KvStoreType;
using OHOS::DistributedKv::Options;
using OHOS::DistributedKv::SingleKvStore;
using OHOS::DistributedKv::Status;
using OHOS::DistributedKv::SubscribeType;
using OHOS::DistributedKv::Value;
namespace OHOS {
namespace DistributedHardware {
#undef DH_LOG_TAG
#define DH_LOG_TAG "DBAdapter"
DBAdapter::DBAdapter(const std::string &appId, const std::string &storeId,
const std::shared_ptr<DistributedKv::KvStoreObserver> &changeListener)
{
this->appId_.appId = appId;
this->storeId_.storeId = storeId;
this->dataChangeListener_ = changeListener;
DHLOGI("DBAdapter Constructor Success, appId: %s, storeId: %s", appId.c_str(), storeId.c_str());
}
DBAdapter::~DBAdapter()
{
DHLOGI("DBAdapter Destruction");
}
Status DBAdapter::GetKvStorePtr()
{
Options options = {
.createIfMissing = true,
.encrypt = false,
.autoSync = true,
.securityLevel = DistributedKv::SecurityLevel::S2,
.kvStoreType = KvStoreType::SINGLE_VERSION
};
return kvDataMgr_.GetSingleKvStore(options, appId_, storeId_, kvStoragePtr_);
}
int32_t DBAdapter::Init()
{
DHLOGI("Init DB, storeId: %s", storeId_.storeId.c_str());
std::lock_guard<std::mutex> lock(dbAdapterMutex_);
int32_t tryTimes = MAX_INIT_RETRY_TIMES;
while (tryTimes > 0) {
Status status = GetKvStorePtr();
if (status == Status::SUCCESS && kvStoragePtr_) {
DHLOGI("Init KvStorePtr Success");
RegisterManualSyncListener();
RegisterChangeListener();
RegisterKvStoreDeathListener();
return DH_FWK_SUCCESS;
}
DHLOGD("CheckKvStore, left times: %d", tryTimes);
usleep(INIT_RETRY_SLEEP_INTERVAL);
tryTimes--;
}
if (kvStoragePtr_ == nullptr) {
DHLOGE("Init KvStorePtr failed");
return ERR_DH_FWK_RESOURCE_KV_STORAGE_POINTER_NULL;
}
return DH_FWK_SUCCESS;
}
void DBAdapter::UnInit()
{
DHLOGI("DBAdapter UnInit");
std::lock_guard<std::mutex> lock(dbAdapterMutex_);
if (kvStoragePtr_ == nullptr) {
DHLOGE("kvStoragePtr_ is null");
return;
}
UnRegisterKvStoreDeathListener();
UnRegisterChangeListener();
UnRegisterManualSyncListener();
kvStoragePtr_.reset();
}
int32_t DBAdapter::ReInit()
{
DHLOGI("ReInit DB, storeId: %s", storeId_.storeId.c_str());
std::lock_guard<std::mutex> lock(dbAdapterMutex_);
if (kvStoragePtr_ == nullptr) {
DHLOGE("kvStoragePtr_ is null");
return ERR_DH_FWK_RESOURCE_KV_STORAGE_POINTER_NULL;
}
UnRegisterManualSyncListener();
kvStoragePtr_.reset();
Status status = GetKvStorePtr();
if (status != Status::SUCCESS || !kvStoragePtr_) {
DHLOGW("Get kvStoragePtr_ failed, status: %d", status);
return ERR_DH_FWK_RESOURCE_KV_STORAGE_OPERATION_FAIL;
}
RegisterManualSyncListener();
RegisterKvStoreDeathListener();
return DH_FWK_SUCCESS;
}
void DBAdapter::SyncCompleted(const std::map<std::string, DistributedKv::Status> &results)
{
DHLOGI("DBAdapter SyncCompleted start");
std::lock_guard<std::mutex> lock(dbAdapterMutex_);
for (const auto &result : results) {
std::string deviceId = result.first;
DHLOGI("SyncCompleted, deviceId: %s", GetAnonyString(deviceId).c_str());
if (manualSyncCountMap_.count(deviceId) == 0) {
DHLOGE("SyncCompleted, error, ManualSyncCount is removed");
return;
}
DHLOGI("ManualSyncCallback::SyncCompleted, retryCount: %d", manualSyncCountMap_[deviceId]);
if (result.second == DistributedKv::Status::SUCCESS) {
CapabilityInfoManager::GetInstance()->NotifySyncCompleted();
manualSyncCountMap_[deviceId] = 0;
} else {
manualSyncCountMap_[deviceId]++;
if (manualSyncCountMap_[deviceId] >= MANUAL_SYNC_TIMES) {
manualSyncCountMap_[deviceId] = 0;
} else {
auto retryTask = [this, deviceId] {
this->ManualSync(deviceId);
usleep(MANUAL_SYNC_INTERVAL);
};
DHContext::GetInstance().GetEventBus()->PostTask(retryTask, "retryTask", 0);
}
}
}
}
int32_t DBAdapter::GetDataByKey(const std::string &key, std::string &data)
{
DHLOGI("Get data by key: %s", GetAnonyString(key).c_str());
std::lock_guard<std::mutex> lock(dbAdapterMutex_);
if (kvStoragePtr_ == nullptr) {
DHLOGE("kvStoragePtr_ is null");
return ERR_DH_FWK_RESOURCE_KV_STORAGE_POINTER_NULL;
}
Key kvKey(key);
Value kvValue;
Status status = kvStoragePtr_->Get(kvKey, kvValue);
if (status != Status::SUCCESS) {
DHLOGE("Query from db failed, key: %s", GetAnonyString(key).c_str());
return ERR_DH_FWK_RESOURCE_KV_STORAGE_OPERATION_FAIL;
}
data = kvValue.ToString();
return DH_FWK_SUCCESS;
}
int32_t DBAdapter::GetDataByKeyPrefix(const std::string &keyPrefix, std::vector<std::string> &values)
{
DHLOGI("Get data by key prefix: %s", GetAnonyString(keyPrefix).c_str());
std::lock_guard<std::mutex> lock(dbAdapterMutex_);
if (kvStoragePtr_ == nullptr) {
DHLOGE("kvStoragePtr_ is null");
return ERR_DH_FWK_RESOURCE_KV_STORAGE_POINTER_NULL;
}
// if prefix is empty, get all entries.
Key allEntryKeyPrefix(keyPrefix);
std::vector<Entry> allEntries;
Status status = kvStoragePtr_->GetEntries(allEntryKeyPrefix, allEntries);
if (status != Status::SUCCESS) {
DHLOGE("Query data by keyPrefix failed, prefix: %s",
GetAnonyString(keyPrefix).c_str());
return ERR_DH_FWK_RESOURCE_KV_STORAGE_OPERATION_FAIL;
}
for (const auto& item : allEntries) {
values.push_back(item.value.ToString());
}
return DH_FWK_SUCCESS;
}
int32_t DBAdapter::PutData(const std::string &key, std::string &value)
{
std::lock_guard<std::mutex> lock(dbAdapterMutex_);
if (kvStoragePtr_ == nullptr) {
DHLOGE("kvStoragePtr_ is null");
return ERR_DH_FWK_RESOURCE_KV_STORAGE_POINTER_NULL;
}
Key kvKey(key);
Value kvValue(value);
Status status = kvStoragePtr_->Put(kvKey, kvValue);
if (status == Status::IPC_ERROR) {
DHLOGE("Put kv to db failed, ret: %d", status);
return ERR_DH_FWK_RESOURCE_KV_STORAGE_OPERATION_FAIL;
}
return DH_FWK_SUCCESS;
}
int32_t DBAdapter::PutDataBatch(const std::vector<std::string> &keys, const std::vector<std::string> &values)
{
std::lock_guard<std::mutex> lock(dbAdapterMutex_);
if (kvStoragePtr_ == nullptr) {
DHLOGE("kvStoragePtr_ is null");
return ERR_DH_FWK_RESOURCE_KV_STORAGE_POINTER_NULL;
}
if (keys.size() != values.size()) {
DHLOGE("Param invalid");
return ERR_DH_FWK_PARA_INVALID;
}
std::vector<Entry> entries;
for (unsigned long i = 0; i < keys.size(); i++) {
Entry entry;
entry.key = keys[i];
entry.value = values[i];
entries.push_back(entry);
}
Status status = kvStoragePtr_->PutBatch(entries);
if (status != Status::SUCCESS) {
DHLOGE("Put kv batch to db failed, ret: %d", status);
return ERR_DH_FWK_RESOURCE_KV_STORAGE_OPERATION_FAIL;
}
DHLOGI("Put kv batch to db success");
return DH_FWK_SUCCESS;
}
void DBAdapter::CreateManualSyncCount(const std::string &deviceId)
{
std::lock_guard<std::mutex> lock(dbAdapterMutex_);
manualSyncCountMap_[deviceId] = 0;
}
void DBAdapter::RemoveManualSyncCount(const std::string &deviceId)
{
std::lock_guard<std::mutex> lock(dbAdapterMutex_);
manualSyncCountMap_.erase(deviceId);
}
int32_t DBAdapter::ManualSync(const std::string &networkId)
{
DHLOGI("Manual sync between networkId: %s", GetAnonyString(networkId).c_str());
std::lock_guard<std::mutex> lock(dbAdapterMutex_);
if (kvStoragePtr_ == nullptr) {
DHLOGE("kvStoragePtr_ is null");
return ERR_DH_FWK_RESOURCE_KV_STORAGE_POINTER_NULL;
}
std::vector<std::string> devList = { networkId };
Status status = kvStoragePtr_->Sync(devList, DistributedKv::SyncMode::PULL);
if (status != Status::SUCCESS) {
DHLOGE("ManualSync Data failed, networkId: %s", GetAnonyString(networkId).c_str());
return ERR_DH_FWK_RESOURCE_KV_STORAGE_OPERATION_FAIL;
}
return DH_FWK_SUCCESS;
}
void DBAdapter::SyncDBForRecover()
{
DHLOGI("Sync store id: %s after db recover", storeId_.storeId.c_str());
CapabilityInfoEvent recoverEvent(*this, CapabilityInfoEvent::EventType::RECOVER);
DHContext::GetInstance().GetEventBus()->PostEvent<CapabilityInfoEvent>(recoverEvent);
}
int32_t DBAdapter::RegisterChangeListener()
{
DHLOGI("Register db data change listener");
if (kvStoragePtr_ == nullptr) {
DHLOGE("kvStoragePtr_ is null");
return ERR_DH_FWK_RESOURCE_KV_STORAGE_POINTER_NULL;
}
Status status = kvStoragePtr_->SubscribeKvStore(SubscribeType::SUBSCRIBE_TYPE_REMOTE, dataChangeListener_);
if (status == Status::IPC_ERROR) {
DHLOGE("Register db data change listener failed, ret: %d", status);
return ERR_DH_FWK_RESOURCE_REGISTER_DB_FAILED;
}
return DH_FWK_SUCCESS;
}
int32_t DBAdapter::UnRegisterChangeListener()
{
DHLOGI("UnRegister db data change listener");
if (kvStoragePtr_ == nullptr) {
DHLOGE("kvStoragePtr_ is null");
return ERR_DH_FWK_RESOURCE_KV_STORAGE_POINTER_NULL;
}
Status status = kvStoragePtr_->UnSubscribeKvStore(SubscribeType::SUBSCRIBE_TYPE_REMOTE, dataChangeListener_);
if (status == Status::IPC_ERROR) {
DHLOGE("UnRegister db data change listener failed, ret: %d", status);
return ERR_DH_FWK_RESOURCE_UNREGISTER_DB_FAILED;
}
return DH_FWK_SUCCESS;
}
void DBAdapter::RegisterKvStoreDeathListener()
{
DHLOGI("Register kvStore death listener");
kvDataMgr_.RegisterKvStoreServiceDeathRecipient(shared_from_this());
}
void DBAdapter::UnRegisterKvStoreDeathListener()
{
DHLOGI("UnRegister kvStore death listener");
kvDataMgr_.UnRegisterKvStoreServiceDeathRecipient(shared_from_this());
}
void DBAdapter::RegisterManualSyncListener()
{
DHLOGI("Register manualSyncCallback");
if (kvStoragePtr_ == nullptr) {
DHLOGE("kvStoragePtr_ is null");
return;
}
kvStoragePtr_->RegisterSyncCallback(shared_from_this());
}
void DBAdapter::UnRegisterManualSyncListener()
{
DHLOGI("UnRegister manualSyncCallback");
if (kvStoragePtr_ == nullptr) {
DHLOGE("kvStoragePtr_ is null");
return;
}
kvStoragePtr_->UnRegisterSyncCallback();
}
void DBAdapter::OnRemoteDied()
{
DHLOGI("OnRemoteDied, recover db begin");
auto ReInitTask = [this] {
int32_t times = 0;
while (times < DIED_CHECK_MAX_TIMES) {
// init kvStore.
if (this->ReInit() != DH_FWK_SUCCESS) {
// register data change listener again.
this->RegisterChangeListener();
this->SyncDBForRecover();
DHLOGE("Current times is %d", times);
break;
}
times++;
usleep(DIED_CHECK_INTERVAL);
}
};
DHContext::GetInstance().GetEventBus()->PostTask(ReInitTask, "ReInitTask", 0);
DHLOGI("OnRemoteDied, recover db end");
}
void DBAdapter::DeleteKvStore()
{
std::lock_guard<std::mutex> lock(dbAdapterMutex_);
Status status = kvDataMgr_.DeleteKvStore(appId_, storeId_);
if (status != Status::SUCCESS) {
DHLOGE("DeleteKvStore error, appId: %s, storeId: %s, status: %d",
appId_.appId.c_str(), storeId_.storeId.c_str(), status);
return;
}
DHLOGI("DeleteKvStore success appId: %s", appId_.appId.c_str());
}
int32_t DBAdapter::RemoveDeviceData(const std::string &deviceId)
{
std::lock_guard<std::mutex> lock(dbAdapterMutex_);
if (kvStoragePtr_ == nullptr) {
DHLOGE("kvStoragePtr_ is null");
return ERR_DH_FWK_RESOURCE_KV_STORAGE_POINTER_NULL;
}
Status status = kvStoragePtr_->RemoveDeviceData(deviceId);
if (status != Status::SUCCESS) {
DHLOGE("Remove device data failed, deviceId: %s", GetAnonyString(deviceId).c_str());
return ERR_DH_FWK_RESOURCE_KV_STORAGE_OPERATION_FAIL;
}
DHLOGD("Remove device data success, deviceId: %s", GetAnonyString(deviceId).c_str());
return DH_FWK_SUCCESS;
}
int32_t DBAdapter::RemoveDataByKey(const std::string &key)
{
std::lock_guard<std::mutex> lock(dbAdapterMutex_);
if (kvStoragePtr_ == nullptr) {
DHLOGE("kvStoragePtr_ is null");
return ERR_DH_FWK_RESOURCE_KV_STORAGE_POINTER_NULL;
}
Key kvKey(key);
Status status = kvStoragePtr_->Delete(kvKey);
if (status != Status::SUCCESS) {
DHLOGE("Remove data by key failed");
return ERR_DH_FWK_RESOURCE_KV_STORAGE_OPERATION_FAIL;
}
DHLOGD("Remove data by key success");
return DH_FWK_SUCCESS;
}
}
}

View File

@ -0,0 +1,72 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "disable_task.h"
#include "anonymous_string.h"
#include "component_manager.h"
#include "distributed_hardware_errno.h"
#include "distributed_hardware_log.h"
#include "offline_task.h"
#include "task_board.h"
namespace OHOS {
namespace DistributedHardware {
#undef DH_LOG_TAG
#define DH_LOG_TAG "DisableTask"
DisableTask::DisableTask(const std::string &networkId, const std::string &devId, const std::string &dhId)
: Task(networkId, devId, dhId)
{
SetTaskType(TaskType::DISABLE);
SetTaskSteps(std::vector<TaskStep> { TaskStep::DO_DISABLE });
DHLOGD("id = %s, devId = %s", GetId().c_str(), GetAnonyString(devId).c_str());
}
DisableTask::~DisableTask()
{
DHLOGD("id = %s, devId = %s", GetId().c_str(), GetAnonyString(GetDevId()).c_str());
}
void DisableTask::DoTask()
{
DHLOGD("id = %s, devId = %s, dhId = %s", GetId().c_str(), GetAnonyString(GetDevId()).c_str(), GetDhId().c_str());
SetTaskState(TaskState::RUNNING);
/* trigger Unregister Distributed Hardware Task, sync function */
auto result = UnRegisterHardware();
auto state = (result == DH_FWK_SUCCESS) ? TaskState::SUCCESS : TaskState::FAIL;
SetTaskState(state);
/* if finish task, notify father finish */
std::shared_ptr<Task> father = GetFatherTask().lock();
if (father != nullptr) {
auto offLineTask = std::static_pointer_cast<OffLineTask>(father);
offLineTask->NotifyFatherFinish(GetId());
}
TaskBoard::GetInstance().RemoveTask(GetId());
DHLOGD("finish disable task, remove it, id = %s", GetId().c_str());
}
int32_t DisableTask::UnRegisterHardware()
{
auto result = ComponentManager::GetInstance().Disable(GetNetworkId(), GetDevId(), GetDhId());
DHLOGI("disable task %s, id = %s, devId = %s, dhId = %s", (result == DH_FWK_SUCCESS) ? "success" : "failed",
GetId().c_str(), GetAnonyString(GetDevId()).c_str(), GetDhId().c_str());
return result;
}
}
}

View File

@ -0,0 +1,64 @@
/*
* 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 "enable_task.h"
#include <chrono>
#include <thread>
#include "anonymous_string.h"
#include "component_manager.h"
#include "distributed_hardware_errno.h"
#include "distributed_hardware_log.h"
#include "task_board.h"
namespace OHOS {
namespace DistributedHardware {
#undef DH_LOG_TAG
#define DH_LOG_TAG "EnableTask"
EnableTask::EnableTask(const std::string &networkId, const std::string &devId, const std::string &dhId)
: Task(networkId, devId, dhId)
{
SetTaskType(TaskType::ENABLE);
SetTaskSteps(std::vector<TaskStep> { TaskStep::DO_ENABLE });
DHLOGD("id = %s, devId = %s", GetId().c_str(), GetAnonyString(devId).c_str());
}
EnableTask::~EnableTask()
{
DHLOGD("id = %s, devId = %s", GetId().c_str(), GetAnonyString(GetDevId()).c_str());
}
void EnableTask::DoTask()
{
DHLOGD("id = %s, devId = %s, dhId = %s", GetId().c_str(), GetAnonyString(GetDevId()).c_str(), GetDhId().c_str());
SetTaskState(TaskState::RUNNING);
auto result = RegisterHardware();
auto state = (result == DH_FWK_SUCCESS) ? TaskState::SUCCESS : TaskState::FAIL;
SetTaskState(state);
TaskBoard::GetInstance().RemoveTask(GetId());
DHLOGD("finish enable task, remove it, id = %s", GetId().c_str());
}
int32_t EnableTask::RegisterHardware()
{
auto result = ComponentManager::GetInstance().Enable(GetNetworkId(), GetDevId(), GetDhId());
DHLOGI("enable task %s, id = %s, devId = %s, dhId = %s", (result == DH_FWK_SUCCESS) ? "success" : "failed",
GetId().c_str(), GetAnonyString(GetDevId()).c_str(), GetDhId().c_str());
return result;
}
}
}

View File

@ -0,0 +1,133 @@
/*
* 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 "offline_task.h"
#include <thread>
#include "anonymous_string.h"
#include "capability_info_manager.h"
#include "distributed_hardware_errno.h"
#include "distributed_hardware_log.h"
#include "task_board.h"
#include "task_executor.h"
#include "task_factory.h"
namespace OHOS {
namespace DistributedHardware {
#undef DH_LOG_TAG
#define DH_LOG_TAG "OffLineTask"
OffLineTask::OffLineTask(const std::string &networkId, const std::string &devId, const std::string &dhId)
: Task(networkId, devId, dhId)
{
this->SetTaskType(TaskType::OFF_LINE);
this->SetTaskSteps({TaskStep::UNREGISTER_OFFLINE_DISTRIBUTED_HARDWARE, TaskStep::WAIT_UNREGISTGER_COMPLETE,
TaskStep::CLEAR_OFFLINE_INFO});
DHLOGD("id = %s, devId = %s", GetId().c_str(), GetAnonyString(devId).c_str());
}
OffLineTask::~OffLineTask()
{
DHLOGD("id = %s, devId = %s", GetId().c_str(), GetAnonyString(GetDevId()).c_str());
}
void OffLineTask::DoTask()
{
std::thread(&OffLineTask::DoTaskInner, this).detach();
}
void OffLineTask::DoTaskInner()
{
DHLOGD("start offline task, id = %s, devId = %s", GetId().c_str(), GetAnonyString(GetDevId()).c_str());
this->SetTaskState(TaskState::RUNNING);
for (auto& step : this->GetTaskSteps()) {
switch (step) {
case TaskStep::UNREGISTER_OFFLINE_DISTRIBUTED_HARDWARE: {
CreateDisableTask();
break;
}
case TaskStep::WAIT_UNREGISTGER_COMPLETE: {
WaitDisableTaskFinish();
break;
}
case TaskStep::CLEAR_OFFLINE_INFO: {
ClearOffLineInfo();
break;
}
default: {
break;
}
}
}
this->SetTaskState(TaskState::SUCCESS);
TaskBoard::GetInstance().RemoveTask(this->GetId());
DHLOGD("Finish OffLine task, remove it, id: %s", GetId().c_str());
}
void OffLineTask::CreateDisableTask()
{
DHLOGI("networkId = %s, devId = %s", GetAnonyString(GetNetworkId()).c_str(), GetAnonyString(GetDevId()).c_str());
std::vector<std::shared_ptr<CapabilityInfo>> capabilityInfos;
CapabilityInfoManager::GetInstance()->GetCapabilitiesByDeviceId(GetDevId(), capabilityInfos);
if (capabilityInfos.empty()) {
DHLOGE("capabilityInfos is empty, can not create disableTask, devId = %s", GetAnonyString(GetDevId()).c_str());
return;
}
for (const auto &iter : capabilityInfos) {
if (iter == nullptr) {
DHLOGE("capabilityInfo is null");
continue;
}
auto task = TaskFactory::GetInstance().CreateTask(TaskType::DISABLE, GetNetworkId(), GetDevId(),
iter->GetDHId(), shared_from_this());
TaskExecutor::GetInstance().PushTask(task);
}
}
void OffLineTask::WaitDisableTaskFinish()
{
DHLOGI("start wait disable task finish");
std::unique_lock<std::mutex> waitLock(unFinishTaskMtx_);
finishCondVar_.wait(waitLock, [&] { return this->unFinishChildrenTasks_.empty(); });
DHLOGI("all disable task finish");
}
void OffLineTask::ClearOffLineInfo()
{
DHLOGI("start clear resource when device offline, devId = %s", GetAnonyString(GetDevId()).c_str());
auto ret = CapabilityInfoManager::GetInstance()->RemoveCapabilityInfoInMem(GetDevId());
if (ret != DH_FWK_SUCCESS) {
DHLOGE("RemoveCapabilityInfoInMem failed, devId = %s, errCode = %d", GetAnonyString(GetDevId()).c_str(), ret);
}
}
void OffLineTask::NotifyFatherFinish(std::string taskId)
{
{
std::lock_guard<std::mutex> lock(unFinishTaskMtx_);
this->unFinishChildrenTasks_.erase(taskId);
}
finishCondVar_.notify_all();
}
void OffLineTask::AddChildrenTask(std::shared_ptr<Task> childrenTask)
{
std::lock_guard<std::mutex> lock(unFinishTaskMtx_);
this->unFinishChildrenTasks_.insert(childrenTask->GetId());
}
}
}

View File

@ -0,0 +1,102 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "online_task.h"
#include "anonymous_string.h"
#include "capability_info_manager.h"
#include "distributed_hardware_errno.h"
#include "distributed_hardware_log.h"
#include "task_board.h"
#include "task_executor.h"
#include "task_factory.h"
namespace OHOS {
namespace DistributedHardware {
#undef DH_LOG_TAG
#define DH_LOG_TAG "OnLineTask"
OnLineTask::OnLineTask(const std::string &networkId, const std::string &devId, const std::string &dhId)
: Task(networkId, devId, dhId)
{
SetTaskType(TaskType::ON_LINE);
SetTaskSteps(std::vector<TaskStep> { TaskStep::SYNC_ONLINE_INFO, TaskStep::REGISTER_ONLINE_DISTRIBUTED_HARDWARE });
DHLOGD("id = %s, devId = %s", GetId().c_str(), GetAnonyString(devId).c_str());
}
OnLineTask::~OnLineTask()
{
DHLOGD("id = %s, devId = %s", GetId().c_str(), GetAnonyString(GetDevId()).c_str());
}
void OnLineTask::DoTask()
{
DHLOGD("start online task, id = %s, devId = %s", GetId().c_str(), GetAnonyString(GetDevId()).c_str());
this->SetTaskState(TaskState::RUNNING);
for (auto& step : this->GetTaskSteps()) {
switch (step) {
case TaskStep::SYNC_ONLINE_INFO: {
DoSyncInfo();
break;
}
case TaskStep::REGISTER_ONLINE_DISTRIBUTED_HARDWARE: {
CreateEnableTask();
break;
}
default: {
break;
}
}
}
SetTaskState(TaskState::SUCCESS);
TaskBoard::GetInstance().RemoveTask(this->GetId());
DHLOGD("finish online task, remove it, id = %s.", GetId().c_str());
}
void OnLineTask::DoSyncInfo()
{
DHLOGI("start sync resource when device online, devId = %s", GetAnonyString(GetDevId()).c_str());
auto ret = CapabilityInfoManager::GetInstance()->ManualSync(GetNetworkId());
if (ret != DH_FWK_SUCCESS) {
DHLOGW("ManualSync failed, devId = %s, errCode = %d", GetAnonyString(GetDevId()).c_str(), ret);
}
ret = CapabilityInfoManager::GetInstance()->SyncDeviceInfoFromDB(GetDevId());
if (ret != DH_FWK_SUCCESS) {
DHLOGE("SyncDeviceInfoFromDB failed, devId = %s, errCode = %d", GetAnonyString(GetDevId()).c_str(), ret);
return;
}
}
void OnLineTask::CreateEnableTask()
{
DHLOGI("networkId = %s, devId = %s", GetAnonyString(GetNetworkId()).c_str(), GetAnonyString(GetDevId()).c_str());
std::vector<std::shared_ptr<CapabilityInfo>> capabilityInfos;
CapabilityInfoManager::GetInstance()->GetCapabilitiesByDeviceId(GetDevId(), capabilityInfos);
if (capabilityInfos.empty()) {
DHLOGE("capabilityInfos is empty, can not create enableTask, devId = %s", GetAnonyString(GetDevId()).c_str());
return;
}
for (const auto &iter : capabilityInfos) {
if (iter == nullptr) {
DHLOGE("capabilityInfo is null");
continue;
}
auto task = TaskFactory::GetInstance().CreateTask(TaskType::ENABLE, GetNetworkId(), GetDevId(),
iter->GetDHId(), shared_from_this());
TaskExecutor::GetInstance().PushTask(task);
}
}
}
}

View File

@ -0,0 +1,104 @@
/*
* 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 "task.h"
#include "constants.h"
#include "dh_utils_tool.h"
namespace OHOS {
namespace DistributedHardware {
Task::Task(const std::string &networkId, const std::string &devId, const std::string &dhId)
: id_(DH_TASK_NAME_PREFIX + GetRandomID()), networkId_(networkId), devId_(devId), dhId_(dhId)
{}
Task::~Task()
{
this->childrenTasks_.clear();
}
std::string Task::GetId()
{
return this->id_;
}
std::string Task::GetNetworkId()
{
return this->networkId_;
}
std::string Task::GetDevId()
{
return this->devId_;
}
std::string Task::GetDhId()
{
return this->dhId_;
}
TaskType Task::GetTaskType()
{
return this->taskType_;
}
void Task::SetTaskType(TaskType taskType)
{
this->taskType_ = taskType;
}
void Task::SetTaskSteps(std::vector<TaskStep> taskSteps)
{
this->taskSteps_.swap(taskSteps);
}
const std::vector<TaskStep> Task::GetTaskSteps()
{
return this->taskSteps_;
}
TaskState Task::GetTaskState()
{
return this->taskState_;
}
void Task::SetTaskState(TaskState taskState)
{
this->taskState_ = taskState;
}
void Task::AddChildrenTask(std::shared_ptr<Task> childrenTask)
{
std::lock_guard<std::mutex> lock(taskMtx_);
this->childrenTasks_.push_back(childrenTask);
}
const std::vector<std::shared_ptr<Task>> Task::GetChildrenTasks()
{
std::lock_guard<std::mutex> lock(taskMtx_);
return this->childrenTasks_;
}
const std::weak_ptr<Task> Task::GetFatherTask()
{
return this->fatherTask_;
}
void Task::SetFatherTask(std::shared_ptr<Task> fatherTask)
{
this->fatherTask_ = fatherTask;
}
}
}

View File

@ -0,0 +1,89 @@
/*
* 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 "task_board.h"
#include "dh_context.h"
#include "dh_utils_tool.h"
#include "distributed_hardware_errno.h"
#include "distributed_hardware_log.h"
namespace OHOS {
namespace DistributedHardware {
#undef DH_LOG_TAG
#define DH_LOG_TAG "TaskBoard"
constexpr int32_t TASK_TIMEOUT_MS = 5000;
IMPLEMENT_SINGLE_INSTANCE(TaskBoard);
int32_t TaskBoard::WaitForALLTaskFinish()
{
// wait for all task finish until timeout
std::unique_lock<std::mutex> lock(tasksMtx_);
auto status = conVar_.wait_for(lock, std::chrono::milliseconds(TASK_TIMEOUT_MS),
[this]() { return tasks_.empty(); });
if (!status) {
DHLOGE("wait for all task finish timeout");
return ERR_DH_FWK_TASK_TIMEOUT;
}
DHLOGI("all task finished");
return DH_FWK_SUCCESS;
}
bool TaskBoard::IsAllTaskFinish()
{
std::lock_guard<std::mutex> lock(tasksMtx_);
return this->tasks_.empty();
}
void TaskBoard::AddTask(std::shared_ptr<Task> task)
{
if (task == nullptr) {
DHLOGE("task is null, error");
return;
}
std::lock_guard<std::mutex> lock(tasksMtx_);
DHLOGI("Add task, id: %s", task->GetId().c_str());
if (this->tasks_.find(task->GetId()) != this->tasks_.end()) {
DHLOGE("Task id duplicate, id: %d", task->GetId().c_str());
return;
}
this->tasks_.emplace(task->GetId(), task);
}
void TaskBoard::RemoveTask(std::string taskId)
{
std::lock_guard<std::mutex> lock(tasksMtx_);
DHLOGI("Remove task, id: %s", taskId.c_str());
RemoveTaskInner(taskId);
if (tasks_.empty()) {
conVar_.notify_one();
}
}
void TaskBoard::RemoveTaskInner(std::string taskId)
{
if (tasks_.find(taskId) == tasks_.end()) {
DHLOGE("Can not find removed task");
return;
}
tasks_.erase(taskId);
}
}
}

View File

@ -0,0 +1,91 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "task_executor.h"
#include <thread>
#include "dh_context.h"
#include "distributed_hardware_log.h"
#include "event_bus.h"
namespace OHOS {
namespace DistributedHardware {
IMPLEMENT_SINGLE_INSTANCE(TaskExecutor);
TaskExecutor::TaskExecutor() : taskThreadFlag_(true)
{
DHLOGI("Ctor TaskExecutor");
std::thread(&TaskExecutor::TriggerTask, this).detach();
}
TaskExecutor::~TaskExecutor()
{
DHLOGI("Dtor TaskExecutor");
taskThreadFlag_ = false;
}
void TaskExecutor::PushTask(const std::shared_ptr<Task>& task)
{
if (task == nullptr) {
DHLOGE("Task is null");
return;
}
{
DHLOGI("Push task: %s", task->GetId().c_str());
std::unique_lock<std::mutex> lock(taskQueueMtx_);
taskQueue_.push(task);
}
condVar_.notify_one();
}
std::shared_ptr<Task> TaskExecutor::PopTask()
{
std::shared_ptr<Task> task = nullptr;
std::unique_lock<std::mutex> lock(taskQueueMtx_);
condVar_.wait(lock, [this] {
return !(this->taskQueue_.empty());
});
if (!taskQueue_.empty()) {
task = taskQueue_.front();
taskQueue_.pop();
DHLOGI("Pop task: %s", task->GetId().c_str());
}
return task;
}
void TaskExecutor::TriggerTask()
{
while (taskThreadFlag_) {
std::shared_ptr<Task> task = PopTask();
if (task == nullptr) {
DHLOGE("Pop a null task, error");
continue;
}
auto taskFunc = [task]() {
task->DoTask();
};
DHLOGI("Post task to EventBus: %s", task->GetId().c_str());
DHContext::GetInstance().GetEventBus()->PostTask(taskFunc, task->GetId());
}
}
}
}

View File

@ -0,0 +1,70 @@
/*
* 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 "task_factory.h"
#include "anonymous_string.h"
#include "disable_task.h"
#include "distributed_hardware_log.h"
#include "enable_task.h"
#include "offline_task.h"
#include "online_task.h"
#include "task_board.h"
namespace OHOS {
namespace DistributedHardware {
#undef DH_LOG_TAG
#define DH_LOG_TAG "TaskFactory"
IMPLEMENT_SINGLE_INSTANCE(TaskFactory);
std::shared_ptr<Task> TaskFactory::CreateTask(TaskType taskType, const std::string &networkId, const std::string &devId,
const std::string &dhId, std::shared_ptr<Task> fatherTask)
{
DHLOGI("taskType = %d, networkId = %s, devId = %s, dhId = %s", static_cast<int32_t>(taskType),
GetAnonyString(networkId).c_str(), GetAnonyString(devId).c_str(), dhId.c_str());
std::shared_ptr<Task> task = nullptr;
switch (taskType) {
case TaskType::ENABLE: {
task = std::make_shared<EnableTask>(networkId, devId, dhId);
break;
}
case TaskType::DISABLE: {
task = std::make_shared<DisableTask>(networkId, devId, dhId);
break;
}
case TaskType::ON_LINE: {
task = std::make_shared<OnLineTask>(networkId, devId, dhId);
break;
}
case TaskType::OFF_LINE: {
task = std::make_shared<OffLineTask>(networkId, devId, dhId);
break;
}
default: {
DHLOGE("CreateTask type invalid, type: %d", taskType);
return nullptr;
}
}
if (fatherTask != nullptr) {
task->SetFatherTask(fatherTask);
fatherTask->AddChildrenTask(task);
}
TaskBoard::GetInstance().AddTask(task);
return task;
}
}
}

View File

@ -0,0 +1,89 @@
/*
* 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 "dh_context.h"
#include "dh_utils_tool.h"
#include "distributed_hardware_errno.h"
#include "distributed_hardware_log.h"
namespace OHOS {
namespace DistributedHardware {
IMPLEMENT_SINGLE_INSTANCE(DHContext);
DHContext::DHContext() : eventBus_(std::make_shared<EventBus>()) {}
DHContext::~DHContext()
{
if (eventBus_ != nullptr) {
eventBus_.reset();
eventBus_ = nullptr;
}
}
std::shared_ptr<EventBus> DHContext::GetEventBus()
{
return eventBus_;
}
const DeviceInfo& DHContext::GetDeviceInfo()
{
std::lock_guard<std::mutex> lock(devMutex_);
if (!devInfo_.deviceId.empty()) {
return devInfo_;
}
devInfo_ = GetLocalDeviceInfo();
return devInfo_;
}
void DHContext::AddOnlineDevice(const std::string &devId, const std::string &networkId)
{
std::unique_lock<std::shared_mutex> lock(onlineDevMutex_);
if (!devId.empty() && !networkId.empty()) {
onlineDeviceMap_[devId] = networkId;
}
}
void DHContext::RemoveOnlineDevice(const std::string &devId)
{
std::unique_lock<std::shared_mutex> lock(onlineDevMutex_);
auto iter = onlineDeviceMap_.find(devId);
if (iter != onlineDeviceMap_.end()) {
onlineDeviceMap_.erase(iter);
}
}
bool DHContext::IsDeviceOnline(const std::string &devId)
{
std::shared_lock<std::shared_mutex> lock(onlineDevMutex_);
return onlineDeviceMap_.find(devId) != onlineDeviceMap_.end();
}
size_t DHContext::GetOnlineCount()
{
std::shared_lock<std::shared_mutex> lock(onlineDevMutex_);
return onlineDeviceMap_.size();
}
std::string DHContext::GetNetworkIdByUUID(const std::string &devId)
{
std::unique_lock<std::shared_mutex> lock(onlineDevMutex_);
if (onlineDeviceMap_.find(devId) == onlineDeviceMap_.end()) {
DHLOGE("Can not find networkId in onlineDeviceMap_: %s", GetAnonyString(devId).c_str());
return "";
}
return onlineDeviceMap_[devId];
}
}
}

View File

@ -0,0 +1,116 @@
/*
* 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 "versionmanager/version_manager.h"
#include "anonymous_string.h"
#include "componentloader/component_loader.h"
#include "dh_context.h"
#include "distributed_hardware_log.h"
namespace OHOS {
namespace DistributedHardware {
#undef DH_LOG_TAG
#define DH_LOG_TAG "VersionManager"
IMPLEMENT_SINGLE_INSTANCE(VersionManager);
int32_t VersionManager::Init()
{
DHLOGI("start");
DHVersion dhVersion;
int32_t ret = ComponentLoader::GetInstance().GetLocalDHVersion(dhVersion);
if (ret != DH_FWK_SUCCESS) {
DHLOGE("GetLocalDHVersion fail");
return ret;
}
dhVersion.dhVersion = DH_LOCAL_VERSION;
ShowLocalVersion(dhVersion);
std::string strDevID = DHContext::GetInstance().GetDeviceInfo().deviceId;
AddDHVersion(strDevID, dhVersion);
return DH_FWK_SUCCESS;
}
void VersionManager::UnInit()
{
DHLOGI("start");
dhVersions_.clear();
}
void VersionManager::ShowLocalVersion(const DHVersion &dhVersion) const
{
for (const auto &item : dhVersion.compVersions) {
DHLOGI("LocalDHVersion = %s, DHtype = %#X, handlerVersion = %s, sourceVersion = %s, sinkVersion = %s",
dhVersion.dhVersion.c_str(), item.first, item.second.handlerVersion.c_str(),
item.second.sourceVersion.c_str(), item.second.sinkVersion.c_str());
}
}
int32_t VersionManager::AddDHVersion(const std::string &devId, const DHVersion &dhVersion)
{
DHLOGI("devId: %s", GetAnonyString(devId).c_str());
std::lock_guard<std::mutex> lock(versionMutex_);
dhVersions_.insert(std::pair<std::string, DHVersion>(devId, dhVersion));
return DH_FWK_SUCCESS;
}
int32_t VersionManager::RemoveDHVersion(const std::string &devId)
{
DHLOGI("devId: %s", GetAnonyString(devId).c_str());
std::lock_guard<std::mutex> lock(versionMutex_);
std::unordered_map<std::string, DHVersion>::iterator iter = dhVersions_.find(devId);
if (iter == dhVersions_.end()) {
DHLOGE("there is no devId: %s, remove fail", GetAnonyString(devId).c_str());
return ERR_DH_FWK_VERSION_DEVICE_ID_NOT_EXIST;
}
dhVersions_.erase(iter);
return DH_FWK_SUCCESS;
}
int32_t VersionManager::GetDHVersion(const std::string &devId, DHVersion &dhVersion)
{
DHLOGI("devId: %s", GetAnonyString(devId).c_str());
std::lock_guard<std::mutex> lock(versionMutex_);
std::unordered_map<std::string, DHVersion>::iterator iter = dhVersions_.find(devId);
if (iter == dhVersions_.end()) {
DHLOGE("there is no devId: %s, get version fail", GetAnonyString(devId).c_str());
return ERR_DH_FWK_VERSION_DEVICE_ID_NOT_EXIST;
} else {
dhVersion = dhVersions_[devId];
return DH_FWK_SUCCESS;
}
}
int32_t VersionManager::GetCompVersion(const std::string &devId, const DHType dhType, CompVersion &compVersion)
{
DHVersion dhVersion;
int32_t ret = GetDHVersion(devId, dhVersion);
if (ret != DH_FWK_SUCCESS) {
DHLOGE("GetDHVersion fail, devId: %s", GetAnonyString(devId).c_str());
return ret;
}
if (dhVersion.compVersions.find(dhType) == dhVersion.compVersions.end()) {
DHLOGE("not find dhType: %#X", dhType);
return ERR_DH_FWK_TYPE_NOT_EXIST;
}
compVersion = dhVersion.compVersions[dhType];
return DH_FWK_SUCCESS;
}
std::string VersionManager::GetLocalDeviceVersion()
{
return DH_LOCAL_VERSION;
}
}
}

View File

@ -0,0 +1,24 @@
# 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.
group("svrimpl_test") {
testonly = true
deps = [
"common/task:dh_task_test",
"common/componentmanager:component_manager_test",
"common/versionmanager:version_manager_test",
"common/componentloader:component_loader_test",
"common/resourcemanager:resource_manager_test",
"common:distributed_hardware_manager_test",
]
}

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.
import("//build/test.gni")
import("//foundation/distributedhardware/distributedhardwarefwk/distributedhardwarefwk.gni")
module_out_path = "distributed_hardware_fwk/dh_manager_test"
config("module_private_config") {
visibility = [ ":*" ]
include_dirs = [
"include",
"${utils_path}/include",
"${utils_path}/include/log",
"${utils_path}/include/eventbus",
"${common_path}/log/include",
"${common_path}/utils/include",
"${services_path}/distributedhardwarefwkserviceimpl/include",
"${services_path}/distributedhardwarefwkserviceimpl/include/task",
"${services_path}/distributedhardwarefwkserviceimpl/include/utils",
"//utils/native/base/include",
]
}
ohos_unittest("DistributedHardwareManagerTest") {
module_out_path = module_out_path
sources = [
"distributed_hardware_manager_test.cpp"
]
configs = [ ":module_private_config" ]
deps = [
"//third_party/googletest:gtest_main",
"//third_party/googletest:gmock_main",
"//foundation/distributedhardware/distributedhardwarefwk/utils:distributedhardwareutils",
"//foundation/distributedhardware/distributedhardwarefwk/services/distributedhardwarefwkserviceimpl:distributedhardwarefwksvr_impl"
]
defines = [
"HI_LOG_ENABLE",
"DH_LOG_TAG=\"DistributedHardwareManagerTest\"",
"LOG_DOMAIN=0xD004100",
]
external_deps = [
"bundle_framework:appexecfwk_base",
"bundle_framework:appexecfwk_core",
"eventhandler:libeventhandler",
"hiviewdfx_hilog_native:libhilog",
"dsoftbus_standard:softbus_client",
]
}
group("distributed_hardware_manager_test") {
testonly = true
deps = [ ":DistributedHardwareManagerTest" ]
}

View File

@ -0,0 +1,57 @@
# Copyright (c) 2021 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import("//build/test.gni")
import("//foundation/distributedhardware/distributedhardwarefwk/distributedhardwarefwk.gni")
module_out_path = "distributed_hardware_fwk/component_loader_test"
config("module_private_config") {
visibility = [ ":*" ]
include_dirs = [
"include",
"${utils_path}/include",
"${utils_path}/include/log",
"${services_path}/distributedhardwarefwkserviceimpl/include",
"${services_path}/distributedhardwarefwkserviceimpl/include/versionmanager",
"${services_path}/distributedhardwarefwkserviceimpl/include/componentloader",
"${services_path}/distributedhardwarefwkserviceimpl/include/utils",
"${common_path}/utils/include",
"${common_path}/log/include",
]
}
ohos_unittest("ComponentLoaderTest") {
module_out_path = module_out_path
sources = [
"src/component_loader_test.cpp"
]
configs = [ ":module_private_config" ]
deps = [
"//third_party/googletest:gtest_main",
"//foundation/distributedhardware/distributedhardwarefwk/services/distributedhardwarefwkserviceimpl:distributedhardwarefwksvr_impl"
]
defines = [
"HI_LOG_ENABLE",
"DH_LOG_TAG=\"ComponentLoaderTest\"",
"LOG_DOMAIN=0xD004100",
]
}
group("component_loader_test") {
testonly = true
deps = [ ":ComponentLoaderTest" ]
}

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 OHOS_DISTRIBUTED_HARDWARE_COMPONENT_LOADER_TEST_H
#define OHOS_DISTRIBUTED_HARDWARE_COMPONENT_LOADER_TEST_H
#include <gtest/gtest.h>
namespace OHOS {
namespace DistributedHardware {
class ComponentLoaderTest : public testing::Test {
public:
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
};
}
}
#endif

View File

@ -0,0 +1,154 @@
/*
* 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 "component_loader_test.h"
#define private public
#include "component_loader.h"
#undef private
#include "versionmanager/version_manager.h"
using namespace testing::ext;
namespace OHOS {
namespace DistributedHardware {
void ComponentLoaderTest::SetUpTestCase(void) {}
void ComponentLoaderTest::TearDownTestCase(void) {}
void ComponentLoaderTest::SetUp() {}
void ComponentLoaderTest::TearDown() {}
/**
* @tc.name: component_loader_test_001
* @tc.desc: Verify the Init function.
* @tc.type: FUNC
* @tc.require: AR000GHSK3
*/
HWTEST_F(ComponentLoaderTest, component_loader_test_001, TestSize.Level0)
{
auto ret = ComponentLoader::GetInstance().Init();
EXPECT_EQ(DH_FWK_SUCCESS, ret);
EXPECT_TRUE(ComponentLoader::GetInstance().compHandlerMap_.size() != 0);
}
/**
* @tc.name: component_loader_test_002
* @tc.desc: Verify the GetLocalDHVersion function.
* @tc.type: FUNC
* @tc.require: AR000GHSK3
*/
HWTEST_F(ComponentLoaderTest, component_loader_test_002, TestSize.Level0)
{
DHVersion dhVersion;
auto ret = ComponentLoader::GetInstance().GetLocalDHVersion(dhVersion);
EXPECT_EQ(DH_FWK_SUCCESS, ret);
EXPECT_TRUE(!dhVersion.compVersions.empty());
}
/**
* @tc.name: component_loader_test_003
* @tc.desc: Verify the GetAllCompTypes function.
* @tc.type: FUNC
* @tc.require: AR000GHSK3
*/
HWTEST_F(ComponentLoaderTest, component_loader_test_003, TestSize.Level0)
{
std::vector<DHType> dhTypes = ComponentLoader::GetInstance().GetAllCompTypes();
EXPECT_TRUE(dhTypes.size() != 0);
}
/**
* @tc.name: component_loader_test_004
* @tc.desc: Verify the GetHardwareHandler function.
* @tc.type: FUNC
* @tc.require: AR000GHSK3
*/
HWTEST_F(ComponentLoaderTest, component_loader_test_004, TestSize.Level0)
{
IHardwareHandler *hardwareHandlerPtr = nullptr;
auto ret = ComponentLoader::GetInstance().GetHardwareHandler(DHType::CAMERA, hardwareHandlerPtr);
EXPECT_EQ(DH_FWK_SUCCESS, ret);
EXPECT_TRUE(hardwareHandlerPtr != nullptr);
}
/**
* @tc.name: component_loader_test_005
* @tc.desc: Verify the GetSource function.
* @tc.type: FUNC
* @tc.require: AR000GHSK3
*/
HWTEST_F(ComponentLoaderTest, component_loader_test_005, TestSize.Level0)
{
IDistributedHardwareSource *sourcePtr = nullptr;
auto ret = ComponentLoader::GetInstance().GetSource(DHType::CAMERA, sourcePtr);
EXPECT_EQ(DH_FWK_SUCCESS, ret);
EXPECT_TRUE(sourcePtr != nullptr);
}
/**
* @tc.name: component_loader_test_006
* @tc.desc: Verify the GetSink function.
* @tc.type: FUNC
* @tc.require: AR000GHSK3
*/
HWTEST_F(ComponentLoaderTest, component_loader_test_006, TestSize.Level0)
{
IDistributedHardwareSink *sinkPtr = nullptr;
auto ret = ComponentLoader::GetInstance().GetSink(DHType::CAMERA, sinkPtr);
EXPECT_EQ(DH_FWK_SUCCESS, ret);
EXPECT_TRUE(sinkPtr != nullptr);
}
/**
* @tc.name: component_loader_test_007
* @tc.desc: Verify the ReleaseHardwareHandler function.
* @tc.type: FUNC
* @tc.require: AR000GHSK3
*/
HWTEST_F(ComponentLoaderTest, component_loader_test_007, TestSize.Level0)
{
auto ret = ComponentLoader::GetInstance().ReleaseHardwareHandler(DHType::CAMERA);
EXPECT_EQ(DH_FWK_SUCCESS, ret);
EXPECT_TRUE(ComponentLoader::GetInstance().compHandlerMap_[DHType::CAMERA].hardwareHandler == nullptr);
}
/**
* @tc.name: component_loader_test_008
* @tc.desc: Verify the ReleaseSource function.
* @tc.type: FUNC
* @tc.require: AR000GHSK3
*/
HWTEST_F(ComponentLoaderTest, component_loader_test_008, TestSize.Level0)
{
auto ret = ComponentLoader::GetInstance().ReleaseSource(DHType::CAMERA);
EXPECT_EQ(DH_FWK_SUCCESS, ret);
EXPECT_TRUE(ComponentLoader::GetInstance().compHandlerMap_[DHType::CAMERA].sourceHandler == nullptr);
}
/**
* @tc.name: component_loader_test_009
* @tc.desc: Verify the ReleaseSink function.
* @tc.type: FUNC
* @tc.require: AR000GHSK3
*/
HWTEST_F(ComponentLoaderTest, component_loader_test_009, TestSize.Level0)
{
auto ret = ComponentLoader::GetInstance().ReleaseSink(DHType::CAMERA);
EXPECT_EQ(DH_FWK_SUCCESS, ret);
EXPECT_TRUE(ComponentLoader::GetInstance().compHandlerMap_[DHType::CAMERA].sinkHandler == nullptr);
}
}
}

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("//build/test.gni")
import("//foundation/distributedhardware/distributedhardwarefwk/distributedhardwarefwk.gni")
module_out_path = "distributed_hardware_fwk/component_manager_test"
config("module_private_config") {
visibility = [ ":*" ]
include_dirs = [
"include",
"${utils_path}/include",
"${utils_path}/include/log",
"${services_path}/distributedhardwarefwkserviceimpl/include",
"${services_path}/distributedhardwarefwkserviceimpl/include/componentmanager",
"${services_path}/distributedhardwarefwkserviceimpl/include/utils",
"${common_path}/utils/include",
"${common_path}/log/include",
"//utils/native/base/include",
]
}
ohos_unittest("ComponentManagerTest") {
module_out_path = module_out_path
sources = [
"src/component_manager_test.cpp"
]
configs = [ ":module_private_config" ]
deps = [
"//third_party/googletest:gtest_main",
"//third_party/googletest:gmock_main",
"//foundation/distributedhardware/distributedhardwarefwk/utils:distributedhardwareutils",
"//foundation/distributedhardware/distributedhardwarefwk/services/distributedhardwarefwkserviceimpl:distributedhardwarefwksvr_impl"
]
defines = [
"HI_LOG_ENABLE",
"DH_LOG_TAG=\"ComponentManagerTest\"",
"LOG_DOMAIN=0xD004100",
]
external_deps = [
"ipc:ipc_core",
]
}
group("component_manager_test") {
testonly = true
deps = [ ":ComponentManagerTest" ]
}

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 OHOS_DISTRIBUTED_HARDWARE_COMPONENT_MANAGER_TEST_H
#define OHOS_DISTRIBUTED_HARDWARE_COMPONENT_MANAGER_TEST_H
#include "gtest/gtest.h"
namespace OHOS {
namespace DistributedHardware {
class ComponentManagerTest : public testing::Test {
public:
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
int32_t Enable(int32_t timeout, int32_t status);
int32_t Disable(int32_t timeout, int32_t status);
};
}
}
#endif

View File

@ -0,0 +1,44 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DISTRIBUTED_HARDWARE_MOCK_IDISTRIBUTED_HARDWARE_SINK_H
#define OHOS_DISTRIBUTED_HARDWARE_MOCK_IDISTRIBUTED_HARDWARE_SINK_H
#include <string>
#include "gmock/gmock.h"
#include "idistributed_hardware_sink.h"
namespace OHOS {
namespace DistributedHardware {
class MockIDistributedHardwareSink : public IDistributedHardwareSink {
public:
virtual ~MockIDistributedHardwareSink() {}
MOCK_METHOD1(InitSink, int32_t(const std::string &params));
MOCK_METHOD0(ReleaseSink, int32_t());
int32_t SubscribeLocalHardware(const std::string &dhId, const std::string &parameter)
{
return 0;
}
int32_t UnsubscribeLocalHardware(const std::string &dhId)
{
return 0;
}
};
}
}
#endif

View File

@ -0,0 +1,44 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_MOCK_IDISTRIBUTED_HARDWARE_SOURCE_H
#define OHOS_MOCK_IDISTRIBUTED_HARDWARE_SOURCE_H
#include <string>
#include "gmock/gmock.h"
#include "idistributed_hardware_source.h"
namespace OHOS {
namespace DistributedHardware {
class MockIDistributedHardwareSource : public IDistributedHardwareSource {
public:
virtual ~MockIDistributedHardwareSource() {}
MOCK_METHOD1(InitSource, int32_t(const std::string &params));
MOCK_METHOD0(ReleaseSource, int32_t());
MOCK_METHOD4(RegisterDistributedHardware, int32_t(const std::string &devId, const std::string &dhId,
const EnableParam &parameters, std::shared_ptr<RegisterCallback> callback));
MOCK_METHOD3(UnregisterDistributedHardware,
int32_t(const std::string &devId, const std::string &dhId, std::shared_ptr<UnregisterCallback> callback));
int32_t ConfigDistributedHardware(const std::string &devId, const std::string &dhId, const std::string &key,
const std::string &value)
{
return 0;
}
};
}
}
#endif

View File

@ -0,0 +1,343 @@
/*
* 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 "component_manager_test.h"
#include <chrono>
#include <thread>
#include <vector>
#include <gmock/gmock.h>
#include "component_disable.h"
#include "component_enable.h"
#define private public
#include "component_manager.h"
#undef private
#include "constants.h"
#include "distributed_hardware_errno.h"
#include "distributed_hardware_log.h"
#include "mock_idistributed_hardware_sink.h"
#include "mock_idistributed_hardware_source.h"
using namespace testing::ext;
namespace OHOS {
namespace DistributedHardware {
#undef DH_LOG_TAG
#define DH_LOG_TAG "ComponentManagerTest"
constexpr int32_t EXECUTE_TIME_TEST = 1000;
const std::string DEV_ID_TEST = "123456";
const std::string DH_ID_TEST = "Camera_0";
void ComponentManagerTest::SetUpTestCase(void) {}
void ComponentManagerTest::TearDownTestCase(void) {}
void ComponentManagerTest::SetUp()
{
ComponentManager::GetInstance().compSource_.clear();
ComponentManager::GetInstance().compSink_.clear();
}
void ComponentManagerTest::TearDown() {}
int32_t ComponentManagerTest::Enable(int32_t timeout, int32_t status)
{
MockIDistributedHardwareSource stub;
auto compEnable = std::make_shared<ComponentEnable>();
EnableParam parameters;
std::future<int32_t> future;
auto handler = [&future, timeout, status, compEnable](std::string devId, std::string dhId,
const EnableParam &parameters, std::shared_ptr<RegisterCallback> callback) {
future = std::async(std::launch::async, [timeout, compEnable, devId, dhId, status]() {
std::this_thread::sleep_for(std::chrono::milliseconds(timeout));
return compEnable->OnRegisterResult(devId, dhId, status, "");
});
return DH_FWK_SUCCESS;
};
EXPECT_CALL(stub, RegisterDistributedHardware(DEV_ID_TEST, DH_ID_TEST, testing::_, testing::_))
.Times(1)
.WillOnce(testing::Invoke(handler));
auto start = std::chrono::system_clock::now();
auto ret = compEnable->Enable(DEV_ID_TEST, DH_ID_TEST, parameters, &stub);
auto diff = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - start).count();
DHLOGI("enable callback use time: %d (ms)", diff);
return ret;
}
int32_t ComponentManagerTest::Disable(int32_t timeout, int32_t status)
{
MockIDistributedHardwareSource stub;
auto compDisable = std::make_shared<ComponentDisable>();
std::future<int32_t> future;
auto handler = [&future, timeout, status, compDisable](std::string devId, std::string dhId,
std::shared_ptr<UnregisterCallback> callback) {
future = std::async(std::launch::async, [timeout, compDisable, devId, dhId, status]() {
std::this_thread::sleep_for(std::chrono::milliseconds(timeout));
return compDisable->OnUnregisterResult(devId, dhId, status, "");
});
return DH_FWK_SUCCESS;
};
EXPECT_CALL(stub, UnregisterDistributedHardware(DEV_ID_TEST, DH_ID_TEST, testing::_))
.Times(1)
.WillOnce(testing::Invoke(handler));
auto start = std::chrono::system_clock::now();
auto ret = compDisable->Disable(DEV_ID_TEST, DH_ID_TEST, &stub);
auto diff = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - start).count();
DHLOGI("disable callback use time: %d (ms)", diff);
return ret;
}
/**
* @tc.name: init_test_001
* @tc.desc: Verify the Init function
* @tc.type: FUNC
* @tc.require: AR000GHSK5
*/
HWTEST_F(ComponentManagerTest, init_test_001, TestSize.Level0)
{
auto ret = ComponentManager::GetInstance().Init();
EXPECT_EQ(ERR_DH_FWK_COMPONENT_INIT_SOURCE_FAILED, ret);
}
/**
* @tc.name: init_test_002
* @tc.desc: Verify the Init function
* @tc.type: FUNC
* @tc.require: AR000GHSK5
*/
HWTEST_F(ComponentManagerTest, init_test_002, TestSize.Level0)
{
MockIDistributedHardwareSource cameraSource;
ComponentManager::GetInstance().compSource_.insert(std::make_pair(DHType::CAMERA, &cameraSource));
auto ret = ComponentManager::GetInstance().Init();
EXPECT_EQ(ERR_DH_FWK_COMPONENT_INIT_SINK_FAILED, ret);
}
/**
* @tc.name: init_test_003
* @tc.desc: Verify the Init function
* @tc.type: FUNC
* @tc.require: AR000GHSK5
*/
HWTEST_F(ComponentManagerTest, init_test_003, TestSize.Level0)
{
auto handler = [](std::string param) {
std::this_thread::sleep_for(std::chrono::milliseconds(EXECUTE_TIME_TEST));
return DH_FWK_SUCCESS;
};
MockIDistributedHardwareSource cameraSource;
ComponentManager::GetInstance().compSource_.insert(std::make_pair(DHType::CAMERA, &cameraSource));
EXPECT_CALL(cameraSource, InitSource(testing::_)).Times(1).WillOnce(testing::Invoke(handler));
MockIDistributedHardwareSource speakerSource;
ComponentManager::GetInstance().compSource_.insert(std::make_pair(DHType::SPEAKER, &speakerSource));
EXPECT_CALL(speakerSource, InitSource(testing::_)).Times(1).WillOnce(testing::Invoke(handler));
MockIDistributedHardwareSink micSink;
ComponentManager::GetInstance().compSink_.insert(std::make_pair(DHType::MIC, &micSink));
EXPECT_CALL(micSink, InitSink(testing::_)).Times(1).WillOnce(testing::Invoke(handler));
auto start = std::chrono::system_clock::now();
auto ret = ComponentManager::GetInstance().Init();
EXPECT_EQ(DH_FWK_SUCCESS, ret);
auto diff = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - start).count();
DHLOGI("Init use time: %d (ms)", diff);
ASSERT_TRUE(diff <= EXECUTE_TIME_TEST * 1.1);
}
/**
* @tc.name: unInit_test_001
* @tc.desc: Verify the UnInit function
* @tc.type: FUNC
* @tc.require: AR000GHSK5
*/
HWTEST_F(ComponentManagerTest, unInit_test_001, TestSize.Level0)
{
auto handler = []() {
std::this_thread::sleep_for(std::chrono::milliseconds(EXECUTE_TIME_TEST));
return DH_FWK_SUCCESS;
};
MockIDistributedHardwareSource cameraSource;
ComponentManager::GetInstance().compSource_.insert(std::make_pair(DHType::CAMERA, &cameraSource));
EXPECT_CALL(cameraSource, ReleaseSource()).Times(1).WillOnce(testing::Invoke(handler));
MockIDistributedHardwareSink speakerSink;
ComponentManager::GetInstance().compSink_.insert(std::make_pair(DHType::SPEAKER, &speakerSink));
EXPECT_CALL(speakerSink, ReleaseSink()).Times(1).WillOnce(testing::Invoke(handler));
MockIDistributedHardwareSink micSink;
ComponentManager::GetInstance().compSink_.insert(std::make_pair(DHType::MIC, &micSink));
EXPECT_CALL(micSink, ReleaseSink()).Times(1).WillOnce(testing::Invoke(handler));
auto start = std::chrono::system_clock::now();
auto ret = ComponentManager::GetInstance().UnInit();
EXPECT_EQ(DH_FWK_SUCCESS, ret);
auto diff = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - start).count();
DHLOGI("UnInit use time : %d (ms)", diff);
ASSERT_TRUE(diff <= EXECUTE_TIME_TEST * 1.1);
}
/**
* @tc.name: enable_test_001
* @tc.desc: Verify the Enable success
* @tc.type: FUNC
* @tc.require: AR000GHSK7
*/
HWTEST_F(ComponentManagerTest, enable_test_001, TestSize.Level0)
{
auto result = Enable(ENABLE_TIMEOUT_MS / 2, DH_FWK_SUCCESS);
EXPECT_EQ(DH_FWK_SUCCESS, result);
}
/**
* @tc.name: enable_test_002
* @tc.desc: Verify the Enable failed for register hardware failed
* @tc.type: FUNC
* @tc.require: AR000GHSK7
*/
HWTEST_F(ComponentManagerTest, enable_test_002, TestSize.Level0)
{
auto result = Enable(ENABLE_TIMEOUT_MS / 2, ERR_DH_FWK_COMPONENT_ENABLE_FAILED);
EXPECT_EQ(ERR_DH_FWK_COMPONENT_ENABLE_FAILED, result);
}
/**
* @tc.name: enable_test_003
* @tc.desc: Verify the Enable timeout
* @tc.type: FUNC
* @tc.require: AR000GHSK7
*/
HWTEST_F(ComponentManagerTest, enable_test_003, TestSize.Level0)
{
auto result = Enable(ENABLE_TIMEOUT_MS * 2, ERR_DH_FWK_COMPONENT_ENABLE_FAILED);
EXPECT_EQ(ERR_DH_FWK_COMPONENT_ENABLE_TIMEOUT, result);
}
/**
* @tc.name: enable_test_004
* @tc.desc: Verify the Enable for Multi-thread
* @tc.type: FUNC
* @tc.require: AR000GHSK7
*/
HWTEST_F(ComponentManagerTest, enable_test_004, TestSize.Level0)
{
auto handler = [this](int32_t time, int32_t status, int32_t expect) {
auto ret = this->Enable(time, status);
EXPECT_EQ(expect, ret);
};
std::thread thread1(handler, ENABLE_TIMEOUT_MS / 2, DH_FWK_SUCCESS, DH_FWK_SUCCESS);
std::thread thread2(handler, ENABLE_TIMEOUT_MS / 2, ERR_DH_FWK_COMPONENT_ENABLE_FAILED,
ERR_DH_FWK_COMPONENT_ENABLE_FAILED);
std::thread thread3(handler, ENABLE_TIMEOUT_MS * 3, DH_FWK_SUCCESS, ERR_DH_FWK_COMPONENT_ENABLE_TIMEOUT);
std::thread thread6(handler, ENABLE_TIMEOUT_MS / 10, DH_FWK_SUCCESS, DH_FWK_SUCCESS);
std::thread thread4(handler, ENABLE_TIMEOUT_MS / 10, ERR_DH_FWK_COMPONENT_ENABLE_FAILED,
ERR_DH_FWK_COMPONENT_ENABLE_FAILED);
std::thread thread5(handler, ENABLE_TIMEOUT_MS * 2, DH_FWK_SUCCESS, ERR_DH_FWK_COMPONENT_ENABLE_TIMEOUT);
thread1.join();
thread2.join();
thread3.join();
thread4.join();
thread5.join();
thread6.join();
}
/**
* @tc.name: disable_test_001
* @tc.desc: Verify the Disable success
* @tc.type: FUNC
* @tc.require: AR000GHSK9
*/
HWTEST_F(ComponentManagerTest, disable_test_001, TestSize.Level0)
{
auto result = Disable(DISABLE_TIMEOUT_MS / 2, DH_FWK_SUCCESS);
EXPECT_EQ(DH_FWK_SUCCESS, result);
}
/**
* @tc.name: disable_test_002
* @tc.desc: Verify the Disable failed
* @tc.type: FUNC
* @tc.require: AR000GHSK9
*/
HWTEST_F(ComponentManagerTest, disable_test_002, TestSize.Level0)
{
auto result = Disable(DISABLE_TIMEOUT_MS / 2, ERR_DH_FWK_COMPONENT_DISABLE_FAILED);
EXPECT_EQ(ERR_DH_FWK_COMPONENT_DISABLE_FAILED, result);
}
/**
* @tc.name: disable_test_003
* @tc.desc: Verify the Disable timeout
* @tc.type: FUNC
* @tc.require: AR000GHSK9
*/
HWTEST_F(ComponentManagerTest, disable_test_003, TestSize.Level0)
{
auto result = Disable(DISABLE_TIMEOUT_MS * 2, ERR_DH_FWK_COMPONENT_DISABLE_TIMEOUT);
EXPECT_EQ(ERR_DH_FWK_COMPONENT_DISABLE_TIMEOUT, result);
}
/**
* @tc.name: disable_test_004
* @tc.desc: Verify the Disable for Multi-thread
* @tc.type: FUNC
* @tc.require: AR000GHSK9
*/
HWTEST_F(ComponentManagerTest, disable_test_004, TestSize.Level0)
{
auto handler = [this](int32_t timeout, int32_t status, int32_t expect) {
auto result = this->Disable(timeout, status);
EXPECT_EQ(expect, result);
};
std::thread thread1(handler, DISABLE_TIMEOUT_MS / 2, DH_FWK_SUCCESS, DH_FWK_SUCCESS);
std::thread thread2(handler, DISABLE_TIMEOUT_MS / 2, ERR_DH_FWK_COMPONENT_DISABLE_FAILED,
ERR_DH_FWK_COMPONENT_DISABLE_FAILED);
std::thread thread3(handler, DISABLE_TIMEOUT_MS * 3, DH_FWK_SUCCESS, ERR_DH_FWK_COMPONENT_DISABLE_TIMEOUT);
std::thread thread4(handler, DISABLE_TIMEOUT_MS / 10, ERR_DH_FWK_COMPONENT_DISABLE_FAILED,
ERR_DH_FWK_COMPONENT_DISABLE_FAILED);
std::thread thread6(handler, DISABLE_TIMEOUT_MS / 10, DH_FWK_SUCCESS, DH_FWK_SUCCESS);
std::thread thread5(handler, DISABLE_TIMEOUT_MS * 2, DH_FWK_SUCCESS, ERR_DH_FWK_COMPONENT_DISABLE_TIMEOUT);
thread1.join();
thread2.join();
thread3.join();
thread4.join();
thread5.join();
thread6.join();
}
}
}

View File

@ -0,0 +1,172 @@
/*
* 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 "distributed_hardware_manager_test.h"
#include <chrono>
#include <thread>
#include <vector>
#include "constants.h"
#include "dh_context.h"
#include "distributed_hardware_errno.h"
#include "distributed_hardware_log.h"
#include "distributed_hardware_manager.h"
#include "task_board.h"
using namespace testing::ext;
namespace OHOS {
namespace DistributedHardware {
/* save networkId and deviceId */
const std::vector<std::pair<std::string, std::string>> TEST_DEVICES = {
{ "11111111111111111111111111111111", "22222222222222222222222222222222" },
{ "33333333333333333333333333333333", "44444444444444444444444444444444" },
};
constexpr uint16_t TEST_DEV_TYPE_PAD = 0x11;
void DistributedHardwareManagerTest::SetUpTestCase(void) {}
void DistributedHardwareManagerTest::TearDownTestCase(void) {}
void DistributedHardwareManagerTest::SetUp()
{
for (auto device : TEST_DEVICES) {
DHContext::GetInstance().RemoveOnlineDevice(device.second);
}
}
void DistributedHardwareManagerTest::TearDown() {}
/**
* @tc.name: sendOnLineEvent_test_001
* @tc.desc: Verify the SendOnLineEvent success
* @tc.type: FUNC
* @tc.require: AR000GHSJM
*/
HWTEST_F(DistributedHardwareManagerTest, sendOnLineEvent_test_001, TestSize.Level0)
{
auto onlineResult = DistributedHardwareManager::GetInstance().SendOnLineEvent(TEST_DEVICES[0].first,
TEST_DEVICES[0].second, TEST_DEV_TYPE_PAD);
ASSERT_EQ(DH_FWK_SUCCESS, onlineResult);
ASSERT_EQ(DH_FWK_SUCCESS, TaskBoard::GetInstance().WaitForALLTaskFinish());
ASSERT_TRUE(TaskBoard::GetInstance().IsAllTaskFinish());
}
/**
* @tc.name: sendOnLineEvent_test_002
* @tc.desc: Verify the SendOnLineEvent repeate online
* @tc.type: FUNC
* @tc.require: AR000GHSJM
*/
HWTEST_F(DistributedHardwareManagerTest, sendOnLineEvent_test_002, TestSize.Level0)
{
auto onlineResult = DistributedHardwareManager::GetInstance().SendOnLineEvent(TEST_DEVICES[0].first,
TEST_DEVICES[0].second, TEST_DEV_TYPE_PAD);
ASSERT_EQ(DH_FWK_SUCCESS, onlineResult);
onlineResult = DistributedHardwareManager::GetInstance().SendOnLineEvent(TEST_DEVICES[0].first,
TEST_DEVICES[0].second, TEST_DEV_TYPE_PAD);
ASSERT_EQ(ERR_DH_FWK_HARDWARE_MANAGER_DEVICE_REPEAT_ONLINE, onlineResult);
ASSERT_EQ(DH_FWK_SUCCESS, TaskBoard::GetInstance().WaitForALLTaskFinish());
ASSERT_TRUE(TaskBoard::GetInstance().IsAllTaskFinish());
}
/**
* @tc.name: sendOnLineEvent_test_003
* @tc.desc: Verify the SendOnLineEvent failed for deviceId is empty
* @tc.type: FUNC
* @tc.require: AR000GHSJM
*/
HWTEST_F(DistributedHardwareManagerTest, sendOnLineEvent_test_003, TestSize.Level0)
{
auto onlineResult = DistributedHardwareManager::GetInstance().SendOnLineEvent("", "", TEST_DEV_TYPE_PAD);
ASSERT_EQ(ERR_DH_FWK_REMOTE_NETWORK_ID_IS_EMPTY, onlineResult);
onlineResult =
DistributedHardwareManager::GetInstance().SendOnLineEvent(TEST_DEVICES[0].first, "", TEST_DEV_TYPE_PAD);
ASSERT_EQ(ERR_DH_FWK_REMOTE_DEVICE_ID_IS_EMPTY, onlineResult);
ASSERT_EQ(DH_FWK_SUCCESS, TaskBoard::GetInstance().WaitForALLTaskFinish());
ASSERT_TRUE(TaskBoard::GetInstance().IsAllTaskFinish());
}
/**
* @tc.name: sendOffLineEvent_test_001
* @tc.desc: Verify the SendOffLineEvent success
* @tc.type: FUNC
* @tc.require: AR000GHSJM
*/
HWTEST_F(DistributedHardwareManagerTest, sendOffLineEvent_test_001, TestSize.Level0)
{
auto onlineResult = DistributedHardwareManager::GetInstance().SendOnLineEvent(TEST_DEVICES[0].first,
TEST_DEVICES[0].second, TEST_DEV_TYPE_PAD);
ASSERT_EQ(DH_FWK_SUCCESS, onlineResult);
auto offlineResult = DistributedHardwareManager::GetInstance().SendOffLineEvent(TEST_DEVICES[0].first,
TEST_DEVICES[0].second, TEST_DEV_TYPE_PAD);
ASSERT_EQ(DH_FWK_SUCCESS, offlineResult);
ASSERT_EQ(DH_FWK_SUCCESS, TaskBoard::GetInstance().WaitForALLTaskFinish());
ASSERT_TRUE(TaskBoard::GetInstance().IsAllTaskFinish());
}
/**
* @tc.name: sendOffLineEvent_test_002
* @tc.desc: Verify the SendOffLineEvent repeat
* @tc.type: FUNC
* @tc.require: AR000GHSJM
*/
HWTEST_F(DistributedHardwareManagerTest, sendOffLineEvent_test_002, TestSize.Level0)
{
auto onlineResult = DistributedHardwareManager::GetInstance().SendOnLineEvent(TEST_DEVICES[0].first,
TEST_DEVICES[0].second, TEST_DEV_TYPE_PAD);
ASSERT_EQ(DH_FWK_SUCCESS, onlineResult);
auto offlineResult = DistributedHardwareManager::GetInstance().SendOffLineEvent(TEST_DEVICES[0].first,
TEST_DEVICES[0].second, TEST_DEV_TYPE_PAD);
ASSERT_EQ(DH_FWK_SUCCESS, offlineResult);
offlineResult = DistributedHardwareManager::GetInstance().SendOffLineEvent(TEST_DEVICES[0].first,
TEST_DEVICES[0].second, TEST_DEV_TYPE_PAD);
ASSERT_EQ(ERR_DH_FWK_HARDWARE_MANAGER_DEVICE_REPEAT_OFFLINE, offlineResult);
ASSERT_EQ(DH_FWK_SUCCESS, TaskBoard::GetInstance().WaitForALLTaskFinish());
ASSERT_TRUE(TaskBoard::GetInstance().IsAllTaskFinish());
}
/**
* @tc.name: sendOffLineEvent_test_003
* @tc.desc: Verify the SendOffLineEvent failed for deviceId is empty
* @tc.type: FUNC
* @tc.require: AR000GHSJM
*/
HWTEST_F(DistributedHardwareManagerTest, sendOffLineEvent_test_003, TestSize.Level0)
{
auto offlineResult =
DistributedHardwareManager::GetInstance().SendOffLineEvent("", "", TEST_DEV_TYPE_PAD);
ASSERT_EQ(ERR_DH_FWK_REMOTE_NETWORK_ID_IS_EMPTY, offlineResult);
offlineResult =
DistributedHardwareManager::GetInstance().SendOffLineEvent(TEST_DEVICES[0].first, "", TEST_DEV_TYPE_PAD);
ASSERT_EQ(ERR_DH_FWK_REMOTE_DEVICE_ID_IS_EMPTY, offlineResult);
ASSERT_EQ(DH_FWK_SUCCESS, TaskBoard::GetInstance().WaitForALLTaskFinish());
ASSERT_TRUE(TaskBoard::GetInstance().IsAllTaskFinish());
}
}
}

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 OHOS_DISTRIBUTED_HARDWARE_MANAGER_TEST_H
#define OHOS_DISTRIBUTED_HARDWARE_MANAGER_TEST_H
#include <gtest/gtest.h>
namespace OHOS {
namespace DistributedHardware {
class DistributedHardwareManagerTest : public testing::Test {
public:
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
};
}
}
#endif

View File

@ -0,0 +1,66 @@
# Copyright (c) 2021 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import("//build/test.gni")
import("//foundation/distributedhardware/distributedhardwarefwk/distributedhardwarefwk.gni")
module_out_path = "distributed_hardware_fwk/resource_manager_test"
config("module_private_config") {
visibility = [ ":*" ]
include_dirs = [
"include",
"${utils_path}/include",
"${utils_path}/include/log",
"${utils_path}/include/eventbus",
"${services_path}/distributedhardwarefwkserviceimpl/include",
"${services_path}/distributedhardwarefwkserviceimpl/include/resourcemanager",
"${services_path}/distributedhardwarefwkserviceimpl/include/utils",
"${common_path}/utils/include",
"${common_path}/log/include",
"//utils/native/base/include",
"//third_party/json/include",
"//utils/native/base/include",
"//utils/system/safwk/native/include"
]
}
## UnitTest resource_manager_test
ohos_unittest("ResourceManagerTest") {
module_out_path = module_out_path
sources = [
"src/resource_manager_test.cpp"
]
configs = [ ":module_private_config" ]
deps = [
"//third_party/googletest:gtest_main",
"//utils/native/base:utils",
"//foundation/distributedhardware/distributedhardwarefwk/utils:distributedhardwareutils",
"//foundation/distributedhardware/distributedhardwarefwk/services/distributedhardwarefwkserviceimpl:distributedhardwarefwksvr_impl"
]
external_deps = [
"bundle_framework:appexecfwk_base",
"bundle_framework:appexecfwk_core",
"eventhandler:libeventhandler",
"hiviewdfx_hilog_native:libhilog",
"distributeddatamgr:distributeddata_inner"
]
}
group("resource_manager_test") {
testonly = true
deps = [ ":ResourceManagerTest" ]
}

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 OHOS_DISTRIBUTED_HARDWARE_RESOURCE_MANAGER_TEST_H
#define OHOS_DISTRIBUTED_HARDWARE_RESOURCE_MANAGER_TEST_H
#include <gtest/gtest.h>
namespace OHOS {
namespace DistributedHardware {
class ResourceManagerTest : public testing::Test {
public:
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
};
}
}
#endif

View File

@ -0,0 +1,341 @@
/*
* 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 "resource_manager_test.h"
#include <vector>
#include "capability_info.h"
#define private public
#include "capability_info_manager.h"
#undef private
#include "dh_context.h"
#include "distributed_hardware_errno.h"
#include "distributed_hardware_log.h"
using namespace testing::ext;
using namespace std;
namespace OHOS {
namespace DistributedHardware {
#undef DH_LOG_TAG
#define DH_LOG_TAG "ResourceManagerTest"
namespace {
const string DEV_ID_0 = "bb536a637105409e904d4da83790a4a7";
const string DEV_ID_1 = "bb536a637105409e904d4da83790a4a8";
const string DEV_NAME = "Dev1";
const string DH_ID_0 = "Camera_0";
const string DH_ID_1 = "Mic_0";
const string DH_ID_2 = "Speaker_0";
const string DH_ID_3 = "Display_0";
const string DH_ID_4 = "Input_0";
const string DH_ATTR_0 = "attr0";
const string DH_ATTR_1 = "attr1";
constexpr uint16_t TEST_DEV_TYPE_PAD = 0x11;
constexpr uint32_t TEST_DH_TYPE_CAMERA = 0x01;
constexpr uint32_t TEST_DH_TYPE_MIC = 0x02;
constexpr uint32_t TEST_DH_TYPE_SPEAKER = 0x4;
constexpr uint32_t TEST_DH_TYPE_DISPLAY = 0x08;
constexpr uint32_t TEST_DH_TYPE_BUTTON = 0x20;
constexpr uint32_t TEST_SIZE_0 = 0;
constexpr uint32_t TEST_SIZE_2 = 2;
constexpr uint32_t TEST_SIZE_5 = 5;
constexpr uint32_t TEST_SIZE_10 = 10;
const std::string EMPTY_PREFIX = "";
const shared_ptr<CapabilityInfo> CAP_INFO_0 =
make_shared<CapabilityInfo>(DH_ID_0, DEV_ID_0, DEV_NAME, TEST_DEV_TYPE_PAD, DHType::CAMERA, DH_ATTR_0);
const shared_ptr<CapabilityInfo> CAP_INFO_1 =
make_shared<CapabilityInfo>(DH_ID_1, DEV_ID_0, DEV_NAME, TEST_DEV_TYPE_PAD, DHType::MIC, DH_ATTR_0);
const shared_ptr<CapabilityInfo> CAP_INFO_2 =
make_shared<CapabilityInfo>(DH_ID_2, DEV_ID_0, DEV_NAME, TEST_DEV_TYPE_PAD, DHType::SPEAKER, DH_ATTR_0);
const shared_ptr<CapabilityInfo> CAP_INFO_3 =
make_shared<CapabilityInfo>(DH_ID_3, DEV_ID_0, DEV_NAME, TEST_DEV_TYPE_PAD, DHType::DISPLAY, DH_ATTR_0);
const shared_ptr<CapabilityInfo> CAP_INFO_4 =
make_shared<CapabilityInfo>(DH_ID_4, DEV_ID_0, DEV_NAME, TEST_DEV_TYPE_PAD, DHType::BUTTON, DH_ATTR_0);
const shared_ptr<CapabilityInfo> CAP_INFO_5 =
make_shared<CapabilityInfo>(DH_ID_0, DEV_ID_1, DEV_NAME, TEST_DEV_TYPE_PAD, DHType::CAMERA, DH_ATTR_1);
const shared_ptr<CapabilityInfo> CAP_INFO_6 =
make_shared<CapabilityInfo>(DH_ID_1, DEV_ID_1, DEV_NAME, TEST_DEV_TYPE_PAD, DHType::MIC, DH_ATTR_1);
const shared_ptr<CapabilityInfo> CAP_INFO_7 =
make_shared<CapabilityInfo>(DH_ID_2, DEV_ID_1, DEV_NAME, TEST_DEV_TYPE_PAD, DHType::SPEAKER, DH_ATTR_1);
const shared_ptr<CapabilityInfo> CAP_INFO_8 =
make_shared<CapabilityInfo>(DH_ID_3, DEV_ID_1, DEV_NAME, TEST_DEV_TYPE_PAD, DHType::DISPLAY, DH_ATTR_1);
const shared_ptr<CapabilityInfo> CAP_INFO_9 =
make_shared<CapabilityInfo>(DH_ID_4, DEV_ID_1, DEV_NAME, TEST_DEV_TYPE_PAD, DHType::BUTTON, DH_ATTR_1);
}
void ResourceManagerTest::SetUpTestCase(void) {}
void ResourceManagerTest::TearDownTestCase(void) {}
void ResourceManagerTest::SetUp()
{
vector<shared_ptr<CapabilityInfo>> resInfos { CAP_INFO_0, CAP_INFO_1, CAP_INFO_2, CAP_INFO_3, CAP_INFO_4,
CAP_INFO_5, CAP_INFO_6, CAP_INFO_7, CAP_INFO_8, CAP_INFO_9 };
CapabilityInfoManager::GetInstance()->AddCapability(resInfos);
}
void ResourceManagerTest::TearDown()
{
CapabilityInfoManager::GetInstance()->RemoveCapabilityInfoByKey(CAP_INFO_0->GetKey());
CapabilityInfoManager::GetInstance()->RemoveCapabilityInfoByKey(CAP_INFO_1->GetKey());
CapabilityInfoManager::GetInstance()->RemoveCapabilityInfoByKey(CAP_INFO_2->GetKey());
CapabilityInfoManager::GetInstance()->RemoveCapabilityInfoByKey(CAP_INFO_3->GetKey());
CapabilityInfoManager::GetInstance()->RemoveCapabilityInfoByKey(CAP_INFO_4->GetKey());
CapabilityInfoManager::GetInstance()->RemoveCapabilityInfoByKey(CAP_INFO_5->GetKey());
CapabilityInfoManager::GetInstance()->RemoveCapabilityInfoByKey(CAP_INFO_6->GetKey());
CapabilityInfoManager::GetInstance()->RemoveCapabilityInfoByKey(CAP_INFO_7->GetKey());
CapabilityInfoManager::GetInstance()->RemoveCapabilityInfoByKey(CAP_INFO_8->GetKey());
CapabilityInfoManager::GetInstance()->RemoveCapabilityInfoByKey(CAP_INFO_9->GetKey());
}
/**
* @tc.name: resource_manager_test_001
* @tc.desc: Verify the CapabilityInfoManager UnInit function.
* @tc.type: FUNC
* @tc.require: AR000GHSJE
*/
HWTEST_F(ResourceManagerTest, resource_manager_test_001, TestSize.Level0)
{
EXPECT_EQ(CapabilityInfoManager::GetInstance()->Init(), DH_FWK_SUCCESS);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->UnInit(), DH_FWK_SUCCESS);
}
/**
* @tc.name: resource_manager_test_002
* @tc.desc: Verify the CapabilityInfoManager Init function.
* @tc.type: FUNC
* @tc.require: AR000GHSCV
*/
HWTEST_F(ResourceManagerTest, resource_manager_test_002, TestSize.Level0)
{
EXPECT_EQ(CapabilityInfoManager::GetInstance()->Init(), DH_FWK_SUCCESS);
}
/**
* @tc.name: resource_manager_test_003
* @tc.desc: Verify the CapabilityInfoManager SyncDeviceInfoFromDB function.
* @tc.type: FUNC
* @tc.require: AR000GHSJE
*/
HWTEST_F(ResourceManagerTest, resource_manager_test_003, TestSize.Level0)
{
CapabilityInfoManager::GetInstance()->globalCapInfoMap_.clear();
EXPECT_EQ(CapabilityInfoManager::GetInstance()->SyncDeviceInfoFromDB(DEV_ID_0), DH_FWK_SUCCESS);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->globalCapInfoMap_.size(), TEST_SIZE_5);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->SyncDeviceInfoFromDB(DEV_ID_1), DH_FWK_SUCCESS);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->globalCapInfoMap_.size(), TEST_SIZE_10);
}
/**
* @tc.name: resource_manager_test_004
* @tc.desc: Verify the CapabilityInfoManager SyncRemoteCapabilityInfos function.
* @tc.type: FUNC
* @tc.require: AR000GHSJE
*/
HWTEST_F(ResourceManagerTest, resource_manager_test_004, TestSize.Level0)
{
CapabilityInfoManager::GetInstance()->globalCapInfoMap_.clear();
EXPECT_EQ(CapabilityInfoManager::GetInstance()->SyncRemoteCapabilityInfos(), DH_FWK_SUCCESS);
}
/**
* @tc.name: resource_manager_test_005
* @tc.desc: Verify the CapabilityInfoManager AddCapability function.
* @tc.type: FUNC
* @tc.require: AR000GHSCV
*/
HWTEST_F(ResourceManagerTest, resource_manager_test_005, TestSize.Level0)
{
vector<shared_ptr<CapabilityInfo>> resInfos { CAP_INFO_0, CAP_INFO_1, CAP_INFO_2, CAP_INFO_3, CAP_INFO_4,
CAP_INFO_5, CAP_INFO_6, CAP_INFO_7, CAP_INFO_8, CAP_INFO_9 };
EXPECT_EQ(CapabilityInfoManager::GetInstance()->AddCapability(resInfos), DH_FWK_SUCCESS);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->globalCapInfoMap_.size(), TEST_SIZE_10);
}
/**
* @tc.name: resource_manager_test_006
* @tc.desc: Verify the CapabilityInfoManager AddCapabilityInMem function.
* @tc.type: FUNC
* @tc.require: AR000GHSCV
*/
HWTEST_F(ResourceManagerTest, resource_manager_test_006, TestSize.Level0)
{
vector<shared_ptr<CapabilityInfo>> resInfos { CAP_INFO_0, CAP_INFO_1, CAP_INFO_2, CAP_INFO_3, CAP_INFO_4,
CAP_INFO_5, CAP_INFO_6, CAP_INFO_7, CAP_INFO_8, CAP_INFO_9 };
EXPECT_EQ(CapabilityInfoManager::GetInstance()->AddCapabilityInMem(resInfos), DH_FWK_SUCCESS);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->globalCapInfoMap_.size(), TEST_SIZE_10);
}
/**
* @tc.name: resource_manager_test_007
* @tc.desc: Verify the CapabilityInfoManager RemoveCapabilityInfoByKey function.
* @tc.type: FUNC
* @tc.require: AR000GHSJE
*/
HWTEST_F(ResourceManagerTest, resource_manager_test_007, TestSize.Level0)
{
EXPECT_EQ(CapabilityInfoManager::GetInstance()->RemoveCapabilityInfoByKey(CAP_INFO_0->GetKey()), DH_FWK_SUCCESS);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->RemoveCapabilityInfoByKey(CAP_INFO_1->GetKey()), DH_FWK_SUCCESS);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->RemoveCapabilityInfoByKey(CAP_INFO_2->GetKey()), DH_FWK_SUCCESS);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->RemoveCapabilityInfoByKey(CAP_INFO_3->GetKey()), DH_FWK_SUCCESS);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->RemoveCapabilityInfoByKey(CAP_INFO_4->GetKey()), DH_FWK_SUCCESS);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->RemoveCapabilityInfoByKey(CAP_INFO_5->GetKey()), DH_FWK_SUCCESS);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->RemoveCapabilityInfoByKey(CAP_INFO_6->GetKey()), DH_FWK_SUCCESS);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->RemoveCapabilityInfoByKey(CAP_INFO_7->GetKey()), DH_FWK_SUCCESS);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->RemoveCapabilityInfoByKey(CAP_INFO_8->GetKey()), DH_FWK_SUCCESS);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->RemoveCapabilityInfoByKey(CAP_INFO_9->GetKey()), DH_FWK_SUCCESS);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->globalCapInfoMap_.size(), TEST_SIZE_0);
}
/**
* @tc.name: resource_manager_test_008
* @tc.desc: Verify the CapabilityInfoManager QueryCapabilityByFilters function.
* @tc.type: FUNC
* @tc.require: AR000GHSJE
*/
HWTEST_F(ResourceManagerTest, resource_manager_test_008, TestSize.Level0)
{
map<CapabilityInfoFilter, string> queryMap0 { { CapabilityInfoFilter::FILTER_DEVICE_ID, DEV_ID_0 } };
map<CapabilityInfoFilter, string> queryMap1 { { CapabilityInfoFilter::FILTER_DEVICE_ID, DEV_ID_1 } };
map<CapabilityInfoFilter, string> queryMap2 { { CapabilityInfoFilter::FILTER_DEVICE_NAME, DEV_NAME } };
map<CapabilityInfoFilter, string> queryMap3 { { CapabilityInfoFilter::FILTER_DH_ID, DH_ID_0 } };
map<CapabilityInfoFilter, string> queryMap4 { { CapabilityInfoFilter::FILTER_DH_ID, DH_ID_1 } };
map<CapabilityInfoFilter, string> queryMap5 { { CapabilityInfoFilter::FILTER_DH_ID, DH_ID_2 } };
map<CapabilityInfoFilter, string> queryMap6 { { CapabilityInfoFilter::FILTER_DH_ID, DH_ID_3 } };
map<CapabilityInfoFilter, string> queryMap7 { { CapabilityInfoFilter::FILTER_DH_ID, DH_ID_4 } };
map<CapabilityInfoFilter, string> queryMap8 { { CapabilityInfoFilter::FILTER_DEVICE_TYPE,
to_string(TEST_DEV_TYPE_PAD) } };
map<CapabilityInfoFilter, string> queryMap9 { { CapabilityInfoFilter::FILTER_DH_TYPE,
to_string(TEST_DH_TYPE_CAMERA) } };
map<CapabilityInfoFilter, string> queryMap10 { { CapabilityInfoFilter::FILTER_DH_TYPE,
to_string(TEST_DH_TYPE_MIC) } };
map<CapabilityInfoFilter, string> queryMap11 { { CapabilityInfoFilter::FILTER_DH_TYPE,
to_string(TEST_DH_TYPE_SPEAKER) } };
map<CapabilityInfoFilter, string> queryMap12 { { CapabilityInfoFilter::FILTER_DH_TYPE,
to_string(TEST_DH_TYPE_DISPLAY) } };
map<CapabilityInfoFilter, string> queryMap13 { { CapabilityInfoFilter::FILTER_DH_TYPE,
to_string(TEST_DH_TYPE_BUTTON) } };
EXPECT_EQ(CapabilityInfoManager::GetInstance()->QueryCapabilityByFilters(queryMap0).size(), TEST_SIZE_5);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->QueryCapabilityByFilters(queryMap1).size(), TEST_SIZE_5);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->QueryCapabilityByFilters(queryMap2).size(), TEST_SIZE_10);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->QueryCapabilityByFilters(queryMap3).size(), TEST_SIZE_2);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->QueryCapabilityByFilters(queryMap4).size(), TEST_SIZE_2);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->QueryCapabilityByFilters(queryMap5).size(), TEST_SIZE_2);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->QueryCapabilityByFilters(queryMap6).size(), TEST_SIZE_2);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->QueryCapabilityByFilters(queryMap7).size(), TEST_SIZE_2);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->QueryCapabilityByFilters(queryMap8).size(), TEST_SIZE_10);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->QueryCapabilityByFilters(queryMap9).size(), TEST_SIZE_2);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->QueryCapabilityByFilters(queryMap10).size(), TEST_SIZE_2);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->QueryCapabilityByFilters(queryMap11).size(), TEST_SIZE_2);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->QueryCapabilityByFilters(queryMap12).size(), TEST_SIZE_2);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->QueryCapabilityByFilters(queryMap13).size(), TEST_SIZE_2);
}
/**
* @tc.name: resource_manager_test_009
* @tc.desc: Verify the HasCapability function.
* @tc.type: FUNC
* @tc.require: AR000GHSCV
*/
HWTEST_F(ResourceManagerTest, resource_manager_test_009, TestSize.Level0)
{
EXPECT_EQ(CapabilityInfoManager::GetInstance()->HasCapability(DEV_ID_0, DH_ID_0), true);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->HasCapability(DEV_ID_0, DH_ID_1), true);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->HasCapability(DEV_ID_0, DH_ID_2), true);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->HasCapability(DEV_ID_0, DH_ID_3), true);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->HasCapability(DEV_ID_0, DH_ID_4), true);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->HasCapability(DEV_ID_1, DH_ID_0), true);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->HasCapability(DEV_ID_1, DH_ID_1), true);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->HasCapability(DEV_ID_1, DH_ID_2), true);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->HasCapability(DEV_ID_1, DH_ID_3), true);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->HasCapability(DEV_ID_1, DH_ID_4), true);
}
/**
* @tc.name: resource_manager_test_010
* @tc.desc: Verify the GetCapabilitiesByDeviceId function.
* @tc.type: FUNC
* @tc.require: AR000GHSJE
*/
HWTEST_F(ResourceManagerTest, resource_manager_test_010, TestSize.Level0)
{
vector<shared_ptr<CapabilityInfo>> capInfos;
CapabilityInfoManager::GetInstance()->GetCapabilitiesByDeviceId(DEV_ID_0, capInfos);
EXPECT_EQ(capInfos.size(), TEST_SIZE_5);
CapabilityInfoManager::GetInstance()->GetCapabilitiesByDeviceId(DEV_ID_1, capInfos);
EXPECT_EQ(capInfos.size(), TEST_SIZE_10);
}
/**
* @tc.name: resource_manager_test_011
* @tc.desc: Verify the GetCapability function.
* @tc.type: FUNC
* @tc.require: AR000GHSJE
*/
HWTEST_F(ResourceManagerTest, resource_manager_test_011, TestSize.Level0)
{
shared_ptr<CapabilityInfo> capInfo;
EXPECT_EQ(CapabilityInfoManager::GetInstance()->GetCapability(DEV_ID_0, DH_ID_0, capInfo), DH_FWK_SUCCESS);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->GetCapability(DEV_ID_0, DH_ID_1, capInfo), DH_FWK_SUCCESS);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->GetCapability(DEV_ID_0, DH_ID_2, capInfo), DH_FWK_SUCCESS);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->GetCapability(DEV_ID_0, DH_ID_3, capInfo), DH_FWK_SUCCESS);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->GetCapability(DEV_ID_0, DH_ID_4, capInfo), DH_FWK_SUCCESS);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->GetCapability(DEV_ID_1, DH_ID_0, capInfo), DH_FWK_SUCCESS);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->GetCapability(DEV_ID_1, DH_ID_1, capInfo), DH_FWK_SUCCESS);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->GetCapability(DEV_ID_1, DH_ID_2, capInfo), DH_FWK_SUCCESS);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->GetCapability(DEV_ID_1, DH_ID_3, capInfo), DH_FWK_SUCCESS);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->GetCapability(DEV_ID_1, DH_ID_4, capInfo), DH_FWK_SUCCESS);
}
/**
* @tc.name: resource_manager_test_012
* @tc.desc: Verify the GetDataByKey function.
* @tc.type: FUNC
* @tc.require: AR000GHSJE
*/
HWTEST_F(ResourceManagerTest, resource_manager_test_012, TestSize.Level0)
{
shared_ptr<CapabilityInfo> capInfo;
EXPECT_EQ(CapabilityInfoManager::GetInstance()->GetDataByKey(CAP_INFO_0->GetKey(), capInfo), DH_FWK_SUCCESS);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->GetDataByKey(CAP_INFO_1->GetKey(), capInfo), DH_FWK_SUCCESS);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->GetDataByKey(CAP_INFO_2->GetKey(), capInfo), DH_FWK_SUCCESS);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->GetDataByKey(CAP_INFO_3->GetKey(), capInfo), DH_FWK_SUCCESS);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->GetDataByKey(CAP_INFO_4->GetKey(), capInfo), DH_FWK_SUCCESS);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->GetDataByKey(CAP_INFO_5->GetKey(), capInfo), DH_FWK_SUCCESS);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->GetDataByKey(CAP_INFO_6->GetKey(), capInfo), DH_FWK_SUCCESS);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->GetDataByKey(CAP_INFO_7->GetKey(), capInfo), DH_FWK_SUCCESS);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->GetDataByKey(CAP_INFO_8->GetKey(), capInfo), DH_FWK_SUCCESS);
EXPECT_EQ(CapabilityInfoManager::GetInstance()->GetDataByKey(CAP_INFO_9->GetKey(), capInfo), DH_FWK_SUCCESS);
}
/**
* @tc.name: resource_manager_test_013
* @tc.desc: Verify the GetDataByKeyPrefix function.
* @tc.type: FUNC
* @tc.require: AR000GHSJE
*/
HWTEST_F(ResourceManagerTest, resource_manager_test_013, TestSize.Level0)
{
CapabilityInfoMap capMap;
EXPECT_EQ(CapabilityInfoManager::GetInstance()->GetDataByKeyPrefix(EMPTY_PREFIX, capMap), DH_FWK_SUCCESS);
EXPECT_EQ(capMap.size(), TEST_SIZE_10);
}
}
}

View File

@ -0,0 +1,64 @@
# 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")
import("//foundation/distributedhardware/distributedhardwarefwk/distributedhardwarefwk.gni")
module_out_path = "distributed_hardware_fwk/dh_task_test"
config("module_private_config") {
visibility = [ ":*" ]
include_dirs = [
"include",
"${utils_path}/include",
"${utils_path}/include/log",
"${services_path}/distributedhardwarefwkserviceimpl/include",
"${services_path}/distributedhardwarefwkserviceimpl/include/task",
"${services_path}/distributedhardwarefwkserviceimpl/include/utils",
"${common_path}/utils/include",
"${common_path}/log/include",
"//utils/native/base/include",
]
}
## UnitTest dh_task_test
ohos_unittest("DHTaskTest") {
module_out_path = module_out_path
sources = [
"src/mock_disable_task.cpp",
"src/mock_enable_task.cpp",
"src/mock_offline_task.cpp",
"src/mock_online_task.cpp",
"src/mock_task_factory.cpp",
"src/task_test.cpp"
]
configs = [ ":module_private_config" ]
deps = [
"//third_party/googletest:gtest_main",
"//foundation/distributedhardware/distributedhardwarefwk/utils:distributedhardwareutils",
"//foundation/distributedhardware/distributedhardwarefwk/services/distributedhardwarefwkserviceimpl:distributedhardwarefwksvr_impl"
]
defines = [
"HI_LOG_ENABLE",
"DH_LOG_TAG=\"TaskTest\"",
"LOG_DOMAIN=0xD004100",
]
}
group("dh_task_test") {
testonly = true
deps = [ ":DHTaskTest" ]
}

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 OHOS_DISTRIBUTED_HARDWARE_MOCK_DISABLE_TASK_H
#define OHOS_DISTRIBUTED_HARDWARE_MOCK_DISABLE_TASK_H
#include "disable_task.h"
namespace OHOS {
namespace DistributedHardware {
class MockDisableTask : public DisableTask {
public:
MockDisableTask() = delete;
MockDisableTask(const std::string &networkId, const std::string &devId, const std::string &dhId);
private:
/* synchronous function for unregister distributed hardware, return on asynchronous unregister finish */
int32_t UnRegisterHardware();
};
}
}
#endif

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 OHOS_DISTRIBUTED_HARDWARE_MOCK_ENABLE_TASK_H
#define OHOS_DISTRIBUTED_HARDWARE_MOCK_ENABLE_TASK_H
#include "enable_task.h"
namespace OHOS {
namespace DistributedHardware {
class MockEnableTask : public EnableTask {
public:
MockEnableTask() = delete;
MockEnableTask(const std::string &networkId, const std::string &devId, const std::string &dhId);
private:
/* synchronous function for register distributed hardware, return on asynchronous register finish */
int32_t RegisterHardware();
};
}
}
#endif

View File

@ -0,0 +1,40 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DISTRIBUTED_HARDWARE_MOCK_OFFLINE_TASK_H
#define OHOS_DISTRIBUTED_HARDWARE_MOCK_OFFLINE_TASK_H
#include "mock_task_utils.h"
#include "offline_task.h"
namespace OHOS {
namespace DistributedHardware {
class MockOffLineTask : public OffLineTask {
public:
MockOffLineTask() = delete;
MockOffLineTask(const std::string &networkId, const std::string &devId, const std::string &dhId);
void SetOffLineDevInfos(std::vector<MockDevInfo> offLineDevInfos);
private:
/* create disable tasks for off line device */
void CreateDisableTask();
/* clear off line device info */
void ClearOffLineInfo();
std::vector<MockDevInfo> offLineDevInfos;
};
}
}
#endif

View File

@ -0,0 +1,40 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DISTRIBUTED_HARDWARE_MOCK_ONLINE_TASK_H
#define OHOS_DISTRIBUTED_HARDWARE_MOCK_ONLINE_TASK_H
#include <vector>
#include "mock_task_utils.h"
#include "online_task.h"
namespace OHOS {
namespace DistributedHardware {
class MockOnLineTask : public OnLineTask {
public:
MockOnLineTask() = delete;
MockOnLineTask(const std::string &networkId, const std::string &devId, const std::string &dhId);
void SetOnLineDevInfos(std::vector<MockDevInfo> devInfos);
private:
void DoSyncInfo();
void CreateEnableTask();
std::vector<MockDevInfo> onLineDevInfos;
};
}
}
#endif

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 OHOS_DISTRIBUTED_HARDWARE_MOCK_TASK_FACTORY_H
#define OHOS_DISTRIBUTED_HARDWARE_MOCK_TASK_FACTORY_H
#include <memory>
#include "single_instance.h"
#include "task.h"
namespace OHOS {
namespace DistributedHardware {
class MockTaskFactory {
DECLARE_SINGLE_INSTANCE(MockTaskFactory);
public:
std::shared_ptr<Task> CreateTask(TaskType taskType, const std::string &networkId, const std::string &devId,
const std::string &dhId, std::shared_ptr<Task> fatherTask);
};
}
}
#endif

View File

@ -0,0 +1,30 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DISTRIBUTED_HARDWARE_MOCK_TASK_UTILS_H
#define OHOS_DISTRIBUTED_HARDWARE_MOCK_TASK_UTILS_H
#include <string>
namespace OHOS {
namespace DistributedHardware {
struct MockDevInfo {
std::string networkId;
std::string devId;
std::string dhId;
};
}
}
#endif

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 OHOS_DISTRIBUTED_HARDWARE_TASK_TEST_H
#define OHOS_DISTRIBUTED_HARDWARE_TASK_TEST_H
#include <gtest/gtest.h>
namespace OHOS {
namespace DistributedHardware {
class TaskTest : public testing::Test {
public:
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
};
}
}
#endif

Some files were not shown because too many files have changed in this diff Show More