From 536b611b9a56f18a68eb3045a3db0238541ee9b5 Mon Sep 17 00:00:00 2001 From: hwzhangchuang Date: Mon, 28 Feb 2022 19:29:56 +0800 Subject: [PATCH 1/5] add distributed_hardware_fwk base code to sig Signed-off-by: hwzhangchuang --- LICENSE | 178 ++++++ OAT.xml | 65 +++ README.md | 39 -- README_zh.md | 73 +++ bundle.json | 54 ++ common/log/include/distributed_hardware_log.h | 38 ++ common/utils/include/constants.h | 47 ++ common/utils/include/device_type.h | 48 ++ .../include/distributed_hardware_errno.h | 91 +++ common/utils/include/idistributed_hardware.h | 40 ++ .../include/idistributed_hardware_manager.h | 40 ++ .../include/idistributed_hardware_sink.h | 39 ++ .../include/idistributed_hardware_source.h | 56 ++ common/utils/include/ihardware_handler.h | 49 ++ common/utils/include/single_instance.h | 44 ++ distributedhardwarefwk.gni | 24 + figures/distributedhardwarefwk_arch.png | Bin 0 -> 29401 bytes sa_profile/4801.xml | 27 + sa_profile/BUILD.gn | 20 + .../distributedhardwarefwkservice/BUILD.gn | 77 +++ .../distributedhardware_fwk.cfg | 15 + .../include/accessmanager/access_manager.h | 65 +++ .../distributed_hardware_manager_factory.h | 48 ++ .../include/distributed_hardware_service.h | 52 ++ .../include/distributed_hardware_stub.h | 30 + .../src/accessmanager/access_manager.cpp | 164 ++++++ .../distributed_hardware_manager_factory.cpp | 190 +++++++ .../src/distributed_hardware_service.cpp | 85 +++ .../src/distributed_hardware_stub.cpp | 68 +++ .../test/unittest/BUILD.gn | 18 + .../unittest/common/accessmanager/BUILD.gn | 73 +++ .../accessmanager/access_manager_test.cpp | 264 +++++++++ .../BUILD.gn | 91 +++ .../componentloader/component_loader.h | 88 +++ .../componentmanager/component_disable.h | 42 ++ .../componentmanager/component_enable.h | 42 ++ .../componentmanager/component_manager.h | 78 +++ .../include/distributed_hardware_manager.h | 37 ++ .../include/distributed_hardware_proxy.h | 44 ++ .../local_hardware_manager.h | 52 ++ .../include/resourcemanager/capability_info.h | 91 +++ .../resourcemanager/capability_info_event.h | 55 ++ .../resourcemanager/capability_info_manager.h | 115 ++++ .../resourcemanager/capability_utils.h | 42 ++ .../include/resourcemanager/db_adapter.h | 89 +++ .../include/task/disable_task.h | 36 ++ .../include/task/enable_task.h | 36 ++ .../include/task/offline_task.h | 54 ++ .../include/task/online_task.h | 36 ++ .../include/task/task.h | 70 +++ .../include/task/task_board.h | 48 ++ .../include/task/task_executor.h | 47 ++ .../include/task/task_factory.h | 34 ++ .../include/utils/dh_context.h | 56 ++ .../include/utils/impl_utils.h | 65 +++ .../include/versionmanager/version_manager.h | 52 ++ .../src/componentloader/component_loader.cpp | 322 +++++++++++ .../componentmanager/component_disable.cpp | 78 +++ .../src/componentmanager/component_enable.cpp | 78 +++ .../componentmanager/component_manager.cpp | 350 ++++++++++++ .../src/distributed_hardware_manager.cpp | 164 ++++++ .../src/distributed_hardware_proxy.cpp | 73 +++ .../local_hardware_manager.cpp | 100 ++++ .../src/resourcemanager/capability_info.cpp | 155 +++++ .../capability_info_manager.cpp | 528 ++++++++++++++++++ .../src/resourcemanager/capability_utils.cpp | 54 ++ .../src/resourcemanager/db_adapter.cpp | 413 ++++++++++++++ .../src/task/disable_task.cpp | 72 +++ .../src/task/enable_task.cpp | 64 +++ .../src/task/offline_task.cpp | 133 +++++ .../src/task/online_task.cpp | 102 ++++ .../src/task/task.cpp | 104 ++++ .../src/task/task_board.cpp | 89 +++ .../src/task/task_executor.cpp | 91 +++ .../src/task/task_factory.cpp | 70 +++ .../src/utils/dh_context.cpp | 89 +++ .../src/versionmanager/version_manager.cpp | 116 ++++ .../test/unittest/BUILD.gn | 24 + .../test/unittest/common/BUILD.gn | 68 +++ .../unittest/common/componentloader/BUILD.gn | 57 ++ .../include/component_loader_test.h | 32 ++ .../src/component_loader_test.cpp | 154 +++++ .../unittest/common/componentmanager/BUILD.gn | 63 +++ .../include/component_manager_test.h | 34 ++ .../include/mock_idistributed_hardware_sink.h | 44 ++ .../mock_idistributed_hardware_source.h | 44 ++ .../src/component_manager_test.cpp | 343 ++++++++++++ .../distributed_hardware_manager_test.cpp | 172 ++++++ .../distributed_hardware_manager_test.h | 32 ++ .../unittest/common/resourcemanager/BUILD.gn | 66 +++ .../include/resource_manager_test.h | 32 ++ .../src/resource_manager_test.cpp | 341 +++++++++++ .../test/unittest/common/task/BUILD.gn | 64 +++ .../common/task/include/mock_disable_task.h | 34 ++ .../common/task/include/mock_enable_task.h | 34 ++ .../common/task/include/mock_offline_task.h | 40 ++ .../common/task/include/mock_online_task.h | 40 ++ .../common/task/include/mock_task_factory.h | 34 ++ .../common/task/include/mock_task_utils.h | 30 + .../unittest/common/task/include/task_test.h | 32 ++ .../common/task/src/mock_disable_task.cpp | 37 ++ .../common/task/src/mock_enable_task.cpp | 36 ++ .../common/task/src/mock_offline_task.cpp | 52 ++ .../common/task/src/mock_online_task.cpp | 54 ++ .../common/task/src/mock_task_factory.cpp | 64 +++ .../unittest/common/task/src/task_test.cpp | 158 ++++++ .../unittest/common/versionmanager/BUILD.gn | 58 ++ .../include/version_manager_test.h | 35 ++ .../src/version_manager_test.cpp | 158 ++++++ utils/BUILD.gn | 53 ++ utils/include/anonymous_string.h | 27 + utils/include/dh_utils_tool.h | 41 ++ utils/include/eventbus/event.h | 49 ++ utils/include/eventbus/event_bus.h | 206 +++++++ utils/include/eventbus/event_registration.h | 50 ++ utils/include/eventbus/event_sender.h | 27 + utils/include/eventbus/eventbus_handler.h | 39 ++ utils/include/log/dh_log.h | 43 ++ utils/src/anonymous_string.cpp | 71 +++ utils/src/dh_utils_tool.cpp | 95 ++++ utils/src/log/dh_log.cpp | 87 +++ utils/test/unittest/BUILD.gn | 20 + utils/test/unittest/common/eventbus/BUILD.gn | 50 ++ .../common/eventbus/event_bus_test.cpp | 151 +++++ .../unittest/common/eventbus/event_bus_test.h | 109 ++++ utils/test/unittest/common/utilstool/BUILD.gn | 46 ++ .../common/utilstool/utils_tool_test.cpp | 121 ++++ .../common/utilstool/utils_tool_test.h | 32 ++ 128 files changed, 10510 insertions(+), 39 deletions(-) create mode 100644 LICENSE create mode 100644 OAT.xml delete mode 100644 README.md create mode 100644 README_zh.md create mode 100644 bundle.json create mode 100644 common/log/include/distributed_hardware_log.h create mode 100644 common/utils/include/constants.h create mode 100644 common/utils/include/device_type.h create mode 100644 common/utils/include/distributed_hardware_errno.h create mode 100644 common/utils/include/idistributed_hardware.h create mode 100644 common/utils/include/idistributed_hardware_manager.h create mode 100644 common/utils/include/idistributed_hardware_sink.h create mode 100644 common/utils/include/idistributed_hardware_source.h create mode 100644 common/utils/include/ihardware_handler.h create mode 100644 common/utils/include/single_instance.h create mode 100644 distributedhardwarefwk.gni create mode 100644 figures/distributedhardwarefwk_arch.png create mode 100644 sa_profile/4801.xml create mode 100644 sa_profile/BUILD.gn create mode 100644 services/distributedhardwarefwkservice/BUILD.gn create mode 100644 services/distributedhardwarefwkservice/distributedhardware_fwk.cfg create mode 100644 services/distributedhardwarefwkservice/include/accessmanager/access_manager.h create mode 100644 services/distributedhardwarefwkservice/include/distributed_hardware_manager_factory.h create mode 100644 services/distributedhardwarefwkservice/include/distributed_hardware_service.h create mode 100644 services/distributedhardwarefwkservice/include/distributed_hardware_stub.h create mode 100644 services/distributedhardwarefwkservice/src/accessmanager/access_manager.cpp create mode 100644 services/distributedhardwarefwkservice/src/distributed_hardware_manager_factory.cpp create mode 100644 services/distributedhardwarefwkservice/src/distributed_hardware_service.cpp create mode 100644 services/distributedhardwarefwkservice/src/distributed_hardware_stub.cpp create mode 100644 services/distributedhardwarefwkservice/test/unittest/BUILD.gn create mode 100644 services/distributedhardwarefwkservice/test/unittest/common/accessmanager/BUILD.gn create mode 100644 services/distributedhardwarefwkservice/test/unittest/common/accessmanager/access_manager_test.cpp create mode 100644 services/distributedhardwarefwkserviceimpl/BUILD.gn create mode 100644 services/distributedhardwarefwkserviceimpl/include/componentloader/component_loader.h create mode 100644 services/distributedhardwarefwkserviceimpl/include/componentmanager/component_disable.h create mode 100644 services/distributedhardwarefwkserviceimpl/include/componentmanager/component_enable.h create mode 100644 services/distributedhardwarefwkserviceimpl/include/componentmanager/component_manager.h create mode 100644 services/distributedhardwarefwkserviceimpl/include/distributed_hardware_manager.h create mode 100644 services/distributedhardwarefwkserviceimpl/include/distributed_hardware_proxy.h create mode 100644 services/distributedhardwarefwkserviceimpl/include/localhardwaremanager/local_hardware_manager.h create mode 100644 services/distributedhardwarefwkserviceimpl/include/resourcemanager/capability_info.h create mode 100644 services/distributedhardwarefwkserviceimpl/include/resourcemanager/capability_info_event.h create mode 100644 services/distributedhardwarefwkserviceimpl/include/resourcemanager/capability_info_manager.h create mode 100644 services/distributedhardwarefwkserviceimpl/include/resourcemanager/capability_utils.h create mode 100644 services/distributedhardwarefwkserviceimpl/include/resourcemanager/db_adapter.h create mode 100644 services/distributedhardwarefwkserviceimpl/include/task/disable_task.h create mode 100644 services/distributedhardwarefwkserviceimpl/include/task/enable_task.h create mode 100644 services/distributedhardwarefwkserviceimpl/include/task/offline_task.h create mode 100644 services/distributedhardwarefwkserviceimpl/include/task/online_task.h create mode 100644 services/distributedhardwarefwkserviceimpl/include/task/task.h create mode 100644 services/distributedhardwarefwkserviceimpl/include/task/task_board.h create mode 100644 services/distributedhardwarefwkserviceimpl/include/task/task_executor.h create mode 100644 services/distributedhardwarefwkserviceimpl/include/task/task_factory.h create mode 100644 services/distributedhardwarefwkserviceimpl/include/utils/dh_context.h create mode 100644 services/distributedhardwarefwkserviceimpl/include/utils/impl_utils.h create mode 100644 services/distributedhardwarefwkserviceimpl/include/versionmanager/version_manager.h create mode 100644 services/distributedhardwarefwkserviceimpl/src/componentloader/component_loader.cpp create mode 100644 services/distributedhardwarefwkserviceimpl/src/componentmanager/component_disable.cpp create mode 100644 services/distributedhardwarefwkserviceimpl/src/componentmanager/component_enable.cpp create mode 100644 services/distributedhardwarefwkserviceimpl/src/componentmanager/component_manager.cpp create mode 100644 services/distributedhardwarefwkserviceimpl/src/distributed_hardware_manager.cpp create mode 100644 services/distributedhardwarefwkserviceimpl/src/distributed_hardware_proxy.cpp create mode 100644 services/distributedhardwarefwkserviceimpl/src/localhardwaremanager/local_hardware_manager.cpp create mode 100644 services/distributedhardwarefwkserviceimpl/src/resourcemanager/capability_info.cpp create mode 100644 services/distributedhardwarefwkserviceimpl/src/resourcemanager/capability_info_manager.cpp create mode 100644 services/distributedhardwarefwkserviceimpl/src/resourcemanager/capability_utils.cpp create mode 100644 services/distributedhardwarefwkserviceimpl/src/resourcemanager/db_adapter.cpp create mode 100644 services/distributedhardwarefwkserviceimpl/src/task/disable_task.cpp create mode 100644 services/distributedhardwarefwkserviceimpl/src/task/enable_task.cpp create mode 100644 services/distributedhardwarefwkserviceimpl/src/task/offline_task.cpp create mode 100644 services/distributedhardwarefwkserviceimpl/src/task/online_task.cpp create mode 100644 services/distributedhardwarefwkserviceimpl/src/task/task.cpp create mode 100644 services/distributedhardwarefwkserviceimpl/src/task/task_board.cpp create mode 100644 services/distributedhardwarefwkserviceimpl/src/task/task_executor.cpp create mode 100644 services/distributedhardwarefwkserviceimpl/src/task/task_factory.cpp create mode 100644 services/distributedhardwarefwkserviceimpl/src/utils/dh_context.cpp create mode 100644 services/distributedhardwarefwkserviceimpl/src/versionmanager/version_manager.cpp create mode 100644 services/distributedhardwarefwkserviceimpl/test/unittest/BUILD.gn create mode 100644 services/distributedhardwarefwkserviceimpl/test/unittest/common/BUILD.gn create mode 100644 services/distributedhardwarefwkserviceimpl/test/unittest/common/componentloader/BUILD.gn create mode 100644 services/distributedhardwarefwkserviceimpl/test/unittest/common/componentloader/include/component_loader_test.h create mode 100644 services/distributedhardwarefwkserviceimpl/test/unittest/common/componentloader/src/component_loader_test.cpp create mode 100644 services/distributedhardwarefwkserviceimpl/test/unittest/common/componentmanager/BUILD.gn create mode 100644 services/distributedhardwarefwkserviceimpl/test/unittest/common/componentmanager/include/component_manager_test.h create mode 100644 services/distributedhardwarefwkserviceimpl/test/unittest/common/componentmanager/include/mock_idistributed_hardware_sink.h create mode 100644 services/distributedhardwarefwkserviceimpl/test/unittest/common/componentmanager/include/mock_idistributed_hardware_source.h create mode 100644 services/distributedhardwarefwkserviceimpl/test/unittest/common/componentmanager/src/component_manager_test.cpp create mode 100644 services/distributedhardwarefwkserviceimpl/test/unittest/common/distributed_hardware_manager_test.cpp create mode 100644 services/distributedhardwarefwkserviceimpl/test/unittest/common/distributed_hardware_manager_test.h create mode 100644 services/distributedhardwarefwkserviceimpl/test/unittest/common/resourcemanager/BUILD.gn create mode 100644 services/distributedhardwarefwkserviceimpl/test/unittest/common/resourcemanager/include/resource_manager_test.h create mode 100644 services/distributedhardwarefwkserviceimpl/test/unittest/common/resourcemanager/src/resource_manager_test.cpp create mode 100644 services/distributedhardwarefwkserviceimpl/test/unittest/common/task/BUILD.gn create mode 100644 services/distributedhardwarefwkserviceimpl/test/unittest/common/task/include/mock_disable_task.h create mode 100644 services/distributedhardwarefwkserviceimpl/test/unittest/common/task/include/mock_enable_task.h create mode 100644 services/distributedhardwarefwkserviceimpl/test/unittest/common/task/include/mock_offline_task.h create mode 100644 services/distributedhardwarefwkserviceimpl/test/unittest/common/task/include/mock_online_task.h create mode 100644 services/distributedhardwarefwkserviceimpl/test/unittest/common/task/include/mock_task_factory.h create mode 100644 services/distributedhardwarefwkserviceimpl/test/unittest/common/task/include/mock_task_utils.h create mode 100644 services/distributedhardwarefwkserviceimpl/test/unittest/common/task/include/task_test.h create mode 100644 services/distributedhardwarefwkserviceimpl/test/unittest/common/task/src/mock_disable_task.cpp create mode 100644 services/distributedhardwarefwkserviceimpl/test/unittest/common/task/src/mock_enable_task.cpp create mode 100644 services/distributedhardwarefwkserviceimpl/test/unittest/common/task/src/mock_offline_task.cpp create mode 100644 services/distributedhardwarefwkserviceimpl/test/unittest/common/task/src/mock_online_task.cpp create mode 100644 services/distributedhardwarefwkserviceimpl/test/unittest/common/task/src/mock_task_factory.cpp create mode 100644 services/distributedhardwarefwkserviceimpl/test/unittest/common/task/src/task_test.cpp create mode 100644 services/distributedhardwarefwkserviceimpl/test/unittest/common/versionmanager/BUILD.gn create mode 100644 services/distributedhardwarefwkserviceimpl/test/unittest/common/versionmanager/include/version_manager_test.h create mode 100644 services/distributedhardwarefwkserviceimpl/test/unittest/common/versionmanager/src/version_manager_test.cpp create mode 100644 utils/BUILD.gn create mode 100644 utils/include/anonymous_string.h create mode 100644 utils/include/dh_utils_tool.h create mode 100644 utils/include/eventbus/event.h create mode 100644 utils/include/eventbus/event_bus.h create mode 100644 utils/include/eventbus/event_registration.h create mode 100644 utils/include/eventbus/event_sender.h create mode 100644 utils/include/eventbus/eventbus_handler.h create mode 100644 utils/include/log/dh_log.h create mode 100644 utils/src/anonymous_string.cpp create mode 100644 utils/src/dh_utils_tool.cpp create mode 100644 utils/src/log/dh_log.cpp create mode 100644 utils/test/unittest/BUILD.gn create mode 100644 utils/test/unittest/common/eventbus/BUILD.gn create mode 100644 utils/test/unittest/common/eventbus/event_bus_test.cpp create mode 100644 utils/test/unittest/common/eventbus/event_bus_test.h create mode 100644 utils/test/unittest/common/utilstool/BUILD.gn create mode 100644 utils/test/unittest/common/utilstool/utils_tool_test.cpp create mode 100644 utils/test/unittest/common/utilstool/utils_tool_test.h diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..e454a525 --- /dev/null +++ b/LICENSE @@ -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 + diff --git a/OAT.xml b/OAT.xml new file mode 100644 index 00000000..175029b2 --- /dev/null +++ b/OAT.xml @@ -0,0 +1,65 @@ + + + + + + + + + + + + diff --git a/README.md b/README.md deleted file mode 100644 index e8ef82d1..00000000 --- a/README.md +++ /dev/null @@ -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/) diff --git a/README_zh.md b/README_zh.md new file mode 100644 index 00000000..fd625d7d --- /dev/null +++ b/README_zh.md @@ -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) + + diff --git a/bundle.json b/bundle.json new file mode 100644 index 00000000..dce07b82 --- /dev/null +++ b/bundle.json @@ -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" + ] + } + } +} diff --git a/common/log/include/distributed_hardware_log.h b/common/log/include/distributed_hardware_log.h new file mode 100644 index 00000000..9b02114c --- /dev/null +++ b/common/log/include/distributed_hardware_log.h @@ -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 + +#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 \ No newline at end of file diff --git a/common/utils/include/constants.h b/common/utils/include/constants.h new file mode 100644 index 00000000..3aa1d18e --- /dev/null +++ b/common/utils/include/constants.h @@ -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 +#include + +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 \ No newline at end of file diff --git a/common/utils/include/device_type.h b/common/utils/include/device_type.h new file mode 100644 index 00000000..d5bdef79 --- /dev/null +++ b/common/utils/include/device_type.h @@ -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 + +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 \ No newline at end of file diff --git a/common/utils/include/distributed_hardware_errno.h b/common/utils/include/distributed_hardware_errno.h new file mode 100644 index 00000000..478616bf --- /dev/null +++ b/common/utils/include/distributed_hardware_errno.h @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_HARDWARE_ERRNO +#define OHOS_DISTRIBUTED_HARDWARE_ERRNO + +#include + +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 diff --git a/common/utils/include/idistributed_hardware.h b/common/utils/include/idistributed_hardware.h new file mode 100644 index 00000000..16a6181c --- /dev/null +++ b/common/utils/include/idistributed_hardware.h @@ -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 + +#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 &versionMap) = 0; + +public: + enum { + QUERY_SINK_VERSION = 1 + }; +}; +} +} +#endif \ No newline at end of file diff --git a/common/utils/include/idistributed_hardware_manager.h b/common/utils/include/idistributed_hardware_manager.h new file mode 100644 index 00000000..a7b34807 --- /dev/null +++ b/common/utils/include/idistributed_hardware_manager.h @@ -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 +#include + +#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 &versionMap) = 0; +}; +} +} +#endif diff --git a/common/utils/include/idistributed_hardware_sink.h b/common/utils/include/idistributed_hardware_sink.h new file mode 100644 index 00000000..1947022f --- /dev/null +++ b/common/utils/include/idistributed_hardware_sink.h @@ -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 + +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 ¶ms) = 0; + virtual int32_t ReleaseSink() = 0; + virtual int32_t SubscribeLocalHardware(const std::string &dhId, const std::string ¶ms) = 0; + virtual int32_t UnsubscribeLocalHardware(const std::string &dhId) = 0; +}; +extern "C" __attribute__((visibility("default"))) IDistributedHardwareSink* GetSinkHardwareHandler(); +} +} +#endif \ No newline at end of file diff --git a/common/utils/include/idistributed_hardware_source.h b/common/utils/include/idistributed_hardware_source.h new file mode 100644 index 00000000..2b7d9263 --- /dev/null +++ b/common/utils/include/idistributed_hardware_source.h @@ -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 +#include + +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 ¶ms) = 0; + virtual int32_t ReleaseSource() = 0; + virtual int32_t RegisterDistributedHardware(const std::string &devId, const std::string &dhId, + const EnableParam ¶m, std::shared_ptr callback) = 0; + virtual int32_t UnregisterDistributedHardware(const std::string &devId, const std::string &dhId, + std::shared_ptr 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 \ No newline at end of file diff --git a/common/utils/include/ihardware_handler.h b/common/utils/include/ihardware_handler.h new file mode 100644 index 00000000..3f8f0cf7 --- /dev/null +++ b/common/utils/include/ihardware_handler.h @@ -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 +#include +#include +#include + +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 Query() = 0; + virtual std::map QueryExtraInfo() = 0; + virtual bool IsSupportPlugin() = 0; + virtual void RegisterPluginListener(std::shared_ptr listener) = 0; +}; +extern "C" __attribute__((visibility("default"))) IHardwareHandler* GetHardwareHandler(); +} +} +#endif \ No newline at end of file diff --git a/common/utils/include/single_instance.h b/common/utils/include/single_instance.h new file mode 100644 index 00000000..11a86f69 --- /dev/null +++ b/common/utils/include/single_instance.h @@ -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 \ No newline at end of file diff --git a/distributedhardwarefwk.gni b/distributedhardwarefwk.gni new file mode 100644 index 00000000..1d1ada75 --- /dev/null +++ b/distributedhardwarefwk.gni @@ -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" ] diff --git a/figures/distributedhardwarefwk_arch.png b/figures/distributedhardwarefwk_arch.png new file mode 100644 index 0000000000000000000000000000000000000000..e914d0d4229d9791fce47976b46f14e10649ff23 GIT binary patch literal 29401 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 JK-Kc@zX89v0|o#9 literal 0 HcmV?d00001 diff --git a/sa_profile/4801.xml b/sa_profile/4801.xml new file mode 100644 index 00000000..87bbf234 --- /dev/null +++ b/sa_profile/4801.xml @@ -0,0 +1,27 @@ + + + + dhardware + + 4801 + libdistributedhardwarefwksvr.z.so + 4802 + 60000 + true + true + 1 + + diff --git a/sa_profile/BUILD.gn b/sa_profile/BUILD.gn new file mode 100644 index 00000000..4f5fbabd --- /dev/null +++ b/sa_profile/BUILD.gn @@ -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" +} diff --git a/services/distributedhardwarefwkservice/BUILD.gn b/services/distributedhardwarefwkservice/BUILD.gn new file mode 100644 index 00000000..982d8793 --- /dev/null +++ b/services/distributedhardwarefwkservice/BUILD.gn @@ -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" +} \ No newline at end of file diff --git a/services/distributedhardwarefwkservice/distributedhardware_fwk.cfg b/services/distributedhardwarefwkservice/distributedhardware_fwk.cfg new file mode 100644 index 00000000..22b7ee41 --- /dev/null +++ b/services/distributedhardwarefwkservice/distributedhardware_fwk.cfg @@ -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"] + }] +} \ No newline at end of file diff --git a/services/distributedhardwarefwkservice/include/accessmanager/access_manager.h b/services/distributedhardwarefwkservice/include/accessmanager/access_manager.h new file mode 100644 index 00000000..04731b8a --- /dev/null +++ b/services/distributedhardwarefwkservice/include/accessmanager/access_manager.h @@ -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 +#include +#include +#include +#include + +#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, + 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 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 diff --git a/services/distributedhardwarefwkservice/include/distributed_hardware_manager_factory.h b/services/distributedhardwarefwkservice/include/distributed_hardware_manager_factory.h new file mode 100644 index 00000000..f9114428 --- /dev/null +++ b/services/distributedhardwarefwkservice/include/distributed_hardware_manager_factory.h @@ -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 + +#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 &versionMap); + +private: + bool Init(); + void UnInit(); + int32_t LoadLibrary(); + void CloseLibrary(); + +private: + void *handler_ { nullptr }; + IDistributedHardwareManager *distributedHardwareMgrPtr_ { nullptr }; + std::mutex mutex_; +}; +} +} +#endif \ No newline at end of file diff --git a/services/distributedhardwarefwkservice/include/distributed_hardware_service.h b/services/distributedhardwarefwkservice/include/distributed_hardware_service.h new file mode 100644 index 00000000..fe82313c --- /dev/null +++ b/services/distributedhardwarefwkservice/include/distributed_hardware_service.h @@ -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 &versionMap) override; + +protected: + void OnStart() override; + void OnStop() override; + +private: + bool Init(); + +private: + bool registerToService_ = false; + ServiceRunningState state_ = ServiceRunningState::STATE_NOT_START; +}; +} +} +#endif \ No newline at end of file diff --git a/services/distributedhardwarefwkservice/include/distributed_hardware_stub.h b/services/distributedhardwarefwkservice/include/distributed_hardware_stub.h new file mode 100644 index 00000000..464e5f13 --- /dev/null +++ b/services/distributedhardwarefwkservice/include/distributed_hardware_stub.h @@ -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 { +public: + int32_t OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + +private: + std::string ToJson(const std::unordered_map &versionMap) const; +}; +} +} \ No newline at end of file diff --git a/services/distributedhardwarefwkservice/src/accessmanager/access_manager.cpp b/services/distributedhardwarefwkservice/src/accessmanager/access_manager.cpp new file mode 100644 index 00000000..031c6680 --- /dev/null +++ b/services/distributedhardwarefwkservice/src/accessmanager/access_manager.cpp @@ -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 +#include + +#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::GetInstance() +{ + static std::shared_ptr 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 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 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 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); + } +} +} +} diff --git a/services/distributedhardwarefwkservice/src/distributed_hardware_manager_factory.cpp b/services/distributedhardwarefwkservice/src/distributed_hardware_manager_factory.cpp new file mode 100644 index 00000000..c4f8a927 --- /dev/null +++ b/services/distributedhardwarefwkservice/src/distributed_hardware_manager_factory.cpp @@ -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 +#include + +#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 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 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 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(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 &versionMap) +{ + DHLOGI("start"); + std::lock_guard lock(mutex_); + if (distributedHardwareMgrPtr_ == nullptr) { + DHLOGE("distributedHardwareMgr is null"); + return ERR_DH_FWK_HARDWARE_MANAGER_LIB_IMPL_IS_NULL; + } + return distributedHardwareMgrPtr_->GetComponentVersion(versionMap); +} +} +} diff --git a/services/distributedhardwarefwkservice/src/distributed_hardware_service.cpp b/services/distributedhardwarefwkservice/src/distributed_hardware_service.cpp new file mode 100644 index 00000000..3c2351f7 --- /dev/null +++ b/services/distributedhardwarefwkservice/src/distributed_hardware_service.cpp @@ -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 &versionMap) +{ + return 0; +} +} +} diff --git a/services/distributedhardwarefwkservice/src/distributed_hardware_stub.cpp b/services/distributedhardwarefwkservice/src/distributed_hardware_stub.cpp new file mode 100644 index 00000000..f49c11a7 --- /dev/null +++ b/services/distributedhardwarefwkservice/src/distributed_hardware_stub.cpp @@ -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 + +#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 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 &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(); +} +} +} diff --git a/services/distributedhardwarefwkservice/test/unittest/BUILD.gn b/services/distributedhardwarefwkservice/test/unittest/BUILD.gn new file mode 100644 index 00000000..bdee75a0 --- /dev/null +++ b/services/distributedhardwarefwkservice/test/unittest/BUILD.gn @@ -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", ] +} diff --git a/services/distributedhardwarefwkservice/test/unittest/common/accessmanager/BUILD.gn b/services/distributedhardwarefwkservice/test/unittest/common/accessmanager/BUILD.gn new file mode 100644 index 00000000..5fc00a80 --- /dev/null +++ b/services/distributedhardwarefwkservice/test/unittest/common/accessmanager/BUILD.gn @@ -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" ] +} diff --git a/services/distributedhardwarefwkservice/test/unittest/common/accessmanager/access_manager_test.cpp b/services/distributedhardwarefwkservice/test/unittest/common/accessmanager/access_manager_test.cpp new file mode 100644 index 00000000..1f75dc9e --- /dev/null +++ b/services/distributedhardwarefwkservice/test/unittest/common/accessmanager/access_manager_test.cpp @@ -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 +#include +#include +#include + +#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> 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 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 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 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(); }); +} +} +} diff --git a/services/distributedhardwarefwkserviceimpl/BUILD.gn b/services/distributedhardwarefwkserviceimpl/BUILD.gn new file mode 100644 index 00000000..55ef0b73 --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/BUILD.gn @@ -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" +} \ No newline at end of file diff --git a/services/distributedhardwarefwkserviceimpl/include/componentloader/component_loader.h b/services/distributedhardwarefwkserviceimpl/include/componentloader/component_loader.h new file mode 100644 index 00000000..120fc12b --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/include/componentloader/component_loader.h @@ -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 +#include +#include + +#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 GetAllCompTypes(); + int32_t GetLocalDHVersion(DHVersion &dhVersion); + +private: + void *GetHandler(const std::string &soName); + void GetAllHandler(std::map &dhtypeMap); + int32_t ReleaseHandler(void *&handler); + int32_t GetCompPathAndVersion(const std::string &jsonStr, std::map &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 compHandlerMap_; + std::atomic isLocalVersionInit_; +}; +} +} +#endif diff --git a/services/distributedhardwarefwkserviceimpl/include/componentmanager/component_disable.h b/services/distributedhardwarefwkserviceimpl/include/componentmanager/component_disable.h new file mode 100644 index 00000000..5301d0d6 --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/include/componentmanager/component_disable.h @@ -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 +#include + +#include "idistributed_hardware_source.h" + +namespace OHOS { +namespace DistributedHardware { +class ComponentDisable : public std::enable_shared_from_this, 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 diff --git a/services/distributedhardwarefwkserviceimpl/include/componentmanager/component_enable.h b/services/distributedhardwarefwkserviceimpl/include/componentmanager/component_enable.h new file mode 100644 index 00000000..bcb1d9f0 --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/include/componentmanager/component_enable.h @@ -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 +#include + +#include "idistributed_hardware_source.h" + +namespace OHOS { +namespace DistributedHardware { +class ComponentEnable : public std::enable_shared_from_this, public RegisterCallback { +public: + ComponentEnable(); + virtual ~ComponentEnable(); + int32_t Enable(const std::string &devId, const std::string &dhId, const EnableParam ¶m, + 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 diff --git a/services/distributedhardwarefwkserviceimpl/include/componentmanager/component_manager.h b/services/distributedhardwarefwkserviceimpl/include/componentmanager/component_manager.h new file mode 100644 index 00000000..420e949b --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/include/componentmanager/component_manager.h @@ -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 +#include +#include +#include + +#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 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 ¶m); + 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 GetRemoteDHMS(const std::string &networkId) const; + +private: + std::map compSource_; + std::map compSink_; + std::unordered_map> sinkVersions_; + std::mutex sinkVersionMutex_; +}; +} +} +#endif diff --git a/services/distributedhardwarefwkserviceimpl/include/distributed_hardware_manager.h b/services/distributedhardwarefwkserviceimpl/include/distributed_hardware_manager.h new file mode 100644 index 00000000..718ab866 --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/include/distributed_hardware_manager.h @@ -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 &versionMap) override; +}; +} +} +#endif \ No newline at end of file diff --git a/services/distributedhardwarefwkserviceimpl/include/distributed_hardware_proxy.h b/services/distributedhardwarefwkserviceimpl/include/distributed_hardware_proxy.h new file mode 100644 index 00000000..d362558e --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/include/distributed_hardware_proxy.h @@ -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 + +#include "iremote_proxy.h" +#include "refbase.h" +#include "idistributed_hardware.h" + +namespace OHOS { +namespace DistributedHardware { +class DistributedHardwareProxy : public IRemoteProxy { +public: + explicit DistributedHardwareProxy(const sptr& impl) + : IRemoteProxy(impl) + { + } + + virtual ~DistributedHardwareProxy() {} + int32_t QuerySinkVersion(std::unordered_map &versionMap) override; + +private: + std::unordered_map FromJson(const std::string &json) const; + + static inline BrokerDelegator delegator_; +}; +} +} +#endif diff --git a/services/distributedhardwarefwkserviceimpl/include/localhardwaremanager/local_hardware_manager.h b/services/distributedhardwarefwkserviceimpl/include/localhardwaremanager/local_hardware_manager.h new file mode 100644 index 00000000..d12c3e03 --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/include/localhardwaremanager/local_hardware_manager.h @@ -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 +#include +#include + +#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 &dhItems, const DHType dhType); + +private: + std::map compToolFuncsMap_; +}; +} +} +#endif diff --git a/services/distributedhardwarefwkserviceimpl/include/resourcemanager/capability_info.h b/services/distributedhardwarefwkserviceimpl/include/resourcemanager/capability_info.h new file mode 100644 index 00000000..6a461ab1 --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/include/resourcemanager/capability_info.h @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_HARDWARE_CAPABILITY_INFO_H +#define OHOS_DISTRIBUTED_HARDWARE_CAPABILITY_INFO_H + +#include +#include +#include + +#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>; +} +} +#endif diff --git a/services/distributedhardwarefwkserviceimpl/include/resourcemanager/capability_info_event.h b/services/distributedhardwarefwkserviceimpl/include/resourcemanager/capability_info_event.h new file mode 100644 index 00000000..ba61aa14 --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/include/resourcemanager/capability_info_event.h @@ -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 + +#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 diff --git a/services/distributedhardwarefwkserviceimpl/include/resourcemanager/capability_info_manager.h b/services/distributedhardwarefwkserviceimpl/include/resourcemanager/capability_info_manager.h new file mode 100644 index 00000000..a1e19008 --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/include/resourcemanager/capability_info_manager.h @@ -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 +#include +#include + +#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, + public EventSender, + public DistributedKv::KvStoreObserver, + public EventBusHandler { +public: + CapabilityInfoManager(const CapabilityInfoManager &) = delete; + CapabilityInfoManager &operator = (const CapabilityInfoManager &) = delete; + CapabilityInfoManager(CapabilityInfoManager &&) = delete; + CapabilityInfoManager &operator = (CapabilityInfoManager &&) = delete; + static std::shared_ptr 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> &resInfos); + /* Save CapabilityInfo in memory */ + int32_t AddCapabilityInMem(const std::vector> &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> QueryCapabilityByFilters( + const std::map &filters); + bool IsCapabilityMatchFilter(const std::shared_ptr &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> &resInfos); + + /* Queries capability information based on deviceId and dhId. */ + int32_t GetCapability(const std::string &deviceId, const std::string &dhId, + std::shared_ptr &capPtr); + int32_t GetDataByKey(const std::string &key, std::shared_ptr& 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 snapshot) override; + /* EventBus async processing callback */ + void OnEvent(CapabilityInfoEvent &e) override; + +private: + CapabilityInfoManager(); + void HandleCapabilityAddChange(const std::vector &insertRecords); + void HandleCapabilityUpdateChange(const std::vector &updateRecords); + void HandleCapabilityDeleteChange(const std::vector &deleteRecords); + +private: + mutable std::mutex capInfoMgrMutex_; + int32_t manualSyncResult_; + std::condition_variable manualSyncCondVar_; + std::shared_ptr dbAdapterPtr_; + CapabilityInfoMap globalCapInfoMap_; +}; +} +} +#endif \ No newline at end of file diff --git a/services/distributedhardwarefwkserviceimpl/include/resourcemanager/capability_utils.h b/services/distributedhardwarefwkserviceimpl/include/resourcemanager/capability_utils.h new file mode 100644 index 00000000..7bac49dd --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/include/resourcemanager/capability_utils.h @@ -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 +#include + +#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 &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 diff --git a/services/distributedhardwarefwkserviceimpl/include/resourcemanager/db_adapter.h b/services/distributedhardwarefwkserviceimpl/include/resourcemanager/db_adapter.h new file mode 100644 index 00000000..c1f937dc --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/include/resourcemanager/db_adapter.h @@ -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 +#include +#include +#include +#include +#include + +#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, + public EventSender, + public DistributedKv::KvStoreSyncCallback, + public DistributedKv::KvStoreDeathRecipient { +public: + DBAdapter(const std::string &appId, const std::string &storeId, + const std::shared_ptr &changeListener); + + virtual ~DBAdapter(); + + int32_t Init(); + void UnInit(); + int32_t ReInit(); + void SyncCompleted(const std::map &results) override; + int32_t GetDataByKey(const std::string &key, std::string &data); + int32_t GetDataByKeyPrefix(const std::string &keyPrefix, std::vector &values); + int32_t PutData(const std::string &key, std::string &value); + int32_t PutDataBatch(const std::vector &keys, const std::vector &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 kvStoragePtr_; + std::shared_ptr dataChangeListener_; + std::mutex dbAdapterMutex_; + std::unordered_map manualSyncCountMap_; +}; +} +} +#endif \ No newline at end of file diff --git a/services/distributedhardwarefwkserviceimpl/include/task/disable_task.h b/services/distributedhardwarefwkserviceimpl/include/task/disable_task.h new file mode 100644 index 00000000..2f7f1c7b --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/include/task/disable_task.h @@ -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 \ No newline at end of file diff --git a/services/distributedhardwarefwkserviceimpl/include/task/enable_task.h b/services/distributedhardwarefwkserviceimpl/include/task/enable_task.h new file mode 100644 index 00000000..9b9ff625 --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/include/task/enable_task.h @@ -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 \ No newline at end of file diff --git a/services/distributedhardwarefwkserviceimpl/include/task/offline_task.h b/services/distributedhardwarefwkserviceimpl/include/task/offline_task.h new file mode 100644 index 00000000..15bc0865 --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/include/task/offline_task.h @@ -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 +#include + +#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 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 unFinishChildrenTasks_; +}; +} +} +#endif diff --git a/services/distributedhardwarefwkserviceimpl/include/task/online_task.h b/services/distributedhardwarefwkserviceimpl/include/task/online_task.h new file mode 100644 index 00000000..b9a59887 --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/include/task/online_task.h @@ -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 \ No newline at end of file diff --git a/services/distributedhardwarefwkserviceimpl/include/task/task.h b/services/distributedhardwarefwkserviceimpl/include/task/task.h new file mode 100644 index 00000000..8e432a53 --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/include/task/task.h @@ -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 +#include +#include +#include +#include + +#include "impl_utils.h" + +namespace OHOS { +namespace DistributedHardware { +class Task : public std::enable_shared_from_this { +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 taskSteps); + const std::vector GetTaskSteps(); + + TaskState GetTaskState(); + void SetTaskState(TaskState taskState); + + virtual void AddChildrenTask(std::shared_ptr childrenTask); + const std::vector> GetChildrenTasks(); + + const std::weak_ptr GetFatherTask(); + void SetFatherTask(std::shared_ptr fatherTask); + +private: + std::string id_; + std::string networkId_; + std::string devId_; + std::string dhId_; + TaskType taskType_ { TaskType::UNKNOWN }; + std::vector taskSteps_; + std::weak_ptr fatherTask_; + + std::mutex taskMtx_; + std::vector> childrenTasks_; + + TaskState taskState_ { TaskState::INIT }; +}; +} +} +#endif \ No newline at end of file diff --git a/services/distributedhardwarefwkserviceimpl/include/task/task_board.h b/services/distributedhardwarefwkserviceimpl/include/task/task_board.h new file mode 100644 index 00000000..3a88cc22 --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/include/task/task_board.h @@ -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 +#include +#include +#include +#include + +#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); + 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> tasks_; +}; +} +} +#endif \ No newline at end of file diff --git a/services/distributedhardwarefwkserviceimpl/include/task/task_executor.h b/services/distributedhardwarefwkserviceimpl/include/task/task_executor.h new file mode 100644 index 00000000..08fae4a2 --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/include/task/task_executor.h @@ -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 +#include +#include + +#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); + +private: + std::shared_ptr PopTask(); + void TriggerTask(); + +private: + std::queue> taskQueue_; + std::mutex taskQueueMtx_; + std::condition_variable condVar_; + bool taskThreadFlag_; +}; +} +} +#endif \ No newline at end of file diff --git a/services/distributedhardwarefwkserviceimpl/include/task/task_factory.h b/services/distributedhardwarefwkserviceimpl/include/task/task_factory.h new file mode 100644 index 00000000..b5368e4d --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/include/task/task_factory.h @@ -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 + +#include "single_instance.h" +#include "task.h" + +namespace OHOS { +namespace DistributedHardware { +class TaskFactory { +DECLARE_SINGLE_INSTANCE(TaskFactory); +public: + std::shared_ptr CreateTask(TaskType taskType, const std::string &networkId, const std::string &devId, + const std::string &dhId, std::shared_ptr fatherTask); +}; +} +} +#endif \ No newline at end of file diff --git a/services/distributedhardwarefwkserviceimpl/include/utils/dh_context.h b/services/distributedhardwarefwkserviceimpl/include/utils/dh_context.h new file mode 100644 index 00000000..51b2dfe4 --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/include/utils/dh_context.h @@ -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 +#include +#include +#include + +#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 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_; + DeviceInfo devInfo_ { "", "", 0 }; + std::mutex devMutex_; + + /* Save online device UUID and networkId */ + std::unordered_map onlineDeviceMap_; + std::shared_mutex onlineDevMutex_; +}; +} +} +#endif \ No newline at end of file diff --git a/services/distributedhardwarefwkserviceimpl/include/utils/impl_utils.h b/services/distributedhardwarefwkserviceimpl/include/utils/impl_utils.h new file mode 100644 index 00000000..b5daf2f5 --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/include/utils/impl_utils.h @@ -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 + +#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 compVersions; +}; +} +} +#endif \ No newline at end of file diff --git a/services/distributedhardwarefwkserviceimpl/include/versionmanager/version_manager.h b/services/distributedhardwarefwkserviceimpl/include/versionmanager/version_manager.h new file mode 100644 index 00000000..6bb78c65 --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/include/versionmanager/version_manager.h @@ -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 +#include +#include + +#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 dhVersions_; + std::mutex versionMutex_; +}; +} +} +#endif \ No newline at end of file diff --git a/services/distributedhardwarefwkserviceimpl/src/componentloader/component_loader.cpp b/services/distributedhardwarefwkserviceimpl/src/componentloader/component_loader.cpp new file mode 100644 index 00000000..da4bb5c0 --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/src/componentloader/component_loader.cpp @@ -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 +#include +#include + +#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 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 ComponentLoader::GetAllCompTypes() +{ + std::vector DHTypeALL; + for (std::map::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 &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 vecJsnCfg = + jsonCfg.at(COMPONENTSLOAD_DISTRIBUTED_COMPONENTS).get>(); + DHLOGI("get distributed_components CompConfig size is %d", vecJsnCfg.size()); + for (std::vector::iterator iter = vecJsnCfg.begin(); iter != vecJsnCfg.end(); iter++) { + dhtypeMap.insert(std::pair((*iter).type, (*iter))); + localDHVersion_.compVersions.insert( + std::pair((*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 &dhtypeMap) +{ + std::map::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(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 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::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; +} +} +} \ No newline at end of file diff --git a/services/distributedhardwarefwkserviceimpl/src/componentmanager/component_disable.cpp b/services/distributedhardwarefwkserviceimpl/src/componentmanager/component_disable.cpp new file mode 100644 index 00000000..4f9f756b --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/src/componentmanager/component_disable.cpp @@ -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 + +#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::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 lock(mutex_); + auto waitStatus = conVar_.wait_for(lock, std::chrono::milliseconds(DISABLE_TIMEOUT_MS), + [this]() { return status_ != std::numeric_limits::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 lock(mutex_); + status_ = status; + conVar_.notify_all(); + return status_; +} +} +} diff --git a/services/distributedhardwarefwkserviceimpl/src/componentmanager/component_enable.cpp b/services/distributedhardwarefwkserviceimpl/src/componentmanager/component_enable.cpp new file mode 100644 index 00000000..d86e590d --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/src/componentmanager/component_enable.cpp @@ -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 + +#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::max()) {} + +ComponentEnable::~ComponentEnable() {} + +int32_t ComponentEnable::Enable(const std::string &networkId, const std::string &dhId, const EnableParam ¶m, + 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 lock(mutex_); + auto waitStatus = conVar_.wait_for(lock, std::chrono::milliseconds(ENABLE_TIMEOUT_MS), + [this]() { return status_ != std::numeric_limits::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 lock(mutex_); + status_ = status; + conVar_.notify_all(); + return status_; +} +} +} \ No newline at end of file diff --git a/services/distributedhardwarefwkserviceimpl/src/componentmanager/component_manager.cpp b/services/distributedhardwarefwkserviceimpl/src/componentmanager/component_manager.cpp new file mode 100644 index 00000000..e0f33d38 --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/src/componentmanager/component_manager.cpp @@ -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 +#include + +#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 lock(sinkVersionMutex_); + sinkVersions_.clear(); + } + DHLOGI("Release component success"); + return DH_FWK_SUCCESS; +} + +ComponentManager::ActionResult ComponentManager::StartSource() +{ + DHLOGI("start."); + std::unordered_map> 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> 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> 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> 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(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(); + 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(); + 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 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 ¶m) +{ + std::shared_ptr 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 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 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 versions; + auto ret = dhms->QuerySinkVersion(versions); + if (ret != DH_FWK_SUCCESS) { + DHLOGE("QuerySinkVersion failed, errCode = %d", ret); + return ret; + } + { + std::lock_guard lock(sinkVersionMutex_); + sinkVersions_.emplace(devId, versions); + } + DHLOGI("QuerySinkVersion success"); + return DH_FWK_SUCCESS; +} + +sptr 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(object); +} +} +} diff --git a/services/distributedhardwarefwkserviceimpl/src/distributed_hardware_manager.cpp b/services/distributedhardwarefwkserviceimpl/src/distributed_hardware_manager.cpp new file mode 100644 index 00000000..938cca7f --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/src/distributed_hardware_manager.cpp @@ -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 &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; +} +} +} diff --git a/services/distributedhardwarefwkserviceimpl/src/distributed_hardware_proxy.cpp b/services/distributedhardwarefwkserviceimpl/src/distributed_hardware_proxy.cpp new file mode 100644 index 00000000..7a94a7b6 --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/src/distributed_hardware_proxy.cpp @@ -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 + +#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 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 &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 &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, sinkVersion)); + } +} + +std::unordered_map DistributedHardwareProxy::FromJson(const std::string &json) const +{ + return nlohmann::json::parse(json).get>(); +} +} +} diff --git a/services/distributedhardwarefwkserviceimpl/src/localhardwaremanager/local_hardware_manager.cpp b/services/distributedhardwarefwkserviceimpl/src/localhardwaremanager/local_hardware_manager.cpp new file mode 100644 index 00000000..b309d82d --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/src/localhardwaremanager/local_hardware_manager.cpp @@ -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 + +#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 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 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 &dhItems, const DHType dhType) +{ + std::vector> 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 dhCapabilityInfo = + std::make_shared(dhItem.dhId, deviceId, devName, devType, dhType, dhItem.attrs); + capabilityInfos.push_back(dhCapabilityInfo); + } + CapabilityInfoManager::GetInstance()->AddCapability(capabilityInfos); +} +} +} diff --git a/services/distributedhardwarefwkserviceimpl/src/resourcemanager/capability_info.cpp b/services/distributedhardwarefwkserviceimpl/src/resourcemanager/capability_info.cpp new file mode 100644 index 00000000..31782244 --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/src/resourcemanager/capability_info.cpp @@ -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 + +#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()); + } + if (jsonObject.find(DEV_ID) != jsonObject.end()) { + capability.SetDeviceId(jsonObject.at(DEV_ID).get()); + } + if (jsonObject.find(DEV_NAME) != jsonObject.end()) { + capability.SetDeviceName(jsonObject.at(DEV_NAME).get()); + } + if (jsonObject.find(DEV_TYPE) != jsonObject.end()) { + capability.SetDeviceType(jsonObject.at(DEV_TYPE).get()); + } + if (jsonObject.find(DH_TYPE) != jsonObject.end()) { + capability.SetDHType(jsonObject.at(DH_TYPE).get()); + } + if (jsonObject.find(DH_ATTRS) != jsonObject.end()) { + capability.SetDHAttrs(jsonObject.at(DH_ATTRS).get()); + } +} +} +} diff --git a/services/distributedhardwarefwkserviceimpl/src/resourcemanager/capability_info_manager.cpp b/services/distributedhardwarefwkserviceimpl/src/resourcemanager/capability_info_manager.cpp new file mode 100644 index 00000000..189a8042 --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/src/resourcemanager/capability_info_manager.cpp @@ -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 +#include +#include +#include + +#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::GetInstance() +{ + static std::shared_ptr instance(new CapabilityInfoManager); + return instance; +} + +int32_t CapabilityInfoManager::Init() +{ + DHLOGI("CapabilityInfoManager instance init!"); + std::lock_guard lock(capInfoMgrMutex_); + dbAdapterPtr_ = std::make_shared(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.GetType(), *this); + DHLOGI("CapabilityInfoManager instance init success"); + return DH_FWK_SUCCESS; +} + +int32_t CapabilityInfoManager::UnInit() +{ + DHLOGI("CapabilityInfoManager UnInit"); + std::lock_guard 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 lock(capInfoMgrMutex_); + if (dbAdapterPtr_ == nullptr) { + DHLOGE("dbAdapterPtr_ is null"); + return ERR_DH_FWK_RESOURCE_DB_ADAPTER_POINTER_NULL; + } + std::vector 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; + 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 lock(capInfoMgrMutex_); + if (dbAdapterPtr_ == nullptr) { + DHLOGE("dbAdapterPtr_ is null"); + return ERR_DH_FWK_RESOURCE_DB_ADAPTER_POINTER_NULL; + } + std::vector 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; + 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> &resInfos) +{ + std::lock_guard lock(capInfoMgrMutex_); + if (dbAdapterPtr_ == nullptr) { + DHLOGE("dbAdapterPtr_ is null"); + return ERR_DH_FWK_RESOURCE_DB_ADAPTER_POINTER_NULL; + } + std::vector keys; + std::vector 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> &resInfos) +{ + std::lock_guard 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 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 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 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> CapabilityInfoManager::QueryCapabilityByFilters( + const std::map &filters) +{ + std::lock_guard lock(capInfoMgrMutex_); + std::map> 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 lock(capInfoMgrMutex_); + if (dbAdapterPtr_ == nullptr) { + DHLOGE("dbAdapterPtr_ is null"); + return; + } + dbAdapterPtr_->CreateManualSyncCount(deviceId); +} + +void CapabilityInfoManager::RemoveManualSyncCount(const std::string &deviceId) +{ + std::lock_guard 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 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 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 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 &insertRecords) +{ + std::lock_guard lock(capInfoMgrMutex_); + for (const auto &item : insertRecords) { + const std::string value = item.value.ToString(); + std::shared_ptr 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 &updateRecords) +{ + std::lock_guard lock(capInfoMgrMutex_); + for (const auto &item : updateRecords) { + const std::string value = item.value.ToString(); + std::shared_ptr 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 &deleteRecords) +{ + std::lock_guard lock(capInfoMgrMutex_); + for (const auto &item : deleteRecords) { + const std::string value = item.value.ToString(); + std::shared_ptr 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 &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(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> &resInfos) +{ + std::lock_guard 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 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 &capPtr) +{ + std::lock_guard 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 &capInfoPtr) +{ + std::lock_guard 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 lock(capInfoMgrMutex_); + if (dbAdapterPtr_ == nullptr) { + DHLOGI("dbAdapterPtr_ is null"); + return ERR_DH_FWK_RESOURCE_DB_ADAPTER_POINTER_NULL; + } + std::vector 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; + 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; +} +} +} diff --git a/services/distributedhardwarefwkserviceimpl/src/resourcemanager/capability_utils.cpp b/services/distributedhardwarefwkserviceimpl/src/resourcemanager/capability_utils.cpp new file mode 100644 index 00000000..cfca0b93 --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/src/resourcemanager/capability_utils.cpp @@ -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 +#include +#include + +#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 &capPtr) +{ + capPtr = std::make_shared(); + 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; +} +} +} \ No newline at end of file diff --git a/services/distributedhardwarefwkserviceimpl/src/resourcemanager/db_adapter.cpp b/services/distributedhardwarefwkserviceimpl/src/resourcemanager/db_adapter.cpp new file mode 100644 index 00000000..70ba5b48 --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/src/resourcemanager/db_adapter.cpp @@ -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 +#include + +#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 &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 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 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 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 &results) +{ + DHLOGI("DBAdapter SyncCompleted start"); + std::lock_guard 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 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 &values) +{ + DHLOGI("Get data by key prefix: %s", GetAnonyString(keyPrefix).c_str()); + std::lock_guard 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 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 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 &keys, const std::vector &values) +{ + std::lock_guard 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 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 lock(dbAdapterMutex_); + manualSyncCountMap_[deviceId] = 0; +} + +void DBAdapter::RemoveManualSyncCount(const std::string &deviceId) +{ + std::lock_guard 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 lock(dbAdapterMutex_); + if (kvStoragePtr_ == nullptr) { + DHLOGE("kvStoragePtr_ is null"); + return ERR_DH_FWK_RESOURCE_KV_STORAGE_POINTER_NULL; + } + std::vector 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(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 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 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 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; +} +} +} diff --git a/services/distributedhardwarefwkserviceimpl/src/task/disable_task.cpp b/services/distributedhardwarefwkserviceimpl/src/task/disable_task.cpp new file mode 100644 index 00000000..8bf53b64 --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/src/task/disable_task.cpp @@ -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::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 father = GetFatherTask().lock(); + if (father != nullptr) { + auto offLineTask = std::static_pointer_cast(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; +} +} +} \ No newline at end of file diff --git a/services/distributedhardwarefwkserviceimpl/src/task/enable_task.cpp b/services/distributedhardwarefwkserviceimpl/src/task/enable_task.cpp new file mode 100644 index 00000000..02715a71 --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/src/task/enable_task.cpp @@ -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 +#include + +#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::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; +} +} +} \ No newline at end of file diff --git a/services/distributedhardwarefwkserviceimpl/src/task/offline_task.cpp b/services/distributedhardwarefwkserviceimpl/src/task/offline_task.cpp new file mode 100644 index 00000000..7925a1b0 --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/src/task/offline_task.cpp @@ -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 + +#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> 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 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 lock(unFinishTaskMtx_); + this->unFinishChildrenTasks_.erase(taskId); + } + finishCondVar_.notify_all(); +} + +void OffLineTask::AddChildrenTask(std::shared_ptr childrenTask) +{ + std::lock_guard lock(unFinishTaskMtx_); + this->unFinishChildrenTasks_.insert(childrenTask->GetId()); +} +} +} \ No newline at end of file diff --git a/services/distributedhardwarefwkserviceimpl/src/task/online_task.cpp b/services/distributedhardwarefwkserviceimpl/src/task/online_task.cpp new file mode 100644 index 00000000..8142264c --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/src/task/online_task.cpp @@ -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::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> 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); + } +} +} +} \ No newline at end of file diff --git a/services/distributedhardwarefwkserviceimpl/src/task/task.cpp b/services/distributedhardwarefwkserviceimpl/src/task/task.cpp new file mode 100644 index 00000000..6d4b6fa0 --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/src/task/task.cpp @@ -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 taskSteps) +{ + this->taskSteps_.swap(taskSteps); +} + +const std::vector 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 childrenTask) +{ + std::lock_guard lock(taskMtx_); + this->childrenTasks_.push_back(childrenTask); +} + +const std::vector> Task::GetChildrenTasks() +{ + std::lock_guard lock(taskMtx_); + return this->childrenTasks_; +} + +const std::weak_ptr Task::GetFatherTask() +{ + return this->fatherTask_; +} + +void Task::SetFatherTask(std::shared_ptr fatherTask) +{ + this->fatherTask_ = fatherTask; +} +} +} \ No newline at end of file diff --git a/services/distributedhardwarefwkserviceimpl/src/task/task_board.cpp b/services/distributedhardwarefwkserviceimpl/src/task/task_board.cpp new file mode 100644 index 00000000..1d9decae --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/src/task/task_board.cpp @@ -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 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 lock(tasksMtx_); + return this->tasks_.empty(); +} + +void TaskBoard::AddTask(std::shared_ptr task) +{ + if (task == nullptr) { + DHLOGE("task is null, error"); + return; + } + + std::lock_guard 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 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); +} +} +} diff --git a/services/distributedhardwarefwkserviceimpl/src/task/task_executor.cpp b/services/distributedhardwarefwkserviceimpl/src/task/task_executor.cpp new file mode 100644 index 00000000..aa2c6007 --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/src/task/task_executor.cpp @@ -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 + +#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) +{ + if (task == nullptr) { + DHLOGE("Task is null"); + return; + } + + { + DHLOGI("Push task: %s", task->GetId().c_str()); + std::unique_lock lock(taskQueueMtx_); + taskQueue_.push(task); + } + + condVar_.notify_one(); +} + +std::shared_ptr TaskExecutor::PopTask() +{ + std::shared_ptr task = nullptr; + + std::unique_lock 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 = 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()); + } +} +} +} \ No newline at end of file diff --git a/services/distributedhardwarefwkserviceimpl/src/task/task_factory.cpp b/services/distributedhardwarefwkserviceimpl/src/task/task_factory.cpp new file mode 100644 index 00000000..89b7083f --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/src/task/task_factory.cpp @@ -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 TaskFactory::CreateTask(TaskType taskType, const std::string &networkId, const std::string &devId, + const std::string &dhId, std::shared_ptr fatherTask) +{ + DHLOGI("taskType = %d, networkId = %s, devId = %s, dhId = %s", static_cast(taskType), + GetAnonyString(networkId).c_str(), GetAnonyString(devId).c_str(), dhId.c_str()); + std::shared_ptr task = nullptr; + switch (taskType) { + case TaskType::ENABLE: { + task = std::make_shared(networkId, devId, dhId); + break; + } + case TaskType::DISABLE: { + task = std::make_shared(networkId, devId, dhId); + break; + } + case TaskType::ON_LINE: { + task = std::make_shared(networkId, devId, dhId); + break; + } + case TaskType::OFF_LINE: { + task = std::make_shared(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; +} +} +} \ No newline at end of file diff --git a/services/distributedhardwarefwkserviceimpl/src/utils/dh_context.cpp b/services/distributedhardwarefwkserviceimpl/src/utils/dh_context.cpp new file mode 100644 index 00000000..9f920ee2 --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/src/utils/dh_context.cpp @@ -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()) {} + +DHContext::~DHContext() +{ + if (eventBus_ != nullptr) { + eventBus_.reset(); + eventBus_ = nullptr; + } +} + +std::shared_ptr DHContext::GetEventBus() +{ + return eventBus_; +} + +const DeviceInfo& DHContext::GetDeviceInfo() +{ + std::lock_guard 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 lock(onlineDevMutex_); + if (!devId.empty() && !networkId.empty()) { + onlineDeviceMap_[devId] = networkId; + } +} + +void DHContext::RemoveOnlineDevice(const std::string &devId) +{ + std::unique_lock lock(onlineDevMutex_); + auto iter = onlineDeviceMap_.find(devId); + if (iter != onlineDeviceMap_.end()) { + onlineDeviceMap_.erase(iter); + } +} + +bool DHContext::IsDeviceOnline(const std::string &devId) +{ + std::shared_lock lock(onlineDevMutex_); + return onlineDeviceMap_.find(devId) != onlineDeviceMap_.end(); +} + +size_t DHContext::GetOnlineCount() +{ + std::shared_lock lock(onlineDevMutex_); + return onlineDeviceMap_.size(); +} + +std::string DHContext::GetNetworkIdByUUID(const std::string &devId) +{ + std::unique_lock lock(onlineDevMutex_); + if (onlineDeviceMap_.find(devId) == onlineDeviceMap_.end()) { + DHLOGE("Can not find networkId in onlineDeviceMap_: %s", GetAnonyString(devId).c_str()); + return ""; + } + return onlineDeviceMap_[devId]; +} +} +} diff --git a/services/distributedhardwarefwkserviceimpl/src/versionmanager/version_manager.cpp b/services/distributedhardwarefwkserviceimpl/src/versionmanager/version_manager.cpp new file mode 100644 index 00000000..66df996d --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/src/versionmanager/version_manager.cpp @@ -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 lock(versionMutex_); + dhVersions_.insert(std::pair(devId, dhVersion)); + return DH_FWK_SUCCESS; +} + +int32_t VersionManager::RemoveDHVersion(const std::string &devId) +{ + DHLOGI("devId: %s", GetAnonyString(devId).c_str()); + std::lock_guard lock(versionMutex_); + std::unordered_map::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 lock(versionMutex_); + std::unordered_map::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; +} +} +} diff --git a/services/distributedhardwarefwkserviceimpl/test/unittest/BUILD.gn b/services/distributedhardwarefwkserviceimpl/test/unittest/BUILD.gn new file mode 100644 index 00000000..58d73d37 --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/test/unittest/BUILD.gn @@ -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", + ] +} \ No newline at end of file diff --git a/services/distributedhardwarefwkserviceimpl/test/unittest/common/BUILD.gn b/services/distributedhardwarefwkserviceimpl/test/unittest/common/BUILD.gn new file mode 100644 index 00000000..be5ddaf0 --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/test/unittest/common/BUILD.gn @@ -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" ] +} diff --git a/services/distributedhardwarefwkserviceimpl/test/unittest/common/componentloader/BUILD.gn b/services/distributedhardwarefwkserviceimpl/test/unittest/common/componentloader/BUILD.gn new file mode 100644 index 00000000..e7a4ecf7 --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/test/unittest/common/componentloader/BUILD.gn @@ -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" ] +} diff --git a/services/distributedhardwarefwkserviceimpl/test/unittest/common/componentloader/include/component_loader_test.h b/services/distributedhardwarefwkserviceimpl/test/unittest/common/componentloader/include/component_loader_test.h new file mode 100644 index 00000000..a5b422ce --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/test/unittest/common/componentloader/include/component_loader_test.h @@ -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 + +namespace OHOS { +namespace DistributedHardware { +class ComponentLoaderTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; +} +} +#endif \ No newline at end of file diff --git a/services/distributedhardwarefwkserviceimpl/test/unittest/common/componentloader/src/component_loader_test.cpp b/services/distributedhardwarefwkserviceimpl/test/unittest/common/componentloader/src/component_loader_test.cpp new file mode 100644 index 00000000..786d27b6 --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/test/unittest/common/componentloader/src/component_loader_test.cpp @@ -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 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); +} +} +} diff --git a/services/distributedhardwarefwkserviceimpl/test/unittest/common/componentmanager/BUILD.gn b/services/distributedhardwarefwkserviceimpl/test/unittest/common/componentmanager/BUILD.gn new file mode 100644 index 00000000..5b83af89 --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/test/unittest/common/componentmanager/BUILD.gn @@ -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" ] +} diff --git a/services/distributedhardwarefwkserviceimpl/test/unittest/common/componentmanager/include/component_manager_test.h b/services/distributedhardwarefwkserviceimpl/test/unittest/common/componentmanager/include/component_manager_test.h new file mode 100644 index 00000000..50046e78 --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/test/unittest/common/componentmanager/include/component_manager_test.h @@ -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 \ No newline at end of file diff --git a/services/distributedhardwarefwkserviceimpl/test/unittest/common/componentmanager/include/mock_idistributed_hardware_sink.h b/services/distributedhardwarefwkserviceimpl/test/unittest/common/componentmanager/include/mock_idistributed_hardware_sink.h new file mode 100644 index 00000000..350aa760 --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/test/unittest/common/componentmanager/include/mock_idistributed_hardware_sink.h @@ -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 + +#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 ¶ms)); + MOCK_METHOD0(ReleaseSink, int32_t()); + + int32_t SubscribeLocalHardware(const std::string &dhId, const std::string ¶meter) + { + return 0; + } + int32_t UnsubscribeLocalHardware(const std::string &dhId) + { + return 0; + } +}; +} +} +#endif \ No newline at end of file diff --git a/services/distributedhardwarefwkserviceimpl/test/unittest/common/componentmanager/include/mock_idistributed_hardware_source.h b/services/distributedhardwarefwkserviceimpl/test/unittest/common/componentmanager/include/mock_idistributed_hardware_source.h new file mode 100644 index 00000000..381e031c --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/test/unittest/common/componentmanager/include/mock_idistributed_hardware_source.h @@ -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 + +#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 ¶ms)); + MOCK_METHOD0(ReleaseSource, int32_t()); + MOCK_METHOD4(RegisterDistributedHardware, int32_t(const std::string &devId, const std::string &dhId, + const EnableParam ¶meters, std::shared_ptr callback)); + MOCK_METHOD3(UnregisterDistributedHardware, + int32_t(const std::string &devId, const std::string &dhId, std::shared_ptr callback)); + + int32_t ConfigDistributedHardware(const std::string &devId, const std::string &dhId, const std::string &key, + const std::string &value) + { + return 0; + } +}; +} +} +#endif \ No newline at end of file diff --git a/services/distributedhardwarefwkserviceimpl/test/unittest/common/componentmanager/src/component_manager_test.cpp b/services/distributedhardwarefwkserviceimpl/test/unittest/common/componentmanager/src/component_manager_test.cpp new file mode 100644 index 00000000..217fe998 --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/test/unittest/common/componentmanager/src/component_manager_test.cpp @@ -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 +#include +#include + +#include + +#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(); + EnableParam parameters; + std::future future; + auto handler = [&future, timeout, status, compEnable](std::string devId, std::string dhId, + const EnableParam ¶meters, std::shared_ptr 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::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(); + + std::future future; + auto handler = [&future, timeout, status, compDisable](std::string devId, std::string dhId, + std::shared_ptr 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::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::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::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(); +} +} +} diff --git a/services/distributedhardwarefwkserviceimpl/test/unittest/common/distributed_hardware_manager_test.cpp b/services/distributedhardwarefwkserviceimpl/test/unittest/common/distributed_hardware_manager_test.cpp new file mode 100644 index 00000000..af2d9c24 --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/test/unittest/common/distributed_hardware_manager_test.cpp @@ -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 +#include +#include + +#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> 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()); +} +} +} diff --git a/services/distributedhardwarefwkserviceimpl/test/unittest/common/distributed_hardware_manager_test.h b/services/distributedhardwarefwkserviceimpl/test/unittest/common/distributed_hardware_manager_test.h new file mode 100644 index 00000000..20fd1dd6 --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/test/unittest/common/distributed_hardware_manager_test.h @@ -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 + +namespace OHOS { +namespace DistributedHardware { +class DistributedHardwareManagerTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; +} +} +#endif \ No newline at end of file diff --git a/services/distributedhardwarefwkserviceimpl/test/unittest/common/resourcemanager/BUILD.gn b/services/distributedhardwarefwkserviceimpl/test/unittest/common/resourcemanager/BUILD.gn new file mode 100644 index 00000000..05ce090e --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/test/unittest/common/resourcemanager/BUILD.gn @@ -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" ] +} diff --git a/services/distributedhardwarefwkserviceimpl/test/unittest/common/resourcemanager/include/resource_manager_test.h b/services/distributedhardwarefwkserviceimpl/test/unittest/common/resourcemanager/include/resource_manager_test.h new file mode 100644 index 00000000..63fecacc --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/test/unittest/common/resourcemanager/include/resource_manager_test.h @@ -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 + +namespace OHOS { +namespace DistributedHardware { +class ResourceManagerTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; +} +} +#endif diff --git a/services/distributedhardwarefwkserviceimpl/test/unittest/common/resourcemanager/src/resource_manager_test.cpp b/services/distributedhardwarefwkserviceimpl/test/unittest/common/resourcemanager/src/resource_manager_test.cpp new file mode 100644 index 00000000..8b0a8e8e --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/test/unittest/common/resourcemanager/src/resource_manager_test.cpp @@ -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 + +#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 CAP_INFO_0 = + make_shared(DH_ID_0, DEV_ID_0, DEV_NAME, TEST_DEV_TYPE_PAD, DHType::CAMERA, DH_ATTR_0); +const shared_ptr CAP_INFO_1 = + make_shared(DH_ID_1, DEV_ID_0, DEV_NAME, TEST_DEV_TYPE_PAD, DHType::MIC, DH_ATTR_0); +const shared_ptr CAP_INFO_2 = + make_shared(DH_ID_2, DEV_ID_0, DEV_NAME, TEST_DEV_TYPE_PAD, DHType::SPEAKER, DH_ATTR_0); +const shared_ptr CAP_INFO_3 = + make_shared(DH_ID_3, DEV_ID_0, DEV_NAME, TEST_DEV_TYPE_PAD, DHType::DISPLAY, DH_ATTR_0); +const shared_ptr CAP_INFO_4 = + make_shared(DH_ID_4, DEV_ID_0, DEV_NAME, TEST_DEV_TYPE_PAD, DHType::BUTTON, DH_ATTR_0); + +const shared_ptr CAP_INFO_5 = + make_shared(DH_ID_0, DEV_ID_1, DEV_NAME, TEST_DEV_TYPE_PAD, DHType::CAMERA, DH_ATTR_1); +const shared_ptr CAP_INFO_6 = + make_shared(DH_ID_1, DEV_ID_1, DEV_NAME, TEST_DEV_TYPE_PAD, DHType::MIC, DH_ATTR_1); +const shared_ptr CAP_INFO_7 = + make_shared(DH_ID_2, DEV_ID_1, DEV_NAME, TEST_DEV_TYPE_PAD, DHType::SPEAKER, DH_ATTR_1); +const shared_ptr CAP_INFO_8 = + make_shared(DH_ID_3, DEV_ID_1, DEV_NAME, TEST_DEV_TYPE_PAD, DHType::DISPLAY, DH_ATTR_1); +const shared_ptr CAP_INFO_9 = + make_shared(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> 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> 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> 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 queryMap0 { { CapabilityInfoFilter::FILTER_DEVICE_ID, DEV_ID_0 } }; + map queryMap1 { { CapabilityInfoFilter::FILTER_DEVICE_ID, DEV_ID_1 } }; + map queryMap2 { { CapabilityInfoFilter::FILTER_DEVICE_NAME, DEV_NAME } }; + map queryMap3 { { CapabilityInfoFilter::FILTER_DH_ID, DH_ID_0 } }; + map queryMap4 { { CapabilityInfoFilter::FILTER_DH_ID, DH_ID_1 } }; + map queryMap5 { { CapabilityInfoFilter::FILTER_DH_ID, DH_ID_2 } }; + map queryMap6 { { CapabilityInfoFilter::FILTER_DH_ID, DH_ID_3 } }; + map queryMap7 { { CapabilityInfoFilter::FILTER_DH_ID, DH_ID_4 } }; + map queryMap8 { { CapabilityInfoFilter::FILTER_DEVICE_TYPE, + to_string(TEST_DEV_TYPE_PAD) } }; + map queryMap9 { { CapabilityInfoFilter::FILTER_DH_TYPE, + to_string(TEST_DH_TYPE_CAMERA) } }; + map queryMap10 { { CapabilityInfoFilter::FILTER_DH_TYPE, + to_string(TEST_DH_TYPE_MIC) } }; + map queryMap11 { { CapabilityInfoFilter::FILTER_DH_TYPE, + to_string(TEST_DH_TYPE_SPEAKER) } }; + map queryMap12 { { CapabilityInfoFilter::FILTER_DH_TYPE, + to_string(TEST_DH_TYPE_DISPLAY) } }; + map 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> 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 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 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); +} +} +} diff --git a/services/distributedhardwarefwkserviceimpl/test/unittest/common/task/BUILD.gn b/services/distributedhardwarefwkserviceimpl/test/unittest/common/task/BUILD.gn new file mode 100644 index 00000000..aae45106 --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/test/unittest/common/task/BUILD.gn @@ -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" ] +} diff --git a/services/distributedhardwarefwkserviceimpl/test/unittest/common/task/include/mock_disable_task.h b/services/distributedhardwarefwkserviceimpl/test/unittest/common/task/include/mock_disable_task.h new file mode 100644 index 00000000..8aaf3a69 --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/test/unittest/common/task/include/mock_disable_task.h @@ -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 \ No newline at end of file diff --git a/services/distributedhardwarefwkserviceimpl/test/unittest/common/task/include/mock_enable_task.h b/services/distributedhardwarefwkserviceimpl/test/unittest/common/task/include/mock_enable_task.h new file mode 100644 index 00000000..04ffd779 --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/test/unittest/common/task/include/mock_enable_task.h @@ -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 \ No newline at end of file diff --git a/services/distributedhardwarefwkserviceimpl/test/unittest/common/task/include/mock_offline_task.h b/services/distributedhardwarefwkserviceimpl/test/unittest/common/task/include/mock_offline_task.h new file mode 100644 index 00000000..5a17042c --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/test/unittest/common/task/include/mock_offline_task.h @@ -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 offLineDevInfos); +private: + /* create disable tasks for off line device */ + void CreateDisableTask(); + /* clear off line device info */ + void ClearOffLineInfo(); + + std::vector offLineDevInfos; +}; +} +} +#endif \ No newline at end of file diff --git a/services/distributedhardwarefwkserviceimpl/test/unittest/common/task/include/mock_online_task.h b/services/distributedhardwarefwkserviceimpl/test/unittest/common/task/include/mock_online_task.h new file mode 100644 index 00000000..8551649a --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/test/unittest/common/task/include/mock_online_task.h @@ -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 + +#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 devInfos); +private: + void DoSyncInfo(); + void CreateEnableTask(); + + std::vector onLineDevInfos; +}; +} +} +#endif \ No newline at end of file diff --git a/services/distributedhardwarefwkserviceimpl/test/unittest/common/task/include/mock_task_factory.h b/services/distributedhardwarefwkserviceimpl/test/unittest/common/task/include/mock_task_factory.h new file mode 100644 index 00000000..47524a5d --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/test/unittest/common/task/include/mock_task_factory.h @@ -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 + +#include "single_instance.h" +#include "task.h" + +namespace OHOS { +namespace DistributedHardware { +class MockTaskFactory { +DECLARE_SINGLE_INSTANCE(MockTaskFactory); +public: + std::shared_ptr CreateTask(TaskType taskType, const std::string &networkId, const std::string &devId, + const std::string &dhId, std::shared_ptr fatherTask); +}; +} +} +#endif \ No newline at end of file diff --git a/services/distributedhardwarefwkserviceimpl/test/unittest/common/task/include/mock_task_utils.h b/services/distributedhardwarefwkserviceimpl/test/unittest/common/task/include/mock_task_utils.h new file mode 100644 index 00000000..628efa1c --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/test/unittest/common/task/include/mock_task_utils.h @@ -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 + +namespace OHOS { +namespace DistributedHardware { +struct MockDevInfo { + std::string networkId; + std::string devId; + std::string dhId; +}; +} +} +#endif \ No newline at end of file diff --git a/services/distributedhardwarefwkserviceimpl/test/unittest/common/task/include/task_test.h b/services/distributedhardwarefwkserviceimpl/test/unittest/common/task/include/task_test.h new file mode 100644 index 00000000..dc872f85 --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/test/unittest/common/task/include/task_test.h @@ -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 + +namespace OHOS { +namespace DistributedHardware { +class TaskTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; +} +} +#endif \ No newline at end of file diff --git a/services/distributedhardwarefwkserviceimpl/test/unittest/common/task/src/mock_disable_task.cpp b/services/distributedhardwarefwkserviceimpl/test/unittest/common/task/src/mock_disable_task.cpp new file mode 100644 index 00000000..ca9e6137 --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/test/unittest/common/task/src/mock_disable_task.cpp @@ -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. + */ + +#include "mock_disable_task.h" + +#include +#include + +#include "distributed_hardware_errno.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +MockDisableTask::MockDisableTask(const std::string &networkId, const std::string &devId, const std::string &dhId) + : DisableTask(networkId, devId, dhId) +{} + +int32_t MockDisableTask::UnRegisterHardware() +{ + using namespace std::chrono_literals; + std::this_thread::sleep_for(200ms); + return DH_FWK_SUCCESS; +} +} +} \ No newline at end of file diff --git a/services/distributedhardwarefwkserviceimpl/test/unittest/common/task/src/mock_enable_task.cpp b/services/distributedhardwarefwkserviceimpl/test/unittest/common/task/src/mock_enable_task.cpp new file mode 100644 index 00000000..6646eb06 --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/test/unittest/common/task/src/mock_enable_task.cpp @@ -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. + */ + +#include "mock_enable_task.h" + +#include +#include + +#include "distributed_hardware_errno.h" + +namespace OHOS { +namespace DistributedHardware { +MockEnableTask::MockEnableTask(const std::string &networkId, const std::string &devId, const std::string &dhId) + : EnableTask(networkId, devId, dhId) +{} + +int32_t MockEnableTask::RegisterHardware() +{ + using namespace std::chrono_literals; + std::this_thread::sleep_for(300ms); + return DH_FWK_SUCCESS; +} +} +} \ No newline at end of file diff --git a/services/distributedhardwarefwkserviceimpl/test/unittest/common/task/src/mock_offline_task.cpp b/services/distributedhardwarefwkserviceimpl/test/unittest/common/task/src/mock_offline_task.cpp new file mode 100644 index 00000000..c20d9e28 --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/test/unittest/common/task/src/mock_offline_task.cpp @@ -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. + */ + +#include "mock_offline_task.h" + +#include +#include + +#include "distributed_hardware_log.h" +#include "mock_task_factory.h" +#include "task_executor.h" + +namespace OHOS { +namespace DistributedHardware { +MockOffLineTask::MockOffLineTask(const std::string &networkId, const std::string &devId, const std::string &dhId) + : OffLineTask(networkId, devId, dhId) +{} + +void MockOffLineTask::CreateDisableTask() +{ + for (auto &devInfo : offLineDevInfos) { + std::shared_ptr disableTask = MockTaskFactory::GetInstance().CreateTask(TaskType::DISABLE, + devInfo.networkId, devInfo.devId, devInfo.dhId, shared_from_this()); + TaskExecutor::GetInstance().PushTask(disableTask); + } +} + +void MockOffLineTask::ClearOffLineInfo() +{ + DHLOGI("ClearOffLineInfo"); + using namespace std::chrono_literals; + std::this_thread::sleep_for(200ms); +} + +void MockOffLineTask::SetOffLineDevInfos(std::vector offLineDevInfos) +{ + this->offLineDevInfos = offLineDevInfos; +} +} +} \ No newline at end of file diff --git a/services/distributedhardwarefwkserviceimpl/test/unittest/common/task/src/mock_online_task.cpp b/services/distributedhardwarefwkserviceimpl/test/unittest/common/task/src/mock_online_task.cpp new file mode 100644 index 00000000..1ac00bfe --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/test/unittest/common/task/src/mock_online_task.cpp @@ -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 "mock_online_task.h" + +#include +#include + +#include "distributed_hardware_log.h" +#include "mock_task_factory.h" +#include "task_executor.h" + +namespace OHOS { +namespace DistributedHardware { +MockOnLineTask::MockOnLineTask(const std::string &networkId, const std::string &devId, const std::string &dhId) + : OnLineTask(networkId, devId, dhId) +{ + DHLOGI("Ctor MockOnLineTask: %s, type: %d", this->GetId().c_str(), this->GetTaskType()); +} + +void MockOnLineTask::DoSyncInfo() +{ + DHLOGI("DoSyncInfo"); + using namespace std::chrono_literals; + std::this_thread::sleep_for(200ms); +} + +void MockOnLineTask::CreateEnableTask() +{ + for (const auto& devInfo : onLineDevInfos) { + std::shared_ptr enableTask = MockTaskFactory::GetInstance().CreateTask(TaskType::ENABLE, + devInfo.networkId, devInfo.devId, devInfo.dhId, shared_from_this()); + TaskExecutor::GetInstance().PushTask(enableTask); + } +} + +void MockOnLineTask::SetOnLineDevInfos(std::vector devInfos) +{ + this->onLineDevInfos = devInfos; +} +} +} \ No newline at end of file diff --git a/services/distributedhardwarefwkserviceimpl/test/unittest/common/task/src/mock_task_factory.cpp b/services/distributedhardwarefwkserviceimpl/test/unittest/common/task/src/mock_task_factory.cpp new file mode 100644 index 00000000..eabe6a5b --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/test/unittest/common/task/src/mock_task_factory.cpp @@ -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 "mock_task_factory.h" + +#include "distributed_hardware_log.h" +#include "mock_disable_task.h" +#include "mock_enable_task.h" +#include "mock_offline_task.h" +#include "mock_online_task.h" +#include "task_board.h" + +namespace OHOS { +namespace DistributedHardware { +IMPLEMENT_SINGLE_INSTANCE(MockTaskFactory); +std::shared_ptr MockTaskFactory::CreateTask(TaskType taskType, const std::string &networkId, + const std::string &devId, const std::string &dhId, std::shared_ptr fatherTask) +{ + std::shared_ptr task = nullptr; + switch (taskType) { + case TaskType::ENABLE: { + task = std::make_shared(networkId, devId, dhId); + break; + } + case TaskType::DISABLE: { + task = std::make_shared(networkId, devId, dhId); + break; + } + case TaskType::ON_LINE: { + task = std::make_shared(networkId, devId, dhId); + break; + } + case TaskType::OFF_LINE: { + task = std::make_shared(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; +} +} +} \ No newline at end of file diff --git a/services/distributedhardwarefwkserviceimpl/test/unittest/common/task/src/task_test.cpp b/services/distributedhardwarefwkserviceimpl/test/unittest/common/task/src/task_test.cpp new file mode 100644 index 00000000..e5ee6567 --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/test/unittest/common/task/src/task_test.cpp @@ -0,0 +1,158 @@ +/* + * 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_test.h" + +#include +#include + +#include "dh_utils_tool.h" +#include "distributed_hardware_errno.h" +#include "mock_disable_task.h" +#include "mock_enable_task.h" +#include "mock_offline_task.h" +#include "mock_online_task.h" +#include "mock_task_factory.h" +#include "mock_task_utils.h" + +#include "task_board.h" +#include "task_executor.h" + +using namespace testing::ext; + +namespace OHOS { +namespace DistributedHardware { +namespace { +const std::string DEV_ID_1 = "bb536a637105409e904d4da83790a4a8"; +const std::string DEV_NETWORK_ID_1 = "nt36a637105409e904d4da83790a4a8"; +const MockDevInfo DEV_INFO_11 = { DEV_NETWORK_ID_1, DEV_ID_1, "Camera_1" }; +const MockDevInfo DEV_INFO_12 = { DEV_NETWORK_ID_1, DEV_ID_1, "Speaker_1" }; +const MockDevInfo DEV_INFO_13 = { DEV_NETWORK_ID_1, DEV_ID_1, "Mic_1" }; +const MockDevInfo DEV_INFO_14 = { DEV_NETWORK_ID_1, DEV_ID_1, "Display_1" }; +const MockDevInfo DEV_INFO_15 = { DEV_NETWORK_ID_1, DEV_ID_1, "Input_1" }; + +const std::string DEV_ID_2 = "06d177ffa09543389f3b445b4722f9be"; +const std::string DEV_NETWORK_ID_2 = "ntd177ffa09543389f3b445b4722f9be"; +const MockDevInfo DEV_INFO_21 = { DEV_NETWORK_ID_2, DEV_ID_2, "Camera_1" }; +const MockDevInfo DEV_INFO_22 = { DEV_NETWORK_ID_2, DEV_ID_2, "Speaker_1" }; +const MockDevInfo DEV_INFO_23 = { DEV_NETWORK_ID_2, DEV_ID_2, "Mic_1" }; +const MockDevInfo DEV_INFO_24 = { DEV_NETWORK_ID_2, DEV_ID_2, "Display_1" }; +const MockDevInfo DEV_INFO_25 = { DEV_NETWORK_ID_2, DEV_ID_2, "Input_1" }; +} + +void TaskTest::SetUpTestCase(void) +{ +} + +void TaskTest::TearDownTestCase(void) +{ +} + +void TaskTest::SetUp() +{ +} + +void TaskTest::TearDown() +{ +} + +/** + * @tc.name: task_test_001 + * @tc.desc: Verify the Execute OnLineTask function + * @tc.type: FUNC + * @tc.require: AR000GHSKP + */ +HWTEST_F(TaskTest, task_test_001, TestSize.Level0) +{ + std::shared_ptr onlineTask = + std::static_pointer_cast( + MockTaskFactory::GetInstance().CreateTask(TaskType::ON_LINE, DEV_NETWORK_ID_1, DEV_ID_1, "", nullptr)); + onlineTask->SetOnLineDevInfos({ DEV_INFO_11, DEV_INFO_12, DEV_INFO_13, DEV_INFO_14, DEV_INFO_15 }); + TaskExecutor::GetInstance().PushTask(onlineTask); + + ASSERT_EQ(DH_FWK_SUCCESS, TaskBoard::GetInstance().WaitForALLTaskFinish()); + ASSERT_TRUE(TaskBoard::GetInstance().IsAllTaskFinish()); +} + +/** + * @tc.name: task_test_002 + * @tc.desc: Verify the Execute OnLineTask function + * @tc.type: FUNC + * @tc.require: AR000GHSKN + */ +HWTEST_F(TaskTest, task_test_002, TestSize.Level0) +{ + std::shared_ptr onlineTask1 = std::static_pointer_cast( + MockTaskFactory::GetInstance().CreateTask(TaskType::ON_LINE, DEV_NETWORK_ID_1, DEV_ID_1, "", nullptr)); + onlineTask1->SetOnLineDevInfos({ DEV_INFO_11, DEV_INFO_12, DEV_INFO_13, DEV_INFO_14, DEV_INFO_15 }); + + std::shared_ptr onlineTask2 = std::static_pointer_cast( + MockTaskFactory::GetInstance().CreateTask(TaskType::ON_LINE, DEV_NETWORK_ID_2, DEV_ID_2, "", nullptr)); + onlineTask2->SetOnLineDevInfos({ DEV_INFO_21, DEV_INFO_22, DEV_INFO_23, DEV_INFO_24, DEV_INFO_25 }); + + TaskExecutor::GetInstance().PushTask(onlineTask1); + TaskExecutor::GetInstance().PushTask(onlineTask2); + + ASSERT_EQ(DH_FWK_SUCCESS, TaskBoard::GetInstance().WaitForALLTaskFinish()); + ASSERT_TRUE(TaskBoard::GetInstance().IsAllTaskFinish()); +} + +/** + * @tc.name: task_test_003 + * @tc.desc: Verify the Execute OffLineTask function + * @tc.type: FUNC + * @tc.require: AR000GHSJM + */ +HWTEST_F(TaskTest, task_test_003, TestSize.Level0) +{ + std::shared_ptr offlineTask = + std::static_pointer_cast( + MockTaskFactory::GetInstance().CreateTask(TaskType::OFF_LINE, DEV_NETWORK_ID_1, DEV_ID_1, "", nullptr)); + offlineTask->SetOffLineDevInfos({ DEV_INFO_11, DEV_INFO_12, DEV_INFO_13, DEV_INFO_14, DEV_INFO_15 }); + TaskExecutor::GetInstance().PushTask(offlineTask); + + ASSERT_EQ(DH_FWK_SUCCESS, TaskBoard::GetInstance().WaitForALLTaskFinish()); + ASSERT_TRUE(TaskBoard::GetInstance().IsAllTaskFinish()); +} + +/** + * @tc.name: task_test_004 + * @tc.desc: Verify the Execute OnLineTask and OffLineTask function + * @tc.type: FUNC + * @tc.require: AR000GHSJE + */ +HWTEST_F(TaskTest, task_test_004, TestSize.Level0) +{ + std::shared_ptr onlineTask = + std::static_pointer_cast( + MockTaskFactory::GetInstance().CreateTask(TaskType::ON_LINE, DEV_NETWORK_ID_1, DEV_ID_1, "", nullptr)); + onlineTask->SetOnLineDevInfos({ DEV_INFO_11, DEV_INFO_12, DEV_INFO_13, DEV_INFO_14, DEV_INFO_15 }); + + std::shared_ptr offlineTask = + std::static_pointer_cast( + MockTaskFactory::GetInstance().CreateTask(TaskType::OFF_LINE, DEV_NETWORK_ID_1, DEV_ID_1, "", nullptr)); + offlineTask->SetOffLineDevInfos({ DEV_INFO_11, DEV_INFO_12, DEV_INFO_13, DEV_INFO_14, DEV_INFO_15 }); + + TaskExecutor::GetInstance().PushTask(onlineTask); + + ASSERT_EQ(ERR_DH_FWK_TASK_TIMEOUT, TaskBoard::GetInstance().WaitForALLTaskFinish()); + ASSERT_FALSE(TaskBoard::GetInstance().IsAllTaskFinish()); + + TaskExecutor::GetInstance().PushTask(offlineTask); + ASSERT_EQ(DH_FWK_SUCCESS, TaskBoard::GetInstance().WaitForALLTaskFinish()); + ASSERT_TRUE(TaskBoard::GetInstance().IsAllTaskFinish()); +} +} +} \ No newline at end of file diff --git a/services/distributedhardwarefwkserviceimpl/test/unittest/common/versionmanager/BUILD.gn b/services/distributedhardwarefwkserviceimpl/test/unittest/common/versionmanager/BUILD.gn new file mode 100644 index 00000000..094574fb --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/test/unittest/common/versionmanager/BUILD.gn @@ -0,0 +1,58 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/distributedhardware/distributedhardwarefwk/distributedhardwarefwk.gni") +module_out_path = "distributed_hardware_fwk/version_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/componentloader", + "${services_path}/distributedhardwarefwkserviceimpl/include/versionmanager", + "${services_path}/distributedhardwarefwkserviceimpl/include/utils", + "${common_path}/utils/include", + "${common_path}/log/include", + "//utils/native/base/include", + ] +} + +ohos_unittest("VersionManagerTest") { + module_out_path = module_out_path + + sources = [ + "src/version_manager_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=\"VersionManagerTest\"", + "LOG_DOMAIN=0xD004100", + ] +} + +group("version_manager_test") { + testonly = true + deps = [ ":VersionManagerTest" ] +} diff --git a/services/distributedhardwarefwkserviceimpl/test/unittest/common/versionmanager/include/version_manager_test.h b/services/distributedhardwarefwkserviceimpl/test/unittest/common/versionmanager/include/version_manager_test.h new file mode 100644 index 00000000..5a53290f --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/test/unittest/common/versionmanager/include/version_manager_test.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_HARDWARE_VERSION_MANAGER_TEST_H +#define OHOS_DISTRIBUTED_HARDWARE_VERSION_MANAGER_TEST_H + +#include +#include + +#include + +namespace OHOS { +namespace DistributedHardware { +class VersionManagerTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; +} +} +#endif \ No newline at end of file diff --git a/services/distributedhardwarefwkserviceimpl/test/unittest/common/versionmanager/src/version_manager_test.cpp b/services/distributedhardwarefwkserviceimpl/test/unittest/common/versionmanager/src/version_manager_test.cpp new file mode 100644 index 00000000..692a4e11 --- /dev/null +++ b/services/distributedhardwarefwkserviceimpl/test/unittest/common/versionmanager/src/version_manager_test.cpp @@ -0,0 +1,158 @@ +/* + * 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 "version_manager_test.h" + +#include "component_loader.h" +#include "version_manager.h" + +using namespace testing::ext; + +namespace OHOS { +namespace DistributedHardware { +void VersionManagerTest::SetUpTestCase(void) {} + +void VersionManagerTest::TearDownTestCase(void) {} + +void VersionManagerTest::SetUp() +{ + ComponentLoader::GetInstance().Init(); +} + +void VersionManagerTest::TearDown() +{ + ComponentLoader::GetInstance().UnInit(); +} + +namespace { +const std::string TEST_DEVICE_ID_1 = "bb536a637105409e904d4da83790a4a7"; +const std::string TEST_DEVICE_ID_2 = "bb536a637105409e904d4da83790a4a8"; +const std::string TEST_DEVICE_ID_3 = "bb536a637105409e904d4da83790a4a9"; +const std::string TEST_DEVICE_ID_4 = "bb536a637105409e904d4da83790a4a0"; +const std::string TEST_HANDLER_VERSION_1 = "1.0"; +const std::string TEST_HANDLER_VERSION_2 = "3.0"; +const std::string TEST_HANDLER_VERSION_3 = "5.0"; +const std::string TEST_SOURCE_VERSION_1 = "2.2"; +const std::string TEST_SOURCE_VERSION_2 = "2.0"; +const std::string TEST_SOURCE_VERSION_3 = "6.0"; +const std::string TEST_SINK_VERSION_1 = "2.4"; +const std::string TEST_SINK_VERSION_2 = "2.0"; +const std::string TEST_SINK_VERSION_3 = "2.0"; +const std::string TEST_DH_VERSION = "3.1"; +const std::string TEST_COMPONENT_NAME_1 = "distributed_camera"; +const std::string TEST_COMPONENT_NAME_2 = "distributed_speaker"; +const std::string TEST_COMPONENT_NAME_3 = "distributed_mic"; +} + +/** + * @tc.name: version_manager_test_001 + * @tc.desc: Verify the Init function. + * @tc.type: FUNC + * @tc.require: AR000GHSKN + */ +HWTEST_F(VersionManagerTest, version_manager_test_001, TestSize.Level0) +{ + auto ret = VersionManager::GetInstance().Init(); + EXPECT_EQ(DH_FWK_SUCCESS, ret); +} + +void CompVersionGetValue(CompVersion &cVs, std::string name, DHType dhType, std::string handlerVersion, + std::string sourceVersion, std::string sinkVersion) +{ + cVs.name = name; + cVs.dhType = dhType; + cVs.handlerVersion = handlerVersion; + cVs.sourceVersion = sourceVersion; + cVs.sinkVersion = sinkVersion; +} + +/** + * @tc.name: version_manager_test_002 + * @tc.desc: Verify AddDHVersion function + * @tc.type: FUNC + * @tc.require: AR000GHSKN + */ +HWTEST_F(VersionManagerTest, version_manager_test_002, TestSize.Level0) +{ + DHVersion dhVersion; + CompVersion cVs1; + CompVersionGetValue(cVs1, TEST_COMPONENT_NAME_1, DHType::CAMERA, TEST_HANDLER_VERSION_1, TEST_SOURCE_VERSION_1, + TEST_SINK_VERSION_1); + CompVersion cVs2; + CompVersionGetValue(cVs2, TEST_COMPONENT_NAME_2, DHType::SPEAKER, TEST_HANDLER_VERSION_2, TEST_SOURCE_VERSION_2, + TEST_SINK_VERSION_2); + CompVersion cVs3; + CompVersionGetValue(cVs3, TEST_COMPONENT_NAME_3, DHType::MIC, TEST_HANDLER_VERSION_3, TEST_SOURCE_VERSION_3, + TEST_SINK_VERSION_3); + dhVersion.devId = TEST_DEVICE_ID_1; + dhVersion.dhVersion = TEST_DH_VERSION; + dhVersion.compVersions.insert(std::make_pair(cVs1.dhType, cVs1)); + dhVersion.compVersions.insert(std::make_pair(cVs2.dhType, cVs2)); + dhVersion.compVersions.insert(std::make_pair(cVs3.dhType, cVs3)); + int32_t ret = VersionManager::GetInstance().AddDHVersion(dhVersion.devId, dhVersion); + EXPECT_EQ(DH_FWK_SUCCESS, ret); + dhVersion.devId = TEST_DEVICE_ID_2; + ret = VersionManager::GetInstance().AddDHVersion(dhVersion.devId, dhVersion); + EXPECT_EQ(DH_FWK_SUCCESS, ret); +} + +/** + * @tc.name: version_manager_test_003 + * @tc.desc: Verify GetLocalDeviceVersion function + * @tc.type: FUNC + * @tc.require: AR000GHSKN + */ +HWTEST_F(VersionManagerTest, version_manager_test_003, TestSize.Level0) +{ + std::string strVersion = VersionManager::GetInstance().GetLocalDeviceVersion(); + EXPECT_EQ(DH_LOCAL_VERSION, strVersion); +} + +/** + * @tc.name: version_manager_test_004 + * @tc.desc: Verify GetDHVersion function + * @tc.type: FUNC + * @tc.require: AR000GHSKN + */ +HWTEST_F(VersionManagerTest, version_manager_test_004, TestSize.Level0) +{ + DHVersion dhVersion; + int32_t ret = VersionManager::GetInstance().GetDHVersion(TEST_DEVICE_ID_2, dhVersion); + EXPECT_EQ(DH_FWK_SUCCESS, ret); + EXPECT_EQ(TEST_HANDLER_VERSION_2, dhVersion.compVersions[DHType::SPEAKER].handlerVersion); + EXPECT_EQ(TEST_DH_VERSION, dhVersion.dhVersion); + ret = VersionManager::GetInstance().GetDHVersion(TEST_DEVICE_ID_3, dhVersion); + EXPECT_EQ(ERR_DH_FWK_VERSION_DEVICE_ID_NOT_EXIST, ret); +} + +/** + * @tc.name: version_manager_test_005 + * @tc.desc: Verify RemoveDHVersion function + * @tc.type: FUNC + * @tc.require: AR000GHSKN + */ +HWTEST_F(VersionManagerTest, version_manager_test_005, TestSize.Level0) +{ + int32_t ret = VersionManager::GetInstance().RemoveDHVersion(TEST_DEVICE_ID_2); + EXPECT_EQ(DH_FWK_SUCCESS, ret); + ret = VersionManager::GetInstance().RemoveDHVersion(TEST_DEVICE_ID_4); + EXPECT_EQ(ERR_DH_FWK_VERSION_DEVICE_ID_NOT_EXIST, ret); + ret = VersionManager::GetInstance().RemoveDHVersion(TEST_DEVICE_ID_2); + EXPECT_EQ(ERR_DH_FWK_VERSION_DEVICE_ID_NOT_EXIST, ret); + ret = VersionManager::GetInstance().RemoveDHVersion(TEST_DEVICE_ID_1); + EXPECT_EQ(DH_FWK_SUCCESS, ret); +} +} +} diff --git a/utils/BUILD.gn b/utils/BUILD.gn new file mode 100644 index 00000000..ce60423d --- /dev/null +++ b/utils/BUILD.gn @@ -0,0 +1,53 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/distributedhardware/distributedhardwarefwk/distributedhardwarefwk.gni") + +ohos_shared_library("distributedhardwareutils") { + include_dirs = [ + "//utils/native/base/include", + "//utils/system/safwk/native/include", + "${common_path}/log/include", + "${common_path}/utils/include", + "include", + "include/log", + "include/eventbus", + ] + + sources = [ + "src/anonymous_string.cpp", + "src/log/dh_log.cpp", + "src/dh_utils_tool.cpp" + ] + + deps = [ "//utils/native/base:utils" ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"distributedhardwareutils\"", + "LOG_DOMAIN=0xD004100", + ] + + external_deps = [ + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "eventhandler:libeventhandler", + "hiviewdfx_hilog_native:libhilog", + "dsoftbus_standard:softbus_client", + ] + + subsystem_name = "distributedhardware" + + part_name = "distributed_hardware_fwk" +} diff --git a/utils/include/anonymous_string.h b/utils/include/anonymous_string.h new file mode 100644 index 00000000..f2a88e03 --- /dev/null +++ b/utils/include/anonymous_string.h @@ -0,0 +1,27 @@ +/* + * 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_ANONYMOUS_STRING_H +#define OHOS_DISTRIBUTED_HARDWARE_ANONYMOUS_STRING_H + +#include + +namespace OHOS { +namespace DistributedHardware { +std::string GetAnonyString(const std::string &value); +std::string GetAnonyInt32(const int32_t value); +} +} +#endif \ No newline at end of file diff --git a/utils/include/dh_utils_tool.h b/utils/include/dh_utils_tool.h new file mode 100644 index 00000000..00198874 --- /dev/null +++ b/utils/include/dh_utils_tool.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_HARDWARE_DHUTILS_TOOL_H +#define OHOS_DISTRIBUTED_HARDWARE_DHUTILS_TOOL_H + +#include +#include + +#include "device_type.h" + +namespace OHOS { +namespace DistributedHardware { +/** + * return current time in millisecond. + */ +int64_t GetCurrentTime(); + +/** + * return a random string id. + */ +std::string GetRandomID(); + +std::string GetUUIDByNetworkId(const std::string &networkId); + +DeviceInfo GetLocalDeviceInfo(); +} +} +#endif \ No newline at end of file diff --git a/utils/include/eventbus/event.h b/utils/include/eventbus/event.h new file mode 100644 index 00000000..8c907534 --- /dev/null +++ b/utils/include/eventbus/event.h @@ -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_EVENT_H +#define OHOS_DISTRIBUTED_HARDWARE_EVENT_H + +#include + +#include "event_sender.h" + +namespace OHOS { +namespace DistributedHardware { +#define TYPEINDENT(className) public: \ + virtual std::string GetType() const \ + { \ + return #className; \ + } + +class Event { +TYPEINDENT(Event) + +public: + Event(EventSender &sender) : sender_(sender) {} + + virtual ~Event() = default; + + const EventSender &GetSender() const + { + return sender_; + } + +private: + EventSender &sender_; +}; +} +} +#endif \ No newline at end of file diff --git a/utils/include/eventbus/event_bus.h b/utils/include/eventbus/event_bus.h new file mode 100644 index 00000000..2d1a9774 --- /dev/null +++ b/utils/include/eventbus/event_bus.h @@ -0,0 +1,206 @@ +/* + * 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_EVENT_BUS_H +#define OHOS_DISTRIBUTED_HARDWARE_EVENT_BUS_H + +#include +#include +#include +#include + +#include "event_handler.h" + +#include "dh_log.h" +#include "anonymous_string.h" +#include "event.h" +#include "eventbus_handler.h" +#include "event_registration.h" + +#ifndef DH_LOG_TAG +#define DH_LOG_TAG "DHEventBus" +#endif + +namespace OHOS { +namespace DistributedHardware { +enum POSTMODE : uint32_t { + POST_ASYNC = 0, + POST_SYNC, +}; + +class EventBus final { +public: + EventBus() + { + ULOGI("ctor EventBus"); + if (!eventbusHandler_) { + auto busRunner = OHOS::AppExecFwk::EventRunner::Create("DHEventbusHandler"); + eventbusHandler_ = std::make_shared(busRunner); + } + } + ~EventBus() + { + ULOGI("dtor EventBus"); + } + + template + std::shared_ptr AddHandler(const std::string &typeId, + DistributedHardware::EventBusHandler &handler) + { + std::lock_guard lock(handlerMtx); + Registrations *registrations = handlers[typeId]; + + if (registrations == nullptr) { + registrations = new EventRegistration::Registrations(); + handlers[typeId] = registrations; + } + + for (auto ® : *registrations) { + if (reg->GetHandler() == static_cast(&handler) && reg->GetSender() == nullptr) { + return reg; + } + } + + std::shared_ptr registration = + std::make_shared(static_cast(&handler), nullptr); + registrations->insert(registration); + + return registration; + } + + template + std::shared_ptr AddHandler(const std::string &typeId, EventBusHandler &handler, + EventSender &sender) + { + std::lock_guard lock(handlerMtx); + Registrations *registrations = handlers[typeId]; + + if (registrations == nullptr) { + registrations = new EventRegistration::Registrations(); + handlers[typeId] = registrations; + } + + for (auto ® : *registrations) { + if (reg->GetHandler() == static_cast(&handler) && reg->GetSender() == &sender) { + return reg; + } + } + + std::shared_ptr registration = + std::make_shared(static_cast(&handler), &sender); + registrations->insert(registration); + + return registration; + } + + template + bool RemoveHandler(const std::string &typeId, std::shared_ptr &EvenReg) + { + std::lock_guard lock(handlerMtx); + Registrations *registrations = handlers[typeId]; + if (registrations == nullptr) { + return false; + } + + bool ret = false; + auto regIter = registrations->find(EvenReg); + if (regIter != registrations->end()) { + registrations->erase(regIter); + ret = true; + } + + return ret; + } + + template + void PostEvent(T &e, POSTMODE mode = POSTMODE::POST_ASYNC) + { + if (mode == POSTMODE::POST_SYNC) { + PostEventInner(e); + } else { + auto eventFunc = [this, e]() mutable { + PostEventInner(e); + }; + if (!(eventbusHandler_ && eventbusHandler_->PostTask(eventFunc))) { + ULOGE("Eventbus::PostEvent Async PostTask fail"); + } + } + } + + template + void PostEvent(T &e, int64_t delayTime) + { + auto eventFunc = [this, e]() mutable { + PostEventInner(e); + }; + if (!(eventbusHandler_ && eventbusHandler_->PostTask(eventFunc, e->getType(), delayTime))) { + ULOGE("Eventbus::PostEvent Async PostTask fail"); + } + } + + template + void RemoveEvent(T &e) + { + if (!(eventbusHandler_ && eventbusHandler_->RemoveTask(e->getType()))) { + ULOGE("Eventbus::RemoveEvent fail"); + } + } + + void PostTask(const OHOS::AppExecFwk::InnerEvent::Callback& callback, + const std::string& name, + int64_t delayTimeInMs = 0) + { + ULOGI("Eventbus::PostTask Async PostTask, taskName:%{public}s.", GetAnonyString(name).c_str()); + if (eventbusHandler_ != nullptr) { + eventbusHandler_->PostTask(callback, name, delayTimeInMs); + } + } + + void RemoveTask(const std::string& name) + { + ULOGI("Eventbus::RemoveTask, taskName:%{public}s.", GetAnonyString(name).c_str()); + if (eventbusHandler_ != nullptr) { + eventbusHandler_->RemoveTask(name); + } + } + +private: + template + void PostEventInner(T &e) + { + std::lock_guard lock(handlerMtx); + Registrations *registrations = handlers[e.GetType()]; + if (registrations == nullptr) { + return; + } + + for (auto ® : *registrations) { + if ((reg->GetSender() == nullptr) || (reg->GetSender() == &e.GetSender())) { + static_cast *>(const_cast(reg->GetHandler()))->Dispatch(e); + } + } + } + +private: + std::shared_ptr eventbusHandler_; + + using Registrations = std::set>; + std::mutex handlerMtx; + using TypeMap = std::unordered_map> *>; + TypeMap handlers; +}; +} +} +#endif \ No newline at end of file diff --git a/utils/include/eventbus/event_registration.h b/utils/include/eventbus/event_registration.h new file mode 100644 index 00000000..623835ab --- /dev/null +++ b/utils/include/eventbus/event_registration.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_HARDWARE_EVENT_REGISTRATION_H +#define OHOS_DISTRIBUTED_HARDWARE_EVENT_REGISTRATION_H + +#include +#include + +#include "event_sender.h" + +namespace OHOS { +namespace DistributedHardware { +class EventRegistration { +public: + using Registrations = std::set>; + + EventRegistration(void * const handler, EventSender * const sender) : handler(handler), sender(sender) {} + + virtual ~EventRegistration() {} + + const void *GetHandler() + { + return handler; + } + + const EventSender *GetSender() + { + return sender; + } + +private: + void * const handler; + EventSender * const sender; +}; +} +} +#endif \ No newline at end of file diff --git a/utils/include/eventbus/event_sender.h b/utils/include/eventbus/event_sender.h new file mode 100644 index 00000000..1aeaf29f --- /dev/null +++ b/utils/include/eventbus/event_sender.h @@ -0,0 +1,27 @@ +/* + * 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_EVENT_SENDER_H +#define OHOS_DISTRIBUTED_HARDWARE_EVENT_SENDER_H + +namespace OHOS { +namespace DistributedHardware { +class EventSender { +public: + virtual ~EventSender() = default; +}; +} +} +#endif \ No newline at end of file diff --git a/utils/include/eventbus/eventbus_handler.h b/utils/include/eventbus/eventbus_handler.h new file mode 100644 index 00000000..fb99b04c --- /dev/null +++ b/utils/include/eventbus/eventbus_handler.h @@ -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_EVENTBUSHANDLER_H +#define OHOS_DISTRIBUTED_HARDWARE_EVENTBUSHANDLER_H + +namespace OHOS { +namespace DistributedHardware { +template +class EventBusHandler { +public: + EventBusHandler() + { + } + + virtual ~EventBusHandler() = default; + + virtual void OnEvent(T &e) = 0; + + void Dispatch(T &e) + { + OnEvent(e); + } +}; +} +} +#endif \ No newline at end of file diff --git a/utils/include/log/dh_log.h b/utils/include/log/dh_log.h new file mode 100644 index 00000000..94a39137 --- /dev/null +++ b/utils/include/log/dh_log.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DH_LOG_H +#define OHOS_DH_LOG_H + +namespace OHOS { +namespace DistributedHardware { +typedef enum { + DH_LOG_DEBUG, + DH_LOG_INFO, + DH_LOG_WARN, + DH_LOG_ERROR, +} DHLogLevel; + +void DHLog(DHLogLevel logLevel, const char *fmt, ...); + +#define ULOGD(fmt, ...) DHLog(DH_LOG_DEBUG, \ + (std::string("[") + DH_LOG_TAG + "][" + __FUNCTION__ + "]:" + fmt).c_str(), ##__VA_ARGS__) + +#define ULOGI(fmt, ...) DHLog(DH_LOG_INFO, \ + (std::string("[") + DH_LOG_TAG + "][" + __FUNCTION__ + "]:" + fmt).c_str(), ##__VA_ARGS__) + +#define ULOGW(fmt, ...) DHLog(DH_LOG_WARN, \ + (std::string("[") + DH_LOG_TAG + "][" + __FUNCTION__ + "]:" + fmt).c_str(), ##__VA_ARGS__) + +#define ULOGE(fmt, ...) DHLog(DH_LOG_ERROR, \ + (std::string("[") + DH_LOG_TAG + "][" + __FUNCTION__ + "]:" + fmt).c_str(), ##__VA_ARGS__) +} +} +#endif diff --git a/utils/src/anonymous_string.cpp b/utils/src/anonymous_string.cpp new file mode 100644 index 00000000..73d95332 --- /dev/null +++ b/utils/src/anonymous_string.cpp @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "anonymous_string.h" + +#include +#include + +#include "securec.h" + +namespace OHOS { +namespace DistributedHardware { +std::string GetAnonyString(const std::string &value) +{ + constexpr size_t INT32_SHORT_ID_LENGTH = 20; + constexpr size_t INT32_PLAINTEXT_LENGTH = 4; + constexpr size_t INT32_MIN_ID_LENGTH = 3; + std::string res; + std::string tmpStr("******"); + size_t strLen = value.length(); + if (strLen < INT32_MIN_ID_LENGTH) { + return tmpStr; + } + + if (strLen <= INT32_SHORT_ID_LENGTH) { + res += value[0]; + res += tmpStr; + res += value[strLen - 1]; + } else { + res.append(value, 0, INT32_PLAINTEXT_LENGTH); + res += tmpStr; + res.append(value, strLen - INT32_PLAINTEXT_LENGTH, INT32_PLAINTEXT_LENGTH); + } + + return res; +} + +std::string GetAnonyInt32(const int32_t value) +{ + constexpr int32_t INT32_STRING_LENGTH = 40; + char tempBuffer[INT32_STRING_LENGTH] = ""; + int32_t secRet = sprintf_s(tempBuffer, INT32_STRING_LENGTH, "%d", value); + if (secRet <= 0) { + std::string nullString(""); + return nullString; + } + int32_t length = strlen(tempBuffer); + for (int32_t i = 1; i <= length - 1; i++) { + tempBuffer[i] = '*'; + } + if (length == 0x01) { + tempBuffer[0] = '*'; + } + + std::string tempString(tempBuffer); + return tempString; +} +} +} diff --git a/utils/src/dh_utils_tool.cpp b/utils/src/dh_utils_tool.cpp new file mode 100644 index 00000000..05f178a9 --- /dev/null +++ b/utils/src/dh_utils_tool.cpp @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dh_utils_tool.h" + +#include +#include +#include +#include + +#include "softbus_bus_center.h" + +#include "constants.h" +#include "distributed_hardware_errno.h" +#include "distributed_hardware_log.h" + +namespace OHOS { +namespace DistributedHardware { +constexpr int32_t MS_ONE_SECOND = 1000; +constexpr int32_t WORD_WIDTH_8 = 8; +constexpr int32_t WORD_WIDTH_4 = 4; + +int64_t GetCurrentTime() +{ + struct timeval tv { + 0 + }; + gettimeofday(&tv, nullptr); + return tv.tv_sec * MS_ONE_SECOND + tv.tv_usec / MS_ONE_SECOND; +} + +std::string GetRandomID() +{ + static std::random_device rd; + static std::uniform_int_distribution dist(0ULL, 0xFFFFFFFFFFFFFFFFULL); + uint64_t ab = dist(rd); + uint64_t cd = dist(rd); + uint32_t a, b, c, d; + std::stringstream ss; + ab = (ab & 0xFFFFFFFFFFFF0FFFULL) | 0x0000000000004000ULL; + cd = (cd & 0x3FFFFFFFFFFFFFFFULL) | 0x8000000000000000ULL; + a = (ab >> 32U); + b = (ab & 0xFFFFFFFFU); + c = (cd >> 32U); + d = (cd & 0xFFFFFFFFU); + ss << std::hex << std::nouppercase << std::setfill('0'); + ss << std::setw(WORD_WIDTH_8) << (a); + ss << std::setw(WORD_WIDTH_4) << (b >> 16U); + ss << std::setw(WORD_WIDTH_4) << (b & 0xFFFFU); + ss << std::setw(WORD_WIDTH_4) << (c >> 16U); + ss << std::setw(WORD_WIDTH_4) << (c & 0xFFFFU); + ss << std::setw(WORD_WIDTH_8) << d; + + return ss.str(); +} + +std::string GetUUIDByNetworkId(const std::string &networkId) +{ + if (networkId.empty()) { + return ""; + } + char uuid[UUID_BUF_LEN] = {0}; + auto ret = GetNodeKeyInfo(DH_FWK_PKG_NAME.c_str(), networkId.c_str(), NodeDeviceInfoKey::NODE_KEY_UUID, + reinterpret_cast(uuid), UUID_BUF_LEN); + return (ret == DH_FWK_SUCCESS) ? std::string(uuid) : ""; +} + +DeviceInfo GetLocalDeviceInfo() +{ + DeviceInfo devInfo { "", "", 0 }; + auto info = std::make_unique(); + auto ret = GetLocalNodeDeviceInfo(DH_FWK_PKG_NAME.c_str(), info.get()); + if (ret != DH_FWK_SUCCESS) { + DHLOGE("GetLocalNodeDeviceInfo failed, errCode = %d", ret); + return devInfo; + } + devInfo.deviceId = GetUUIDByNetworkId(info->networkId); + devInfo.deviceName = info->deviceName; + devInfo.deviceType = info->deviceTypeId; + return devInfo; +} +} +} diff --git a/utils/src/log/dh_log.cpp b/utils/src/log/dh_log.cpp new file mode 100644 index 00000000..16eb7c5f --- /dev/null +++ b/utils/src/log/dh_log.cpp @@ -0,0 +1,87 @@ +/* + * 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_log.h" + +#include "securec.h" + +#include "constants.h" + +#ifdef HI_LOG_ENABLE +#include "hilog/log.h" +#else +#include +#endif + +namespace OHOS { +namespace DistributedHardware { +static void DHLogOut(DHLogLevel logLevel, const char *logBuf) +{ +#ifdef HI_LOG_ENABLE + LogLevel hiLogLevel = LOG_INFO; + switch (logLevel) { + case DH_LOG_DEBUG: + hiLogLevel = LOG_DEBUG; + break; + case DH_LOG_INFO: + hiLogLevel = LOG_INFO; + break; + case DH_LOG_WARN: + hiLogLevel = LOG_WARN; + break; + case DH_LOG_ERROR: + hiLogLevel = LOG_ERROR; + break; + default: + break; + } + (void)HiLogPrint(LOG_CORE, hiLogLevel, LOG_DOMAIN, DH_LOG_TITLE_TAG.c_str(), "%{public}s", logBuf); +#else + switch (logLevel) { + case DH_LOG_DEBUG: + printf("[D]%s\n", logBuf); + break; + case DH_LOG_INFO: + printf("[I]%s\n", logBuf); + break; + case DH_LOG_WARN: + printf("[W]%s\n", logBuf); + break; + case DH_LOG_ERROR: + printf("[E]%s\n", logBuf); + break; + default: + break; + } +#endif +} + +void DHLog(DHLogLevel logLevel, const char *fmt, ...) +{ + char logBuf[LOG_MAX_LEN] = {0}; + va_list arg; + + (void)memset_s(&arg, sizeof(va_list), 0, sizeof(va_list)); + va_start(arg, fmt); + int32_t ret = vsprintf_s(logBuf, sizeof(logBuf), fmt, arg); + va_end(arg); + if (ret < 0) { + DHLogOut(logLevel, "DH log length error."); + return; + } + DHLogOut(logLevel, logBuf); +} +} +} diff --git a/utils/test/unittest/BUILD.gn b/utils/test/unittest/BUILD.gn new file mode 100644 index 00000000..705c81df --- /dev/null +++ b/utils/test/unittest/BUILD.gn @@ -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. + +group("utils_test") { + testonly = true + deps = [ + "common/eventbus:event_bus_test", + "common/utilstool:utils_tool_test" + ] +} \ No newline at end of file diff --git a/utils/test/unittest/common/eventbus/BUILD.gn b/utils/test/unittest/common/eventbus/BUILD.gn new file mode 100644 index 00000000..c3483808 --- /dev/null +++ b/utils/test/unittest/common/eventbus/BUILD.gn @@ -0,0 +1,50 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/distributedhardware/distributedhardwarefwk/distributedhardwarefwk.gni") +module_out_path = "distributed_hardware_fwk/event_bus_test" + +config("module_private_config") { + visibility = [ ":*" ] + include_dirs = [ + "include", + "${utils_path}/include", + "${utils_path}/include/log", + "${utils_path}/include/eventbus", + "//utils/native/base/include", + ] +} + +## UnitTest dh_common_event_bus_test +ohos_unittest("EventBusTest") { + module_out_path = module_out_path + + sources = [ "${utils_path}/test/unittest/common/eventbus/event_bus_test.cpp" ] + + configs = [ ":module_private_config" ] + + deps = [ + "//third_party/googletest:gtest_main", + "//foundation/distributedhardware/distributedhardwarefwk/utils:distributedhardwareutils" + ] + + external_deps = [ + "eventhandler:libeventhandler", + ] +} + +group("event_bus_test") { + testonly = true + deps = [ ":EventBusTest" ] +} diff --git a/utils/test/unittest/common/eventbus/event_bus_test.cpp b/utils/test/unittest/common/eventbus/event_bus_test.cpp new file mode 100644 index 00000000..87669619 --- /dev/null +++ b/utils/test/unittest/common/eventbus/event_bus_test.cpp @@ -0,0 +1,151 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "event_bus_test.h" + +using namespace testing::ext; + +namespace OHOS { +namespace DistributedHardware { +void EventbusTest::SetUpTestCase(void) +{ +} + +void EventbusTest::TearDownTestCase(void) +{ +} + +void EventbusTest::SetUp() +{ + g_obj = new FakeObject("Player"); + g_listener = new FakeListener(); + g_sender = new FakeSender(); + g_regHandler = nullptr; + g_eventBus = new EventBus(); +} + +void EventbusTest::TearDown() +{ + if (g_obj != nullptr) { + delete g_obj; + g_obj = nullptr; + } + if (g_listener != nullptr) { + delete g_listener; + g_listener = nullptr; + } + if (g_sender != nullptr) { + delete g_sender; + g_sender = nullptr; + } + g_regHandler = nullptr; + + if (g_eventBus != nullptr) { + delete g_eventBus; + g_eventBus = nullptr; + } +} + +/** + * @tc.name: event_bus_test_001 + * @tc.desc: Verify the EventBus AddHandler function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(EventbusTest, event_bus_test_001, TestSize.Level0) +{ + EXPECT_EQ(g_regHandler, nullptr); + + FakeEvent e(*g_sender, *g_obj); + g_regHandler = g_eventBus->AddHandler(e.GetType(), *g_listener); + + EXPECT_NE(g_regHandler, nullptr); + EXPECT_EQ(g_regHandler->GetSender(), nullptr); + EXPECT_EQ(g_regHandler->GetHandler(), (void *)g_listener); +} + +/** + * @tc.name: event_bus_test_002 + * @tc.desc: Verify the EventBus AddHandler function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(EventbusTest, event_bus_test_002, TestSize.Level0) +{ + EXPECT_EQ(g_regHandler, nullptr); + + FakeEvent e(*g_sender, *g_obj); + g_regHandler = g_eventBus->AddHandler(e.GetType(), *g_listener); + std::shared_ptr secondHandler = g_eventBus->AddHandler(e.GetType(), *g_listener); + + EXPECT_NE(secondHandler, nullptr); + EXPECT_EQ(g_regHandler, secondHandler); +} + +/** + * @tc.name: event_bus_test_003 + * @tc.desc: Verify the EventBus AddHandler with sender function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(EventbusTest, event_bus_test_003, TestSize.Level0) +{ + EXPECT_EQ(g_regHandler, nullptr); + + FakeEvent e(*g_sender, *g_obj); + g_regHandler = g_eventBus->AddHandler(e.GetType(), *g_listener); + std::shared_ptr secondHandler = + g_eventBus->AddHandler(e.GetType(), *g_listener, *g_sender); + + EXPECT_NE(g_regHandler, nullptr); + EXPECT_NE(secondHandler, nullptr); + EXPECT_NE(g_regHandler, secondHandler); + EXPECT_EQ(secondHandler->GetSender(), g_sender); + EXPECT_EQ(secondHandler->GetHandler(), (void *)g_listener); +} + +/** + * @tc.name: event_bus_test_004 + * @tc.desc: Verify the EventBus AddHandler and RemoveHandler function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(EventbusTest, event_bus_test_004, TestSize.Level0) +{ + EXPECT_EQ(g_regHandler, nullptr); + FakeEvent e(*g_sender, *g_obj); + EXPECT_EQ(false, g_eventBus->RemoveHandler(e.GetType(), g_regHandler)); + + g_regHandler = g_eventBus->AddHandler(e.GetType(), *g_listener); + EXPECT_EQ(true, g_eventBus->RemoveHandler(e.GetType(), g_regHandler)); +} + +/** + * @tc.name: event_bus_test_005 + * @tc.desc: Verify the EventBus PostEvent function. + * @tc.type: FUNC + * @tc.require: AR000GHSK9 + */ +HWTEST_F(EventbusTest, event_bus_test_005, TestSize.Level0) +{ + EXPECT_EQ(0, g_obj->GetAge()); + + FakeEvent e(*g_sender, *g_obj, 10); + g_regHandler = g_eventBus->AddHandler(e.GetType(), *g_listener); + g_eventBus->PostEvent(e, POSTMODE::POST_SYNC); + EXPECT_EQ(10, g_obj->GetAge()); +} +} +} \ No newline at end of file diff --git a/utils/test/unittest/common/eventbus/event_bus_test.h b/utils/test/unittest/common/eventbus/event_bus_test.h new file mode 100644 index 00000000..c57b4c83 --- /dev/null +++ b/utils/test/unittest/common/eventbus/event_bus_test.h @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_HARDWARE_EVENT_BUS_TEST_H +#define OHOS_DISTRIBUTED_HARDWARE_EVENT_BUS_TEST_H + +#include +#include + +#include + +#include "event_handler.h" + +#include "event.h" +#include "event_bus.h" +#include "event_sender.h" +#include "eventbus_handler.h" + +namespace OHOS { +namespace DistributedHardware { +class FakeObject { +public: + explicit FakeObject(std::string name) : name_(name), age_(0) {} + virtual ~FakeObject() {} + void SetAge(int32_t age) + { + age_ = age; + } + int32_t GetAge() const + { + return age_; + } + +private: + std::string name_; + int32_t age_; +}; + +class FakeEvent : public OHOS::DistributedHardware::Event { + TYPEINDENT(FakeEvent) +public: + FakeEvent(OHOS::DistributedHardware::EventSender &sender, FakeObject &object) + : Event(sender), object_(object), action_(0) + {} + FakeEvent(OHOS::DistributedHardware::EventSender &sender, FakeObject &object, int32_t action) + : Event(sender), object_(object), action_(action) + {} + virtual ~FakeEvent() {} + + FakeObject *GetObject() const + { + return &object_; + } + int32_t GetAction() const + { + return action_; + } + +private: + FakeObject &object_; + int32_t action_; +}; + +class FakeListener : public OHOS::DistributedHardware::EventBusHandler { +public: + FakeListener() {} + virtual ~FakeListener() {} + + virtual void OnEvent(FakeEvent &ev) + { + FakeObject *obj = ev.GetObject(); + obj->SetAge(ev.GetAction()); + } +}; + +class FakeSender : public OHOS::DistributedHardware::EventSender { +public: + FakeSender() {} + virtual ~FakeSender() {} +}; + +class EventbusTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +static FakeObject *g_obj = nullptr; +static FakeSender *g_sender = nullptr; +static FakeListener *g_listener = nullptr; +static std::shared_ptr g_regHandler = nullptr; +static EventBus* g_eventBus = nullptr; +} +} +#endif \ No newline at end of file diff --git a/utils/test/unittest/common/utilstool/BUILD.gn b/utils/test/unittest/common/utilstool/BUILD.gn new file mode 100644 index 00000000..4e67c6e9 --- /dev/null +++ b/utils/test/unittest/common/utilstool/BUILD.gn @@ -0,0 +1,46 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/distributedhardware/distributedhardwarefwk/distributedhardwarefwk.gni") +module_out_path = "distributed_hardware_fwk/utils_tool_test" + +config("module_private_config") { + visibility = [ ":*" ] + include_dirs = [ + "include", + "${utils_path}/include", + "${utils_path}/include/log", + "${common_path}/utils/include", + "//utils/native/base/include", + ] +} + +## UnitTest dh_utils_tool_test +ohos_unittest("UtilsToolTest") { + module_out_path = module_out_path + + sources = [ "${utils_path}/test/unittest/common/utilstool/utils_tool_test.cpp" ] + + configs = [ ":module_private_config" ] + + deps = [ + "//third_party/googletest:gtest_main", + "//foundation/distributedhardware/distributedhardwarefwk/utils:distributedhardwareutils" + ] +} + +group("utils_tool_test") { + testonly = true + deps = [ ":UtilsToolTest" ] +} diff --git a/utils/test/unittest/common/utilstool/utils_tool_test.cpp b/utils/test/unittest/common/utilstool/utils_tool_test.cpp new file mode 100644 index 00000000..e67458ec --- /dev/null +++ b/utils/test/unittest/common/utilstool/utils_tool_test.cpp @@ -0,0 +1,121 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "utils_tool_test.h" + +#include +#include +#include + +#include "anonymous_string.h" +#include "dh_utils_tool.h" + +using namespace testing::ext; + +namespace OHOS { +namespace DistributedHardware { +void UtilsToolTest::SetUpTestCase(void) +{ +} + +void UtilsToolTest::TearDownTestCase(void) +{ +} + +void UtilsToolTest::SetUp() +{ +} + +void UtilsToolTest::TearDown() +{ +} + +/** + * @tc.name: utils_tool_test_001 + * @tc.desc: Verify the utils tool GetCurrentTime function + * @tc.type: FUNC + * @tc.require: AR000GHSK0 + */ +HWTEST_F(UtilsToolTest, utils_tool_test_001, TestSize.Level0) +{ + int64_t time1 = GetCurrentTime(); + using namespace std::chrono_literals; + std::this_thread::sleep_for(100ms); + int64_t time2 = GetCurrentTime(); + + EXPECT_LT(time1, time2); +} + +/** + * @tc.name: utils_tool_test_002 + * @tc.desc: Verify the utils tool GetRandomID function + * @tc.type: FUNC + * @tc.require: AR000GHSK0 + */ +HWTEST_F(UtilsToolTest, utils_tool_test_002, TestSize.Level0) +{ + uint32_t roundCnt = 100; + std::set idSet; + + for (uint32_t i = 0; i < roundCnt; i++) { + idSet.insert(GetRandomID()); + } + + EXPECT_EQ(idSet.size(), roundCnt); +} + +/** + * @tc.name: utils_tool_test_003 + * @tc.desc: Verify the GetAnonyString function + * @tc.type: FUNC + * @tc.require: AR000GHSK0 + */ +HWTEST_F(UtilsToolTest, utils_tool_test_003, TestSize.Level0) +{ + std::string str1 = "a"; + std::string str2 = "ab"; + std::string str3 = "abc"; + std::string str4 = "abcd"; + std::string str5 = "9a40932aff004e209e93524c6e35706b"; + + ASSERT_STRNE(str1.c_str(), GetAnonyString(str1).c_str()); + ASSERT_STRNE(str2.c_str(), GetAnonyString(str2).c_str()); + ASSERT_STRNE(str3.c_str(), GetAnonyString(str3).c_str()); + ASSERT_STRNE(str4.c_str(), GetAnonyString(str4).c_str()); + ASSERT_STRNE(str5.c_str(), GetAnonyString(str5).c_str()); +} + +/** + * @tc.name: utils_tool_test_004 + * @tc.desc: Verify the GetAnnoyInt32 function + * @tc.type: FUNC + * @tc.require: AR000GHSK0 + */ +HWTEST_F(UtilsToolTest, utils_tool_test_004, TestSize.Level0) +{ + int32_t i1 = 0; + int32_t i2 = 10; + int32_t i3 = 555; + int32_t i4 = 6666; + int32_t i5 = 88888; + + ASSERT_STRNE(std::to_string(i1).c_str(), GetAnonyInt32(i1).c_str()); + ASSERT_STRNE(std::to_string(i2).c_str(), GetAnonyInt32(i2).c_str()); + ASSERT_STRNE(std::to_string(i3).c_str(), GetAnonyInt32(i3).c_str()); + ASSERT_STRNE(std::to_string(i4).c_str(), GetAnonyInt32(i4).c_str()); + ASSERT_STRNE(std::to_string(i5).c_str(), GetAnonyInt32(i5).c_str()); +} +} +} \ No newline at end of file diff --git a/utils/test/unittest/common/utilstool/utils_tool_test.h b/utils/test/unittest/common/utilstool/utils_tool_test.h new file mode 100644 index 00000000..62926ab0 --- /dev/null +++ b/utils/test/unittest/common/utilstool/utils_tool_test.h @@ -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_UTILS_TOOL_TEST_H +#define OHOS_DISTRIBUTED_HARDWARE_UTILS_TOOL_TEST_H + +#include + +namespace OHOS { +namespace DistributedHardware { +class UtilsToolTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; +} +} +#endif \ No newline at end of file -- Gitee From 77bfa647c7c3015c2767c1b168de21c9b3508a2c Mon Sep 17 00:00:00 2001 From: hwzhangchuang Date: Mon, 28 Feb 2022 19:42:59 +0800 Subject: [PATCH 2/5] modify code check problem Signed-off-by: hwzhangchuang --- .../src/componentloader/component_loader.cpp | 2 +- .../src/resourcemanager/capability_info_manager.cpp | 5 ++--- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/services/distributedhardwarefwkserviceimpl/src/componentloader/component_loader.cpp b/services/distributedhardwarefwkserviceimpl/src/componentloader/component_loader.cpp index da4bb5c0..17881f2f 100644 --- a/services/distributedhardwarefwkserviceimpl/src/componentloader/component_loader.cpp +++ b/services/distributedhardwarefwkserviceimpl/src/componentloader/component_loader.cpp @@ -236,7 +236,7 @@ int32_t ComponentLoader::ParseConfig() int32_t ret; DHLOGI("ParseConfig start"); std::string jsonStr = Readfile(COMPONENTSLOAD_PROFILE_PATH); - if (jsonStr.length() <= 0) { + if (jsonStr.length() == 0) { DHLOGE("profile is empty return"); return ERR_DH_FWK_LOADER_COMPONENT_PROFILE_IS_EMPTY; } diff --git a/services/distributedhardwarefwkserviceimpl/src/resourcemanager/capability_info_manager.cpp b/services/distributedhardwarefwkserviceimpl/src/resourcemanager/capability_info_manager.cpp index 189a8042..b6510fb3 100644 --- a/services/distributedhardwarefwkserviceimpl/src/resourcemanager/capability_info_manager.cpp +++ b/services/distributedhardwarefwkserviceimpl/src/resourcemanager/capability_info_manager.cpp @@ -224,9 +224,8 @@ int32_t CapabilityInfoManager::RemoveCapabilityInfoByKey(const std::string &key) return ERR_DH_FWK_RESOURCE_KEY_IS_EMPTY; } // 1. Clear the cache in the memory. - if (globalCapInfoMap_.find(key) != globalCapInfoMap_.end()) { - globalCapInfoMap_.erase(key); - } + 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()); -- Gitee From 9d4af9cbb5b96b3c23535277f855214ace9e5638 Mon Sep 17 00:00:00 2001 From: hwzhangchuang Date: Mon, 28 Feb 2022 19:55:53 +0800 Subject: [PATCH 3/5] modify readme file name Signed-off-by: hwzhangchuang --- README_zh.md => README_ZH_1.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename README_zh.md => README_ZH_1.md (100%) diff --git a/README_zh.md b/README_ZH_1.md similarity index 100% rename from README_zh.md rename to README_ZH_1.md -- Gitee From ac9cad49f337f594fe9028897ed44c909d241242 Mon Sep 17 00:00:00 2001 From: hwzhangchuang Date: Mon, 28 Feb 2022 19:56:58 +0800 Subject: [PATCH 4/5] modify README name to correct format Signed-off-by: hwzhangchuang --- README_ZH_1.md => README_ZH.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename README_ZH_1.md => README_ZH.md (100%) diff --git a/README_ZH_1.md b/README_ZH.md similarity index 100% rename from README_ZH_1.md rename to README_ZH.md -- Gitee From c7e67eab6da203e96134010d3ad8b9ed26253276 Mon Sep 17 00:00:00 2001 From: hwzhangchuang Date: Mon, 28 Feb 2022 20:31:38 +0800 Subject: [PATCH 5/5] modify README file format Signed-off-by: hwzhangchuang --- README_ZH.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_ZH.md b/README_ZH.md index fd625d7d..f0d88868 100644 --- a/README_ZH.md +++ b/README_ZH.md @@ -65,7 +65,7 @@ 以分布式相机为例,某设备下线后,分布式硬件管理框架去使能下线设备的相机硬件,本地移除分布式相机驱动并通知到相机框架,此时下线设备的分布式相机不可用。 -### **涉及仓** +## **涉及仓** **** **分步式硬件管理框架** [distributed_hardware_fwk](https://gitee.com/openharmony/distributed_hardware_fwk) -- Gitee